From b483b294741920e90815c2d1f4c6827d9921310c Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期二, 22 八月 2023 16:24:54 +0800
Subject: [PATCH] plc写入地址文件通过nsq从云端获取

---
 nsq/msg_handler.go |   61 ++++++++++++++++++++++++++++++
 1 files changed, 61 insertions(+), 0 deletions(-)

diff --git a/nsq/msg_handler.go b/nsq/msg_handler.go
index 9485653..a33cf9f 100644
--- a/nsq/msg_handler.go
+++ b/nsq/msg_handler.go
@@ -2,13 +2,30 @@
 
 import (
 	"apsClient/conf"
+	"apsClient/constvar"
 	"apsClient/model"
 	"apsClient/model/common"
 	"apsClient/pkg/logx"
 	"apsClient/pkg/structx"
+	"apsClient/service/plc_address"
+	"apsClient/utils/file"
 	"encoding/json"
+	"fmt"
+	"github.com/spf13/cast"
 	"gorm.io/gorm"
+	"strings"
 )
+
+type ReceivedMessage struct {
+	Topic   string
+	Message []byte
+}
+
+var ReceivedMessageChan chan *ReceivedMessage
+
+func init() {
+	ReceivedMessageChan = make(chan *ReceivedMessage, 1000)
+}
 
 type MsgHandler interface {
 	HandleMessage(data []byte) (err error)
@@ -65,3 +82,47 @@
 	}
 	return nil
 }
+
+type PlcAddress struct {
+	Topic string
+}
+
+func (slf *PlcAddress) HandleMessage(data []byte) (err error) {
+	logx.Infof("get an PlcAddress message :%s", data)
+	var resp = new(common.ResponsePlcAddress)
+	err = json.Unmarshal(data, &resp)
+	if err != nil {
+		logx.Errorf("ScheduleTask HandleMessage Unmarshal json err: %v", err.Error())
+		return err
+	}
+	//鍐欏叆鍒版枃浠�
+	err = file.WriteFile(fmt.Sprintf("%s%s", constvar.PlcAddressDataPath, constvar.PlcAddressDataKeyFileName), resp.KeyData)
+	if err != nil {
+		return err
+	}
+	err = file.WriteFile(fmt.Sprintf("%s%s", constvar.PlcAddressDataPath, constvar.PlcAddressDataValueFileName), resp.AddressData)
+	if err != nil {
+		return err
+	}
+	//鍐欏叆鍒板唴瀛�
+	keyString := string(resp.KeyData)
+	addressString := string(resp.AddressData)
+
+	keys := strings.Split(keyString, "\n")
+	addresses := strings.Split(addressString, "\n")
+	if len(keys) != len(addresses) {
+		logx.Error("plc address message error: key length not equal address length")
+		return nil
+	}
+	for i := 0; i < len(keys); i++ {
+		key := strings.ReplaceAll(keys[i], "\r", "")
+		address := cast.ToInt(strings.ReplaceAll(addresses[i], "\r", ""))
+		plc_address.Set(key, address)
+	}
+	//閫氱煡鍥炲鏀跺埌
+	ReceivedMessageChan <- &ReceivedMessage{
+		Topic:   slf.Topic,
+		Message: data,
+	}
+	return nil
+}

--
Gitblit v1.8.0