controller.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. "product_key": args.ProductKey,
  158. "timestamp": strconv.Itoa(int(args.Timestamp)),
  159. },
  160. Originator: "device",
  161. }
  162. tpi := queue.ResolvePartition("RULE_ENGINE",
  163. msg.GetQueueName(),
  164. args.VendorId,
  165. args.DeviceId)
  166. g, err := queue.NewGobQueueMessage(msg)
  167. if err != nil {
  168. return err
  169. }
  170. g.Headers.Put("tenant_id", []byte(args.VendorId))
  171. return c.producer.Send(tpi, g, nil)
  172. }
  173. func (c *Controller) processStatusToQueue(args rpcs.ArgsOnStatus) (string, error) {
  174. result := gjson.New(nil)
  175. j, err := gjson.DecodeToJson(args.SubData)
  176. if err != nil {
  177. return "", err
  178. }
  179. switch args.Action {
  180. case klink.DevSendAction:
  181. params := j.GetMap("params")
  182. if err = result.Set(j.GetString("cmd"), params); err != nil {
  183. return "", err
  184. }
  185. }
  186. return result.MustToJsonString(), nil
  187. }
  188. func (c *Controller) processEventToQueue(args rpcs.ArgsOnEvent) (string, error) {
  189. result := gjson.New(nil)
  190. j, err := gjson.DecodeToJson(args.SubData)
  191. if err != nil {
  192. return "", nil
  193. }
  194. params := j.GetMaps("params")
  195. if err = result.Set(j.GetString("cmd"), params); err != nil {
  196. return "", err
  197. }
  198. return result.MustToJsonString(), nil
  199. }
  200. // OnEvent 事件消息处理
  201. func (c *Controller) OnEvent(args rpcs.ArgsOnEvent, reply *rpcs.ReplyOnEvent) error {
  202. t := time.Unix(int64(args.TimeStamp/1000), 0)
  203. data, err := c.processEventToQueue(args)
  204. if err != nil {
  205. return err
  206. }
  207. msg := &protocol.Message{
  208. Id: guid.S(),
  209. Ts: &t,
  210. Type: protocol.POST_EVENT_REQUEST,
  211. Data: data,
  212. Callback: nil,
  213. MetaData: map[string]interface{}{
  214. "tenant_id": args.VendorId,
  215. "device_id": args.DeviceId,
  216. "sub_device_id": args.SubDeviceId,
  217. "product_key": args.ProductKey,
  218. "type": "EVENT",
  219. "timestamp": strconv.Itoa(int(args.TimeStamp)),
  220. },
  221. Originator: "device",
  222. }
  223. tpi := queue.ResolvePartition("RULE_ENGINE",
  224. msg.GetQueueName(),
  225. args.VendorId,
  226. args.DeviceId)
  227. g, err := queue.NewGobQueueMessage(msg)
  228. if err != nil {
  229. return err
  230. }
  231. g.Headers.Put("tenant_id", []byte(args.VendorId))
  232. return c.producer.Send(tpi, g, nil)
  233. }
  234. // CreateRuleChain 规则链生命周期-创建
  235. func (c *Controller) CreateRuleChain(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.CREATED,
  241. }
  242. c.actorContext.AppActor.TellWithHighPriority(msg)
  243. }
  244. return nil
  245. }
  246. // DeleteRuleChain 规则链生命周期-删除
  247. func (c *Controller) DeleteRuleChain(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.DELETED,
  253. }
  254. c.actorContext.AppActor.TellWithHighPriority(msg)
  255. }
  256. return nil
  257. }
  258. // UpdateRuleChain 规则链生命周期-更新
  259. func (c *Controller) UpdateRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  260. if c.actorContext != nil {
  261. msg := &ruleEngine.ComponentLifecycleMsg{
  262. TenantId: args.VendorId,
  263. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  264. EventType: ruleEngine.UPDATED,
  265. }
  266. c.actorContext.AppActor.TellWithHighPriority(msg)
  267. }
  268. return nil
  269. }
  270. // SendCommand 下发设备控制指令
  271. func (c *Controller) SendCommand(args rpcs.ArgsSendCommand, reply *rpcs.ReplySendCommand) error {
  272. rpchost, err := getAccessRPCHost(args.DeviceId)
  273. if err != nil {
  274. return err
  275. }
  276. return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
  277. }
  278. // SendCommandV2 下发设备控制指令适配emqx
  279. func (c *Controller) SendCommandV2(args rpcs.ArgsSendCommand, reply *rpcs.ReplySendCommand) error {
  280. rpchost, err := getAccessRPCHost(args.DeviceId)
  281. if err != nil {
  282. return err
  283. }
  284. return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
  285. }
  286. func getAccessRPCHost(deviceid string) (string, error) {
  287. args := rpcs.ArgsGetDeviceOnlineStatus{
  288. Id: deviceid,
  289. }
  290. reply := &rpcs.ReplyGetDeviceOnlineStatus{}
  291. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", args, reply)
  292. if err != nil {
  293. return "", err
  294. }
  295. return reply.AccessRPCHost, nil
  296. }
  297. // ActorSystem actor system
  298. type ActorSystem struct {
  299. rootActor ruleEngine.Ref
  300. }
  301. // 初始化actor system
  302. func (c *Controller) initActorSystem() (*ActorSystem, error) {
  303. system := ruleEngine.NewDefaultActorSystem(&ruleEngine.DefaultActorSystemConfig{
  304. SchedulerPoolSize: 5,
  305. AppDispatcherPoolSize: 4,
  306. TenantDispatcherPoolSize: 4,
  307. RuleEngineDispatcherPoolSize: 4,
  308. })
  309. _ = system.CreateDispatcher(ruleEngine.APP_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  310. _ = system.CreateDispatcher(ruleEngine.TENANT_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  311. _ = system.CreateDispatcher(ruleEngine.RULE_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  312. // init services
  313. tenantService := &TenantService{}
  314. ruleChainService := &RuleChainService{}
  315. actorContext := ruleEngine.NewSystemContext(system, ruleEngine.SystemContextServiceConfig{
  316. ClusterService: c.cluster,
  317. RuleChainService: ruleChainService,
  318. TenantService: tenantService,
  319. EventService: NewEventService(),
  320. })
  321. appActor, err := system.CreateRootActor(ruleEngine.APP_DISPATCHER_NAME,
  322. actors.NewAppActorCreator(actorContext))
  323. if err != nil {
  324. return nil, err
  325. }
  326. actorContext.AppActor = appActor
  327. server.Log.Debugln("actor system initialized")
  328. time.Sleep(time.Second * 1)
  329. appActor.Tell(&ruleEngine.AppInitMsg{})
  330. c.actorContext = actorContext
  331. return &ActorSystem{rootActor: appActor}, nil
  332. }
  333. // 启动mq consumers
  334. func (c *Controller) launchConsumer() {
  335. msgs, err := c.consumer.Pop(100 * time.Millisecond)
  336. if err != nil {
  337. server.Log.Error(err)
  338. }
  339. for {
  340. select {
  341. case msg := <-msgs:
  342. ruleEngineMsg := &protocol.Message{}
  343. if err := ruleEngineMsg.Decode(msg.GetData()); err != nil {
  344. fmt.Println("解析消息失败")
  345. }
  346. tenantId := msg.GetHeaders().Get("tenant_id")
  347. if c.actorContext != nil {
  348. c.actorContext.Tell(&ruleEngine.QueueToRuleEngineMsg{
  349. TenantId: string(tenantId),
  350. Message: ruleEngineMsg,
  351. })
  352. }
  353. }
  354. }
  355. }