controller.go 9.9 KB

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