From 59b1d337daba44758bf566104179ec70f9db478d Mon Sep 17 00:00:00 2001 From: Jianhui Zhao Date: Wed, 15 Sep 2021 08:31:27 +0000 Subject: [PATCH] refactor: Match the protocol version between rtty and rttys Signed-off-by: Jianhui Zhao --- broker.go | 8 +++++++- device.go | 26 ++++++++++++++------------ 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/broker.go b/broker.go index 2b5f6ea..29df655 100644 --- a/broker.go +++ b/broker.go @@ -77,11 +77,17 @@ func (br *broker) run() { log.Error().Msg("Invalid token from terminal device") msg = "Invalid token" err = 1 + } else if dev.proto < rttyProto { + if dev.proto < rttyProto { + log.Error().Msgf("%s: unsupported protocol version: %d, need %d", dev.id, dev.proto, rttyProto) + msg = "unsupported protocol" + err = 1 + } } else { dev.registered = true br.devices[devid] = c dev.UpdateDb() - log.Info().Msgf("Device '%s' registered", devid) + log.Info().Msgf("Device '%s' registered, proto %d", devid, dev.proto) } c.WriteMsg(msgTypeRegister, append([]byte{err}, msg...)) diff --git a/device.go b/device.go index f9a0cb9..6b81ef3 100644 --- a/device.go +++ b/device.go @@ -31,10 +31,12 @@ const ( msgTypeMax = msgTypeWeb ) +const rttyProto uint8 = 3 const heartbeatInterval = time.Second * 5 type device struct { br *broker + proto uint8 id string desc string /* description of the device */ timestamp int64 /* Connection time */ @@ -114,18 +116,23 @@ func (dev *device) UpdateDb() { } } -func parseDeviceInfo(b []byte) (string, string, string, bool) { +func parseDeviceInfo(dev *device, b []byte) bool { + dev.proto = b[0] + + b = b[1:] + fields := bytes.Split(b, []byte{0}) if len(fields) < 3 { - return "", "", "", false + log.Error().Msg("msgTypeRegister: invalid") + return false } - id := string(fields[0]) - desc := string(fields[1]) - token := string(fields[2]) + dev.id = string(fields[0]) + dev.desc = string(fields[1]) + dev.token = string(fields[2]) - return id, desc, token, true + return true } func parseHeartbeat(dev *device, b []byte) { @@ -208,15 +215,10 @@ func (dev *device) readLoop() { switch typ { case msgTypeRegister: - id, desc, token, ok := parseDeviceInfo(b) - if !ok { - log.Error().Msg("msgTypeRegister: invalid") + if !parseDeviceInfo(dev, b) { return } - dev.id = id - dev.token = token - dev.desc = desc dev.br.register <- dev case msgTypeLogin: