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