package com.xydl.cac.iec104;


import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.StaticVariable;
import com.xydl.cac.socket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Service
@Slf4j
public class RealTime104DataService {
    @Resource
    WebSocketServer webSocketServer;

    public static boolean inDoing = false;

    @PostConstruct
    private void init() {
        try {
//            this.startCollect("192.168.1.177");
        } catch (Exception ignore) {
        }
    }

    public void startCollect(String ip) throws BusinessException {
        inDoing = true;
        try {
            Iec104Client client = new Iec104Client(webSocketServer);
            client.connect(ip, 2404);
            client.keep = true;
        } catch (Exception ex) {
            String err = "IEC104客户端连接异常, ip=" + ip;
            log.error(err, ex);
            throw new BusinessException(err);
        } finally {
            inDoing = false;
        }
    }

    public void stopCollect() {
        if (StaticVariable.realTime104Client != null) {
            StaticVariable.realTime104Client.keep = false;
            StaticVariable.realTime104Client.disconnect();
            StaticVariable.realTime104Client = null;
        }
    }

    @PreDestroy
    private void stop() {
        log.info("关闭IEC104客户端.");
        StaticVariable.shutdown = 1;
        this.stopCollect();
    }

}
