12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package Nats
- import (
- "ColdP_server/conf"
- "ColdP_server/controllers/lib"
- "ColdP_server/models/Account"
- "ColdP_server/models/Device"
- "errors"
- "fmt"
- "github.com/nats-io/nats.go"
- "github.com/vmihailenco/msgpack/v5"
- "time"
- )
- func Init() {
- fmt.Println("============Nats init============")
- var err error
- // 连接Nats服务器
- lib.Nats, err = nats.Connect("nats://" + conf.NatsServer_Url)
- if err != nil {
- fmt.Println("nats 连接失败!")
- panic(err)
- }
- fmt.Println("nats OK!")
- }
- func Read_New_DeviceData(T_sn string, T_id int) (Device.DeviceData_, error) {
- type T_R struct {
- Code int16 `xml:"Code"`
- Msg string `xml:"Msg"`
- Data Device.DeviceData_ `xml:"Data"`
- }
- type T_Req struct {
- T_sn string `xml:"T_sn"`
- T_id int `xml:"T_id"`
- }
- var t_Req T_Req
- t_Req.T_sn = T_sn
- t_Req.T_id = T_id
- marshal, err2 := msgpack.Marshal(&t_Req)
- if err2 != nil {
- return Device.DeviceData_{}, err2
- }
- var t_R T_R
- request, err := lib.Nats.Request("Read_New_DeviceData", marshal, 3*time.Second)
- if err != nil {
- return Device.DeviceData_{}, err
- }
- err = msgpack.Unmarshal(request.Data, &t_R)
- if err != nil {
- return Device.DeviceData_{}, errors.New(t_R.Msg)
- }
- if t_R.Code == 200 {
- return t_R.Data, nil
- }
- return Device.DeviceData_{}, errors.New(t_R.Msg)
- }
- func Verification(GetCookie string, GetString string) (bool, Account.Admin) {
- Admin_tokey := GetCookie
- if len(Admin_tokey) == 0 {
- Admin_tokey = GetString
- }
- if len(Admin_tokey) == 0 {
- return false, Account.Admin{}
- }
- // 请求-响应, 向 verification 发布一个 `ToKey` 请求数据,设置超时间3秒,如果有多个响应,只接收第一个收到的消息
- msg, err := lib.Nats.Request("Cold_Admin_verification", []byte(Admin_tokey), 3*time.Second)
- if err != nil {
- return false, Account.Admin{}
- }
- fmt.Printf("Cold_Admin_verification : %s\n", string(msg.Data))
- type T_R struct {
- Code int16 `xml:"Code"`
- Msg string `xml:"Msg"`
- Data Account.Admin `xml:"Data"` // 泛型
- }
- var t_R T_R
- err = msgpack.Unmarshal(msg.Data, &t_R)
- if err != nil || t_R.Code != 200 {
- return false, Account.Admin{}
- }
- return true, t_R.Data
- }
|