package com.imdroid.beidou.test_device.service;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Layton
 * @date 2023/2/2 21:00
 * 提供两种获取channel的方法：通过deviceId；通过imei。imei是DTU连接服务器最先上报的消息
 * 利用imei-ipaddr-deviceId，可以发现imei和deviceId的绑定关系
 */
public class OnlineChannels {

    public static final OnlineChannels INSTANCE = new OnlineChannels();

    // 设备已连接，deviceId已上报
    private final Map<String, Channel> dataChannels = new ConcurrentHashMap<>();

    private OnlineChannels() {}

    public void updateChannel(String deviceId, Channel channel) {
        dataChannels.put(deviceId, channel);
    }

    public void writeAndFlush(byte[] data){
        for(Channel channel:dataChannels.values()){
            if(channel.isActive()) {
                ByteBuf buf = Unpooled.buffer();
                buf.writeBytes(data);
                channel.writeAndFlush(buf);
            }
        }
    }

}
