saas-smartAi通信协议标准库
gongshangguo
2022-03-03 d3d05d0eecdd76e86eeb3d28dcd765db042dce17
client/client.go
@@ -6,6 +6,7 @@
   "bufio"
   "encoding/binary"
   "encoding/json"
   "errors"
   uuid "github.com/satori/go.uuid"
   "go.uber.org/zap"
   "io"
@@ -60,8 +61,6 @@
   Writer *bufio.Writer
   // 写入通道
   writeChan chan []byte
   // 退出通道
   exitChan chan int8
   // 连接状态
   state State
   // 报文头
@@ -109,7 +108,6 @@
   c.readLock = new(sync.Mutex)
   c.writeLock = new(sync.Mutex)
   c.writeChan = make(chan []byte)
   c.exitChan = make(chan int8)
   c.state = StateInit
   c.tmpByte4Slice = make([]byte, 4)
   c.waitGroup = &util.WaitGroupWrapper{}
@@ -239,6 +237,12 @@
         c.Logger.Error("Write Body Error:", err)
      }
   }()
   if c.IsClosed() {
      errMsg := "Can not write msg into closed chain"
      c.Logger.Warn(errMsg, zap.Any("msg",body))
      return errors.New(errMsg)
   }
   body.Receiver = aiot.RECEIVER_TO_SAAS
   msgData, err := json.Marshal(body)
   if err != nil {
@@ -255,7 +259,7 @@
   c.Logger.Debug("registering...")
   data := c.deviceRegister
   msgData, _ := json.Marshal(data)
   _, err := c.WriteMsg(c.deviceId, aiot.MSG_TYPE_REGISTER, aiot.REQ_TYPE_REQUEST, msgData, c.GetMsgProto(""))
   _, err := c.WriteMsg(c.deviceId, aiot.MSG_TYPE_REGISTER, aiot.REQ_TYPE_REQUEST, msgData, GetMsgProto(""))
   if err != nil {
      c.Logger.Error("Fail to send device register", zap.Any("msg", msgData))
   }
@@ -279,7 +283,7 @@
            t.Stop()
            return
         }
         go c.WriteMsg(c.deviceId, aiot.MSG_TYPE_HEART_BEAT, aiot.REQ_TYPE_REQUEST, pingData, c.GetMsgProto(""))
         go c.WriteMsg(c.deviceId, aiot.MSG_TYPE_HEART_BEAT, aiot.REQ_TYPE_REQUEST, pingData, GetMsgProto(""))
      }
   }
}
@@ -411,7 +415,7 @@
}
// 拼装消息ID
func (c *Client) GetMsgProto(msgId string) *aiot.MsgIdProto {
func GetMsgProto(msgId string) *aiot.MsgIdProto {
   // 新消息
   if msgId == "" {
      return &aiot.MsgIdProto{
@@ -431,6 +435,11 @@
   return c.deviceId
}
// 获取连接状态
func (c *Client) GetState() State {
   return c.state
}
// 判断连接是否关闭
func (c *Client) IsClosed() bool {
   return c.state == StateDisconnected
@@ -448,7 +457,7 @@
// 关闭TCP
func (c *Client) Close() {
   c.Logger.Debug("Closing connect", zap.String("addr", c.addr))
   c.Logger.Debug("Closing connect...", zap.String("addr", c.addr))
   c.closeLock.Lock()
   defer c.closeLock.Unlock()
   // 关闭通道
@@ -457,8 +466,10 @@
      if c.IsConnected() {
         c.clientCallback.OnClose(c)
      }
      // 设置连接属性
      c.SetState(StateDisconnected)
      close(c.writeChan)
   }
   // 设置连接属性
   c.SetState(StateDisconnected)
   c.Logger.Debug("Connect closed...", zap.String("addr", c.addr))
}