saas-smartAi通信协议标准库
gongshangguo
2022-03-08 a32c642ffa2b9f05e3b55fc88b2c2bed3277a080
client/client.go
@@ -6,6 +6,7 @@
   "bufio"
   "encoding/binary"
   "encoding/json"
   "errors"
   uuid "github.com/satori/go.uuid"
   "go.uber.org/zap"
   "io"
@@ -22,8 +23,6 @@
   DefaultHeartbeatInterval = 15 * time.Second
   // 读取数据超时时间
   DefaultReaderTimeOut = 60 * time.Second
   // 连接尝试间隔
   DefaultNetRetry = 10 * time.Second
)
// 连接状态
@@ -38,8 +37,6 @@
   StateDisconnected
)
var syncReq map[string]chan *aiot.Protocol
// 连接状态
type State int32
@@ -48,10 +45,12 @@
   net.Conn
   // 注册包
   deviceRegister *aiot.DeviceRegister
   // 客户端锁
   lock *sync.Mutex
   // 消息锁
   msgLock *sync.Mutex
   // 关闭锁
   closeLock *sync.Mutex
   // 读取锁
   readLock *sync.Mutex
   // 写入锁
   writeLock *sync.Mutex
   // 连接地址
   addr string
   // 设备ID
@@ -62,8 +61,6 @@
   Writer *bufio.Writer
   // 写入通道
   writeChan chan []byte
   // 退出通道
   exitChan chan int8
   // 连接状态
   state State
   // 报文头
@@ -83,11 +80,12 @@
   logger.Debug("New Client...")
   return &Client{
      deviceRegister: deviceRegister,
      lock: new(sync.Mutex),
      readLock: new(sync.Mutex),
      closeLock: new(sync.Mutex),
      writeLock: new(sync.Mutex),
      addr: addr,
      deviceId: clientId,
      writeChan: make(chan []byte),
      exitChan: make(chan int8),
      state: StateInit,
      tmpByte4Slice: make([]byte, 4),
      waitGroup: &util.WaitGroupWrapper{},
@@ -106,9 +104,10 @@
func (c *Client) InitClient() {
   // 初始化当前属性值
   c.Conn = nil
   c.lock = new(sync.Mutex)
   c.closeLock = new(sync.Mutex)
   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{}
@@ -189,17 +188,12 @@
   byte4 := make([]byte,4)
   for {
      select {
      case <- c.exitChan:
         c.Logger.Debug("Close client", zap.String("deviceId", c.deviceId))
         c.Close()
         c.Logger.Warn("writeLoop Done...")
         return
      case bodyByte := <- c.writeChan:
         binary.BigEndian.PutUint32(byte4, uint32(len(bodyByte)))
         body = append(byte4, bodyByte...)
         c.lock.Lock()
         c.writeLock.Lock()
         _,err = c.Conn.Write(body)
         c.lock.Unlock()
         c.writeLock.Unlock()
         if err != nil {
            c.Logger.Error("Fail to write message", zap.Error(err), zap.String("msg", string(bodyByte)))
            c.Close()
@@ -216,20 +210,16 @@
}
// 发送消息
func (c *Client) WriteMsg(senderId string, msgType aiot.MSG_TYPE, reqType aiot.REQ_TYPE, data []byte, msgProto *aiot.MsgIdProto) (*aiot.Protocol, error) {
   // 锁
   c.lock.Lock()
func (c *Client) writeMsg(senderId string, msgType aiot.MSG_TYPE, reqType aiot.REQ_TYPE, data []byte, msgProto *aiot.MsgIdProto) (*aiot.Protocol, error) {
   // 关闭的连接不能写入
   if c.IsClosed() {
      c.Logger.Error("Can not write msg on the closed chan", zap.Any("msgType", msgType), zap.Any("reqType", reqType), zap.Any("data", string(data)))
      c.lock.Unlock()
      return nil,nil
   }
   c.lock.Unlock()
   // 拼装并发送消息
   body := &aiot.Protocol{
      Receiver: aiot.RECEIVER_TO_SAAS,
      SenderId: senderId,
      MsgType: msgType,
      ReqType: reqType,
@@ -238,7 +228,7 @@
   }
   // 发送消息
   c.WriteBody(body)
   _ = c.WriteBody(body)
   return body, nil
}
@@ -248,7 +238,18 @@
         c.Logger.Error("Write Body Error:", err)
      }
   }()
   body.Receiver = aiot.RECEIVER_TO_SAAS
   // 通道已关闭,不能写入
   if c.IsClosed() {
      errMsg := "Can not write msg into closed chain"
      c.Logger.Warn(errMsg, zap.Any("msg",body))
      return errors.New(errMsg)
   }
   // 消息ID默认处理
   if body.MsgProto == nil {
      body.MsgProto = GetMsgProto("")
   }
   msgData, err := json.Marshal(body)
   if err != nil {
      c.Logger.Error("Fail to Marshal send data", zap.Error(err))
@@ -264,7 +265,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))
   }
@@ -288,7 +289,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(""))
      }
   }
}
@@ -323,11 +324,11 @@
   var length uint32
   for {
      c.tmpByte4Slice = make([]byte, 4)
      c.SetDeadline(time.Now().Add(DefaultReaderTimeOut))
      _ = c.SetDeadline(time.Now().Add(DefaultReaderTimeOut))
      // 读取长度
      c.lock.Lock()
      c.readLock.Lock()
      _, err = io.ReadFull(c.Reader, c.tmpByte4Slice)
      c.lock.Unlock()
      c.readLock.Unlock()
      if err != nil {
         if err == io.EOF {
            c.Logger.Error("Fail to read request byte4", zap.Error(err))
@@ -344,9 +345,9 @@
      }
      // 读取body
      bodyByte := make([]byte, length)
      c.lock.Lock()
      c.readLock.Lock()
      _, err = io.ReadFull(c.Reader, bodyByte)
      c.lock.Unlock()
      c.readLock.Unlock()
      if err != nil {
         if err == io.EOF {
            c.Logger.Error("Fail to read request body", zap.Error(err))
@@ -369,7 +370,7 @@
   c.Logger.Warn("ReadLoop Done...")
   // 关闭连接
   c.exitChan <- 1
   c.Close()
}
// 处理回调
@@ -384,12 +385,12 @@
   switch body.MsgType {
   // 心跳回复
   case aiot.MSG_TYPE_HEART_BEAT:
      c.clientCallback.OnHeartBeat(c,body)
      go c.clientCallback.OnHeartBeat(c, body)
      return
   // 注册回复
   case aiot.MSG_TYPE_REGISTER:
      c.clientCallback.OnRegister(c,body)
      go c.clientCallback.OnRegister(c, body)
      return
   // 设备控制
@@ -420,7 +421,7 @@
}
// 拼装消息ID
func (c *Client) GetMsgProto(msgId string) *aiot.MsgIdProto {
func GetMsgProto(msgId string) *aiot.MsgIdProto {
   // 新消息
   if msgId == "" {
      return &aiot.MsgIdProto{
@@ -440,6 +441,11 @@
   return c.deviceId
}
// 获取连接状态
func (c *Client) GetState() State {
   return c.state
}
// 判断连接是否关闭
func (c *Client) IsClosed() bool {
   return c.state == StateDisconnected
@@ -457,22 +463,19 @@
// 关闭TCP
func (c *Client) Close() {
   c.Logger.Debug("Closing connect", zap.String("addr", c.addr))
   c.lock.Lock()
   defer c.lock.Unlock()
   c.Logger.Debug("Closing connect...", zap.String("addr", c.addr))
   c.closeLock.Lock()
   defer c.closeLock.Unlock()
   // 关闭通道
   if !c.IsClosed() {
      c.Conn.Close()
      _ = c.Conn.Close()
      if c.IsConnected() {
         c.clientCallback.OnClose(c)
      }
      // 设置连接属性
      c.SetState(StateDisconnected)
      // 关闭管道
      close(c.exitChan)
      close(c.writeChan)
   }
   // 设置连接属性
   c.SetState(StateDisconnected)
   c.Logger.Debug("Connect closed...", zap.String("addr", c.addr))
}