package com.yeejoin.equipmanage.remote;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.util.HashMap;

/**
 * @Author: xl
 * @Description:
 * @Date: 2021/9/29 11:11
 */
@Component(value = "webMqttHandler")
public class WebMqttHandler {

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

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private EmqKeeper emqKeeper;

    public void publish(String topic, HashMap<String, Object> body) {
        try {
            SimpleModule simpleModule = new SimpleModule();
            simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
            objectMapper.registerModule(simpleModule);
            String jsonStr = objectMapper.writeValueAsString(body);
            emqKeeper.getMqttClient().publish(topic, jsonStr.getBytes(), 1, false);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
