package com.pwt.netty.handler;

import com.pwt.netty.common.chargerold.ChargerMessageHeader;
import com.pwt.netty.common.chargerold.RequestMessage;
import com.pwt.netty.common.chargerold.client.BatteryFaultData;
import com.pwt.netty.common.chargerold.client.BatteryStatusData;
import com.pwt.netty.util.ObjUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author linyun
 * @version V1.0
 * @Title: ChargerClientHandler
 * @Description: 充电机客户端处理器
 * @date 2022/11/09
 **/
@Slf4j
public class ChargerClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 服务端发消息触发
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception
    {
        BatteryStatusData batteryStatus = new BatteryStatusData();
        batteryStatus.decode(byteBuf);

        log.info("充电机客户端接收服务端数据:{}",batteryStatus);
    }

    // 连接成功后触发的操作
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        ByteBuf buf = Unpooled.buffer();
        ChargerMessageHeader header = new ChargerMessageHeader();
        header.setStart(0X12);
        header.setSerialNo(1551771312);
        header.setChargerAddress("32110010101111");
        header.setLength(10);
        BatteryFaultData data = (BatteryFaultData) ObjUtil.getProperty(new BatteryFaultData());
        RequestMessage message = new RequestMessage();
        message.setHeader(header);
        message.setMessageData(data);
        message.setEnd(0X18);
        message.encode(buf);
        ctx.writeAndFlush(buf);
        log.info("充电机客户端连接服务端成功...");
    }

    /**
     * 断开触发
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        log.info("连接断开！！！");
    }
}
