modbus.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package utils
  2. import (
  3. "bigdata_archives/configs"
  4. "bigdata_archives/global"
  5. "bigdata_archives/simple_zap"
  6. "context"
  7. "fmt"
  8. "github.com/simonvetter/modbus"
  9. "time"
  10. )
  11. type Temperature struct {
  12. BaseModel
  13. SlaveID int `gorm:"type:int(11)" json:"slave_id"` //设备ID
  14. Temperature float64 `gorm:"type:float(10,2)" json:"temperature"` //温度
  15. Humidity float64 `gorm:"type:float(10,2)" json:"humidity"` //湿度
  16. UploadTime Time `gorm:"type:datetime" json:"upload_time"` //上传时间
  17. TemperatureAlarm int `gorm:"type:int(11)" json:"temperature_alarm"` //温度报警 1报警
  18. HumidityAlarm int `gorm:"type:int(11)" json:"humidity_alarm"` //湿度报警 1报警
  19. }
  20. var LatestData map[int]Temperature
  21. func ModBus() error {
  22. var client *modbus.ModbusClient
  23. var err error
  24. // 创建并配置Modbus客户端
  25. client, err = modbus.NewClient(&modbus.ClientConfiguration{
  26. URL: configs.Config.GetString("Modbus.url"),
  27. Timeout: 3 * time.Second,
  28. })
  29. if err != nil {
  30. simple_zap.WithCtx(context.Background()).Sugar().Error(err, "连接失败")
  31. return err
  32. }
  33. defer client.Close()
  34. err = client.Open()
  35. if err != nil {
  36. simple_zap.WithCtx(context.Background()).Sugar().Error(err, "连接打开失败")
  37. return err
  38. }
  39. ticker := time.NewTicker(1 * time.Second) // 每秒获取一次数据
  40. hourlyTicker := time.NewTicker(1 * time.Hour) // 每小时记录一次数据
  41. LatestData = make(map[int]Temperature)
  42. for {
  43. select {
  44. case <-ticker.C:
  45. for i := 1; i <= 6; i++ {
  46. client.SetUnitId(uint8(i))
  47. temperature, err := client.ReadRegister(0, modbus.INPUT_REGISTER)
  48. humidity, err := client.ReadRegister(1, modbus.INPUT_REGISTER)
  49. if err != nil {
  50. simple_zap.WithCtx(context.Background()).Sugar().Error(err, "读取失败")
  51. break
  52. }
  53. fmt.Printf("设备:%v 温度: %v\n", i, int16(temperature))
  54. fmt.Printf("设备:%v 湿度: %v\n", i, int16(humidity))
  55. // 存储最新的数据
  56. LatestData[i] = Temperature{
  57. SlaveID: i,
  58. Temperature: float64(temperature) / 10,
  59. Humidity: float64(humidity) / 10,
  60. UploadTime: Time(time.Now()),
  61. }
  62. }
  63. case <-hourlyTicker.C:
  64. // 每小时保存最新数据
  65. for _, data := range LatestData {
  66. if err := global.DBLink.Create(&data).Error; err != nil {
  67. simple_zap.WithCtx(context.Background()).Sugar().Error(err, "写入失败")
  68. break
  69. }
  70. }
  71. }
  72. }
  73. }
  74. // Gettemperature 获取最近一周的数据
  75. func Gettemperature() []Temperature {
  76. var temperatureHumidity []Temperature
  77. now := time.Now()
  78. oneWeekAgo := now.AddDate(0, 0, -7)
  79. formattedTime := oneWeekAgo.Format("2006-01-02 15:04:05")
  80. tx := global.DBLink.Where("upload_time >= ?", formattedTime).Find(&temperatureHumidity)
  81. if tx.Error == nil && tx.RowsAffected >= 0 {
  82. return temperatureHumidity
  83. }
  84. return nil
  85. }