MqttLogService.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package com.zy.omp.service;
  2. import com.baomidou.mybatisplus.core.metadata.IPage;
  3. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  4. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  5. import com.zy.omp.common.Constant;
  6. import com.zy.omp.pojo.io.pc.MqttLogsIO;
  7. import com.zy.omp.mapper.MqttLogMapper;
  8. import com.zy.omp.model.MqttLog;
  9. import com.zy.omp.pojo.dto.MqttMsgDto;
  10. import org.springframework.stereotype.Service;
  11. import java.util.HashSet;
  12. /**
  13. * MQTT 收发日志 Service
  14. *
  15. * @author chenyi
  16. * Create on 2020/4/10
  17. */
  18. @Service
  19. public class MqttLogService extends ServiceImpl<MqttLogMapper, MqttLog> {
  20. //所有的注册主题
  21. private static final HashSet<String> registerSet = new HashSet<>();
  22. static {
  23. registerSet.add(Constant.TOPIC_REGISTER_CLIENT);
  24. registerSet.add(Constant.TOPIC_REGISTER_SERVER);
  25. }
  26. /**
  27. * 保存接收的消息日志
  28. *
  29. * @param topic 主题
  30. * @param payload 消息内容
  31. */
  32. public void saveReceiveLog(String topic, String payload) {
  33. saveLog(topic, payload, 0);
  34. }
  35. /**
  36. * 保存发送的消息日志
  37. *
  38. * @param topic 主题
  39. * @param payload 消息内容
  40. */
  41. public void saveSendLog(String topic, String payload) {
  42. saveLog(topic, payload, 1);
  43. }
  44. /**
  45. * 保存 日志
  46. *
  47. * @param topic 主题
  48. * @param payload 消息内容
  49. * @param tag 0收 1发
  50. */
  51. private void saveLog(String topic, String payload, Integer tag) {
  52. MqttLog entity = new MqttLog();
  53. entity.setTopic(topic);
  54. //mqtt 日志类型
  55. entity.setTag(tag);
  56. //获取消息解析对象
  57. MqttMsgDto mqttMsgDto = MqttMsgDto.parse(payload);
  58. //注册报文与普通报文不同,注册报文取设备随机码
  59. String[] topicSplit = topic.split("/");
  60. String deviceId = topicSplit.length > 1 ? topicSplit[1] : null;
  61. entity.setDeviceId(registerSet.contains(topic) ? mqttMsgDto.getString("regnum") : deviceId);
  62. //mqtt 指令
  63. entity.setInstruction(mqttMsgDto.getM());
  64. entity.setContent(payload);
  65. baseMapper.insert(entity);
  66. }
  67. /**
  68. * 分页查询日志
  69. *
  70. * @param io 查询条件
  71. */
  72. public IPage<MqttLog> getListPage(MqttLogsIO io) {
  73. Page<MqttLog> page = new Page<>(io.getCurrent(), io.getSize());
  74. return baseMapper.getListPage(page, io);
  75. }
  76. }