From dd75b36c03049be232a94d97eff1c4a5cc751fb5 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期二, 31 十月 2023 22:08:39 +0800
Subject: [PATCH] 支持设备ID切换
---
service/task.go | 13 +-
model/device.go | 10 ++
service/device_plc.go | 2
api/v1/config.go | 2
api/v1/device.go | 81 ++++++++++++++++++++
model/request/task.go | 10 +-
api/v1/task.go | 10 +-
constvar/const.go | 6 +
service/cache_store.go | 2
service/progress.go | 2
model/request/common.go | 4 +
service/device.go | 40 ++++++++++
service/process_model.go | 2
conf/config.go | 4 +
model/response/common.go | 6 +
main.go | 23 +++++
16 files changed, 196 insertions(+), 21 deletions(-)
diff --git a/api/v1/config.go b/api/v1/config.go
index 08642f8..ee22af0 100644
--- a/api/v1/config.go
+++ b/api/v1/config.go
@@ -125,7 +125,7 @@
return
}
- params.DeviceID = conf.Conf.System.DeviceId
+ params.DeviceID = conf.Conf.CurrentDeviceID
if params.Method == constvar.PlcMethodModbusTCP && (params.Address == "" || params.Port == 0) {
ctx.FailWithMsg(ecode.ParamsErr, "褰撴帴鍙f柟寮忎负modbusTCP鏃讹紝鍦板潃鍜岀鍙e彿涓嶈兘涓虹┖")
return
diff --git a/api/v1/device.go b/api/v1/device.go
new file mode 100644
index 0000000..ab7f965
--- /dev/null
+++ b/api/v1/device.go
@@ -0,0 +1,81 @@
+package v1
+
+import (
+ "apsClient/conf"
+ "apsClient/constvar"
+ "apsClient/crontask"
+ "apsClient/model/request"
+ "apsClient/model/response"
+ _ "apsClient/model/response"
+ "apsClient/pkg/contextx"
+ "apsClient/pkg/ecode"
+ "apsClient/pkg/logx"
+ "apsClient/service"
+ "github.com/gin-gonic/gin"
+)
+
+type DeviceApi struct{}
+
+// Set
+// @Tags 璁惧
+// @Summary 璁剧疆褰撳墠璁惧id
+// @Produce application/json
+// @Param object body request.SetCurrentDevice true "鏌ヨ鍙傛暟"
+// @Success 200 {object} contextx.Response{} "鎴愬姛"
+// @Router /v1/device/set [post]
+func (slf *DeviceApi) Set(c *gin.Context) {
+ var params request.SetCurrentDevice
+ ctx, ok := contextx.NewContext(c, ¶ms)
+ if !ok {
+ return
+ }
+ if params.CurrentDeviceID != "" {
+ ctx.Fail(ecode.ParamsErr)
+ return
+ }
+ list, err := service.GetDeviceIDList()
+ findFlag := false
+ for _, item := range list {
+ if item == params.CurrentDeviceID {
+ findFlag = true
+ }
+ }
+ if !findFlag {
+ ctx.Fail(ecode.ParamsErr)
+ return
+ }
+ service.SetDeviceIDToFile(params.CurrentDeviceID)
+ conf.Conf.SerfClusterStatus = params.CurrentDeviceID
+ err = crontask.RestartTask(conf.Conf.SerfClusterStatus != constvar.SerfClusterStatusSlave)
+ if err != nil {
+ logx.Errorf("restart task failed:%v", err)
+ ctx.Fail(ecode.UnknownErr)
+ return
+ }
+
+ ctx.Ok()
+}
+
+// DeviceList
+// @Tags Device
+// @Summary 鑾峰彇褰撳墠闈㈡澘缁戝畾鐨勮澶囧垪琛�
+// @Produce application/json
+// @Success 200 {object} contextx.Response{data=response.DeviceListResponse} "鎴愬姛"
+// @Router /v1/device/list [post]
+func (slf *DeviceApi) DeviceList(c *gin.Context) {
+ ctx, ok := contextx.NewContext(c, nil)
+ if !ok {
+ return
+ }
+ list, err := service.GetDeviceIDList()
+ if err != nil {
+ ctx.Fail(ecode.DBErr)
+ return
+ }
+ resp := response.DeviceListResponse{
+ SystemDeviceID: conf.Conf.System.DeviceId,
+ CurrentDeviceID: conf.Conf.CurrentDeviceID,
+ DeviceIDList: list,
+ }
+ ctx.OkWithDetailed(resp)
+}
diff --git a/api/v1/task.go b/api/v1/task.go
index cd04286..d700a97 100644
--- a/api/v1/task.go
+++ b/api/v1/task.go
@@ -63,8 +63,7 @@
ctx.FailWithMsg(ecode.NeedConfirmedErr, err.Error())
return
}
-
- taskCount := service.NewTaskService().NewTaskCount()
+ taskCount := service.NewTaskService().NewTaskCount(conf.Conf.CurrentDeviceID)
params.Page = 1
if params.PageSize <= 0 {
if params.TaskMode == constvar.TaskModeUnStarted {
@@ -79,7 +78,7 @@
taskMode = params.TaskMode
}
- taskResponse, code := service.NewTaskService().GetTask(params.Page, params.PageSize, taskMode, nil) //鍙栬繘琛屼腑鐨勬垨鏈紑濮嬬殑
+ taskResponse, code := service.NewTaskService().GetTask(params.DeviceID, params.Page, params.PageSize, taskMode, nil) //鍙栬繘琛屼腑鐨勬垨鏈紑濮嬬殑
if code != ecode.OK {
ctx.Fail(code)
return
@@ -94,7 +93,7 @@
if existsChannel[int32(i)] {
continue
}
- taskResponseTemp, code := service.NewTaskService().GetTask(params.Page, 1, constvar.TaskModeLastFinished, []int32{int32(i)}) //鍙栦笂涓�涓畬鎴愮殑
+ taskResponseTemp, code := service.NewTaskService().GetTask(params.DeviceID, params.Page, 1, constvar.TaskModeLastFinished, []int32{int32(i)}) //鍙栦笂涓�涓畬鎴愮殑
if code != ecode.OK {
ctx.Fail(code)
return
@@ -434,6 +433,7 @@
ctx.FailWithMsg(ecode.NeedConfirmedErr, err.Error())
return
}
+ params.DeviceID = conf.Conf.CurrentDeviceID
dataMap := make(map[int32]*response.TaskResponse, channelAmount)
if params.Channel != nil {
@@ -469,7 +469,7 @@
}
func getTaskResponseByChannel(params request.TaskListByChannel, channel int32) (taskResponse *response.TaskResponse, err error) {
- taskResponse, err = service.NewTaskService().GetTask2(params.Offset, params.Limit, []int32{channel}, params.Type) //鍙栬繘琛屼腑鐨勬垨鏈紑濮嬬殑
+ taskResponse, err = service.NewTaskService().GetTask2(params.DeviceID, params.Offset, params.Limit, []int32{channel}, params.Type) //鍙栬繘琛屼腑鐨勬垨鏈紑濮嬬殑
if err != nil {
return
}
diff --git a/conf/config.go b/conf/config.go
index 1888f21..ad8f0cc 100644
--- a/conf/config.go
+++ b/conf/config.go
@@ -101,6 +101,10 @@
PLC plc
Prompt Prompt
+
+ CurrentDeviceID string //璁剧疆褰撳墠闈㈡澘鎺у埗鐨勮澶�
+
+ SerfClusterStatus string
}
)
diff --git a/constvar/const.go b/constvar/const.go
index abe1c72..bb73e7e 100644
--- a/constvar/const.go
+++ b/constvar/const.go
@@ -91,3 +91,9 @@
}
return ""
}
+
+const (
+ SerfClusterStatusNull = "" //鏈姞鍏ラ泦缇�
+ SerfClusterStatusMaster = "master" //闆嗙兢master
+ SerfClusterStatusSlave = "slave" //闆嗙兢slave
+)
diff --git a/main.go b/main.go
index 8aa04c1..b1a14d7 100644
--- a/main.go
+++ b/main.go
@@ -2,6 +2,7 @@
import (
"apsClient/conf"
+ "apsClient/constvar"
"apsClient/crontask"
"apsClient/model"
"apsClient/nsq"
@@ -9,6 +10,7 @@
"apsClient/pkg/sqlitex"
"apsClient/router"
"apsClient/serf"
+ "apsClient/service"
"apsClient/service/plc_address"
"fmt"
"log"
@@ -52,9 +54,18 @@
return
}
+ //浠庢枃浠堕噷璇诲彇褰撳墠鐢熶骇璁惧id
+ conf.Conf.CurrentDeviceID = service.ReadDeviceIDFromFile()
+ if conf.Conf.CurrentDeviceID == "" {
+ conf.Conf.CurrentDeviceID = conf.Conf.System.DeviceId
+ }
+
// 鍒ゆ柇褰撳墠闆嗙兢鐘舵��
logx.Infof("current agent.ClusterStatus:%v", agent.ClusterStatus)
log.Println("current agent.ClusterStatus:", agent.ClusterStatus)
+
+ conf.Conf.SerfClusterStatus = agent.ClusterStatus
+
if agent.ClusterStatus != "slave" {
if err := nsq.Init(); err != nil {
logx.Errorf("nsq Init err:%v", err)
@@ -79,6 +90,7 @@
}
func serfClusterEvent(stat int) {
+ ChangeClusterStatus(stat)
switch stat {
case serf.EventCreateCluster, serf.EventSlave2Master, serf.EventLeaveCluster:
if err := nsq.Init(); err != nil { //寮�鍚痭sq
@@ -101,3 +113,14 @@
logx.Infof("serf cluster event: %v", stat)
}
+
+func ChangeClusterStatus(stat int) {
+ switch stat {
+ case serf.EventSlave2Master, serf.EventCreateCluster:
+ conf.Conf.SerfClusterStatus = constvar.SerfClusterStatusMaster
+ case serf.EventLeaveCluster:
+ conf.Conf.SerfClusterStatus = constvar.SerfClusterStatusNull
+ case serf.EventJoinCluster, serf.EventMaster2Slave:
+ conf.Conf.SerfClusterStatus = constvar.SerfClusterStatusSlave
+ }
+}
diff --git a/model/device.go b/model/device.go
index 2919584..a4f8edf 100644
--- a/model/device.go
+++ b/model/device.go
@@ -14,6 +14,7 @@
DeviceID string `gorm:"column:device_id;type:varchar(255);not null;unique" json:"deviceID"` //璁惧缂栧彿
ExtChannelAmount int `gorm:"type:tinyint;default:0" json:"extChannelAmount"`
Procedures string `gorm:"column:procedure;type:varchar(255);not null;default ''" json:"procedures"` //璁惧鏀寔鐨勫伐搴忥紝鐢ㄩ�楀彿鍒嗛殧
+ DeviceMac string `gorm:"type:varchar(255);" json:"deviceMac"` //缁戝畾鐨勫伐鎺ф満璁惧ID
ProceduresArr []string `gorm:"-" json:"procedureAdd"` //璁惧鏀寔鐨勫伐搴忓垏鐗�
}
@@ -65,6 +66,11 @@
return slf
}
+func (slf *DeviceSearch) SetDeviceMac(deviceMac string) *DeviceSearch {
+ slf.DeviceMac = deviceMac
+ return slf
+}
+
func (slf *DeviceSearch) SetDeviceIds(deviceIds []string) *DeviceSearch {
slf.DeviceIDs = deviceIds
return slf
@@ -81,6 +87,10 @@
db = db.Where("device_id = ?", slf.DeviceID)
}
+ if slf.DeviceMac != "" {
+ db = db.Where("device_mac = ?", slf.DeviceMac)
+ }
+
if len(slf.DeviceIDs) != 0 {
db = db.Where("device_id in (?)", slf.DeviceIDs)
}
diff --git a/model/request/common.go b/model/request/common.go
index 952d6c6..c515c4e 100644
--- a/model/request/common.go
+++ b/model/request/common.go
@@ -8,3 +8,7 @@
type GetById struct {
ID uint `json:"id"` // 涓婚敭ID
}
+
+type SetCurrentDevice struct {
+ CurrentDeviceID string `json:"currentDeviceID,omitempty"` //褰撳墠閫夊畾鐨勭敓浜ц澶�
+}
diff --git a/model/request/task.go b/model/request/task.go
index afa11d5..f72f5d5 100644
--- a/model/request/task.go
+++ b/model/request/task.go
@@ -15,6 +15,7 @@
type TaskList struct {
PageInfo
TaskMode constvar.TaskMode `json:"taskMode" form:"taskMode"`
+ DeviceID string `json:"deviceID"`
}
type SendProcessParams struct {
@@ -34,10 +35,11 @@
// TaskListByChannel 鎸塩hannel杩斿洖浠诲姟鍒楄〃璇锋眰鍙傛暟
type TaskListByChannel struct {
- Offset int `json:"offset,omitempty" form:"offset"` //榛樿0
- Limit int `json:"limit,omitempty" form:"limit"` //榛樿3
- Type QueryType `json:"type,omitempty" form:"type"` //1 鏈畬鎴� 2 浠婂ぉ鏈畬鎴� 3 宸插畬鎴�
- Channel *int32 `json:"channel" form:"channel"` //閫氶亾鍙枫�備笉浼犲彇鍏ㄩ儴鐨�
+ Offset int `json:"offset,omitempty" form:"offset"` //榛樿0
+ Limit int `json:"limit,omitempty" form:"limit"` //榛樿3
+ Type QueryType `json:"type,omitempty" form:"type"` //1 鏈畬鎴� 2 浠婂ぉ鏈畬鎴� 3 宸插畬鎴�
+ Channel *int32 `json:"channel" form:"channel"` //閫氶亾鍙枫�備笉浼犲彇鍏ㄩ儴鐨�
+ DeviceID string `json:"deviceID"`
}
type QueryType int
diff --git a/model/response/common.go b/model/response/common.go
index dae30ae..78341ce 100644
--- a/model/response/common.go
+++ b/model/response/common.go
@@ -69,3 +69,9 @@
Event string
Data interface{}
}
+
+type DeviceListResponse struct {
+ SystemDeviceID string `json:"systemDeviceID,omitempty"` //宸ユ帶鏈鸿澶嘔D
+ CurrentDeviceID string `json:"currentDeviceID,omitempty"` //褰撳墠閫夊畾鐨勭敓浜ц澶�
+ DeviceIDList []string `json:"deviceIDList,omitempty"` //鐢熶骇璁惧id鍒楄〃
+}
diff --git a/service/cache_store.go b/service/cache_store.go
index 743e4a7..1d9b7d1 100644
--- a/service/cache_store.go
+++ b/service/cache_store.go
@@ -92,7 +92,7 @@
if v, ok := defaultCacheStore.Get(fmt.Sprintf(CurrentTaskCacheKey, channel)); ok {
return v.(bool)
}
- _, err := model.NewProceduresSearch(nil).SetDeviceId(conf.Conf.System.DeviceId).SetStatus(model.ProcedureStatusProcessing).SetChannels([]int32{channel}).First()
+ _, err := model.NewProceduresSearch(nil).SetDeviceId(conf.Conf.CurrentDeviceID).SetStatus(model.ProcedureStatusProcessing).SetChannels([]int32{channel}).First()
if err == gorm.ErrRecordNotFound {
defaultCacheStore.Add(fmt.Sprintf(CurrentTaskCacheKey, channel), false)
return false
diff --git a/service/device.go b/service/device.go
new file mode 100644
index 0000000..f778f25
--- /dev/null
+++ b/service/device.go
@@ -0,0 +1,40 @@
+package service
+
+import (
+ "apsClient/conf"
+ "apsClient/model"
+ "fmt"
+ "os"
+)
+
+func GetDeviceIDList() (deviceIds []string, err error) {
+ devices, err := model.NewDeviceSearch().SetDeviceMac(conf.Conf.System.DeviceId).FindNotTotal()
+ if err != nil {
+ return nil, err
+ }
+ deviceIds = make([]string, 0, len(devices))
+ for _, device := range devices {
+ deviceIds = append(deviceIds, device.DeviceID)
+ }
+ return deviceIds, nil
+}
+
+const deviceIDFile = "currentDeviceID.txt"
+
+func SetDeviceIDToFile(deviceID string) {
+ err := os.WriteFile(deviceIDFile, []byte(deviceID), 0644)
+ if err != nil {
+ fmt.Printf("鏃犳硶鍐欏叆璁惧ID鍒版枃浠�: %v\n", err)
+ } else {
+ fmt.Println("璁惧ID宸插啓鍏ユ枃浠�")
+ }
+}
+
+func ReadDeviceIDFromFile() string {
+ data, err := os.ReadFile(deviceIDFile)
+ if err != nil {
+ fmt.Printf("鏃犳硶璇诲彇璁惧ID鏂囦欢: %v\n", err)
+ return ""
+ }
+ return string(data)
+}
diff --git a/service/device_plc.go b/service/device_plc.go
index d98d689..ebe9d56 100644
--- a/service/device_plc.go
+++ b/service/device_plc.go
@@ -19,7 +19,7 @@
}
func (slf DevicePlcService) GetDevicePlc() (*model.DevicePlc, int) {
- DevicePlc, err := model.NewDevicePlcSearch().SetDeviceId(conf.Conf.System.DeviceId).First()
+ DevicePlc, err := model.NewDevicePlcSearch().SetDeviceId(conf.Conf.CurrentDeviceID).First()
if err == gorm.ErrRecordNotFound {
return &model.DevicePlc{
DeviceID: "",
diff --git a/service/process_model.go b/service/process_model.go
index bb42646..d1154a3 100644
--- a/service/process_model.go
+++ b/service/process_model.go
@@ -6,7 +6,7 @@
)
func GetProcessModelList(offset, limit int, currentNumber string) (list []*model.ProcessModel, total int64, err error) {
- device, err := model.NewDeviceSearch().SetDeviceId(conf.Conf.System.DeviceId).First()
+ device, err := model.NewDeviceSearch().SetDeviceId(conf.Conf.CurrentDeviceID).First()
if err != nil {
return
}
diff --git a/service/progress.go b/service/progress.go
index ed904f1..2e7bc07 100644
--- a/service/progress.go
+++ b/service/progress.go
@@ -55,7 +55,7 @@
var ok bool
progressCache, ok = ProgressCacheGet(channel)
if !ok {
- progressCache, err = model.NewProductionProgressSearch(nil).SetDeviceId(conf.Conf.System.DeviceId).SetChannel(channel).SetOrder("id desc").First()
+ progressCache, err = model.NewProductionProgressSearch(nil).SetDeviceId(conf.Conf.CurrentDeviceID).SetChannel(channel).SetOrder("id desc").First()
if err == gorm.ErrRecordNotFound {
return nil, errors.New("progress not found")
}
diff --git a/service/task.go b/service/task.go
index 8f6388d..adb83c1 100644
--- a/service/task.go
+++ b/service/task.go
@@ -1,7 +1,6 @@
package service
import (
- "apsClient/conf"
"apsClient/constvar"
"apsClient/model"
"apsClient/model/common"
@@ -22,7 +21,7 @@
}
// GetTask 鑾峰彇浠诲姟锛屾湭瀹屾垚鐨勫紑濮嬫椂闂村皬浜庣瓑浜庡綋鍓嶆椂闂达紝缁撴潫鏃堕棿澶т簬褰撳墠鏃堕棿鐨勪换鍔�
-func (slf TaskService) GetTask(page, pageSize int, mode constvar.TaskMode, channels []int32) (taskResp *response.TaskResponse, code int) {
+func (slf TaskService) GetTask(deviceID string, page, pageSize int, mode constvar.TaskMode, channels []int32) (taskResp *response.TaskResponse, code int) {
var taskList []*response.TaskData
var count int64
var workers []*common.ProcedureWorker
@@ -40,7 +39,7 @@
workOrderIds []string
)
search := model.NewProceduresSearch(nil).
- SetDeviceId(conf.Conf.System.DeviceId).
+ SetDeviceId(deviceID).
SetPage(page, pageSize)
if mode == constvar.TaskModeUnStarted {
@@ -106,8 +105,8 @@
}
return taskResp, ecode.OK
}
-func (slf TaskService) NewTaskCount() (count int64) {
- count, _ = model.NewProceduresSearch(nil).SetDeviceId(conf.Conf.System.DeviceId).SetStatus(model.ProcedureStatusWaitProcess).Count()
+func (slf TaskService) NewTaskCount(deviceId string) (count int64) {
+ count, _ = model.NewProceduresSearch(nil).SetDeviceId(deviceId).SetStatus(model.ProcedureStatusWaitProcess).Count()
return count
}
@@ -204,7 +203,7 @@
}
// GetTask2 鑾峰彇浠诲姟鍒楄〃2
-func (slf TaskService) GetTask2(offset, limit int, channels []int32, queryType request.QueryType) (taskResp *response.TaskResponse, err error) {
+func (slf TaskService) GetTask2(deviceID string, offset, limit int, channels []int32, queryType request.QueryType) (taskResp *response.TaskResponse, err error) {
var taskList []*response.TaskData
var count int64
var workers []*common.ProcedureWorker
@@ -221,7 +220,7 @@
workOrderIds []string
)
search := model.NewProceduresSearch(nil).
- SetDeviceId(conf.Conf.System.DeviceId).
+ SetDeviceId(deviceID).
SetOffset(offset, limit).SetChannels(channels)
nowTs := time.Now().Unix()
switch queryType {
--
Gitblit v1.8.0