123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package utils
- import (
- "bigdata_archives/configs"
- "bigdata_archives/global"
- "bigdata_archives/simple_zap"
- "context"
- "fmt"
- "github.com/simonvetter/modbus"
- "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报警
- }
- var LatestData map[int]Temperature
- func ModBus() error {
- var client *modbus.ModbusClient
- var err error
- // 创建并配置Modbus客户端
- client, err = modbus.NewClient(&modbus.ClientConfiguration{
- URL: configs.Config.GetString("Modbus.url"),
- Timeout: 3 * time.Second,
- })
- if err != nil {
- simple_zap.WithCtx(context.Background()).Sugar().Error(err, "连接失败")
- return err
- }
- defer client.Close()
- err = client.Open()
- if err != nil {
- simple_zap.WithCtx(context.Background()).Sugar().Error(err, "连接打开失败")
- return err
- }
- ticker := time.NewTicker(1 * time.Second) // 每秒获取一次数据
- hourlyTicker := time.NewTicker(1 * time.Hour) // 每小时记录一次数据
- LatestData = make(map[int]Temperature)
- for {
- select {
- case <-ticker.C:
- for i := 1; i <= 6; i++ {
- client.SetUnitId(uint8(i))
- temperature, err := client.ReadRegister(0, modbus.INPUT_REGISTER)
- humidity, err := client.ReadRegister(1, modbus.INPUT_REGISTER)
- if err != nil {
- simple_zap.WithCtx(context.Background()).Sugar().Error(err, "读取失败")
- break
- }
- fmt.Printf("设备:%v 温度: %v\n", i, int16(temperature))
- fmt.Printf("设备:%v 湿度: %v\n", i, int16(humidity))
- // 存储最新的数据
- LatestData[i] = Temperature{
- SlaveID: i,
- Temperature: float64(temperature) / 10,
- Humidity: float64(humidity) / 10,
- UploadTime: Time(time.Now()),
- }
- }
- case <-hourlyTicker.C:
- // 每小时保存最新数据
- for _, data := range LatestData {
- if err := global.DBLink.Create(&data).Error; err != nil {
- simple_zap.WithCtx(context.Background()).Sugar().Error(err, "写入失败")
- break
- }
- }
- }
- }
- }
- // Gettemperature 获取最近一周的数据
- func Gettemperature() []Temperature {
- var temperatureHumidity []Temperature
- now := time.Now()
- oneWeekAgo := now.AddDate(0, 0, -7)
- formattedTime := oneWeekAgo.Format("2006-01-02 15:04:05")
- tx := global.DBLink.Where("upload_time >= ?", formattedTime).Find(&temperatureHumidity)
- if tx.Error == nil && tx.RowsAffected >= 0 {
- return temperatureHumidity
- }
- return nil
- }
|