ソースを参照

更新了设备id

lijian 4 年 前
コミット
961bf83b84
64 ファイル変更265 行追加244 行削除
  1. 4 4
      pkg/coap/manager.go
  2. 4 4
      pkg/coap/provider.go
  3. 6 26
      pkg/generator/key_gen.go
  4. 6 5
      pkg/generator/key_gen_test.go
  5. 15 15
      pkg/models/alarmrule.go
  6. 2 1
      pkg/models/application.go
  7. 3 2
      pkg/models/device.go
  8. 3 1
      pkg/models/product.go
  9. 1 0
      pkg/models/protocal.go
  10. 1 0
      pkg/models/relation.go
  11. 1 0
      pkg/models/roles.go
  12. 2 1
      pkg/models/rule.go
  13. 1 0
      pkg/models/rulechain.go
  14. 1 0
      pkg/models/rulenode.go
  15. 1 0
      pkg/models/sensor.go
  16. 2 1
      pkg/models/user.go
  17. 1 1
      pkg/models/vendor.go
  18. 2 2
      pkg/mqtt/broker.go
  19. 12 7
      pkg/mqtt/connection.go
  20. 7 7
      pkg/mqtt/manager.go
  21. 4 4
      pkg/mqtt/provider.go
  22. 0 3
      pkg/mysql/migrate.go
  23. 9 10
      pkg/online/online.go
  24. 2 2
      pkg/rpcs/access.go
  25. 1 1
      pkg/rpcs/common.go
  26. 2 2
      pkg/rpcs/controller.go
  27. 3 3
      pkg/rpcs/devicemanager.go
  28. 1 1
      pkg/rpcs/registry.go
  29. 3 3
      pkg/rule/ifttt.go
  30. 2 2
      pkg/rule/rule_action.go
  31. 2 0
      pkg/ruleEngine/nodes/rest_api_request_node.go
  32. 1 1
      pkg/server/rpc_client.go
  33. 7 8
      pkg/token/token.go
  34. 5 5
      services/apiprovider/actions.go
  35. 1 1
      services/apiprovider/middleware.go
  36. 1 1
      services/apiprovider/notifier.go
  37. 1 0
      services/apiprovider/router.go
  38. 1 1
      services/apiprovider/token.go
  39. 4 4
      services/coapaccess/coap_provider.go
  40. 4 6
      services/controller/controller.go
  41. 3 7
      services/httpaccess/actions.go
  42. 2 2
      services/knowoapi/controllers/alert.go
  43. 3 6
      services/knowoapi/controllers/device.go
  44. 3 3
      services/knowoapi/controllers/product.go
  45. 3 3
      services/knowoapi/controllers/token.go
  46. 7 7
      services/knowoapi/model/alert.go
  47. 3 3
      services/knowoapi/model/application.go
  48. 10 10
      services/knowoapi/model/device.go
  49. 2 2
      services/knowoapi/model/product.go
  50. 10 8
      services/knowoapi/services/alert.go
  51. 7 5
      services/knowoapi/services/application.go
  52. 16 17
      services/knowoapi/services/device.go
  53. 7 5
      services/knowoapi/services/product.go
  54. 2 0
      services/knowoapi/services/protocal.go
  55. 2 0
      services/knowoapi/services/role.go
  56. 2 0
      services/knowoapi/services/sensor.go
  57. 6 3
      services/knowoapi/services/user.go
  58. 4 4
      services/mqttaccess/mqtt_provider.go
  59. 2 2
      services/mqttaccess/status.go
  60. 6 4
      services/registry/product.go
  61. 32 14
      services/registry/registry.go
  62. 1 1
      services/registry/utils.go
  63. BIN
      tests/device/device
  64. 3 3
      tests/device/main.go

+ 4 - 4
pkg/coap/manager.go

@@ -4,7 +4,6 @@ import (
 	"net"
 	"sparrow/pkg/rpcs"
 	"sparrow/pkg/server"
-	"strconv"
 	"sync/atomic"
 	"time"
 )
@@ -110,7 +109,8 @@ func (m *Manager) serve(w *Request) {
 	if msg.IsConfirmable() && len(msg.Path()) > 1 {
 		token := msg.GetToken()
 		// TODO:想别的deviceid的
-		deviceid, err := strconv.ParseUint(msg.Path()[0], 10, 0)
+		var err error
+		deviceid :=""
 		if err != nil {
 			server.Log.Errorf("device id error:%s", msg.Path()[0])
 			return
@@ -166,8 +166,8 @@ func (m *Manager) serve(w *Request) {
 		switch topic {
 		case pubStatusTopic, pubEventTopic, subCommandTopic:
 			server.Log.Infof("%s, publish status", w.Addr.String())
-			m.Provider.OnDeviceMessage(uint64(deviceid), topic, msg.GetPayload())
-			err := m.Provider.OnDeviceHeartBeat(uint64(deviceid))
+			m.Provider.OnDeviceMessage(deviceid, topic, msg.GetPayload())
+			err := m.Provider.OnDeviceHeartBeat(deviceid)
 			if err != nil {
 				server.Log.Warnf("heartbeat set error:%s", w.Addr.String())
 				return

+ 4 - 4
pkg/coap/provider.go

@@ -4,9 +4,9 @@ import "sparrow/pkg/rpcs"
 
 // Provider 处理设备业务逻辑
 type Provider interface {
-	ValidateDeviceToken(deviceid uint64, token []byte) error
+	ValidateDeviceToken(deviceid string, token []byte) error
 	OnDeviceOnline(args rpcs.ArgsGetOnline) error
-	OnDeviceOffline(deviceid uint64) error
-	OnDeviceHeartBeat(deviceid uint64) error
-	OnDeviceMessage(deviceid uint64, msgtype string, message []byte)
+	OnDeviceOffline(deviceid string) error
+	OnDeviceHeartBeat(deviceid string) error
+	OnDeviceMessage(deviceid string, msgtype string, message []byte)
 }

+ 6 - 26
pkg/generator/key_gen.go

@@ -1,11 +1,9 @@
 package generator
 
 import (
-	"bytes"
 	"crypto/aes"
 	"crypto/cipher"
 	"crypto/rand"
-	"encoding/binary"
 	"encoding/hex"
 	"errors"
 	"io"
@@ -68,46 +66,28 @@ func NewKeyGenerator(key string) (*KeyGenerator, error) {
 }
 
 // GenRandomKey get random key
-func (g *KeyGenerator) GenRandomKey(id int64) (string, error) {
-	buf := make([]byte, maxEncodeLen-binary.Size(id)-aes.BlockSize)
-	if _, err := io.ReadFull(rand.Reader, buf); err != nil {
-		return "", nil
-	}
-
-	binid := bytes.NewBuffer([]byte{})
-	binary.Write(binid, binary.BigEndian, id)
-
-	buf = append(buf, binid.Bytes()...)
-
-	binkey, err := encryptAESCFB(buf, []byte(g.AESKey))
+func (g *KeyGenerator) GenRandomKey(id string) (string, error) {
+	binkey, err := encryptAESCFB([]byte(id), []byte(g.AESKey))
 	if err != nil {
 		return "", err
 	}
-
 	return hex.EncodeToString(binkey), nil
 }
 
 // DecodeIDFromRandomKey get id from encrypt strings
-func (g *KeyGenerator) DecodeIDFromRandomKey(encrypted string) (int64, error) {
+func (g *KeyGenerator) DecodeIDFromRandomKey(encrypted string) (string, error) {
 	buf, err := hex.DecodeString(encrypted)
 	if err != nil {
-		return 0, err
+		return "", err
 	}
 
 	raw, err := decryptAESCFB(buf, []byte(g.AESKey))
 	if err != nil {
-		return 0, err
+		return "", err
 	}
 
-	var id int64
-
-	if len(raw) > maxEncodeLen || len(raw) < maxEncodeLen-aes.BlockSize-binary.Size(id) {
-		return 0, errors.New("invalid key format")
-	}
 
-	binbuf := bytes.NewBuffer(raw[maxEncodeLen-aes.BlockSize-binary.Size(id):])
-	binary.Read(binbuf, binary.BigEndian, &id)
 
-	return id, nil
+	return string(raw), nil
 
 }

+ 6 - 5
pkg/generator/key_gen_test.go

@@ -9,7 +9,7 @@ func TestKeyGen(t *testing.T) {
 	if err == nil {
 		t.Error("should return error when key length is invalid")
 	}
-	testid := int64(1)
+	 testid := "lijian"
 	generator, err = NewKeyGenerator("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
 	if err != nil {
 		t.Fatal(err)
@@ -19,20 +19,21 @@ func TestKeyGen(t *testing.T) {
 		t.Error(err)
 	}
 	t.Log(key)
-	id, err := generator.DecodeIdFromRandomKey(key)
+	id, err := generator.DecodeIDFromRandomKey(key)
 	if err != nil {
 		t.Error(err)
 	}
+	t.Log(id)
 	if id != testid {
-		t.Errorf("wrong id %d, want %d", id, testid)
+		t.Errorf("wrong id %s, want %s", id, testid)
 	}
 
-	id, err = generator.DecodeIdFromRandomKey("")
+	id, err = generator.DecodeIDFromRandomKey("")
 	if err == nil {
 		t.Error("decode id from random key should return error for empty key.")
 	}
 
-	id, err = generator.DecodeIdFromRandomKey("1111111111111111111111111111111111111111")
+	id, err = generator.DecodeIDFromRandomKey("1111111111111111111111111111111111111111")
 	if err == nil {
 		t.Errorf("decode id from random key should return error for bad key : %s", "1111111111111111111111111111111111111111")
 	}

+ 15 - 15
pkg/models/alarmrule.go

@@ -11,34 +11,34 @@ import (
 // 用来监控设备的状态异常等
 type AlarmRule struct {
 	gorm.Model
-
+	RecordId       string `gorm:"primary_key;column:record_id;size:32;index"`
 	AlertName      string `gorm:"size:30;not null"` //规则名称
-	ProtocalID     int    //所属数据点ID
-	ProtocalName   string //协议名称
-	AlertCondition int    //对应触发条件的属性编号
+	ProtocalID     string                           //所属数据点ID
+	ProtocalName   string                           //协议名称
+	AlertCondition int                              //对应触发条件的属性编号
 	// |1|小于|
 	// |2|等于|
 	// |3|大于|
 	// |4|小于等于|
 	// |5|大于等于|
 	// |6|不等于|
-	AlertValue   int    //触发对比数值
-	AlertContent string `gorm:"size:500;not null"` // 告警内容
-	AlertType    int    // 告警类型:1:设备异常 2:设备警告
-	NoticeType   int    // 通知类型:1:通知型<br>2:告警型
-	NoticeWay    int    //通知方式 1:短信通知<br>2:极光推送<br>3:微信通知<br>
-	ProductID    int    //关联的产品ID
-	VendorID     uint   //关联厂商ID
-	StartIndex   int    //字符串或字节数组的开始位置
-	EndIndex     int    //字符串或字节数组的结束位置
-	Status       int    //状态,1正常,0禁用
+	AlertValue   int                                             //触发对比数值
+	AlertContent string `gorm:"size:500;not null"`               // 告警内容
+	AlertType    int                                             // 告警类型:1:设备异常 2:设备警告
+	NoticeType   int                                             // 通知类型:1:通知型<br>2:告警型
+	NoticeWay    int                                             //通知方式 1:短信通知<br>2:极光推送<br>3:微信通知<br>
+	ProductID    string `gorm:"column:product_id;size:32;index"` //关联的产品ID
+	VendorID     string `gorm:"column:vendor_id;size:32;index"`  //关联厂商ID
+	StartIndex   int                                             //字符串或字节数组的开始位置
+	EndIndex     int                                             //字符串或字节数组的结束位置
+	Status       int                                             //状态,1正常,0禁用
 }
 
 // Validate 验证
 func (a *AlarmRule) Validate() error {
 	if a.AlertName == "" ||
 		a.AlertCondition == 0 || a.AlertValue == 0 || a.AlertContent == "" ||
-		a.AlertType == 0 || a.NoticeType == 0 || a.ProductID == 0 {
+		a.AlertType == 0 || a.NoticeType == 0 || a.ProductID == "" {
 		return errors.New("非法参数")
 	}
 	return nil

+ 2 - 1
pkg/models/application.go

@@ -10,6 +10,7 @@ import (
 // application is app who will use the cloud api
 type Application struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	// App-Key for api
 	AppKey string `sql:"type:varchar(200);not null;"`
 	//Secret-Key
@@ -25,7 +26,7 @@ type Application struct {
 	// app domain which allows wildcard string like "*", "vendor/12", "product/10"
 	AppDomain string `sql:"type:varchar(200);not null;"`
 	// vendor id
-	VendorID uint
+	VendorID string `gorm:"column:vendor_id;index;size:32"`
 	AppIcon  string
 	AppType  string
 }

+ 3 - 2
pkg/models/device.go

@@ -6,8 +6,9 @@ import "github.com/jinzhu/gorm"
 // device is a product instance, which is managed by our platform
 type Device struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	// which product the device belongs to
-	ProductID int32
+	ProductID string `gorm:"column:product_id;size:32;index"`
 	// universal device identifier, generated from vendorid-productid-deviceserial
 	DeviceIdentifier string `sql:"type:varchar(200);not null;unique;key"`
 	// device secret which is auto generated by the platform
@@ -21,7 +22,7 @@ type Device struct {
 	// device version(the agent version)
 	DeviceVersion string `sql:"type:text;not null;"`
 	// vendor id
-	VendorID uint
+	VendorID string `gorm:"column:vendor_id;size:32;index"`
 	//通讯模组名称
 	ModuleName string
 }

+ 3 - 1
pkg/models/product.go

@@ -9,9 +9,11 @@ import (
 // Product product
 // product is a abstract define of same devices made by some vendor
 type Product struct {
+
 	gorm.Model
+	RecordId string `gorm:"primary_key;column:record_id;size:32;index"`
 	// which vendor
-	VendorID int32
+	VendorID string `gorm:"column:vendor_id;size:32;index"`
 	// name
 	ProductName string `sql:"type:varchar(200);not null;"`
 	// desc

+ 1 - 0
pkg/models/protocal.go

@@ -9,6 +9,7 @@ import (
 // Protocal 产品协议(数据点)
 type Protocal struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	Name          string `gorm:"size:30;not null;"` //名称
 	Label         string `gorm:"size:20;not null;"` // 标签
 	Type          int    //读写类型

+ 1 - 0
pkg/models/relation.go

@@ -2,6 +2,7 @@ package models
 
 // Relation 规则节点关系
 type Relation struct {
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	FromID            int
 	FromType          string
 	ToID              int

+ 1 - 0
pkg/models/roles.go

@@ -9,6 +9,7 @@ import (
 // Role 角色表
 type Role struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	RoleName string `gorm:"size:50;not null"`
 	RoleCode int32
 	MenuList string `gorm:"size:100000;"`

+ 2 - 1
pkg/models/rule.go

@@ -8,8 +8,9 @@ import (
 // rule is used for automated works such as timers, ifttts.
 type Rule struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	// which device the rule belongs to
-	DeviceID int64
+	DeviceID string
 	// rule type, timmer | ifttt
 	RuleType string `sql:"type:varchar(20);not null;"`
 	// which action triggers the rule

+ 1 - 0
pkg/models/rulechain.go

@@ -7,6 +7,7 @@ import (
 // RuleChain 规则链
 type RuleChain struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	AdditionalInfo  string `gorm:"column:additional_info"`    //节点属性信息
 	Configuration   string `gorm:"column:configuration"`      //配置信息
 	Name            string `gorm:"column:name"`               //名称

+ 1 - 0
pkg/models/rulenode.go

@@ -7,6 +7,7 @@ import (
 // RuleNode 规则链中的节点
 type RuleNode struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	RuleChainID    int    //关联rulechain id
 	AdditionalInfo string //附加属性信息
 	Configuration  string //配置信息

+ 1 - 0
pkg/models/sensor.go

@@ -8,6 +8,7 @@ import (
 // Sensor 传感器
 type Sensor struct {
 	gorm.Model
+	RecordId string `gorm:"column:record_id;size:32;index"`
 	Name      string `gorm:"size:30;not null;"` //名称
 	Label     uint   // 标签
 	ProductID uint   //所属产品

+ 2 - 1
pkg/models/user.go

@@ -9,6 +9,7 @@ import (
 // User user
 type User struct {
 	gorm.Model
+	RecordId   string `gorm:"column:record_id;size:32;index"`
 	UserKey    string
 	UserRoleID int
 	UserName   string `sql:"type:varchar(20);not null;"`
@@ -16,7 +17,7 @@ type User struct {
 	Phone      string `sql:"type:varchar(20);not null;"`
 	Email      string `sql:"type:varchar(200);not null;"`
 	UserType   int    `sql:"default:1;not null;"`
-	VendorID   uint
+	VendorID   string `gorm:"column:vendor_id;size:32;index"`
 	Status     int    `sql:"default:1;not null;"`
 	Vendor     Vendor `gorm:"foreignkey:VendorID"`
 }

+ 1 - 1
pkg/models/vendor.go

@@ -10,7 +10,7 @@ import (
 // vendor is those who make products
 type Vendor struct {
 	gorm.Model
-	RecordId string `gorm:"column:record_id;size:32;index"`
+	RecordId string `gorm:"primary_key;column:record_id;size:32;index"`
 	// vendor name
 	VendorName string `sql:"type:varchar(200);not null;"`
 	// vendor key

+ 2 - 2
pkg/mqtt/broker.go

@@ -25,7 +25,7 @@ func (b *Broker) Handle(conn net.Conn) {
 }
 
 // SendMessageToDevice send message to device
-func (b *Broker) SendMessageToDevice(deviceid uint64, msgtype string, message []byte, timeout time.Duration) error {
+func (b *Broker) SendMessageToDevice(deviceid string, msgtype string, message []byte, timeout time.Duration) error {
 	msg := &Publish{}
 	msg.Header.QosLevel = QosAtLeastOnce
 	msg.TopicName = msgtype
@@ -34,6 +34,6 @@ func (b *Broker) SendMessageToDevice(deviceid uint64, msgtype string, message []
 }
 
 // GetToken get device token with device id
-func (b *Broker) GetToken(deviceid uint64) ([]byte, error) {
+func (b *Broker) GetToken(deviceid string) ([]byte, error) {
 	return b.mgr.GetToken(deviceid)
 }

+ 12 - 7
pkg/mqtt/connection.go

@@ -4,6 +4,7 @@ import (
 	"encoding/hex"
 	"errors"
 	"net"
+	"sparrow/pkg/models"
 	"sparrow/pkg/rpcs"
 	"sparrow/pkg/server"
 	"time"
@@ -25,7 +26,7 @@ type ResponseType struct {
 // Connection client connection
 type Connection struct {
 	Mgr             *Manager
-	DeviceID        uint64
+	DeviceID        string
 	Conn            net.Conn
 	SendChan        chan Message
 	MessageID       uint16
@@ -168,8 +169,14 @@ func (c *Connection) RcvMsgFromClient() {
 				c.Close()
 				return
 			}
-			c.DeviceID = DeviceID
-
+			device := &models.Device{}
+			err = server.RPCCallByName(nil, "registry", "Registry.FindDeviceById", DeviceID, device)
+			if err != nil {
+				server.Log.Warn("device not found %d", ret, DeviceID)
+				c.Close()
+				return
+			}
+			c.DeviceID = device.RecordId
 			token, err := hex.DecodeString(msg.Password)
 			if err != nil {
 				server.Log.Warn("token format error : %v", err)
@@ -190,9 +197,8 @@ func (c *Connection) RcvMsgFromClient() {
 				c.Close()
 				return
 			}
-
 			args := rpcs.ArgsGetOnline{
-				Id:                c.DeviceID,
+				Id:                device.RecordId,
 				ClientIP:          host,
 				AccessRPCHost:     server.GetRPCHost(),
 				HeartbeatInterval: uint32(c.KeepAlive),
@@ -217,8 +223,7 @@ func (c *Connection) RcvMsgFromClient() {
 
 		case *Publish:
 			server.Log.Infof("%s, publish topic: %s", host, msg.TopicName)
-
-			c.Mgr.PublishMessage2Server(c.DeviceID, msg)
+			_ = c.Mgr.PublishMessage2Server(c.DeviceID, msg)
 			if msg.QosLevel.IsAtLeastOnce() {
 				server.Log.Infof("publish ack send now")
 				publishack := &PubAck{MessageID: msg.MessageID}

+ 7 - 7
pkg/mqtt/manager.go

@@ -10,13 +10,13 @@ import (
 type Manager struct {
 	Provider Provider
 	CxtMutex sync.RWMutex
-	IdToConn map[uint64]*Connection
+	IdToConn map[string]*Connection
 }
 
 func NewManager(p Provider) *Manager {
 	m := &Manager{
 		Provider: p,
-		IdToConn: make(map[uint64]*Connection),
+		IdToConn: make(map[string]*Connection),
 	}
 
 	go m.CleanWorker()
@@ -28,7 +28,7 @@ func (m *Manager) NewConn(conn net.Conn) {
 	NewConnection(conn, m)
 }
 
-func (m *Manager) AddConn(id uint64, c *Connection) {
+func (m *Manager) AddConn(id string, c *Connection) {
 	m.CxtMutex.Lock()
 	oldSub, exist := m.IdToConn[id]
 	if exist {
@@ -39,7 +39,7 @@ func (m *Manager) AddConn(id uint64, c *Connection) {
 	m.CxtMutex.Unlock()
 }
 
-func (m *Manager) DelConn(id uint64) {
+func (m *Manager) DelConn(id string) {
 	m.CxtMutex.Lock()
 	_, exist := m.IdToConn[id]
 
@@ -49,7 +49,7 @@ func (m *Manager) DelConn(id uint64) {
 	m.CxtMutex.Unlock()
 }
 
-func (m *Manager) GetToken(DeviceID uint64) ([]byte, error) {
+func (m *Manager) GetToken(DeviceID string) ([]byte, error) {
 	m.CxtMutex.RLock()
 	con, exist := m.IdToConn[DeviceID]
 	m.CxtMutex.RUnlock()
@@ -60,7 +60,7 @@ func (m *Manager) GetToken(DeviceID uint64) ([]byte, error) {
 	return con.Token, nil
 }
 
-func (m *Manager) PublishMessage2Device(DeviceID uint64, msg *Publish, timeout time.Duration) error {
+func (m *Manager) PublishMessage2Device(DeviceID string, msg *Publish, timeout time.Duration) error {
 	m.CxtMutex.RLock()
 	con, exist := m.IdToConn[DeviceID]
 	m.CxtMutex.RUnlock()
@@ -71,7 +71,7 @@ func (m *Manager) PublishMessage2Device(DeviceID uint64, msg *Publish, timeout t
 	return con.Publish(msg, timeout)
 }
 
-func (m *Manager) PublishMessage2Server(DeviceID uint64, msg *Publish) error {
+func (m *Manager) PublishMessage2Server(DeviceID string, msg *Publish) error {
 	topic := msg.TopicName
 
 	payload := msg.Payload.(BytesPayload)

+ 4 - 4
pkg/mqtt/provider.go

@@ -5,9 +5,9 @@ import (
 )
 
 type Provider interface {
-	ValidateDeviceToken(deviceid uint64, token []byte) error
+	ValidateDeviceToken(deviceid string, token []byte) error
 	OnDeviceOnline(args rpcs.ArgsGetOnline) error
-	OnDeviceOffline(deviceid uint64) error
-	OnDeviceHeartBeat(deviceid uint64) error
-	OnDeviceMessage(deviceid uint64, msgtype string, message []byte)
+	OnDeviceOffline(deviceid string) error
+	OnDeviceHeartBeat(deviceid string) error
+	OnDeviceMessage(deviceid string, msgtype string, message []byte)
 }

+ 0 - 3
pkg/mysql/migrate.go

@@ -28,9 +28,6 @@ func MigrateDatabase(dbhost, dbport, dbname, dbuser, dbpass string) error {
 	// Disable table name's pluralization
 	db.SingularTable(true)
 	db.LogMode(false)
-
-	db.DB().Query("CREATE DATABASE SparrowCloud; ")
-	db.DB().Query("USE SparrowCloud;")
 	// Automating Migration
 	err = db.Set("gorm:table_options", "ENGINE=MyISAM").AutoMigrate(
 		&models.Device{},

+ 9 - 10
pkg/online/online.go

@@ -3,10 +3,9 @@ package online
 
 import (
 	"errors"
+	"github.com/garyburd/redigo/redis"
 	"sparrow/pkg/redispool"
 	"sparrow/pkg/serializer"
-	"github.com/garyburd/redigo/redis"
-	"strconv"
 )
 
 const (
@@ -30,8 +29,8 @@ func NewManager(host string) *Manager {
 	return mgr
 }
 
-func (mgr *Manager) GetStatus(id uint64) (*Status, error) {
-	key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
+func (mgr *Manager) GetStatus(id string) (*Status, error) {
+	key := OnlineStatusKeyPrefix + id
 	conn, err := redispool.GetClient(mgr.redishost)
 	if err != nil {
 		return nil, err
@@ -51,8 +50,8 @@ func (mgr *Manager) GetStatus(id uint64) (*Status, error) {
 	return status, nil
 }
 
-func (mgr *Manager) GetOnline(id uint64, status Status) error {
-	key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
+func (mgr *Manager) GetOnline(id string, status Status) error {
+	key := OnlineStatusKeyPrefix + id
 	conn, err := redispool.GetClient(mgr.redishost)
 	if err != nil {
 		return err
@@ -74,7 +73,7 @@ func (mgr *Manager) GetOnline(id uint64, status Status) error {
 	return nil
 }
 
-func (mgr *Manager) SetHeartbeat(id uint64) error {
+func (mgr *Manager) SetHeartbeat(id string) error {
 	status, err := mgr.GetStatus(id)
 	if err != nil {
 		return err
@@ -84,7 +83,7 @@ func (mgr *Manager) SetHeartbeat(id uint64) error {
 		return errors.New("device offline.")
 	}
 
-	key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
+	key := OnlineStatusKeyPrefix + id
 	conn, err := redispool.GetClient(mgr.redishost)
 	if err != nil {
 		return err
@@ -98,8 +97,8 @@ func (mgr *Manager) SetHeartbeat(id uint64) error {
 	return nil
 }
 
-func (mgr *Manager) GetOffline(id uint64) error {
-	key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
+func (mgr *Manager) GetOffline(id string) error {
+	key := OnlineStatusKeyPrefix + id
 	conn, err := redispool.GetClient(mgr.redishost)
 	if err != nil {
 		return err

+ 2 - 2
pkg/rpcs/access.go

@@ -6,7 +6,7 @@ import (
 )
 
 type ArgsSetStatus struct {
-	DeviceId uint64
+	DeviceId string
 	Status   []protocol.SubData
 }
 type ReplySetStatus ReplyEmptyResult
@@ -17,7 +17,7 @@ type ReplyGetStatus struct {
 }
 
 type ArgsSendCommand struct {
-	DeviceId  uint64
+	DeviceId  string
 	SubDevice uint16
 	No        uint16
 	Priority  uint16

+ 1 - 1
pkg/rpcs/common.go

@@ -1,7 +1,7 @@
 package rpcs
 
 type ArgsDeviceId struct {
-	Id uint64
+	Id string
 }
 
 type ReplyEmptyResult struct{}

+ 2 - 2
pkg/rpcs/controller.go

@@ -6,14 +6,14 @@ import (
 )
 
 type ArgsOnStatus struct {
-	DeviceId  uint64
+	DeviceId  string
 	Timestamp uint64
 	Subdata   []protocol.SubData
 }
 type ReplyOnStatus ReplyEmptyResult
 
 type ArgsOnEvent struct {
-	DeviceId  uint64
+	DeviceId  string
 	TimeStamp uint64
 	SubDevice uint16
 	No        uint16

+ 3 - 3
pkg/rpcs/devicemanager.go

@@ -10,13 +10,13 @@ type ReplyGenerateDeviceAccessToken struct {
 }
 
 type ArgsValidateDeviceAccessToken struct {
-	Id          uint64
+	Id          string
 	AccessToken []byte
 }
 type ReplyValidateDeviceAccessToken ReplyEmptyResult
 
 type ArgsGetOnline struct {
-	Id                uint64
+	Id                string
 	ClientIP          string
 	AccessRPCHost     string
 	HeartbeatInterval uint32
@@ -27,7 +27,7 @@ type ArgsGetOffline ArgsDeviceId
 type ReplyGetOffline ReplyEmptyResult
 
 type ArgsHeartBeat struct {
-	Id uint64
+	Id string
 }
 type ReplyHeartBeat ReplyEmptyResult
 

+ 1 - 1
pkg/rpcs/registry.go

@@ -10,7 +10,7 @@ type ArgsDeviceRegister struct {
 
 // ArgsDeviceAuth device auth
 type ArgsDeviceAuth struct {
-	DeviceID int64
+	DeviceID string
 }
 
 // ArgsDeviceAuth device auth

+ 3 - 3
pkg/rule/ifttt.go

@@ -13,11 +13,11 @@ func NewIfttt() *Ifttt {
 	return &Ifttt{}
 }
 
-func (ift *Ifttt) Check(deviceid uint64, eventid uint16) error {
+func (ift *Ifttt) Check(deviceid string, eventid uint16) error {
 	actions := &[]models.Rule{}
 	query := &models.Rule{
 		RuleType: "ifttt",
-		DeviceID: int64(deviceid),
+		DeviceID: deviceid,
 	}
 	err := server.RPCCallByName(nil, "registry", "Registry.QueryRules", query, actions)
 	if err != nil {
@@ -27,7 +27,7 @@ func (ift *Ifttt) Check(deviceid uint64, eventid uint16) error {
 
 	if len(*actions) > 0 {
 		device := &models.Device{}
-		err := server.RPCCallByName(nil, "registry", "Registry.FindDeviceById", int64(deviceid), device)
+		err := server.RPCCallByName(nil, "registry", "Registry.FindDeviceById", deviceid, device)
 		if err != nil {
 			server.Log.Errorf("find device error : %v", err)
 			return err

+ 2 - 2
pkg/rule/rule_action.go

@@ -59,7 +59,7 @@ func performRuleAction(target string, action string) error {
 		}
 
 		cmdargs := rpcs.ArgsSendCommand{
-			DeviceId:  uint64(device.ID),
+			DeviceId:  device.RecordId,
 			SubDevice: uint16(command.Head.SubDeviceid),
 			No:        uint16(command.Head.No),
 			WaitTime:  uint32(3000),
@@ -78,7 +78,7 @@ func performRuleAction(target string, action string) error {
 		}
 
 		statusargs := rpcs.ArgsSetStatus{
-			DeviceId: uint64(device.ID),
+			DeviceId: device.RecordId,
 			Status:   status,
 		}
 		statusreply := rpcs.ReplySetStatus{}

+ 2 - 0
pkg/ruleEngine/nodes/rest_api_request_node.go

@@ -3,6 +3,7 @@ package nodes
 import (
 	"bytes"
 	"encoding/json"
+	"fmt"
 	"github.com/gogf/gf/os/grpool"
 	"net/http"
 	"sparrow/pkg/protocol"
@@ -55,6 +56,7 @@ func (r *RestApiRequestNode) OnMessage(ctx ruleEngine.Context, message *protocol
 	for k, v := range r.config.Headers {
 		headers[k] = v
 	}
+	fmt.Printf("%+v\r\n", headers)
 	w := new(bytes.Buffer)
 	if err := json.NewEncoder(w).Encode(body); err != nil {
 		return err

+ 1 - 1
pkg/server/rpc_client.go

@@ -67,7 +67,7 @@ func (client *RPCClient) Call(span opentracing.Span, severName string, serverMet
 		span.SetTag("server.addr", addr)
 		err = rpcCallWithReconnect(client.clients[mapkey], addr, serverMethod, args, reply)
 		if err != nil {
-			Log.Warnf("RpcCallWithReconnect error : %s", err)
+			Log.WithField("method", serverMethod).Warnf("RpcCallWithReconnect error : %s", err)
 			continue
 		}
 

+ 7 - 8
pkg/token/token.go

@@ -5,7 +5,6 @@ import (
 	"reflect"
 	"sparrow/pkg/generator"
 	"sparrow/pkg/redispool"
-	"strconv"
 )
 
 const (
@@ -26,7 +25,7 @@ func NewHelper(host string) *Helper {
 	return helper
 }
 
-func (helper *Helper) GenerateToken(id uint64) ([]byte, error) {
+func (helper *Helper) GenerateToken(recordId string) ([]byte, error) {
 	token, err := generator.GenRandomToken()
 	if err != nil {
 		return nil, err
@@ -37,7 +36,7 @@ func (helper *Helper) GenerateToken(id uint64) ([]byte, error) {
 		return nil, err
 	}
 
-	key := DeviceTokenKeyPrefix + strconv.FormatUint(id, 10)
+	key := DeviceTokenKeyPrefix + recordId
 
 	_, err = conn.Do("SET", key, token)
 	if err != nil {
@@ -52,8 +51,8 @@ func (helper *Helper) GenerateToken(id uint64) ([]byte, error) {
 
 }
 
-func (helper *Helper) ValidateToken(id uint64, token []byte) error {
-	key := DeviceTokenKeyPrefix + strconv.FormatUint(id, 10)
+func (helper *Helper) ValidateToken(id string, token []byte) error {
+	key := DeviceTokenKeyPrefix + id
 
 	conn, err := redispool.GetClient(helper.redishost)
 	if err != nil {
@@ -77,8 +76,8 @@ func (helper *Helper) ValidateToken(id uint64, token []byte) error {
 	return nil
 }
 
-func (helper *Helper) ClearToken(id uint64) error {
-	key := DeviceTokenKeyPrefix + strconv.FormatUint(id, 10)
+func (helper *Helper) ClearToken(id string) error {
+	key := DeviceTokenKeyPrefix + id
 
 	conn, err := redispool.GetClient(helper.redishost)
 	if err != nil {
@@ -93,7 +92,7 @@ func (helper *Helper) ClearToken(id uint64) error {
 	return nil
 }
 
-func (helper *Helper) GenerateAppToken(id uint64, key string) ([]byte, error) {
+func (helper *Helper) GenerateAppToken(id string, key string) ([]byte, error) {
 	token, err := generator.GenRandomToken()
 	if err != nil {
 		return nil, err

+ 5 - 5
services/apiprovider/actions.go

@@ -119,7 +119,7 @@ func GetDeviceCurrentStatus(device *models.Device, config *productconfig.Product
 	server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", device.DeviceIdentifier)
 
 	statusargs := rpcs.ArgsGetStatus{
-		Id: uint64(device.ID),
+		Id: device.RecordId,
 	}
 	statusreply := rpcs.ReplyGetStatus{}
 	//opentracing
@@ -178,7 +178,7 @@ func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
 	}
 
 	statusargs := rpcs.ArgsSetStatus{
-		DeviceId: uint64(device.ID),
+		DeviceId: device.RecordId,
 		Status:   status,
 	}
 	statusreply := rpcs.ReplySetStatus{}
@@ -228,7 +228,7 @@ func SendCommandToDevice(device *models.Device, config *productconfig.ProductCon
 	}
 
 	cmdargs := rpcs.ArgsSendCommand{
-		DeviceId:  uint64(device.ID),
+		DeviceId:  device.RecordId,
 		SubDevice: uint16(command.Head.SubDeviceid),
 		No:        uint16(command.Head.No),
 		WaitTime:  uint32(defaultTimeOut),
@@ -264,7 +264,7 @@ func AddRule(device *models.Device, req *http.Request, r render.Render) {
 	}
 
 	rule := &models.Rule{
-		DeviceID: int64(device.ID),
+		DeviceID: device.RecordId,
 		RuleType: ruleReq.Type,
 		Trigger:  ruleReq.Trigger,
 		Target:   ruleReq.Target,
@@ -298,7 +298,7 @@ func AppAuth(req *http.Request, r render.Render) {
 		return
 	}
 
-	span, ctx := opentracing.StartSpanFromContext(context.Background(), "DeveloperRegist")
+	span, ctx := opentracing.StartSpanFromContext(context.Background(), "AppAuth")
 	defer span.Finish()
 	ext.SpanKindRPCClient.Set(span)
 

+ 1 - 1
services/apiprovider/middleware.go

@@ -101,7 +101,7 @@ func CheckDeviceOnline(context martini.Context, params martini.Params, req *http
 	}
 
 	onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
-		Id: uint64(device.ID),
+		Id: device.RecordId,
 	}
 	onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
 	err = server.RPCCallByName(nil, "devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)

+ 1 - 1
services/apiprovider/notifier.go

@@ -77,7 +77,7 @@ func (n *Notifier) reportEvent(event rpcs.ArgsOnEvent) error {
 	server.Log.Debugf("reporting event %v", event)
 
 	device := &models.Device{}
-	err := server.RPCCallByName(nil, "registry", "Registry.FindDeviceById", int64(event.DeviceId), device)
+	err := server.RPCCallByName(nil, "registry", "Registry.FindDeviceById", event.DeviceId, device)
 	if err != nil {
 		server.Log.Errorf("find device error : %v", err)
 		return err

+ 1 - 0
services/apiprovider/router.go

@@ -28,6 +28,7 @@ func ValidateTokenMiddleware(w http.ResponseWriter, r *http.Request, c martini.C
 	}
 }
 
+
 // martini router
 func route(m *martini.ClassicMartini) {
 

+ 1 - 1
services/apiprovider/token.go

@@ -14,7 +14,7 @@ type AppClaims struct {
 	AppName   string
 	AppKey    string
 	SecretKey string
-	VendorID  uint
+	VendorID  string
 	jwt.StandardClaims
 }
 

+ 4 - 4
services/coapaccess/coap_provider.go

@@ -12,7 +12,7 @@ type CoAPProvider struct {
 func NewCoAPProvider() *CoAPProvider {
 	return &CoAPProvider{}
 }
-func (mp *CoAPProvider) ValidateDeviceToken(deviceid uint64, token []byte) error {
+func (mp *CoAPProvider) ValidateDeviceToken(deviceid string, token []byte) error {
 	args := rpcs.ArgsValidateDeviceAccessToken{
 		Id:          deviceid,
 		AccessToken: token,
@@ -34,7 +34,7 @@ func (mp *CoAPProvider) OnDeviceOnline(args rpcs.ArgsGetOnline) error {
 
 	return err
 }
-func (mp *CoAPProvider) OnDeviceOffline(deviceid uint64) error {
+func (mp *CoAPProvider) OnDeviceOffline(deviceid string) error {
 	args := rpcs.ArgsGetOffline{
 		Id: deviceid,
 	}
@@ -46,7 +46,7 @@ func (mp *CoAPProvider) OnDeviceOffline(deviceid uint64) error {
 
 	return err
 }
-func (mp *CoAPProvider) OnDeviceHeartBeat(deviceid uint64) error {
+func (mp *CoAPProvider) OnDeviceHeartBeat(deviceid string) error {
 	args := rpcs.ArgsDeviceId{
 		Id: deviceid,
 	}
@@ -57,7 +57,7 @@ func (mp *CoAPProvider) OnDeviceHeartBeat(deviceid uint64) error {
 	}
 	return err
 }
-func (mp *CoAPProvider) OnDeviceMessage(deviceid uint64, msgtype string, message []byte) {
+func (mp *CoAPProvider) OnDeviceMessage(deviceid string, msgtype string, message []byte) {
 	server.Log.Infof("device {%v} message {%v} : %x", deviceid, msgtype, message)
 	data := &protocol.Data{}
 	err := data.UnMarshal(message)

+ 4 - 6
services/controller/controller.go

@@ -15,7 +15,6 @@ import (
 	"sparrow/pkg/rule"
 	"sparrow/pkg/ruleEngine"
 	"sparrow/pkg/server"
-	"strconv"
 	"time"
 )
 
@@ -93,7 +92,7 @@ func (c *Controller) OnStatus(args rpcs.ArgsOnStatus, reply *rpcs.ReplyOnStatus)
 	tpi := queue.ResolvePartition("RULE_ENGINE",
 		msg.GetQueueName(),
 		"tenant_1",
-		strconv.Itoa(int(args.DeviceId)))
+		args.DeviceId)
 	g, err := queue.NewGobQueueMessage(msg)
 	if err != nil {
 		return err
@@ -104,14 +103,14 @@ func (c *Controller) OnStatus(args rpcs.ArgsOnStatus, reply *rpcs.ReplyOnStatus)
 func (c *Controller) processStatusToQueue(args rpcs.ArgsOnStatus) (string, error) {
 	var result string
 	device := &models.Device{}
-	err := server.RPCCallByName(nil, "registry", "Registry.FindDeviceById", &rpcs.ArgsDeviceAuth{DeviceID: int64(args.DeviceId)}, device)
+	err := server.RPCCallByName(nil, "registry", "Registry.FindDeviceByRecordId", &rpcs.ArgsDeviceAuth{DeviceID: args.DeviceId}, device)
 	if err != nil {
 		server.Log.Errorf("find device error : %v", err)
 		return result, err
 	}
 
 	product := &models.Product{}
-	err = server.RPCCallByName(nil, "registry", "Registry.FindProduct", device.ProductID, product)
+	err = server.RPCCallByName(nil, "registry", "Registry.FindProduct", &device.ProductID, product)
 	if err != nil {
 		server.Log.Errorf("find product error : %v", err)
 		return result, err
@@ -157,7 +156,7 @@ func (c *Controller) SendCommand(args rpcs.ArgsSendCommand, reply *rpcs.ReplySen
 	return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
 }
 
-func getAccessRPCHost(deviceid uint64) (string, error) {
+func getAccessRPCHost(deviceid string) (string, error) {
 	args := rpcs.ArgsGetDeviceOnlineStatus{
 		Id: deviceid,
 	}
@@ -222,7 +221,6 @@ func (c *Controller) launchConsumer() {
 			if err := ruleEngineMsg.Decode(msg.GetData()); err != nil {
 				fmt.Println("解析消息失败")
 			}
-			fmt.Println(ruleEngineMsg.Data)
 			if c.actorContext != nil {
 				c.actorContext.Tell(&ruleEngine.QueueToRuleEngineMsg{
 					TenantId: "tenant_1",

+ 3 - 7
services/httpaccess/actions.go

@@ -86,16 +86,12 @@ func AuthDevice(args DeviceAuthArgs, r render.Render) {
 	server.Log.Printf("ACTION AuthDevice, args:: %v", args)
 	device := &models.Device{}
 
-	arg := &rpcs.ArgsDeviceAuth{
-		DeviceID: args.DeviceId,
-	}
-
 	span, ctx := opentracing.StartSpanFromContext(context.Background(), "AuthDevice")
 	defer span.Finish()
 
 	ext.SpanKindRPCClient.Set(span)
-
-	err := server.RPCCallByName(ctx, "registry", "Registry.FindDeviceById", arg, device)
+	arg := uint64(args.DeviceId)
+	err := server.RPCCallByName(ctx, "registry", "Registry.FindDeviceById", &arg, device)
 	if err != nil {
 		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
 		return
@@ -108,7 +104,7 @@ func AuthDevice(args DeviceAuthArgs, r render.Render) {
 	}
 
 	hepler := token.NewHelper(*confRedisHost)
-	token, err := hepler.GenerateToken(uint64(int64(device.ID)))
+	token, err := hepler.GenerateToken(device.RecordId)
 	if err != nil {
 		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
 		return

+ 2 - 2
services/knowoapi/controllers/alert.go

@@ -75,7 +75,7 @@ func (a *AlertController) Put() {
 
 // GetBy 根据ID查询
 // GET /alert/{id}
-func (a *AlertController) GetBy(id int) {
+func (a *AlertController) GetBy(id string) {
 	alert, err := a.Service.GetRule(a.Token.getVendorID(a.Ctx), id)
 	if err != nil {
 		responseError(a.Ctx, ErrDatabase, err.Error())
@@ -125,7 +125,7 @@ func (a *AlertController) BeforeActivation(b mvc.BeforeActivation) {
 
 // SetStatus set rule status
 func (a *AlertController) SetStatus() {
-	id, _ := a.Ctx.Params().GetInt("alertid")
+	id := a.Ctx.Params().Get("alertid")
 	status, _ := a.Ctx.Params().GetInt("status")
 	alert, err := a.Service.SetRuleStatus(a.Token.getVendorID(a.Ctx), id, status)
 	if err != nil {

+ 3 - 6
services/knowoapi/controllers/device.go

@@ -67,19 +67,16 @@ func (a *DeviceController) GetDevicecount() {
 // GET /devicestatus?device_id=
 func (a *DeviceController) GetDevicestatus() {
 
-	deviceid, err := a.Ctx.URLParamInt("device_id")
-	if err != nil {
-		deviceid = 0
-	}
+	deviceid := a.Ctx.URLParam("device_id")
 
 	var status int
 
 	onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
-		Id: uint64(deviceid),
+		Id: deviceid,
 	}
 
 	onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
-	err = server.RPCCallByName(nil, "devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
+	err := server.RPCCallByName(nil, "devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
 	if err != nil && err.Error() != "redigo: nil returned" {
 		server.Log.Errorf("get devie online status error: %v", err)
 		responseError(a.Ctx, ErrDatabase, err.Error())

+ 3 - 3
services/knowoapi/controllers/product.go

@@ -27,7 +27,7 @@ func (a *ProductController) Post() {
 		badRequest(a.Ctx, err)
 		return
 	}
-	product.VendorID = int32(a.Token.getVendorID(a.Ctx))
+	product.VendorID = a.Token.getVendorID(a.Ctx)
 
 	// if upload a image file
 	if product.ProductImage != "" {
@@ -65,7 +65,7 @@ func (a *ProductController) Delete() {
 		badRequest(a.Ctx, err)
 		return
 	}
-	if product.VendorID != int32(a.Token.getVendorID(a.Ctx)) {
+	if product.VendorID != a.Token.getVendorID(a.Ctx) {
 		responseError(a.Ctx, ErrNormal, "非法操作")
 		return
 	}
@@ -84,7 +84,7 @@ func (a *ProductController) Put() {
 		badRequest(a.Ctx, err)
 		return
 	}
-	if product.VendorID != int32(a.Token.getVendorID(a.Ctx)) {
+	if product.VendorID != a.Token.getVendorID(a.Ctx) {
 		responseError(a.Ctx, ErrNormal, "非法操作")
 		return
 	}

+ 3 - 3
services/knowoapi/controllers/token.go

@@ -20,7 +20,7 @@ type UserClaims struct {
 	UserName string
 	UserType string
 	RoleCode int
-	VendorID uint
+	VendorID string
 	jwt.StandardClaims
 }
 
@@ -51,9 +51,9 @@ func (t *Token) getRecorID(ctx iris.Context) uint {
 }
 
 // 获取当前用户vendorid
-func (t *Token) getVendorID(ctx iris.Context) uint {
+func (t *Token) getVendorID(ctx iris.Context) string {
 	claims := t.getUserClaims(ctx)
-	return uint(claims["VendorID"].(float64))
+	return claims["VendorID"].(string)
 }
 
 func (t *Token) getRoleID(ctx iris.Context) int {

+ 7 - 7
services/knowoapi/model/alert.go

@@ -40,7 +40,7 @@ func (a *Alert) Delete(alert *models.AlarmRule) error {
 }
 
 // Update 指定厂商ID
-func (a *Alert) Update(vendorid uint, alert *models.AlarmRule) (data models.AlarmRule, err error) {
+func (a *Alert) Update(vendorid string, alert *models.AlarmRule) (data models.AlarmRule, err error) {
 	cache := getCache()
 	key := fmt.Sprintf("Alert:%d", alert.ID)
 	if _, ok := cache.Get(key); ok {
@@ -58,7 +58,7 @@ func (a *Alert) Update(vendorid uint, alert *models.AlarmRule) (data models.Alar
 // proid:产品ID,可选
 // procalid:协议ID, 可选
 // name: 规则名称,可选,模糊搜索
-func (a *Alert) GetRules(vendorid uint, pi, ps, proid, protocalid int, name string) (datas []models.AlarmRule, total int, err error) {
+func (a *Alert) GetRules(vendorid string, pi, ps, proid, protocalid int, name string) (datas []models.AlarmRule, total int, err error) {
 	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
 	if proid != 0 {
 		tx = tx.Where("product_id = ?", proid)
@@ -75,14 +75,14 @@ func (a *Alert) GetRules(vendorid uint, pi, ps, proid, protocalid int, name stri
 }
 
 // GetAlarmRule 获取数据内容
-func (a *Alert) GetAlarmRule(vendorid uint, alertid int) (data models.AlarmRule, err error) {
+func (a *Alert) GetAlarmRule(vendorid string, alertid string) (data models.AlarmRule, err error) {
 	cache := getCache()
 	key := fmt.Sprintf("Alert:%d", alertid)
 	if v, ok := cache.Get(key); ok {
 		_d := v.(*models.AlarmRule)
 		data = *_d
 	} else {
-		err = a.db.Where("vendor_id = ? and id = ?", vendorid, alertid).First(&data).Error
+		err = a.db.Where("vendor_id = ? and record_id = ?", vendorid, alertid).First(&data).Error
 		if err == nil {
 			cache.Set(key, &data)
 		}
@@ -91,7 +91,7 @@ func (a *Alert) GetAlarmRule(vendorid uint, alertid int) (data models.AlarmRule,
 }
 
 // CheckProtocalRuleCount 返回数据点已经添加的告警数量
-func (a *Alert) CheckProtocalRuleCount(vendorid uint, protocalID int) (total int, err error) {
+func (a *Alert) CheckProtocalRuleCount(vendorid string, protocalID string) (total int, err error) {
 	err = a.db.Model(&models.AlarmRule{}).
 		Where("vendor_id = ? and protocal_id = ?", vendorid, protocalID).
 		Count(&total).
@@ -100,8 +100,8 @@ func (a *Alert) CheckProtocalRuleCount(vendorid uint, protocalID int) (total int
 }
 
 // SetRuleState 设置规则的可用、禁用状态
-func (a *Alert) SetRuleState(vendorid uint, id, status int) (data models.AlarmRule, err error) {
-	err = a.db.Model(&data).Where("vendor_id = ? and id = ?", vendorid, id).
+func (a *Alert) SetRuleState(vendorid string, id string, status int) (data models.AlarmRule, err error) {
+	err = a.db.Model(&data).Where("vendor_id = ? and record_id = ?", vendorid, id).
 		Update(map[string]interface{}{
 			"status": status,
 		}).Error

+ 3 - 3
services/knowoapi/model/application.go

@@ -37,7 +37,7 @@ func (a *Application) Delete(app *models.Application) error {
 }
 
 // GetAppCount 查询一个厂商的Application数量
-func (a *Application) GetAppCount(vendorid uint) (int, error) {
+func (a *Application) GetAppCount(vendorid string) (int, error) {
 	var count int
 	err := a.db.Model(&models.Application{}).Where("vendor_id = ?", vendorid).Count(&count).Error
 	if err != nil {
@@ -47,7 +47,7 @@ func (a *Application) GetAppCount(vendorid uint) (int, error) {
 }
 
 // GetVendorApps 获取厂商的app列表
-func (a *Application) GetVendorApps(vendorid uint, pi, ps int, name string) (datas []models.Application, count int, err error) {
+func (a *Application) GetVendorApps(vendorid string, pi, ps int, name string) (datas []models.Application, count int, err error) {
 	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
 	if name != "" {
 		tx = tx.Where("app_name = ?", name)
@@ -58,7 +58,7 @@ func (a *Application) GetVendorApps(vendorid uint, pi, ps int, name string) (dat
 }
 
 // GetAppInfo 查询app信息
-func (a *Application) GetAppInfo(vendorid uint, appkey string) (data models.Application, err error) {
+func (a *Application) GetAppInfo(vendorid string, appkey string) (data models.Application, err error) {
 
 	cache := getCache()
 	key := fmt.Sprintf("Application:%s", appkey)

+ 10 - 10
services/knowoapi/model/device.go

@@ -20,18 +20,18 @@ func (a *Device) Init(db *gorm.DB) *Device {
 }
 
 // GetDeviceCount 获取vendorid下的设备激活总数
-func (a *Device) GetDeviceCount(vendorid uint) (count int, err error) {
+func (a *Device) GetDeviceCount(vendorid string) (count int, err error) {
 	device := &models.Device{
-		VendorID: uint(vendorid),
+		VendorID: vendorid,
 	}
 	err = a.db.Model(device).Where(device).Count(&count).Error
 	return
 }
 
 // GetActiveNumberOfDate 获取某一天的设备激活数量
-func (a *Device) GetActiveNumberOfDate(vendorid uint, datetime string) (count int, err error) {
+func (a *Device) GetActiveNumberOfDate(vendorid string, datetime string) (count int, err error) {
 	device := &models.Device{
-		VendorID: uint(vendorid),
+		VendorID: vendorid,
 	}
 	err = a.db.Model(device).
 		Where("vendor_id = ? and DATE_FORMAT(created_at, '%Y-%m-%d') = ?",
@@ -42,9 +42,9 @@ func (a *Device) GetActiveNumberOfDate(vendorid uint, datetime string) (count in
 }
 
 // GetLivelyCountOfDate 获取某一天的设备活跃数据
-func (a *Device) GetLivelyCountOfDate(vendorid uint, datetime string) (count int, err error) {
+func (a *Device) GetLivelyCountOfDate(vendorid string, datetime string) (count int, err error) {
 	device := &models.Device{
-		VendorID: uint(vendorid),
+		VendorID: vendorid,
 	}
 	err = a.db.Model(device).
 		Where("vendor_id = ? and DATE_FORMAT(updated_at, '%Y-%m-%d') = ?",
@@ -93,7 +93,7 @@ func (a *Device) GetLivelyCountOfDate(vendorid uint, datetime string) (count int
 
 // GetActiveOfNumDays 查询几日内的激活趋势数据
 // days参数为7则查询7日的数据
-func (a *Device) GetActiveOfNumDays(vendorid uint, days int) ([]map[string]interface{}, error) {
+func (a *Device) GetActiveOfNumDays(vendorid string, days int) ([]map[string]interface{}, error) {
 	i := 1
 	datas := make([]map[string]interface{}, 0)
 	for i <= days {
@@ -112,7 +112,7 @@ func (a *Device) GetActiveOfNumDays(vendorid uint, days int) ([]map[string]inter
 }
 
 // GetLivelyOfNumDays 获取设备N日内活跃趋势数据
-func (a *Device) GetLivelyOfNumDays(vendorid uint, days int) ([]map[string]interface{}, error) {
+func (a *Device) GetLivelyOfNumDays(vendorid string, days int) ([]map[string]interface{}, error) {
 	i := 1
 	datas := make([]map[string]interface{}, 0)
 	for i <= days {
@@ -131,7 +131,7 @@ func (a *Device) GetLivelyOfNumDays(vendorid uint, days int) ([]map[string]inter
 }
 
 // GetDevices 获取厂商已经激活的设备列表
-func (a *Device) GetDevices(vendorid uint, proid, pi, ps int, deviceid string) (datas []models.Device, total int, err error) {
+func (a *Device) GetDevices(vendorid string, proid, pi, ps int, deviceid string) (datas []models.Device, total int, err error) {
 	tx := a.db.Where("vendor_id = ?", vendorid)
 	if proid != 0 {
 		tx = tx.Where("product_id = ?", proid)
@@ -145,7 +145,7 @@ func (a *Device) GetDevices(vendorid uint, proid, pi, ps int, deviceid string) (
 }
 
 //GetDevicesByVenderId 获取用户设备
-func (a *Device) GetDevicesByVenderId(vendorid uint) (datas []models.Device, err error) {
+func (a *Device) GetDevicesByVenderId(vendorid string) (datas []models.Device, err error) {
 	a.db.Where("vendor_id = ?", vendorid).Find(&datas)
 	return
 }

+ 2 - 2
services/knowoapi/model/product.go

@@ -56,7 +56,7 @@ func (a *Product) Update(product *models.Product) (pro models.Product, err error
 }
 
 // GetVendorProducts 获取厂商的产品列表
-func (a *Product) GetVendorProducts(vendorid uint, pi, ps int, name string) (datas []models.Product, total int, err error) {
+func (a *Product) GetVendorProducts(vendorid string, pi, ps int, name string) (datas []models.Product, total int, err error) {
 	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
 	if name != "" {
 		tx = tx.Where("product_name like ?", "%"+name+"%")
@@ -67,7 +67,7 @@ func (a *Product) GetVendorProducts(vendorid uint, pi, ps int, name string) (dat
 }
 
 // QueryOne 获取单个产品内容
-func (a *Product) QueryOne(productkey string, vendorid uint) (data models.Product, err error) {
+func (a *Product) QueryOne(productkey string, vendorid string) (data models.Product, err error) {
 	cache := getCache()
 	key := fmt.Sprintf("Product:%s", productkey)
 	if v, ok := cache.Get(key); ok {

+ 10 - 8
services/knowoapi/services/alert.go

@@ -2,6 +2,7 @@ package services
 
 import (
 	"errors"
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
 )
@@ -10,17 +11,17 @@ import (
 type AlertService interface {
 	Create(*models.AlarmRule) error
 	Delete(*models.AlarmRule) error
-	Update(uint, *models.AlarmRule) (models.AlarmRule, error)
+	Update(string, *models.AlarmRule) (models.AlarmRule, error)
 	// GetAlarmRules 获取告警列表
 	// vendorid:厂商ID
 	// proid:产品ID,可选
 	// procalid:协议ID, 可选
 	// name: 规则名称,可选,模糊搜索
-	GetAlarmRules(vendorid uint, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error)
-	GetRule(vendorid uint, alertid int) (models.AlarmRule, error)
+	GetAlarmRules(vendorid string, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error)
+	GetRule(vendorid string, alertid string) (models.AlarmRule, error)
 	// 设置禁用可用状态
 	// 参数(vendorid, recordid, status)
-	SetRuleStatus(uint, int, int) (models.AlarmRule, error)
+	SetRuleStatus(string, string, int) (models.AlarmRule, error)
 }
 
 type alert struct {
@@ -35,6 +36,7 @@ func NewAlertService(model *model.All) AlertService {
 }
 
 func (a alert) Create(alert *models.AlarmRule) error {
+	alert.RecordId = guid.S()
 	count, err := a.model.Alert.CheckProtocalRuleCount(alert.VendorID, alert.ProtocalID)
 	if err != nil {
 		return err
@@ -51,15 +53,15 @@ func (a alert) Delete(alert *models.AlarmRule) error {
 	return a.model.Alert.Delete(alert)
 }
 
-func (a alert) Update(vendorid uint, alert *models.AlarmRule) (models.AlarmRule, error) {
+func (a alert) Update(vendorid string, alert *models.AlarmRule) (models.AlarmRule, error) {
 	return a.model.Alert.Update(vendorid, alert)
 }
-func (a alert) GetAlarmRules(vendorid uint, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error) {
+func (a alert) GetAlarmRules(vendorid string, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error) {
 	return a.model.Alert.GetRules(vendorid, pi, ps, proid, protocalid, name)
 }
-func (a alert) GetRule(vendorid uint, alertid int) (models.AlarmRule, error) {
+func (a alert) GetRule(vendorid string, alertid string) (models.AlarmRule, error) {
 	return a.model.Alert.GetAlarmRule(vendorid, alertid)
 }
-func (a alert) SetRuleStatus(vendorid uint, alertid int, status int) (models.AlarmRule, error) {
+func (a alert) SetRuleStatus(vendorid string, alertid string, status int) (models.AlarmRule, error) {
 	return a.model.Alert.SetRuleState(vendorid, alertid, status)
 }

+ 7 - 5
services/knowoapi/services/application.go

@@ -2,6 +2,7 @@ package services
 
 import (
 	"errors"
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/generator"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
@@ -14,8 +15,8 @@ type ApplicationService interface {
 	Update(*models.Application) (models.Application, error)
 	// 查询App信息
 	// 参数 :厂商ID,APPKey
-	GetAppInfo(uint, string) (models.Application, error)
-	GetVendorApps(vendorid uint, pi, ps int, name string) ([]models.Application, int, error)
+	GetAppInfo(string, string) (models.Application, error)
+	GetVendorApps(vendorid string, pi, ps int, name string) ([]models.Application, int, error)
 }
 
 type appService struct {
@@ -32,6 +33,7 @@ func NewAppService(model *model.All, gen *generator.KeyGenerator) ApplicationSer
 }
 
 func (a appService) Create(app *models.Application) error {
+	app.RecordId = guid.S()
 	count, err := a.model.Application.GetAppCount(app.VendorID)
 	if err != nil {
 		return err
@@ -43,7 +45,7 @@ func (a appService) Create(app *models.Application) error {
 	if err != nil {
 		return err
 	}
-	app.AppKey, _ = a.keyGen.GenRandomKey(int64(app.ID))
+	app.AppKey, _ = a.keyGen.GenRandomKey(app.RecordId)
 	app.SecretKey, _ = generator.GenRandomPassword()
 
 	return a.model.Application.Create(app)
@@ -55,10 +57,10 @@ func (a appService) Delete(app *models.Application) error {
 func (a appService) Update(app *models.Application) (models.Application, error) {
 	return a.model.Application.Update(app)
 }
-func (a appService) GetAppInfo(vendorid uint, key string) (models.Application, error) {
+func (a appService) GetAppInfo(vendorid string, key string) (models.Application, error) {
 	return a.model.Application.GetAppInfo(vendorid, key)
 }
 
-func (a appService) GetVendorApps(vendorid uint, pi, ps int, name string) ([]models.Application, int, error) {
+func (a appService) GetVendorApps(vendorid string, pi, ps int, name string) ([]models.Application, int, error) {
 	return a.model.Application.GetVendorApps(vendorid, pi, ps, name)
 }

+ 16 - 17
services/knowoapi/services/device.go

@@ -10,19 +10,19 @@ import (
 // DeviceService device service接口
 type DeviceService interface {
 	// 获取厂商已经激活的设备总数
-	GetDeviceCount(vendorid uint) (int, error)
+	GetDeviceCount(vendorid string) (int, error)
 	//返回厂商某天激活的设备数
-	GetActiveNumberOfDate(vendor uint, datetime string) (int, error)
+	GetActiveNumberOfDate(vendor string, datetime string) (int, error)
 	//获取厂商某天活跃的设备数
-	GetLivelyCountOfDate(uint, string) (int, error)
+	GetLivelyCountOfDate(string, string) (int, error)
 	//获取近N日激活设备数据
-	GetActiveOfNumDays(uint, int) ([]map[string]interface{}, error)
+	GetActiveOfNumDays(string, int) ([]map[string]interface{}, error)
 	//获取近N日活跃设备数据
-	GetLivelyOfNumDays(uint, int) ([]map[string]interface{}, error)
+	GetLivelyOfNumDays(string, int) ([]map[string]interface{}, error)
 	//获取已经激活的设备列表
-	GetDevices(vendorid uint, proid, pi, ps int, deviceid string) ([]*models.Devices, int, error)
+	GetDevices(vendorid string, proid, pi, ps int, deviceid string) ([]*models.Devices, int, error)
 	//获取用户下所有设备的数量,在线设备的数量,离线设备的数量
-	GetDevicesCountByVenderId(vendorid uint) (map[string]interface{}, error)
+	GetDevicesCountByVenderId(vendorid string) (map[string]interface{}, error)
 }
 
 type deviceservice struct {
@@ -35,7 +35,7 @@ func NewDeviceService(models *model.All) DeviceService {
 		models: models,
 	}
 }
-func (a deviceservice) GetDevices(vendorid uint, proid, pi, ps int, deviceid string) ([]*models.Devices, int, error) {
+func (a deviceservice) GetDevices(vendorid string, proid, pi, ps int, deviceid string) ([]*models.Devices, int, error) {
 
 	data, total, err := a.models.Device.GetDevices(vendorid, proid, pi, ps, deviceid)
 
@@ -48,7 +48,7 @@ func (a deviceservice) GetDevices(vendorid uint, proid, pi, ps int, deviceid str
 	for _, device := range data {
 
 		onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
-			Id: uint64(device.ID),
+			Id: device.RecordId,
 		}
 
 		onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
@@ -72,23 +72,22 @@ func (a deviceservice) GetDevices(vendorid uint, proid, pi, ps int, deviceid str
 
 	return dataMap, total, nil
 }
-
-func (a deviceservice) GetDeviceCount(vendorid uint) (int, error) {
+func (a deviceservice) GetDeviceCount(vendorid string) (int, error) {
 	return a.models.Device.GetDeviceCount(vendorid)
 }
-func (a deviceservice) GetActiveNumberOfDate(vendorid uint, datetime string) (int, error) {
+func (a deviceservice) GetActiveNumberOfDate(vendorid string, datetime string) (int, error) {
 	return a.models.Device.GetActiveNumberOfDate(vendorid, datetime)
 }
-func (a deviceservice) GetLivelyCountOfDate(vendorid uint, datetime string) (int, error) {
+func (a deviceservice) GetLivelyCountOfDate(vendorid string, datetime string) (int, error) {
 	return a.models.Device.GetLivelyCountOfDate(vendorid, datetime)
 }
-func (a deviceservice) GetActiveOfNumDays(vendorid uint, days int) ([]map[string]interface{}, error) {
+func (a deviceservice) GetActiveOfNumDays(vendorid string, days int) ([]map[string]interface{}, error) {
 	return a.models.Device.GetActiveOfNumDays(vendorid, days)
 }
-func (a deviceservice) GetLivelyOfNumDays(vendorid uint, days int) ([]map[string]interface{}, error) {
+func (a deviceservice) GetLivelyOfNumDays(vendorid string, days int) ([]map[string]interface{}, error) {
 	return a.models.Device.GetLivelyOfNumDays(vendorid, days)
 }
-func (a deviceservice) GetDevicesCountByVenderId(vendorid uint) (map[string]interface{}, error) {
+func (a deviceservice) GetDevicesCountByVenderId(vendorid string) (map[string]interface{}, error) {
 	data, err := a.models.Device.GetDevicesByVenderId(vendorid)
 
 	if err != nil {
@@ -100,7 +99,7 @@ func (a deviceservice) GetDevicesCountByVenderId(vendorid uint) (map[string]inte
 	var offlineCount int
 	for _, device := range data {
 		onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
-			Id: uint64(device.ID),
+			Id: device.RecordId,
 		}
 		onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
 		err = server.RPCCallByName(nil, "devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)

+ 7 - 5
services/knowoapi/services/product.go

@@ -1,6 +1,7 @@
 package services
 
 import (
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/generator"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
@@ -12,10 +13,10 @@ type ProductService interface {
 	Delete(*models.Product) error
 	Update(*models.Product) (models.Product, error)
 	// 查询厂商所有产品列表
-	GetVendorProducts(vendorid uint, pi, ps int, name string) ([]models.Product, int, error)
+	GetVendorProducts(vendorid string, pi, ps int, name string) ([]models.Product, int, error)
 	// 查询单个产品信息
 	//参数:厂商ID,产品KEY
-	QueryOne(uint, string) (models.Product, error)
+	QueryOne(string, string) (models.Product, error)
 }
 
 type productService struct {
@@ -31,11 +32,12 @@ func NewProductService(pm *model.All, gen *generator.KeyGenerator) ProductServic
 	}
 }
 func (p *productService) Create(product *models.Product) error {
+	product.RecordId = guid.S()
 	err := p.model.Product.Create(product)
 	if err != nil {
 		return err
 	}
-	product.ProductKey, _ = p.keyGen.GenRandomKey(int64(product.ID))
+	product.ProductKey, _ = p.keyGen.GenRandomKey(product.RecordId)
 	return p.model.Product.Create(product)
 }
 
@@ -47,10 +49,10 @@ func (p *productService) Update(pro *models.Product) (models.Product, error) {
 	return p.model.Product.Update(pro)
 }
 
-func (p *productService) GetVendorProducts(vendorid uint, pi, ps int, name string) ([]models.Product, int, error) {
+func (p *productService) GetVendorProducts(vendorid string, pi, ps int, name string) ([]models.Product, int, error) {
 	return p.model.Product.GetVendorProducts(vendorid, pi, ps, name)
 }
 
-func (p *productService) QueryOne(vendorid uint, key string) (models.Product, error) {
+func (p *productService) QueryOne(vendorid string, key string) (models.Product, error) {
 	return p.model.Product.QueryOne(key, vendorid)
 }

+ 2 - 0
services/knowoapi/services/protocal.go

@@ -1,6 +1,7 @@
 package services
 
 import (
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
 )
@@ -28,6 +29,7 @@ func NewProtocalService(model *model.All) ProtocalService {
 }
 
 func (a protocalService) Create(ptl *models.Protocal) error {
+	ptl.RecordId = guid.S()
 	return a.model.Protocal.Create(ptl)
 }
 func (a protocalService) Delete(ptl *models.Protocal) error {

+ 2 - 0
services/knowoapi/services/role.go

@@ -1,6 +1,7 @@
 package services
 
 import (
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
 )
@@ -26,6 +27,7 @@ func NewRoleService(models *model.All) RoleService {
 }
 
 func (a roleService) Create(role *models.Role) error {
+	role.RecordId = guid.S()
 	return a.models.Role.Create(role)
 }
 

+ 2 - 0
services/knowoapi/services/sensor.go

@@ -1,6 +1,7 @@
 package services
 
 import (
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
 )
@@ -28,6 +29,7 @@ func NewSensorService(model *model.All) SensorService {
 }
 
 func (a sensorService) Create(sensor *models.Sensor) error {
+	sensor.RecordId = guid.S()
 	return a.model.Sensor.Create(sensor)
 }
 func (a sensorService) Delete(sensor *models.Sensor) error {

+ 6 - 3
services/knowoapi/services/user.go

@@ -2,6 +2,7 @@ package services
 
 import (
 	"encoding/base64"
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/generator"
 	"sparrow/pkg/models"
 	"sparrow/pkg/utils"
@@ -46,7 +47,8 @@ func (a userservice) Login(user *models.LoginRequest) (bool, *models.User, error
 
 func (a userservice) Register(user *models.Reqrequest) (*models.User, error) {
 	_u := &models.User{}
-	_u.UserKey, _ = a.keyGen.GenRandomKey(int64(_u.ID))
+	_u.RecordId = guid.S()
+	_u.UserKey, _ = a.keyGen.GenRandomKey(_u.RecordId)
 	_u.UserPass = utils.Md5(user.PassWord + model.SignedString)
 	_u.UserName = user.UserName
 	_u.Phone = user.Phone
@@ -55,12 +57,13 @@ func (a userservice) Register(user *models.Reqrequest) (*models.User, error) {
 	vedor := &models.Vendor{
 		VendorName: user.VendorName,
 	}
-	vedor.VendorKey, _ = a.keyGen.GenRandomKey(int64(vedor.ID))
+	vedor.RecordId = guid.S()
+	vedor.VendorKey, _ = a.keyGen.GenRandomKey(vedor.RecordId)
 	err := a.model.Vendor.Create(vedor)
 	if err != nil {
 		return nil, err
 	}
-	_u.VendorID = vedor.ID
+	_u.VendorID = vedor.RecordId
 	return _u, a.model.User.Create(_u)
 }
 func (a userservice) ModifyPassword(userid uint, new, old string) (bool, error) {

+ 4 - 4
services/mqttaccess/mqtt_provider.go

@@ -12,7 +12,7 @@ func NewMQTTProvider() *MQTTProvider {
 	return &MQTTProvider{}
 }
 
-func (mp *MQTTProvider) ValidateDeviceToken(deviceid uint64, token []byte) error {
+func (mp *MQTTProvider) ValidateDeviceToken(deviceid string, token []byte) error {
 	args := rpcs.ArgsValidateDeviceAccessToken{
 		Id:          deviceid,
 		AccessToken: token,
@@ -34,7 +34,7 @@ func (mp *MQTTProvider) OnDeviceOnline(args rpcs.ArgsGetOnline) error {
 
 	return err
 }
-func (mp *MQTTProvider) OnDeviceOffline(deviceid uint64) error {
+func (mp *MQTTProvider) OnDeviceOffline(deviceid string) error {
 	args := rpcs.ArgsGetOffline{
 		Id: deviceid,
 	}
@@ -46,7 +46,7 @@ func (mp *MQTTProvider) OnDeviceOffline(deviceid uint64) error {
 
 	return err
 }
-func (mp *MQTTProvider) OnDeviceHeartBeat(deviceid uint64) error {
+func (mp *MQTTProvider) OnDeviceHeartBeat(deviceid string) error {
 	args := rpcs.ArgsDeviceId{
 		Id: deviceid,
 	}
@@ -57,7 +57,7 @@ func (mp *MQTTProvider) OnDeviceHeartBeat(deviceid uint64) error {
 	}
 	return err
 }
-func (mp *MQTTProvider) OnDeviceMessage(deviceid uint64, msgtype string, message []byte) {
+func (mp *MQTTProvider) OnDeviceMessage(deviceid string, msgtype string, message []byte) {
 	server.Log.Infof("device {%v} message {%v} : %x", deviceid, msgtype, message)
 	switch msgtype {
 	case "s":

+ 2 - 2
services/mqttaccess/status.go

@@ -4,8 +4,8 @@ import (
 	"sparrow/pkg/protocol"
 )
 
-var StatusChan map[uint64]chan *protocol.Data
+var StatusChan map[string]chan *protocol.Data
 
 func init() {
-	StatusChan = make(map[uint64]chan *protocol.Data)
+	StatusChan = make(map[string]chan *protocol.Data)
 }

+ 6 - 4
services/registry/product.go

@@ -3,6 +3,7 @@ package main
 import (
 	"errors"
 	"fmt"
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/models"
 	"sparrow/pkg/server"
 )
@@ -10,6 +11,7 @@ import (
 // SaveProduct 如果product.ID为空则会添加,否则更新相应产品信息
 func (r *Registry) SaveProduct(product *models.Product, reply *models.Product) error {
 	db, err := getDB()
+	product.RecordId = guid.S()
 	if err != nil {
 		return err
 	}
@@ -21,7 +23,7 @@ func (r *Registry) SaveProduct(product *models.Product, reply *models.Product) e
 			return err
 		}
 
-		key, err := r.keygen.GenRandomKey(int64(product.ID))
+		key, err := r.keygen.GenRandomKey(product.RecordId)
 		if err != nil {
 			return err
 		}
@@ -67,7 +69,7 @@ func (r *Registry) DelProduct(product *models.Product, reply *models.Product) er
 }
 
 // FindProduct will find product by specified ID
-func (r *Registry) FindProduct(id int32, reply *models.Product) error {
+func (r *Registry) FindProduct(id string, reply *models.Product) error {
 	db, err := getDB()
 	if err != nil {
 		return err
@@ -79,7 +81,7 @@ func (r *Registry) FindProduct(id int32, reply *models.Product) error {
 		product := cacheValue.(*models.Product)
 		setProduct(reply, product)
 	} else {
-		err = db.First(reply, id).Error
+		err = db.First(reply, "record_id = ?", id).Error
 		if err != nil {
 			return err
 		}
@@ -111,7 +113,7 @@ func (r *Registry) ValidateProduct(key string, reply *models.Product) error {
 		product := cacheValue.(*models.Product)
 		setProduct(reply, product)
 	} else {
-		err = db.First(reply, id).Error
+		err = db.First(reply, "record_id = ?", id).Error
 		if err != nil {
 			return err
 		}

+ 32 - 14
services/registry/registry.go

@@ -4,6 +4,7 @@ import (
 	"errors"
 	"flag"
 	"fmt"
+	"github.com/gogf/gf/util/guid"
 	"sparrow/pkg/generator"
 	"sparrow/pkg/models"
 	"sparrow/pkg/rpcs"
@@ -80,6 +81,7 @@ func setDevice(target *models.Device, src *models.Device) {
 // SaveVendor will create a vendor if the ID field is not initialized
 // if ID field is initialized, it will update the conresponding vendor.
 func (r *Registry) SaveVendor(vendor *models.Vendor, reply *models.Vendor) error {
+	vendor.RecordId = guid.S()
 	db, err := getDB()
 	if err != nil {
 		return err
@@ -92,7 +94,7 @@ func (r *Registry) SaveVendor(vendor *models.Vendor, reply *models.Vendor) error
 			return err
 		}
 
-		key, err := r.keygen.GenRandomKey(int64(vendor.ID))
+		key, err := r.keygen.GenRandomKey(vendor.RecordId)
 		if err != nil {
 			return err
 		}
@@ -120,6 +122,7 @@ func (r *Registry) SaveVendor(vendor *models.Vendor, reply *models.Vendor) error
 // SaveApplication will create a application if the ID field is not initialized
 // if ID field is initialized, it will update the conresponding application.
 func (r *Registry) SaveApplication(app *models.Application, reply *models.Application) error {
+	app.RecordId = guid.S()
 	db, err := getDB()
 	if err != nil {
 		return err
@@ -131,7 +134,7 @@ func (r *Registry) SaveApplication(app *models.Application, reply *models.Applic
 			return err
 		}
 
-		key, err := r.keygen.GenRandomKey(int64(app.ID))
+		key, err := r.keygen.GenRandomKey(app.RecordId)
 		if err != nil {
 			return err
 		}
@@ -191,19 +194,19 @@ func (r *Registry) ValidateApplication(key string, reply *models.Application) er
 }
 
 // FindVendor will find product by specified ID
-func (r *Registry) FindVendor(id int32, reply *models.Vendor) error {
+func (r *Registry) FindVendor(recordId string, reply *models.Vendor) error {
 	db, err := getDB()
 	if err != nil {
 		return err
 	}
 
 	cache := getCache()
-	cacheKey := fmt.Sprintf("Vendor:%v", id)
+	cacheKey := fmt.Sprintf("Vendor:%v", recordId)
 	if cacheValue, ok := cache.Get(cacheKey); ok {
 		vendor := cacheValue.(*models.Vendor)
 		setVendor(reply, vendor)
 	} else {
-		err = db.First(reply, id).Error
+		err = db.First(reply, "record_id = ?", recordId).Error
 		if err != nil {
 			return err
 		}
@@ -236,7 +239,7 @@ func (r *Registry) GetApplications(noarg int, reply *[]models.Application) error
 }
 
 // FindApplication will find product by specified ID
-func (r *Registry) FindApplication(id int32, reply *models.Application) error {
+func (r *Registry) FindApplication(id string, reply *models.Application) error {
 	db, err := getDB()
 	if err != nil {
 		return err
@@ -248,7 +251,7 @@ func (r *Registry) FindApplication(id int32, reply *models.Application) error {
 		app := cacheValue.(*models.Application)
 		setApplication(reply, app)
 	} else {
-		err = db.First(reply, id).Error
+		err = db.First(reply, "record_id = ?", id).Error
 		if err != nil {
 			return err
 		}
@@ -297,22 +300,23 @@ func (r *Registry) RegisterDevice(args *rpcs.ArgsDeviceRegister, reply *models.D
 		return err
 	}
 
-	identifier := genDeviceIdentifier(product.VendorID, product.ID, args.DeviceCode)
+	identifier := genDeviceIdentifier(product.ID, product.ID, args.DeviceCode)
 	if db.Where(&models.Device{DeviceIdentifier: identifier}).First(reply).RecordNotFound() {
 		// device is not registered yet.
-		reply.ProductID = int32(product.ID)
+		reply.RecordId = guid.S()
+		reply.ProductID = product.RecordId
 		reply.DeviceIdentifier = identifier
 		reply.DeviceName = product.ProductName // product name as default device name.
 		reply.DeviceDescription = product.ProductDescription
 		reply.DeviceVersion = args.DeviceVersion
-		reply.VendorID = uint(product.VendorID)
+		reply.VendorID = product.VendorID
 		reply.ModuleName = args.ModuleName
 		err = db.Save(reply).Error
 		if err != nil {
 			return err
 		}
 		// generate a random device key with hex encoding.
-		reply.DeviceKey, err = r.keygen.GenRandomKey(int64(reply.ID))
+		reply.DeviceKey, err = r.keygen.GenRandomKey(reply.RecordId)
 		if err != nil {
 			return err
 		}
@@ -373,14 +377,28 @@ func (r *Registry) FindDeviceByIdentifier(identifier string, reply *models.Devic
 }
 
 // FindDeviceById will find the device with given id
-func (r *Registry) FindDeviceById(args *rpcs.ArgsDeviceAuth, reply *models.Device) error {
+func (r *Registry) FindDeviceByRecordId(args *rpcs.ArgsDeviceAuth, reply *models.Device) error {
+	db, err := getDB()
+	if err != nil {
+		return err
+	}
+	d := &models.Device{}
+	d.RecordId = args.DeviceID
+	err = db.Where(d).First(reply).Error
+
+	if err != nil {
+		return err
+	}
+	return nil
+}
 
+func (r *Registry) FindDeviceById(args uint64, reply *models.Device) error {
 	db, err := getDB()
 	if err != nil {
 		return err
 	}
 	d := &models.Device{}
-	d.ID = uint(args.DeviceID)
+	d.ID = uint(args)
 	err = db.Where(d).First(reply).Error
 
 	if err != nil {
@@ -398,7 +416,7 @@ func (r *Registry) ValidateDevice(key string, device *models.Device) error {
 	args := rpcs.ArgsDeviceAuth{
 		DeviceID: id,
 	}
-	err = r.FindDeviceById(&args, device)
+	err = r.FindDeviceByRecordId(&args, device)
 	if err != nil {
 		return err
 	}

+ 1 - 1
services/registry/utils.go

@@ -4,6 +4,6 @@ import (
 	"strconv"
 )
 
-func genDeviceIdentifier(vendor int32, product uint, device string) string {
+func genDeviceIdentifier(vendor uint, product uint, device string) string {
 	return strconv.FormatInt(int64(vendor), 16) + "-" + strconv.FormatInt(int64(product), 16) + "-" + device
 }

BIN
tests/device/device


+ 3 - 3
tests/device/main.go

@@ -6,8 +6,8 @@ import (
 )
 
 var (
-	testURL        = flag.String("url", "http://192.168.1.107:8088", "login url")
-	testProductKey = flag.String("productkey", "99b11b395c84435202692e36dada175c7af9452038a62a40b230b5e18b7d51ff", "product key")
+	testURL        = flag.String("url", "http://192.168.1.100:8088", "login url")
+	testProductKey = flag.String("productkey", "2e397f5599a3f6f6a5a3c8fcd45437169501b3c6e239042ad5e9b65303561e41ab5519e9d205facbcbe75a2784354501", "product key")
 	testProtocol   = flag.String("protocol", "mqtt", "access protocol")
 )
 
@@ -19,7 +19,7 @@ func main() {
 		return
 	}
 
-	dev := NewDevice(*testURL, *testProductKey, "ffe34e", "version", *testProtocol)
+	dev := NewDevice(*testURL, *testProductKey, "123456", "1.2.3", *testProtocol)
 
 	err := dev.DoRegister()
 	if err != nil {