|
@@ -0,0 +1,74 @@
|
|
|
+package utils
|
|
|
+
|
|
|
+import (
|
|
|
+ //"bigdata_archives/app/model"
|
|
|
+ "bigdata_archives/configs"
|
|
|
+ "bigdata_archives/global"
|
|
|
+ "bigdata_archives/simple_zap"
|
|
|
+ "context"
|
|
|
+ "fmt"
|
|
|
+ "github.com/goburrow/serial"
|
|
|
+ modbus "github.com/thinkgos/gomodbus/v2"
|
|
|
+ "log"
|
|
|
+ "time"
|
|
|
+)
|
|
|
+
|
|
|
+type Temperature struct {
|
|
|
+ BaseModel
|
|
|
+ SlaveID int `gorm:"type:int(11)" json:"slave_id"` //设备ID
|
|
|
+ Temperature float64 `gorm:"type:float(10,2)" json:"temperature"` //温度
|
|
|
+ Humidity float64 `gorm:"type:float(10,2)" json:"humidity"` //湿度
|
|
|
+ UploadTime Time `gorm:"type:datetime" json:"upload_time"` //上传时间
|
|
|
+ TemperatureAlarm int `gorm:"type:int(11)" json:"temperature_alarm"` //温度报警 1报警
|
|
|
+ HumidityAlarm int `gorm:"type:int(11)" json:"humidity_alarm"` //湿度报警 1报警
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+func ModBus() {
|
|
|
+ provider := modbus.NewRTUClientProvider(
|
|
|
+ modbus.WithEnableLogger(),
|
|
|
+ modbus.WithSerialConfig(serial.Config{
|
|
|
+ Address: configs.Config.GetString("modbus.address"),
|
|
|
+ BaudRate: configs.Config.GetInt("modbus.baudrate"),
|
|
|
+ DataBits: configs.Config.GetInt("modbus.databits"),
|
|
|
+ Parity: configs.Config.GetString("modbus.parity"),
|
|
|
+ Timeout: 5 * time.Second, //连接超时时间
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ client := modbus.NewClient(provider)
|
|
|
+ err := client.Connect()
|
|
|
+ if err != nil {
|
|
|
+ simple_zap.WithCtx(context.Background()).Sugar().Error("modbus连接失败", err)
|
|
|
+ }
|
|
|
+ defer func() {
|
|
|
+ if err := client.Close(); err != nil {
|
|
|
+ simple_zap.WithCtx(context.Background()).Sugar().Error("modbus关闭失败", err)
|
|
|
+ }
|
|
|
+ }()
|
|
|
+ for {
|
|
|
+ for i := 1; i < 4; i++ {
|
|
|
+ results, err := client.ReadInputRegisters(byte(i), 0, 2)
|
|
|
+ if err != nil {
|
|
|
+ log.Printf("modbus读取失败:%v", err)
|
|
|
+ continue
|
|
|
+ }
|
|
|
+
|
|
|
+ temperature := Temperature{
|
|
|
+ SlaveID: i,
|
|
|
+ Humidity: float64(results[1] / 10.0),
|
|
|
+ Temperature: float64(results[0] / 10.0),
|
|
|
+ UploadTime: Time(time.Now()),
|
|
|
+ HumidityAlarm: 0,
|
|
|
+ TemperatureAlarm: 0,
|
|
|
+ }
|
|
|
+ //保存温湿度到数据库
|
|
|
+ global.DBLink.Create(&temperature)
|
|
|
+ fmt.Println("温湿度:", temperature)
|
|
|
+ log.Printf("设备%v,温度: %v", i, results[0]/10.0)
|
|
|
+ log.Printf("设备%v 湿度度: %v", i, results[1]/10.0)
|
|
|
+ log.Printf("客户端状态: %v\n", &client)
|
|
|
+
|
|
|
+ }
|
|
|
+ time.Sleep(60 * time.Second)
|
|
|
+ }
|
|
|
+}
|