controller.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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/entities"
  9. "sparrow/pkg/klink"
  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. // Controller 消息控制器
  20. type Controller struct {
  21. producer queue.QueueProducer
  22. timer *rule.Timer
  23. ift *rule.Ifttt
  24. actorContext *ruleEngine.SystemContext
  25. consumer queue.QueueConsumer
  26. cluster *ClusterService
  27. pool *grpool.Pool
  28. }
  29. // NewController 新建消息控制器
  30. func NewController(rabbithost string) (*Controller, error) {
  31. admin := msgQueue.NewRabbitMessageQueueAdmin(&msgQueue.RabbitMqSettings{Host: rabbithost}, nil)
  32. producer := msgQueue.NewRabbitMqProducer(admin, "default")
  33. consumer := msgQueue.NewRabbitConsumer(admin, "MAIN")
  34. if err := initConsumers(consumer); err != nil {
  35. return nil, err
  36. }
  37. if err := producer.Init(); err != nil {
  38. return nil, err
  39. }
  40. return &Controller{
  41. producer: producer,
  42. consumer: consumer,
  43. cluster: &ClusterService{producer: producer},
  44. pool: grpool.New(),
  45. }, nil
  46. }
  47. func initConsumers(consumer *msgQueue.RabbitMqConsumer) error {
  48. tService := &TenantService{}
  49. tp := make([]*queue.TopicPartitionInfo, 0)
  50. tenants, err := tService.FindTenants()
  51. if err != nil {
  52. return err
  53. }
  54. for _, t := range tenants {
  55. tp = append(tp, &queue.TopicPartitionInfo{
  56. Topic: "MAIN",
  57. TenantId: t.Id,
  58. Partition: 0,
  59. MyPartition: false,
  60. })
  61. }
  62. return consumer.SubscribeWithPartitions(tp)
  63. }
  64. // SetStatus 设置设备状态
  65. func (c *Controller) SetStatus(args rpcs.ArgsSetStatus, reply *rpcs.ReplySetStatus) error {
  66. rpchost, err := getAccessRPCHost(args.DeviceId)
  67. if err != nil {
  68. return err
  69. }
  70. return server.RPCCallByHost(rpchost, "Access.SetStatus", args, reply)
  71. }
  72. // GetStatus 获取设备状态
  73. func (c *Controller) GetStatus(args rpcs.ArgsGetStatus, reply *rpcs.ReplyGetStatus) error {
  74. rpchost, err := getAccessRPCHost(args.Id)
  75. if err != nil {
  76. return err
  77. }
  78. return server.RPCCallByHost(rpchost, "Access.GetStatus", args, reply)
  79. }
  80. // Online 设备上线
  81. func (c *Controller) Online(args rpcs.ArgsGetStatus, reply *rpcs.ReplyEmptyResult) error {
  82. data := gjson.New(nil)
  83. _ = data.Set("device_id", args.Id)
  84. t := time.Now()
  85. msg := &protocol.Message{
  86. Id: guid.S(),
  87. Ts: &t,
  88. Type: protocol.CONNECT_EVENT,
  89. Data: data.MustToJsonString(),
  90. Callback: nil,
  91. MetaData: map[string]interface{}{
  92. "device_id": args.Id,
  93. "vendor_id": args.VendorId,
  94. },
  95. Originator: "device",
  96. }
  97. tpi := queue.ResolvePartition("RULE_ENGINE",
  98. msg.GetQueueName(),
  99. args.VendorId,
  100. args.Id)
  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. // Offline 设备下线
  109. func (c *Controller) Offline(args rpcs.ArgsGetStatus, reply *rpcs.ReplyEmptyResult) error {
  110. if args.Id == "" || args.VendorId == "" {
  111. return nil
  112. }
  113. data := gjson.New(nil)
  114. _ = data.Set("device_id", args.Id)
  115. t := time.Now()
  116. msg := &protocol.Message{
  117. Id: guid.S(),
  118. Ts: &t,
  119. Type: protocol.DISCONNECT_EVENT,
  120. Data: data.MustToJsonString(),
  121. Callback: nil,
  122. MetaData: map[string]interface{}{
  123. "device_id": args.Id,
  124. "vendor_id": args.VendorId,
  125. },
  126. Originator: "device",
  127. }
  128. tpi := queue.ResolvePartition("RULE_ENGINE",
  129. msg.GetQueueName(),
  130. args.VendorId,
  131. args.Id)
  132. g, err := queue.NewGobQueueMessage(msg)
  133. if err != nil {
  134. return err
  135. }
  136. g.Headers.Put("tenant_id", []byte(args.VendorId))
  137. return c.producer.Send(tpi, g, nil)
  138. }
  139. // OnStatus 状态上报消息处理
  140. func (c *Controller) OnStatus(args rpcs.ArgsOnStatus, reply *rpcs.ReplyOnStatus) error {
  141. t := time.Unix(int64(args.Timestamp/1000), 0)
  142. data, err := c.processStatusToQueue(args)
  143. if err != nil {
  144. return err
  145. }
  146. msg := &protocol.Message{
  147. Id: guid.S(),
  148. Ts: &t,
  149. Type: protocol.POST_ATTRIBUTES_REQUEST,
  150. Data: data,
  151. Callback: nil,
  152. MetaData: map[string]interface{}{
  153. "vendor_id": args.VendorId,
  154. "device_id": args.DeviceId,
  155. "sub_device_id": args.SubDeviceId,
  156. "timestamp": args.Timestamp,
  157. },
  158. Originator: "device",
  159. }
  160. tpi := queue.ResolvePartition("RULE_ENGINE",
  161. msg.GetQueueName(),
  162. args.VendorId,
  163. args.DeviceId)
  164. g, err := queue.NewGobQueueMessage(msg)
  165. if err != nil {
  166. return err
  167. }
  168. g.Headers.Put("tenant_id", []byte(args.VendorId))
  169. return c.producer.Send(tpi, g, nil)
  170. }
  171. func (c *Controller) processStatusToQueue(args rpcs.ArgsOnStatus) (string, error) {
  172. result := gjson.New(nil)
  173. j, err := gjson.DecodeToJson(args.SubData)
  174. if err != nil {
  175. return "", err
  176. }
  177. switch args.Action {
  178. case klink.DevSendAction:
  179. params := j.GetMap("params")
  180. if err = result.Set(j.GetString("cmd"), params); err != nil {
  181. return "", err
  182. }
  183. }
  184. return result.MustToJsonString(), nil
  185. }
  186. func (c *Controller) processEventToQueue(args rpcs.ArgsOnEvent) (string, error) {
  187. result := gjson.New(nil)
  188. j, err := gjson.DecodeToJson(args.SubData)
  189. if err != nil {
  190. return "", nil
  191. }
  192. params := j.GetMap("params")
  193. if err = result.Set(j.GetString("cmd"), params); err != nil {
  194. return "", err
  195. }
  196. return result.MustToJsonString(), nil
  197. }
  198. // OnEvent 事件消息处理
  199. func (c *Controller) OnEvent(args rpcs.ArgsOnEvent, reply *rpcs.ReplyOnEvent) error {
  200. t := time.Unix(int64(args.TimeStamp/1000), 0)
  201. data, err := c.processEventToQueue(args)
  202. if err != nil {
  203. return err
  204. }
  205. msg := &protocol.Message{
  206. Id: guid.S(),
  207. Ts: &t,
  208. Type: protocol.POST_EVENT_REQUEST,
  209. Data: data,
  210. Callback: nil,
  211. MetaData: map[string]interface{}{
  212. "tenant_id": args.VendorId,
  213. "device_id": args.DeviceId,
  214. "sub_device_id": args.SubDeviceId,
  215. },
  216. Originator: "device",
  217. }
  218. tpi := queue.ResolvePartition("RULE_ENGINE",
  219. msg.GetQueueName(),
  220. args.VendorId,
  221. args.DeviceId)
  222. g, err := queue.NewGobQueueMessage(msg)
  223. if err != nil {
  224. return err
  225. }
  226. g.Headers.Put("tenant_id", []byte(args.VendorId))
  227. return c.producer.Send(tpi, g, nil)
  228. }
  229. // CreateRuleChain 规则链生命周期-创建
  230. func (c *Controller) CreateRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  231. if c.actorContext != nil {
  232. msg := &ruleEngine.ComponentLifecycleMsg{
  233. TenantId: args.VendorId,
  234. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  235. EventType: ruleEngine.CREATED,
  236. }
  237. c.actorContext.AppActor.TellWithHighPriority(msg)
  238. }
  239. return nil
  240. }
  241. // DeleteRuleChain 规则链生命周期-删除
  242. func (c *Controller) DeleteRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  243. if c.actorContext != nil {
  244. msg := &ruleEngine.ComponentLifecycleMsg{
  245. TenantId: args.VendorId,
  246. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  247. EventType: ruleEngine.DELETED,
  248. }
  249. c.actorContext.AppActor.TellWithHighPriority(msg)
  250. }
  251. return nil
  252. }
  253. // UpdateRuleChain 规则链生命周期-更新
  254. func (c *Controller) UpdateRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  255. if c.actorContext != nil {
  256. msg := &ruleEngine.ComponentLifecycleMsg{
  257. TenantId: args.VendorId,
  258. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  259. EventType: ruleEngine.UPDATED,
  260. }
  261. c.actorContext.AppActor.TellWithHighPriority(msg)
  262. }
  263. return nil
  264. }
  265. // SendCommand 下发设备控制指令
  266. func (c *Controller) SendCommand(args rpcs.ArgsSendCommand, reply *rpcs.ReplySendCommand) error {
  267. rpchost, err := getAccessRPCHost(args.DeviceId)
  268. if err != nil {
  269. return err
  270. }
  271. return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
  272. }
  273. func getAccessRPCHost(deviceid string) (string, error) {
  274. args := rpcs.ArgsGetDeviceOnlineStatus{
  275. Id: deviceid,
  276. }
  277. reply := &rpcs.ReplyGetDeviceOnlineStatus{}
  278. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", args, reply)
  279. if err != nil {
  280. return "", err
  281. }
  282. return reply.AccessRPCHost, nil
  283. }
  284. // ActorSystem actor system
  285. type ActorSystem struct {
  286. rootActor ruleEngine.Ref
  287. }
  288. // 初始化actor system
  289. func (c *Controller) initActorSystem() (*ActorSystem, error) {
  290. system := ruleEngine.NewDefaultActorSystem(&ruleEngine.DefaultActorSystemConfig{
  291. SchedulerPoolSize: 5,
  292. AppDispatcherPoolSize: 4,
  293. TenantDispatcherPoolSize: 4,
  294. RuleEngineDispatcherPoolSize: 4,
  295. })
  296. _ = system.CreateDispatcher(ruleEngine.APP_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  297. _ = system.CreateDispatcher(ruleEngine.TENANT_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  298. _ = system.CreateDispatcher(ruleEngine.RULE_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  299. // init services
  300. tenantService := &TenantService{}
  301. ruleChainService := &RuleChainService{}
  302. actorContext := ruleEngine.NewSystemContext(system, ruleEngine.SystemContextServiceConfig{
  303. ClusterService: c.cluster,
  304. RuleChainService: ruleChainService,
  305. TenantService: tenantService,
  306. EventService: NewEventService(),
  307. })
  308. appActor, err := system.CreateRootActor(ruleEngine.APP_DISPATCHER_NAME,
  309. actors.NewAppActorCreator(actorContext))
  310. if err != nil {
  311. return nil, err
  312. }
  313. actorContext.AppActor = appActor
  314. server.Log.Debugln("actor system initialized")
  315. time.Sleep(time.Second * 1)
  316. appActor.Tell(&ruleEngine.AppInitMsg{})
  317. c.actorContext = actorContext
  318. return &ActorSystem{rootActor: appActor}, nil
  319. }
  320. // 启动mq consumers
  321. func (c *Controller) launchConsumer() {
  322. msgs, err := c.consumer.Pop(100 * time.Millisecond)
  323. if err != nil {
  324. server.Log.Error(err)
  325. }
  326. for {
  327. select {
  328. case msg := <-msgs:
  329. ruleEngineMsg := &protocol.Message{}
  330. if err := ruleEngineMsg.Decode(msg.GetData()); err != nil {
  331. fmt.Println("解析消息失败")
  332. }
  333. tenantId := msg.GetHeaders().Get("tenant_id")
  334. if c.actorContext != nil {
  335. c.actorContext.Tell(&ruleEngine.QueueToRuleEngineMsg{
  336. TenantId: string(tenantId),
  337. Message: ruleEngineMsg,
  338. })
  339. }
  340. }
  341. }
  342. }