controller.go 7.7 KB

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