huangyan 1 month ago
parent
commit
835ec3e651
9 changed files with 128 additions and 7 deletions
  1. 10 1
      .vscode/launch.json
  2. BIN
      cmd/server/city_chips
  3. 1 4
      cmd/server/main.go
  4. 6 1
      config/local.yml
  5. 2 0
      go.mod
  6. 4 0
      go.sum
  7. 50 1
      internal/handler/energy.go
  8. 1 0
      internal/server/http.go
  9. 54 0
      pkg/helper/modbus/modbus.go

+ 10 - 1
.vscode/launch.json

@@ -3,5 +3,14 @@
     // 悬停以查看现有属性的描述。
     // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
     "version": "0.2.0",
-    "configurations": []
+    "configurations": [
+        {
+            "name": "Launch Package",
+            "type": "go",
+            "request": "launch",
+            "mode": "auto",
+            "program": "${workspaceFolder}/cmd/server"
+        }
+
+    ]
 }

BIN
cmd/server/city_chips


+ 1 - 4
cmd/server/main.go

@@ -3,7 +3,6 @@ package main
 import (
 	"city_chips/cmd/server/wire"
 	"city_chips/pkg/config"
-	"city_chips/pkg/helper/hikvision"
 	"city_chips/pkg/http"
 	"city_chips/pkg/log"
 	"fmt"
@@ -16,14 +15,12 @@ func main() {
 	logger := log.NewLog(conf)
 
 	logger.Info("server start", zap.String("host", "http://127.0.0.1:"+conf.GetString("http.port")))
+	// err := helper.ModBus(conf, logger)
 
 	app, cleanup, err := wire.NewWire(conf, logger)
 	if err != nil {
 		panic(err)
 	}
-	conf.GetString("")
-	//aes.ExampleUsage()
-	hikvision.Hikvision()
 	defer cleanup()
 	http.Run(app, fmt.Sprintf(":%d", conf.GetInt("http.port")))
 }

+ 6 - 1
config/local.yml

@@ -73,4 +73,9 @@ broadcast:
 #bacnet
 bacnet:
   ip: "192.168.1.1"
-  port: 47808
+  port: 47808
+Modbus:
+  url: "tcp://"
+obix:
+  username: "obix"
+  password: "Obix123456"

+ 2 - 0
go.mod

@@ -32,6 +32,7 @@ require (
 	github.com/go-playground/universal-translator v0.18.1 // indirect
 	github.com/go-playground/validator/v10 v10.14.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/gofrs/uuid v4.2.0+incompatible // indirect
 	github.com/hashicorp/hcl v1.0.0 // indirect
@@ -46,6 +47,7 @@ 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.0.8 // indirect
+	github.com/simonvetter/modbus v1.6.3 // indirect
 	github.com/sirupsen/logrus v1.8.1 // indirect
 	github.com/spf13/afero v1.9.5 // indirect
 	github.com/spf13/cast v1.5.1 // indirect

+ 4 - 0
go.sum

@@ -98,6 +98,8 @@ github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg
 github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
 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/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=
@@ -218,6 +220,8 @@ github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRl
 github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
 github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
 github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
+github.com/simonvetter/modbus v1.6.3 h1:kDzwVfIPczsM4Iz09il/Dij/bqlT4XiJVa0GYaOVA9w=
+github.com/simonvetter/modbus v1.6.3/go.mod h1:hh90ZaTaPLcK2REj6/fpTbiV0J6S7GWmd8q+GVRObPw=
 github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
 github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
 github.com/sony/sonyflake v1.1.0 h1:wnrEcL3aOkWmPlhScLEGAXKkLAIslnBteNUq4Bw6MM4=

+ 50 - 1
internal/handler/energy.go

@@ -3,10 +3,14 @@ package handler
 import (
 	"city_chips/internal/service"
 	"city_chips/pkg/helper/resp"
+	"encoding/json"
 	"fmt"
+	"math/rand"
+	"strconv"
+	"time"
+
 	"github.com/gin-gonic/gin"
 	"github.com/spf13/viper"
-	"math/rand"
 )
 
 type EnergyHandler struct {
@@ -66,3 +70,48 @@ func (h *EnergyHandler) GetEnergy(ctx *gin.Context) {
 	m["YearCarbonEmissions"] = YearCarbonEmissions             //今年碳排
 	resp.HandleSuccess(ctx, m)
 }
+
+// 水表数据
+func (h *EnergyHandler) GetWaterMmeter(ctx *gin.Context) {
+	// 设置响应头
+	ctx.Header("Content-Type", "text/event-stream")
+	ctx.Header("Cache-Control", "no-cache")
+	ctx.Header("Connection", "keep-alive")
+	// 监听客户端断开连接
+	conn := true
+	notify := ctx.Writer.CloseNotify()
+	type Response struct {
+		RequestId string `protobuf:"bytes,1,opt,name=requestId,proto3" json:"requestId,omitempty"`
+		Code      int32  `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
+		Msg       string `protobuf:"bytes,3,opt,name=msg,proto3" json:"msg,omitempty"`
+		Data      any    `json:"data"`
+	}
+	stationNo := ctx.Query("id")
+	if len(stationNo) == 0 {
+		resp.HandleError(ctx, 1201, "缺少必要参数", nil)
+		return
+	}
+	var response Response
+	for conn {
+		select {
+		case <-notify:
+			conn = false
+			fmt.Println("断开连接")
+			return
+		default:
+			// 模拟数据
+			data := make(map[string]any)
+			response.Code = 200
+			response.RequestId = strconv.Itoa(rand.Intn(1000))
+			response.Msg = "success"
+			data["今日用水"] = rand.Intn(1000)
+			data["昨日用水"] = rand.Intn(1000)
+			data["本月用水量"] = rand.Intn(1000)
+			response.Data = data
+			res, _ := json.Marshal(&response)
+			fmt.Fprintf(ctx.Writer, "data: %s\n\n", string(res))
+			ctx.Writer.Flush()
+			time.Sleep(10 * time.Second)
+		}
+	}
+}

+ 1 - 0
internal/server/http.go

@@ -97,6 +97,7 @@ func NewServerHTTP(
 	ener := r.Group("/energy")
 	{
 		ener.GET("/count", energy.GetEnergy)
+		ener.GET("/GetWaterMmeter", energy.GetWaterMmeter)
 	}
 	//楼宇智控
 	inte := r.Group("/intell")

+ 54 - 0
pkg/helper/modbus/modbus.go

@@ -0,0 +1,54 @@
+package helper
+
+import (
+	"city_chips/pkg/log"
+	"fmt"
+	"time"
+
+	"github.com/simonvetter/modbus"
+	"github.com/spf13/viper"
+)
+
+func ModBus(conf *viper.Viper, logger *log.Logger) error {
+	var client *modbus.ModbusClient
+	var err error
+
+	//创建并配置Modbus客户端
+	client, err = modbus.NewClient(&modbus.ClientConfiguration{
+		URL:     conf.GetString("Modbus.url"),
+		Timeout: 3 * time.Second,
+	})
+	if err != nil {
+		logger.Error(fmt.Errorf("创建Modbus客户端失败: %v", err).Error())
+		return err
+	}
+	defer client.Close()
+	err = client.Open()
+	if err != nil {
+		logger.Error(fmt.Errorf("连接打开失败: %v", err).Error())
+		return err
+	}
+	// LatestData := make(map[int]Temperature)
+	// LatestDatas = nil
+	// for {
+	// 	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()),
+	// 		}
+	// 	}
+	// 	LatestDatas = LatestData
+	// }
+	return nil
+}