Explorar el Código

modbus 获取数据并上传

huangyan hace 7 meses
padre
commit
720b2465ea

+ 82 - 0
app/controller/archives.go

@@ -0,0 +1,82 @@
+package controller
+
+import (
+	"bigdata_archives/app/e"
+	"bigdata_archives/configs"
+	"bytes"
+	"encoding/json"
+	"github.com/gin-gonic/gin"
+	"io"
+	"net/http"
+)
+
+type RequestData struct {
+	AppId  string `json:"appId"`
+	Secret string `json:"secret"`
+}
+type T struct {
+	Success bool   `json:"success"`
+	Message string `json:"message"`
+	Code    int    `json:"code"`
+	Result  struct {
+		QzCount    int `json:"qzCount"`
+		QsCount    int `json:"qsCount"`
+		JsCount    int `json:"jsCount"`
+		DzdaCount  int `json:"dzdaCount"`
+		YjCount    int `json:"yjCount"`
+		CqqsCount  int `json:"cqqsCount"`
+		CqjsCount  int `json:"cqjsCount"`
+		QueryCount int `json:"queryCount"`
+		FileCount  int `json:"fileCount"`
+		ZkList     []struct {
+			Name string `json:"name"`
+			Num  int    `json:"num"`
+		} `json:"zkList"`
+		CkList []struct {
+			Name string `json:"name"`
+			Num  int    `json:"num"`
+		} `json:"ckList"`
+		DrkList []struct {
+			Name string `json:"name"`
+			Num  int    `json:"num"`
+		} `json:"drkList"`
+		DckList []struct {
+			Name string `json:"name"`
+			Num  int    `json:"num"`
+		} `json:"dckList"`
+		ZkNum  int `json:"zkNum"`
+		CkNum  int `json:"ckNum"`
+		DrkNum int `json:"drkNum"`
+		DckNum int `json:"dckNum"`
+	} `json:"result"`
+	Timestamp int64 `json:"timestamp"`
+}
+
+func Archives(c *gin.Context) {
+	// 创建要发送的数据
+	data := &RequestData{
+		AppId:  "1686846386279535435",
+		Secret: "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDvv8hgUuIzp7WdTS5zHQPt9bOytMNRY+s1MBCbLp6C2sz9kg+agQ/cMqztYgwjlYqETyUTiu/uuF0y71VHtfazip6eYI++EHqBCNgmgGBkdyV5EyiSBC+RsJ0tX+oCFFtIIlYzIwgserkZyVKrSF61OieQj+C2rqbJBZq5svXlwIDAQAB",
+	}
+	marshal, err2 := json.Marshal(data)
+	if err2 != nil {
+		e.ResponseWithMsg(c, e.ERROR, "json序列化失败")
+		return
+	}
+	resp, err := http.Post(configs.Config.GetString("archives.arc"), "application/json", bytes.NewReader(marshal))
+	if err != nil {
+		e.ResponseWithMsg(c, e.ERROR, "请求接口失败")
+		return
+	}
+	defer resp.Body.Close()
+	all, _ := io.ReadAll(resp.Body)
+	var datas T
+	json.Unmarshal(all, &datas)
+	if datas.Code == 200 {
+		e.ResponseSuccess(c, datas.Result)
+		return
+	} else {
+		e.ResponseWithMsg(c, e.ERROR, "请求接口失败")
+		return
+	}
+}

+ 1 - 0
app/model/temperature.go

@@ -0,0 +1 @@
+package model

+ 3 - 3
app/router.go

@@ -3,13 +3,13 @@ package app
 import (
 	middlewares "bigdata_archives/app/middleware"
 	"bigdata_archives/app/routers"
-	"bigdata_archives/global"
+	"bigdata_archives/configs"
 	"github.com/gin-gonic/gin"
 )
 
 func InitRouter() error {
 	engine := gin.New()
-	gin.SetMode(global.ServerSetting.Mode)
+	gin.SetMode(configs.Config.GetString("server.mode"))
 	engine.Use(middlewares.Cors())
 	//配置前端静态资源
 	engine.StaticFile("/", "./frontend/dist/index.html")
@@ -19,5 +19,5 @@ func InitRouter() error {
 	routers.UserRouter(engine)
 	engine.Use(middlewares.AdminMiddleware())
 	routers.SystemRouter(engine)
-	return engine.Run(global.ServerSetting.Port)
+	return engine.Run(configs.Config.GetString("server.port"))
 }

+ 1 - 0
app/routers/system.go

@@ -11,4 +11,5 @@ func SystemRouter(r *gin.Engine) {
 	group.POST("/setting", controller.CreateSystem)
 	group.PUT("/setting", controller.UpdateSystem)
 	group.DELETE("/setting", controller.DeleteSystem)
+
 }

+ 1 - 0
app/routers/usersrouter.go

@@ -9,6 +9,7 @@ import (
 func UserRouter(r *gin.Engine) {
 	group := r.Group("/api")
 	group.POST("/login", controller.Login)
+	group.GET("/archives", controller.Archives)
 	group.POST("/user", controller.AddUser).Use(middlewares.AdminMiddleware())
 	group.POST("/userlist", controller.UserList).Use(middlewares.AdminMiddleware())
 	group.GET("/getuser", controller.GetUserById).Use(middlewares.AdminMiddleware())

+ 9 - 1
configs/config.yaml → config.yaml

@@ -42,4 +42,12 @@ nats:
   NatsServer_Url: "nats://127.0.0.0:4222"
 swag:
   # 将环境变量 NAME_OF_ENV_VARIABLE设置为任意值,则 /swagger/*any 返回404响应
-  enable: "NAME_OF_ENV_VARIABLE"
+  enable: "NAME_OF_ENV_VARIABLE"
+archives:
+  arc: "http://45.251.93.106:8082/api/statistics"
+modbus:
+  address: "COM3"
+  baudrate: 4800
+  databits: 8
+  parity: "N"
+

+ 0 - 46
configs/setting.go

@@ -1,46 +0,0 @@
-package global
-
-import "github.com/spf13/viper"
-
-type Settings struct {
-	vp *viper.Viper
-}
-
-var sections = make(map[string]interface{})
-
-// NewSetting 读取配置
-func NewSetting() (*Settings, error) {
-	vp := viper.New()
-	vp.SetConfigName("config")
-	vp.AddConfigPath("configs")
-	vp.SetConfigType("yaml")
-	err := vp.ReadInConfig()
-	if err != nil {
-		return nil, err
-	}
-	s := &Settings{vp}
-	return s, nil
-}
-
-// ReadSection 读取指定的一段
-func (s *Settings) ReadSection(k string, v interface{}) error {
-	err := s.vp.UnmarshalKey(k, v)
-	if err != nil {
-		return err
-	}
-	if _, ok := sections[k]; !ok {
-		sections[k] = v
-	}
-	return nil
-}
-
-// ReloadAllSection 重新加载
-func (s *Settings) ReloadAllSection() error {
-	for k, v := range sections {
-		err := s.ReadSection(k, v)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
-}

+ 2 - 0
database/migrate.go

@@ -2,6 +2,7 @@ package database
 
 import (
 	"bigdata_archives/app/model"
+	"bigdata_archives/utils"
 	"gorm.io/gorm"
 )
 
@@ -9,5 +10,6 @@ func Migrate(db *gorm.DB) {
 	db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(
 		model.User{},
 		model.SystemSettings{},
+		utils.Temperature{},
 	)
 }

+ 7 - 5
global/db.go

@@ -1,6 +1,7 @@
 package global
 
 import (
+	"bigdata_archives/configs"
 	"fmt"
 	"gorm.io/driver/mysql"
 	"gorm.io/gorm"
@@ -16,11 +17,11 @@ var (
 func SetupDBLink() error {
 	var err error
 	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s",
-		DatabaseSetting.UserName,
-		DatabaseSetting.Password,
-		DatabaseSetting.Host,
-		DatabaseSetting.Db,
-		DatabaseSetting.OtherParams,
+		configs.Config.GetString("database.userName"),
+		configs.Config.GetString("database.password"),
+		configs.Config.GetString("database.host"),
+		configs.Config.GetString("database.db"),
+		configs.Config.GetString("database.otherParams"),
 	)
 	//判断当前系统是windows还是linux
 	//runtime获取的是当前Go语言框架的参数,不是实际运行的操作系统的参数
@@ -33,6 +34,7 @@ func SetupDBLink() error {
 		log.Print("当前系统为windows")
 	} else if sysType == "linux" {
 		DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
+
 	}
 
 	if err != nil {

+ 0 - 24
global/redis.go

@@ -1,24 +0,0 @@
-package global
-
-import (
-	"bigdata_archives/simple_zap"
-	"context"
-	"fmt"
-	"github.com/go-redis/redis/v8"
-)
-
-var Rdb *redis.Client
-
-func SetupRedisLink() {
-	Rdb = redis.NewClient(&redis.Options{
-		Addr:     RedisSetting.Addr,
-		Password: "",
-		DB:       0,
-	})
-	ctx := context.Background()
-	_, err := Rdb.Ping(ctx).Result()
-	if err != nil {
-		simple_zap.WithCtx(context.Background()).Sugar().Warn("redis连接失败", err)
-		fmt.Println(err)
-	}
-}

+ 0 - 76
global/setting.go

@@ -1,76 +0,0 @@
-package global
-
-import (
-	global "bigdata_archives/configs"
-)
-
-// DatabaseSettingS 数据库配置
-type DatabaseSettingS struct {
-	Dialect         string `json:"dialect"`
-	Host            string `json:"host"`
-	Port            string `json:"port"`
-	UserName        string `json:"userName"`
-	Password        string `json:"password"`
-	Db              string `json:"db"`
-	OtherParams     string `json:"otherParams"`
-	MaxIdleConn     int    `json:"max_idle_conn"`
-	MaxOpenConn     int    `json:"max_open_conn"`
-	ConnMaxLifetime string `json:"conn_max_lifetime"`
-}
-
-// Nats 配置
-type Nats struct {
-	NatsServerUrl string `json:"NatsServer_Url"`
-}
-
-// Jwt 配置
-type Jwt struct {
-	Secret        string `json:"secret"`
-	RefreshExpire int    `json:"refresh_expire"`
-	Issuer        string `json:"issuer"`
-}
-
-// ServerSettingS 服务器配置
-type ServerSettingS struct {
-	Mode                string `json:"mode"`
-	Port                string `json:"port"`
-	InsecureServingInfo string `json:"insecure_serving_info"`
-}
-type SubMail struct {
-	Appid     string `json:"appid"`
-	Signature string `json:"signature"`
-}
-type Redis struct {
-	Addr     string `json:"addr"`
-	Password string `json:"password"`
-	DB       int    `json:"db"`
-}
-type Swagger struct {
-	Enable string `json:"enable"`
-}
-
-var (
-	DatabaseSetting *DatabaseSettingS
-	NatsSetting     *Nats
-	JwtSetting      *Jwt
-	ServerSetting   *ServerSettingS
-	SubMailSetting  *SubMail
-	RedisSetting    *Redis
-	SwaggerSetting  *Swagger
-)
-
-// SetupSetting 读取配置到全局变量
-func SetupSetting() error {
-	s, err := global.NewSetting()
-	err = s.ReadSection("Database", &DatabaseSetting)
-	err = s.ReadSection("Nats", &NatsSetting)
-	err = s.ReadSection("Jwt", &JwtSetting)
-	err = s.ReadSection("Server", &ServerSetting)
-	err = s.ReadSection("SubMail", &SubMailSetting)
-	err = s.ReadSection("Redis", &RedisSetting)
-	err = s.ReadSection("Swagger", &SwaggerSetting)
-	if err != nil {
-		return err
-	}
-	return nil
-}

+ 7 - 0
go.mod

@@ -18,6 +18,7 @@ require (
 )
 
 require (
+	github.com/aler9/gortsplib v1.0.1 // indirect
 	github.com/bytedance/sonic/loader v0.1.1 // indirect
 	github.com/cespare/xxhash/v2 v2.1.2 // indirect
 	github.com/cloudwego/base64x v0.1.4 // indirect
@@ -27,6 +28,7 @@ require (
 	github.com/gabriel-vasile/mimetype v1.4.3 // indirect
 	github.com/gin-contrib/sse v0.1.0 // indirect
 	github.com/go-sql-driver/mysql v1.7.0 // indirect
+	github.com/goburrow/serial v0.1.0 // indirect
 	github.com/goccy/go-json v0.10.2 // indirect
 	github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
 	github.com/hashicorp/hcl v1.0.0 // indirect
@@ -41,6 +43,10 @@ require (
 	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
 	github.com/modern-go/reflect2 v1.0.2 // indirect
 	github.com/pelletier/go-toml/v2 v2.2.2 // indirect
+	github.com/pion/randutil v0.1.0 // indirect
+	github.com/pion/rtcp v1.2.9 // indirect
+	github.com/pion/rtp v1.7.13 // indirect
+	github.com/pion/sdp/v3 v3.0.5 // indirect
 	github.com/sagikazarmark/locafero v0.4.0 // indirect
 	github.com/sagikazarmark/slog-shim v0.1.0 // indirect
 	github.com/sourcegraph/conc v0.3.0 // indirect
@@ -48,6 +54,7 @@ require (
 	github.com/spf13/cast v1.6.0 // indirect
 	github.com/spf13/pflag v1.0.5 // indirect
 	github.com/subosito/gotenv v1.6.0 // indirect
+	github.com/thinkgos/gomodbus/v2 v2.2.2 // indirect
 	github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
 	github.com/ugorji/go/codec v1.2.12 // indirect
 	go.uber.org/multierr v1.10.0 // indirect

+ 14 - 0
go.sum

@@ -1,3 +1,5 @@
+github.com/aler9/gortsplib v1.0.1 h1:R13+hxlvg2Hvu98+0hzg0o5fPjyUA9ZPJneMIBxKGXk=
+github.com/aler9/gortsplib v1.0.1/go.mod h1:BOWNZ/QBkY/eVcRqUzJbPFEsRJshwxaxBT01K260Jeo=
 github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
 github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
 github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
@@ -38,6 +40,8 @@ github.com/go-resty/resty/v2 v2.13.1 h1:x+LHXBI2nMB1vqndymf26quycC4aggYJ7DECYbiz
 github.com/go-resty/resty/v2 v2.13.1/go.mod h1:GznXlLxkq6Nh4sU59rPmUw3VtgpO3aS96ORAI6Q7d+0=
 github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
 github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
+github.com/goburrow/serial v0.1.0 h1:v2T1SQa/dlUqQiYIT8+Cu7YolfqAi3K96UmhwYyuSrA=
+github.com/goburrow/serial v0.1.0/go.mod h1:sAiqG0nRVswsm1C97xsttiYCzSLBmUZ/VSlVLZJ8haA=
 github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
 github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
 github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
@@ -82,6 +86,14 @@ github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
 github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
 github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
 github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
+github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
+github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
+github.com/pion/rtcp v1.2.9 h1:1ujStwg++IOLIEoOiIQ2s+qBuJ1VN81KW+9pMPsif+U=
+github.com/pion/rtcp v1.2.9/go.mod h1:qVPhiCzAm4D/rxb6XzKeyZiQK69yJpbUDJSF7TgrqNo=
+github.com/pion/rtp v1.7.13 h1:qcHwlmtiI50t1XivvoawdCGTP4Uiypzfrsap+bijcoA=
+github.com/pion/rtp v1.7.13/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko=
+github.com/pion/sdp/v3 v3.0.5 h1:ouvI7IgGl+V4CrqskVtr3AaTrPvPisEOxwgpdktctkU=
+github.com/pion/sdp/v3 v3.0.5/go.mod h1:iiFWFpQO8Fy3S5ldclBkpXqmWy02ns78NOKoLLL0YQw=
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
 github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@@ -115,6 +127,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
 github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
 github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
 github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
+github.com/thinkgos/gomodbus/v2 v2.2.2 h1:2ZkVxPShxg9ew0UCANdRxL7ZGA6anwRo66e8zifo+6w=
+github.com/thinkgos/gomodbus/v2 v2.2.2/go.mod h1:YynqZtDx2kFRhA+Ajy9qtmWOUIs5BOi3EaX6WQwH/jo=
 github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
 github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
 github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=

+ 3 - 6
main.go

@@ -10,13 +10,8 @@ import (
 )
 
 func init() {
-	// 初始化配置
-	err := global.SetupSetting()
-	if err != nil {
-		simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "初始化配置失败")
-	}
 	// 初始化数据库连接
-	err = global.SetupDBLink()
+	err := global.SetupDBLink()
 	if err != nil {
 		simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "初始化数据库连接失败")
 	}
@@ -27,6 +22,8 @@ func init() {
 	//初始化系统设置
 	model.CreateSystemSettings()
 
+	//utils.ModBus()
+
 }
 func main() {
 	err := app.InitRouter()

+ 0 - 47
utils/create_code.go

@@ -1,47 +0,0 @@
-package utils
-
-import (
-	"bigdata_archives/app/e"
-	"bigdata_archives/global"
-	"context"
-	"fmt"
-	"go.uber.org/zap"
-	"math/rand"
-	"time"
-)
-
-func CreatCode() string {
-	const chars = "0123456789"
-	result := make([]byte, 6)
-	rand.Seed(time.Now().UnixNano())
-	for i := range result {
-		index := rand.Intn(len(chars))
-		result[i] = chars[index]
-	}
-	return string(result)
-}
-
-func SendModel(phone string) e.Rescode {
-	ctx := context.Background()
-	ss := NewSMS(global.SubMailSetting.Appid, global.SubMailSetting.Signature)
-	result, err := global.Rdb.Exists(ctx, phone).Result()
-	if result == 1 {
-		fmt.Println("验证码已经发送", zap.Error(err))
-		return e.HasSend
-	}
-	if err != nil {
-		fmt.Println("redis查询出现异常", zap.Error(err))
-		return e.TheSystemIsAbnormal
-	}
-	code := CreatCode()
-	content := fmt.Sprintf("【冷链智控系统】您的短信验证码:%s,请在5分钟内输入", code)
-	res, err := ss.Send(phone, content)
-	if err != nil || res.Status != SUCCESS {
-		fmt.Println("发送短信验证码出现异常", zap.Any("res", res), zap.Error(err))
-		return e.AnExceptionOccursWhenSendingAnSMSVerificationCode
-	} else {
-		//验证码装入redis并且设置过期时间
-		err = global.Rdb.Set(ctx, phone, code, 300*time.Second).Err()
-		return e.SUCCESS
-	}
-}

+ 7 - 7
utils/create_token.go

@@ -2,7 +2,7 @@ package utils
 
 import (
 	"bigdata_archives/app/e"
-	"bigdata_archives/global"
+	"bigdata_archives/configs"
 	"errors"
 	"github.com/golang-jwt/jwt/v4"
 	"time"
@@ -24,16 +24,16 @@ func CreateToken(userId uint, userName, role string) (string, error) {
 		Role:     role,
 		RegisteredClaims: jwt.RegisteredClaims{
 			ExpiresAt: jwt.NewNumericDate(time.Now().Add(TokenExpireDuration)),
-			Issuer:    global.JwtSetting.Issuer,
+			Issuer:    configs.Config.GetString("jwt.Issuer"),
 		},
 	}
-	var mySerect = []byte(global.JwtSetting.Secret)
+	var mySerect = []byte(configs.Config.GetString("jwt.secret"))
 	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
 	return token.SignedString(mySerect)
 }
 func ParseToken(tokenStr string) (*MyClaims, e.Rescode) {
 	// 使用全局配置中的密钥对token进行解析。
-	var mySecret = []byte(global.JwtSetting.Secret)
+	var mySecret = []byte(configs.Config.GetString("jwt.secret"))
 	// 尝试解析并验证JWT令牌。
 	claims := new(MyClaims)
 	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
@@ -42,16 +42,16 @@ func ParseToken(tokenStr string) (*MyClaims, e.Rescode) {
 
 	if err != nil {
 		if errors.Is(err, jwt.ErrSignatureInvalid) || errors.Is(err, jwt.ErrInvalidKey) {
-			return nil, e.TokenIsInvalid
+			return nil, e.TokenIsExpired
 		} else if ve, ok := err.(*jwt.ValidationError); ok && ve.Errors&jwt.ValidationErrorExpired != 0 {
 			return nil, e.TokenIsExpired
 		}
-		return nil, e.TokenIsInvalid
+		return nil, e.TokenIsExpired
 	}
 
 	// 验证令牌是否有效。
 	if !token.Valid {
-		return nil, e.TokenIsInvalid
+		return nil, e.TokenIsExpired
 	}
 
 	// 如果令牌有效,则返回解析出的声明信息。

+ 74 - 0
utils/modbus.go

@@ -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)
+	}
+}