access.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package main
  2. import (
  3. "github.com/gogf/gf/encoding/gjson"
  4. "sparrow/pkg/klink"
  5. "sparrow/pkg/mqtt"
  6. "sparrow/pkg/protocol"
  7. "sparrow/pkg/rpcs"
  8. "sparrow/pkg/server"
  9. "time"
  10. )
  11. const (
  12. defaultTimeoutSecond = 5
  13. commandGetCurrentStatus = uint16(65528)
  14. )
  15. type Access struct {
  16. MqttBroker *mqtt.Broker
  17. }
  18. func NewAccess() (*Access, error) {
  19. p := NewMQTTProvider()
  20. return &Access{
  21. mqtt.NewBroker(p),
  22. }, nil
  23. }
  24. func (a *Access) SetStatus(args rpcs.ArgsSetStatus, reply *rpcs.ReplySetStatus) error {
  25. server.Log.Infof("Access Set Status: %v", args)
  26. data := &protocol.Data{}
  27. data.Head.Timestamp = uint64(time.Now().Unix())
  28. token, err := a.MqttBroker.GetToken(args.DeviceId)
  29. if err != nil {
  30. return err
  31. }
  32. copy(data.Head.Token[:], token[:16])
  33. data.SubData = args.Status
  34. msg, err := data.Marshal()
  35. if err != nil {
  36. return err
  37. }
  38. return a.MqttBroker.SendMessageToDevice(args.DeviceId, "s", msg, defaultTimeoutSecond*time.Second)
  39. }
  40. func (a *Access) GetStatus(args rpcs.ArgsGetStatus, reply *rpcs.ReplyGetStatus) error {
  41. server.Log.Infof("Access Get Status: %v", args)
  42. // first send a get status command
  43. cmdArgs := rpcs.ArgsSendCommand{
  44. DeviceId: args.Id,
  45. WaitTime: 0,
  46. Cmd: "report",
  47. }
  48. cmdReply := rpcs.ReplySendCommand{}
  49. //// then wait for status report
  50. //StatusChan[args.Id] = make(chan *protocol.Data)
  51. //after := time.After(defaultTimeoutSecond * time.Second)
  52. //server.Log.Debug("now waiting 5 seconds for status report...")
  53. //select {
  54. //case <-after:
  55. // // timeout
  56. // close(StatusChan[args.Id])
  57. // delete(StatusChan, args.Id)
  58. // return errors.New("get status timeout.")
  59. //case data := <-StatusChan[args.Id]:
  60. // // go it
  61. // close(StatusChan[args.Id])
  62. // delete(StatusChan, args.Id)
  63. // reply.Status = data.SubData
  64. // return nil
  65. //}
  66. return a.SendCommand(cmdArgs, &cmdReply)
  67. }
  68. func (a *Access) SendCommand(args rpcs.ArgsSendCommand, reply *rpcs.ReplySendCommand) error {
  69. server.Log.Infof("Access Send Command: %v", args)
  70. cmd := &klink.CloudSend{
  71. Action: "cloudSend",
  72. MsgId: 0,
  73. DeviceCode: args.DeviceId,
  74. SubDeviceId: args.SubDevice,
  75. Timestamp: time.Now().Unix(),
  76. Data: &klink.CloudSendData{
  77. Cmd: args.Cmd,
  78. Params: gjson.New(args.Params),
  79. },
  80. }
  81. msg, err := cmd.Marshal()
  82. if err != nil {
  83. return err
  84. }
  85. return a.MqttBroker.SendMessageToDevice(args.DeviceId, "c", msg, time.Duration(args.WaitTime)*time.Second)
  86. }