report.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package iotDownService
  2. import (
  3. "IotAdmin/core/sdk/config"
  4. "IotAdmin/core/tools/writer"
  5. iotProtocol "IotAdmin/iot/protocol"
  6. iotElProtocol "IotAdmin/iot/protocol/electric"
  7. iotStruct "IotAdmin/iot/struct"
  8. "encoding/json"
  9. "log"
  10. "strings"
  11. "time"
  12. )
  13. func init() {
  14. mp = make(map[string]*writer.FileWriter)
  15. }
  16. func reportData(dataArray *[]*iotStruct.CollectData) {
  17. if dataArray == nil || len(*dataArray) == 0 {
  18. return
  19. }
  20. var reportHandler iotProtocol.ReportHandler
  21. for _, data := range *dataArray {
  22. cfg := data.SlaveConfig
  23. if cfg == nil {
  24. continue
  25. }
  26. for _, rc := range *cfg.ReportConfig {
  27. switch rc.Protocol {
  28. case iotProtocol.PlatElHj212:
  29. reportHandler = iotElProtocol.NewElHj212ReportHandler()
  30. default:
  31. }
  32. go func(d *iotStruct.CollectData, cfg *iotStruct.ReportConfig) {
  33. reportHandler.Adapter(d)
  34. str := reportHandler.Report(d, cfg)
  35. go logReport(d, cfg, str)
  36. }(data, &rc)
  37. }
  38. }
  39. }
  40. var mp map[string]*writer.FileWriter
  41. func logReport(data *iotStruct.CollectData, cfg *iotStruct.ReportConfig, dataStr *string) {
  42. output := getWrite(data)
  43. logData := &iotStruct.LogData{
  44. Time: time.Now().Format("20060102150400"),
  45. No: data.SlaveConfig.No,
  46. Data: *data,
  47. ReportHost: cfg.Host,
  48. ReportProtocol: cfg.Protocol,
  49. ReportMn: cfg.MN,
  50. ReportUser: cfg.User,
  51. ReportPwd: cfg.Pwd,
  52. ReportStr: *dataStr,
  53. }
  54. str, err := json.Marshal(logData)
  55. if err != nil {
  56. log.Printf("Report Log Marshal error: %s \r\n", err.Error())
  57. return
  58. }
  59. _, err = output.Write(str)
  60. if err != nil {
  61. log.Printf("Report Log Write error: %s \r\n", err.Error())
  62. return
  63. }
  64. _, err = output.Write([]byte("\r\n"))
  65. }
  66. func getWrite(data *iotStruct.CollectData) *writer.FileWriter {
  67. filePath := config.ApplicationConfig.DataLogFile
  68. if filePath == "" {
  69. filePath = "./_data/iot/"
  70. } else if filePath[len(filePath)-1] != '/' {
  71. filePath += "/"
  72. }
  73. filePath += strings.ReplaceAll(data.SlaveConfig.No, "_", "/")
  74. var output *writer.FileWriter
  75. var ok bool
  76. if output, ok = mp[filePath]; !ok {
  77. var err error
  78. output, err = writer.NewFileWriter(
  79. writer.WithPath(filePath),
  80. // 不切割文件
  81. writer.WithCap(0),
  82. writer.WithSuffix(".data"),
  83. )
  84. if err != nil {
  85. log.Printf("Report Log setup error: %s \r\n", err.Error())
  86. }
  87. mp[filePath] = output
  88. }
  89. return output
  90. }