forLightEnergyService.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package edge_service
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "iot_manager_service/config"
  6. "net/http"
  7. "strings"
  8. )
  9. // ForLightEnergy 获取设备能耗数据
  10. type ForLightEnergy struct{}
  11. // ForLightEnergyReq 请求参数
  12. type ForLightEnergyReq struct {
  13. Codes []string `json:"codes"` //设备sn列表
  14. Start string `json:"start"`
  15. End string `json:"end"`
  16. Flag int `json:"flag"` //1按日 2按月
  17. }
  18. // ForLightEnergyRes 返回数据
  19. type ForLightEnergyRes struct {
  20. Code int `json:"code"`
  21. Msg string `json:"msg"`
  22. Data map[string][]ForLightEnergyData `json:"data"`
  23. }
  24. type ForLightEnergyData struct {
  25. Date string `json:"date"` //日期
  26. Beginning float64 `json:"beginning"` //开始
  27. Ending float64 `json:"ending"` //结束
  28. Difference float64 `json:"difference"` //能耗
  29. }
  30. func (r *ForLightEnergy) GetLightEnergy(reqPostData ForLightEnergyReq) (map[string][]ForLightEnergyData, error) {
  31. cfg := config.Instance()
  32. api := cfg.Foreign.IotEdgeUrl + "/data/v1/energy"
  33. method := "POST"
  34. client := &http.Client{}
  35. marshal, _ := json.Marshal(reqPostData)
  36. req, err := http.NewRequest(method, api, strings.NewReader(string(marshal)))
  37. if err != nil {
  38. return nil, err
  39. }
  40. res, err := client.Do(req)
  41. if err != nil {
  42. return nil, err
  43. }
  44. defer res.Body.Close()
  45. body, err := ioutil.ReadAll(res.Body)
  46. if err != nil {
  47. return nil, err
  48. }
  49. //fmt.Printf("body = %v", string(body))
  50. result := ForLightEnergyRes{}
  51. err = json.Unmarshal(body, &result)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if result.Code != 0 {
  56. panic(result.Msg)
  57. }
  58. //fmt.Printf("result.Data = %v", result.Data)
  59. return result.Data, nil
  60. }