device.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package data
  2. import (
  3. "MeterService/core/logger"
  4. "MeterService/core/utils"
  5. "MeterService/core/utils/httpHelper"
  6. "MeterService/dataStruct"
  7. "MeterService/database/appApi"
  8. "encoding/json"
  9. "errors"
  10. )
  11. func initDevice() error {
  12. appApiMap := dataStruct.NewMapAppApi()
  13. apiMap, ok := appApiMap.Get(dataStruct.GetDevices)
  14. if !ok {
  15. logger.Error("获取 设备加载API 错误")
  16. return errors.New("获取 设备加载API 错误")
  17. }
  18. for k, v := range apiMap {
  19. go loadDevice(k, v)
  20. }
  21. return nil
  22. }
  23. func loadDevice(appId int, api *appApi.AppApi) {
  24. if api == nil {
  25. logger.Error("应用[%d] 获取 设备加载API 错误", appId)
  26. return
  27. }
  28. http := httpHelper.NewHTTPClientHelper()
  29. url := api.Url
  30. if !utils.HasPrefix(&url, "http") {
  31. url = utils.IsPrefix(url, "/")
  32. url = api.Host + url
  33. }
  34. res, err := http.Get(url)
  35. if err != nil {
  36. logger.Error("应用[%d] 获取 设备加载API 错误", appId)
  37. return
  38. }
  39. devices := &[]dataStruct.DtuDevice{}
  40. err = json.Unmarshal(res, devices)
  41. if err != nil {
  42. return
  43. }
  44. for _, device := range *devices {
  45. dtu, err := device.ToDtu()
  46. if err != nil {
  47. return
  48. }
  49. dtuState := &dataStruct.DTUDeviceState{
  50. Info: dtu,
  51. Online: false,
  52. PwrOff: false,
  53. }
  54. DtuMap.Add(dtu.SN, dtuState)
  55. logger.Debug("应用[%d] 加载设备 [ %s ]", appId, dtu.SN)
  56. }
  57. }