/*
 * 文 件 名:  ChargingPileEncoder
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  充电桩协议编码器
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/12/22
 */
package com.ruoyi.ems.charging.core;

import com.ruoyi.ems.charging.model.BaseFrame;
import com.ruoyi.ems.charging.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 充电桩协议编码器
 * 负责将协议帧对象编码为字节流
 *
 * @author lvwenbin
 * @version [版本号, 2025/12/22]
 */
public class ChargingPileEncoder extends MessageToByteEncoder<BaseFrame> {
    
    private static final Logger log = LoggerFactory.getLogger(ChargingPileEncoder.class);
    
    @Override
    protected void encode(ChannelHandlerContext ctx, BaseFrame frame, ByteBuf out) throws Exception {
        try {
            // 编码帧
            byte[] data = frame.encode();
            out.writeBytes(data);
            
            // 调试日志
            if (log.isDebugEnabled()) {
                log.debug("编码发送[{}字节]: {} -> {}", 
                    data.length, frame, ByteUtils.bytesToHex(data));
            }
        } catch (Exception e) {
            log.error("编码失败: {} - {}", frame, e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("编码器异常: {}", cause.getMessage(), cause);
        ctx.close();
    }
}
