package com.xydl.cac.iec104;

import lombok.extern.slf4j.Slf4j;
import org.openmuc.j60870.*;

import java.io.IOException;

@Slf4j
public class Iec104Server implements ServerEventListener {
    Server _server;
    int idCounter = 1;
    public boolean started = false;
    public Integer port = null;

    public Iec104Server() {
    }

    public void start(int port) throws Exception {
        if (!started) {
            _server = Server.builder()
                    .setPort(port)
                    .setIoaFieldLength(3)
                    .setCommonAddressFieldLength(2)
                    .setCotFieldLength(2)
                    .build();
            _server.start(this);
            started = true;
            this.port = port;
            log.info("已启动IEC104服务端在" + port + "端口");
        }
    }

    public void stop() {
        if (_server != null) {
            _server.stop();
            log.info("已停止IEC104服务端于" + port + "端口");
        }
        started = false;
    }


    @Override
    public ConnectionEventListener connectionIndication(Connection connection) {
        return new ServerConnectionEventListener(connection, idCounter++);
    }

    @Override
    public void serverStoppedListeningIndication(IOException e) {

    }

    @Override
    public void connectionAttemptFailed(IOException e) {

    }
}
