package com.ruoyi.integration.iotda.utils.produce; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson2.JSONObject; import com.huaweicloud.sdk.iotda.v5.model.CreateMessageRequest; import com.huaweicloud.sdk.iotda.v5.model.CreateMessageResponse; import com.huaweicloud.sdk.iotda.v5.model.DeviceMessageRequest; import com.ruoyi.common.core.utils.uuid.UUID; import com.ruoyi.integration.iotda.builder.IotBuilder; import com.ruoyi.integration.iotda.utils.tools.IotCommandLog; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; /** * iotda消息发送 */ @Slf4j @RestController public class IotMessageProduce { @Autowired private IotBuilder iotBuilder; /** * 设备消息下发 * @param name 消息名称 * @param message 消息内容 * @return */ @PostMapping("/sendMessage") public String sendMessage(String code, String name, JSONObject message){ CreateMessageRequest request = new CreateMessageRequest(); request.withDeviceId(code); DeviceMessageRequest body = new DeviceMessageRequest(); body.withMessageId(UUID.randomUUID().toString()); body.withName(name); body.withMessage(message); request.withBody(body); // 记录下行指令日志(独立日志文件、含指令中文含义;心跳应答 pong 不记录) String serviceId = message == null ? null : message.getString("service_id"); IotCommandLog.downlink(code, name, serviceId, message); try { CreateMessageResponse response = iotBuilder.buildIot().createMessage(request); return JSON.toJSONString(response); } catch (Exception e) { e.printStackTrace(); IotCommandLog.downlinkFail(code, name, serviceId, message, e.getMessage()); return e.getMessage(); } } }