package com.hw.mqtt.listener;

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.StringUtils;
import net.dreamlu.iot.mqtt.spring.server.MqttServerTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author Wen JY
 * @description: TODO
 * @date 2023-09-11 15:28:18
 * @version: 1.0
 */
@Component
public class RedisMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);

    private final MqttServerTemplate mqttServerTemplate;

    public RedisMessageListener(MqttServerTemplate mqttServerTemplate) {
        this.mqttServerTemplate = mqttServerTemplate;
    }

    /**
     * 订阅设备控制信息、发布设备指令
     * @param message
     */
    public void deviceCommand(String message){
        try {

            if(StringUtils.isEmpty(message)){
                logger.warn("Redis订阅内容为空！！！");
                return;
            }
            logger.info("Redis订阅内容："+message);
            JSONObject jsonObject = JSONObject.parseObject(message);
            String topic = jsonObject.get("Topic").toString();
            String payload = jsonObject.get("Payload").toString();
            boolean publishResult = mqttServerTemplate.publishAll(topic, payload.getBytes(StandardCharsets.UTF_8));
            if(publishResult){
                logger.info("Topic:"+topic+";Payload:"+payload+";消息发布成功");
            }else {
                logger.info("Topic:"+topic+";Payload:"+payload+";消息发布失败！！！");
            }
        }catch (Exception e){
            logger.error("设备控制指令下发异常："+e.getMessage());
        }
    }
}
