controller.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/encoding/gjson"
  5. "github.com/gogf/gf/os/grpool"
  6. "github.com/gogf/gf/util/guid"
  7. "sparrow/pkg/actors"
  8. "sparrow/pkg/klink"
  9. "sparrow/pkg/protocol"
  10. "sparrow/pkg/queue"
  11. "sparrow/pkg/queue/msgQueue"
  12. "sparrow/pkg/rpcs"
  13. "sparrow/pkg/rule"
  14. "sparrow/pkg/ruleEngine"
  15. "sparrow/pkg/server"
  16. "time"
  17. )
  18. type Controller struct {
  19. producer queue.QueueProducer
  20. timer *rule.Timer
  21. ift *rule.Ifttt
  22. actorContext *ruleEngine.SystemContext
  23. consumer queue.QueueConsumer
  24. cluster *ClusterService
  25. pool *grpool.Pool
  26. }
  27. func NewController(rabbithost string) (*Controller, error) {
  28. admin := msgQueue.NewRabbitMessageQueueAdmin(&msgQueue.RabbitMqSettings{Host: rabbithost}, nil)
  29. producer := msgQueue.NewRabbitMqProducer(admin, "default")
  30. consumer := msgQueue.NewRabbitConsumer(admin, "MAIN")
  31. tp := make([]*queue.TopicPartitionInfo, 0)
  32. tp = append(tp, &queue.TopicPartitionInfo{
  33. Topic: "MAIN",
  34. TenantId: "1ps9djpswi0cds7cofynkso300eql4iu",
  35. Partition: 0,
  36. MyPartition: false,
  37. })
  38. tp = append(tp, &queue.TopicPartitionInfo{
  39. Topic: "MAIN",
  40. TenantId: "1ps9djpswi0cds7cofynkso300eql4sw",
  41. Partition: 0,
  42. MyPartition: false,
  43. })
  44. _ = consumer.SubscribeWithPartitions(tp)
  45. if err := producer.Init(); err != nil {
  46. return nil, err
  47. }
  48. return &Controller{
  49. producer: producer,
  50. consumer: consumer,
  51. cluster: &ClusterService{producer: producer},
  52. pool: grpool.New(),
  53. }, nil
  54. }
  55. func (c *Controller) SetStatus(args rpcs.ArgsSetStatus, reply *rpcs.ReplySetStatus) error {
  56. rpchost, err := getAccessRPCHost(args.DeviceId)
  57. if err != nil {
  58. return err
  59. }
  60. return server.RPCCallByHost(rpchost, "Access.SetStatus", args, reply)
  61. }
  62. func (c *Controller) GetStatus(args rpcs.ArgsGetStatus, reply *rpcs.ReplyGetStatus) error {
  63. rpchost, err := getAccessRPCHost(args.Id)
  64. if err != nil {
  65. return err
  66. }
  67. return server.RPCCallByHost(rpchost, "Access.GetStatus", args, reply)
  68. }
  69. func (c *Controller) OnStatus(args rpcs.ArgsOnStatus, reply *rpcs.ReplyOnStatus) error {
  70. t := time.Unix(int64(args.Timestamp/1000), 0)
  71. data, err := c.processStatusToQueue(args)
  72. if err != nil {
  73. return err
  74. }
  75. //reportArgs := &rpcs.ArgsDeviceReport{
  76. // DeviceCode: args.DeviceId,
  77. // Data: data,
  78. //}
  79. //var reportReply *rpcs.ReplyEmptyResult
  80. //if err = server.RPCCallByName(context.Background(), rpcs.ShadowServiceName,
  81. // "ShadowServer.DeviceReport", reportArgs, reportReply); err != nil {
  82. // server.Log.Error(err)
  83. //}
  84. msg := &protocol.Message{
  85. Id: guid.S(),
  86. Ts: &t,
  87. Type: protocol.POST_ATTRIBUTES_REQUEST,
  88. Data: data,
  89. Callback: nil,
  90. MetaData: map[string]interface{}{
  91. "tenant_id": args.VendorId,
  92. "device_id": args.DeviceId,
  93. "sub_device_id": args.SubDeviceId,
  94. },
  95. Originator: "device",
  96. }
  97. tpi := queue.ResolvePartition("RULE_ENGINE",
  98. msg.GetQueueName(),
  99. args.VendorId,
  100. args.DeviceId)
  101. g, err := queue.NewGobQueueMessage(msg)
  102. if err != nil {
  103. return err
  104. }
  105. g.Headers.Put("tenant_id", []byte(args.VendorId))
  106. return c.producer.Send(tpi, g, nil)
  107. }
  108. func (c *Controller) processStatusToQueue(args rpcs.ArgsOnStatus) (string, error) {
  109. result := gjson.New(nil)
  110. j, err := gjson.DecodeToJson(args.SubData)
  111. if err != nil {
  112. return "", err
  113. }
  114. switch args.Action {
  115. case klink.DevSendAction:
  116. params := j.GetMap("params")
  117. if err = result.Set(j.GetString("cmd"), params); err != nil {
  118. return "", err
  119. }
  120. }
  121. return result.MustToJsonString(), nil
  122. }
  123. func (c *Controller) processEventToQueue(args rpcs.ArgsOnEvent) (string, error) {
  124. result := gjson.New(nil)
  125. j, err := gjson.DecodeToJson(args.SubData)
  126. if err != nil {
  127. return "", nil
  128. }
  129. params := j.GetMap("params")
  130. if err = result.Set(j.GetString("cmd"), params); err != nil {
  131. return "", err
  132. }
  133. return result.MustToJsonString(), nil
  134. }
  135. func (c *Controller) OnEvent(args rpcs.ArgsOnEvent, reply *rpcs.ReplyOnEvent) error {
  136. t := time.Unix(int64(args.TimeStamp/1000), 0)
  137. data, err := c.processEventToQueue(args)
  138. if err != nil {
  139. return err
  140. }
  141. msg := &protocol.Message{
  142. Id: guid.S(),
  143. Ts: &t,
  144. Type: protocol.POST_EVENT_REQUEST,
  145. Data: data,
  146. Callback: nil,
  147. MetaData: map[string]interface{}{
  148. "tenant_id": args.VendorId,
  149. "device_id": args.DeviceId,
  150. "sub_device_id": args.SubDeviceId,
  151. },
  152. Originator: "device",
  153. }
  154. tpi := queue.ResolvePartition("RULE_ENGINE",
  155. msg.GetQueueName(),
  156. args.VendorId,
  157. args.DeviceId)
  158. g, err := queue.NewGobQueueMessage(msg)
  159. if err != nil {
  160. return err
  161. }
  162. g.Headers.Put("tenant_id", []byte(args.VendorId))
  163. return c.producer.Send(tpi, g, nil)
  164. }
  165. func (c *Controller) SendCommand(args rpcs.ArgsSendCommand, reply *rpcs.ReplySendCommand) error {
  166. rpchost, err := getAccessRPCHost(args.DeviceId)
  167. if err != nil {
  168. return err
  169. }
  170. return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
  171. }
  172. func getAccessRPCHost(deviceid string) (string, error) {
  173. args := rpcs.ArgsGetDeviceOnlineStatus{
  174. Id: deviceid,
  175. }
  176. reply := &rpcs.ReplyGetDeviceOnlineStatus{}
  177. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", args, reply)
  178. if err != nil {
  179. return "", err
  180. }
  181. return reply.AccessRPCHost, nil
  182. }
  183. type ActorSystem struct {
  184. rootActor ruleEngine.Ref
  185. }
  186. // 初始化actor system
  187. func (c *Controller) initActorSystem() (*ActorSystem, error) {
  188. system := ruleEngine.NewDefaultActorSystem(&ruleEngine.DefaultActorSystemConfig{
  189. SchedulerPoolSize: 5,
  190. AppDispatcherPoolSize: 4,
  191. TenantDispatcherPoolSize: 4,
  192. RuleEngineDispatcherPoolSize: 4,
  193. })
  194. _ = system.CreateDispatcher(ruleEngine.APP_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  195. _ = system.CreateDispatcher(ruleEngine.TENANT_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  196. _ = system.CreateDispatcher(ruleEngine.RULE_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  197. // init services
  198. tenantService := &TenantService{}
  199. ruleChainService := &RuleChainService{}
  200. actorContext := ruleEngine.NewSystemContext(system, ruleEngine.SystemContextServiceConfig{
  201. ClusterService: c.cluster,
  202. RuleChainService: ruleChainService,
  203. TenantService: tenantService,
  204. EventService: NewEventService(),
  205. })
  206. appActor, err := system.CreateRootActor(ruleEngine.APP_DISPATCHER_NAME,
  207. actors.NewAppActorCreator(actorContext))
  208. if err != nil {
  209. return nil, err
  210. }
  211. actorContext.AppActor = appActor
  212. server.Log.Debugln("actor system initialized")
  213. time.Sleep(time.Second * 1)
  214. appActor.Tell(&ruleEngine.AppInitMsg{})
  215. c.actorContext = actorContext
  216. return &ActorSystem{rootActor: appActor}, nil
  217. }
  218. // 启动mq consumers
  219. func (c *Controller) launchConsumer() {
  220. msgs, err := c.consumer.Pop(100 * time.Millisecond)
  221. if err != nil {
  222. server.Log.Error(err)
  223. }
  224. for {
  225. select {
  226. case msg := <-msgs:
  227. ruleEngineMsg := &protocol.Message{}
  228. if err := ruleEngineMsg.Decode(msg.GetData()); err != nil {
  229. fmt.Println("解析消息失败")
  230. }
  231. tanantId := msg.GetHeaders().Get("tenant_id")
  232. if c.actorContext != nil {
  233. c.actorContext.Tell(&ruleEngine.QueueToRuleEngineMsg{
  234. TenantId: string(tanantId),
  235. Message: ruleEngineMsg,
  236. })
  237. }
  238. }
  239. }
  240. }