package org.jeecg.modules.pm.handler;

import com.google.protobuf.ByteString;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.jeecg.modules.pm.entity.eps.EventDis;

import javax.jms.*;

/**
 * @author: JJww
 * @Date:2022/3/28
 */

public class VssMssageListener {

    /**
     * 10.33.47.176:61618和openapi.vss.topic可通过openapi【事件订阅接口】获得
     */
    public static final String BROKER_URL = "failover:(tcp://172.16.16.2:61618)?timeout=2000";

    /**
     * 10.33.47.176:61618和openapi.vss.topic可通过openapi【事件订阅接口】获得
     */
    public static final String TARGET = "openapi.vss.topic";

    public static void run() {
        Connection connection = null;
        Session session = null;
        try {
            // 创建链接工厂
            ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
            // 通过工厂创建一个连接
            connection = factory.createConnection();
            // factory.createConnection(userName, password)
            // 启动连接
            connection.start();
            // 第一个参数表示是否使用事务，第二个参数指定消息的确认模式
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(TARGET);
            MessageConsumer consumer = session.createConsumer(topic);
            // 消费者异步接收topic里的消息
            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message msg) {
                    try {
                        // cms里发送的消息为BytesMessage，此处不做判断亦可
                        if (msg instanceof BytesMessage) {
                            BytesMessage bytesMessage = (BytesMessage) msg;
                            long length = bytesMessage.getBodyLength();
                            byte[] bt = new byte[(int) length];
                            // 将BytesMessage转换为byte类型
                            bytesMessage.readBytes(bt);
                            // 壳文件字段，EventDis类为event_dis.proto文件解析而来，CommEventLog类为事件壳文件类
                            EventDis.CommEventLog parseFrom = EventDis.CommEventLog.parseFrom(bt);
                            // 输出壳文件字段
                            System.out.println(parseFrom.toString());
                            // 扩展字段，此字段为设备上报事件内容，部分事件需要使用pb文件再次解析
                            ByteString extInfo = parseFrom.getExtInfo();
                            // 输出扩展字段
                            System.out.println(extInfo.toStringUtf8());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            System.out.println("ActiveMQ开始监听");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}