controller.go 9.7 KB

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