EmqxApiUtil.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.ruoyi.device.mqtt.api;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.TypeReference;
  4. import com.ruoyi.device.config.MqttConfig;
  5. import com.ruoyi.device.mqtt.api.constants.ApiPathConstants;
  6. import com.ruoyi.device.mqtt.api.item.ClientInfo;
  7. import com.ruoyi.device.mqtt.api.item.EmqxResult;
  8. import jakarta.annotation.Resource;
  9. import org.springframework.http.*;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.client.RestTemplate;
  12. import java.util.List;
  13. /**
  14. * EMQX HTTP API 工具
  15. *
  16. * @author lwm
  17. */
  18. @Component
  19. public class EmqxApiUtil
  20. {
  21. @Resource
  22. private MqttConfig mqttConfig;
  23. /**
  24. * 获取客户端信息
  25. *
  26. * @param deviceType 设备类型
  27. * @param deviceSn 设备 SN
  28. * @return 客户端信息
  29. */
  30. public EmqxResult<List<ClientInfo>> getClientInfo(String deviceType, Long deviceSn)
  31. {
  32. String url = mqttConfig.getApiPath()
  33. + String.format(ApiPathConstants.GET_CLIENT_INFO, getClientId(deviceType, deviceSn));
  34. return get(url, new TypeReference<>() {
  35. });
  36. }
  37. /**
  38. * 获取客户端ID
  39. *
  40. * @param deviceType 设备类型
  41. * @param deviceSn 设备 SN
  42. * @return 客户端ID
  43. */
  44. protected String getClientId(String deviceType, Long deviceSn)
  45. {
  46. String deviceSnFormat = String.format("%010d", deviceSn);
  47. return deviceType + ApiPathConstants.MIDDLELINE + deviceSnFormat;
  48. }
  49. /**
  50. * GET 请求
  51. *
  52. * @param url 请求地址
  53. * @param typeReference 返回数据类型
  54. * @return 返回数据
  55. */
  56. private <T> T get(String url, TypeReference<T> typeReference)
  57. {
  58. HttpHeaders headers = new HttpHeaders();
  59. headers.setBasicAuth(mqttConfig.getApiUserName(), mqttConfig.getApiPassword());
  60. headers.setContentType(MediaType.APPLICATION_JSON);
  61. HttpEntity<Void> entity = new HttpEntity<>(headers);
  62. RestTemplate restTemplate = new RestTemplate();
  63. ResponseEntity<String> responseEntity = restTemplate.exchange(
  64. url, HttpMethod.GET, entity, String.class);
  65. return JSON.parseObject(responseEntity.getBody(), typeReference);
  66. }
  67. }