controller.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. fmt.Printf("收到设备消息:%s", args.DeviceId)
  143. t := time.Unix(int64(args.Timestamp/1000), 0)
  144. data, err := c.processStatusToQueue(args)
  145. if err != nil {
  146. return err
  147. }
  148. msg := &protocol.Message{
  149. Id: guid.S(),
  150. Ts: &t,
  151. Type: protocol.POST_ATTRIBUTES_REQUEST,
  152. Data: data,
  153. Callback: nil,
  154. MetaData: map[string]interface{}{
  155. "vendor_id": args.VendorId,
  156. "device_id": args.DeviceId,
  157. "sub_device_id": args.SubDeviceId,
  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. "type": "EVENT",
  218. "timestamp": strconv.Itoa(int(args.TimeStamp)),
  219. },
  220. Originator: "device",
  221. }
  222. tpi := queue.ResolvePartition("RULE_ENGINE",
  223. msg.GetQueueName(),
  224. args.VendorId,
  225. args.DeviceId)
  226. g, err := queue.NewGobQueueMessage(msg)
  227. if err != nil {
  228. return err
  229. }
  230. g.Headers.Put("tenant_id", []byte(args.VendorId))
  231. return c.producer.Send(tpi, g, nil)
  232. }
  233. // CreateRuleChain 规则链生命周期-创建
  234. func (c *Controller) CreateRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  235. if c.actorContext != nil {
  236. msg := &ruleEngine.ComponentLifecycleMsg{
  237. TenantId: args.VendorId,
  238. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  239. EventType: ruleEngine.CREATED,
  240. }
  241. c.actorContext.AppActor.TellWithHighPriority(msg)
  242. }
  243. return nil
  244. }
  245. // DeleteRuleChain 规则链生命周期-删除
  246. func (c *Controller) DeleteRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  247. if c.actorContext != nil {
  248. msg := &ruleEngine.ComponentLifecycleMsg{
  249. TenantId: args.VendorId,
  250. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  251. EventType: ruleEngine.DELETED,
  252. }
  253. c.actorContext.AppActor.TellWithHighPriority(msg)
  254. }
  255. return nil
  256. }
  257. // UpdateRuleChain 规则链生命周期-更新
  258. func (c *Controller) UpdateRuleChain(args rpcs.ArgsRuleChainAct, reply *rpcs.ReplyEmptyResult) error {
  259. if c.actorContext != nil {
  260. msg := &ruleEngine.ComponentLifecycleMsg{
  261. TenantId: args.VendorId,
  262. EntityId: &entities.RuleChainId{Id: args.RuleChainId},
  263. EventType: ruleEngine.UPDATED,
  264. }
  265. c.actorContext.AppActor.TellWithHighPriority(msg)
  266. }
  267. return nil
  268. }
  269. // SendCommand 下发设备控制指令
  270. func (c *Controller) SendCommand(args rpcs.ArgsSendCommand, reply *rpcs.ReplySendCommand) error {
  271. rpchost, err := getAccessRPCHost(args.DeviceId)
  272. if err != nil {
  273. return err
  274. }
  275. return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
  276. }
  277. func getAccessRPCHost(deviceid string) (string, error) {
  278. args := rpcs.ArgsGetDeviceOnlineStatus{
  279. Id: deviceid,
  280. }
  281. reply := &rpcs.ReplyGetDeviceOnlineStatus{}
  282. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", args, reply)
  283. if err != nil {
  284. return "", err
  285. }
  286. return reply.AccessRPCHost, nil
  287. }
  288. // ActorSystem actor system
  289. type ActorSystem struct {
  290. rootActor ruleEngine.Ref
  291. }
  292. // 初始化actor system
  293. func (c *Controller) initActorSystem() (*ActorSystem, error) {
  294. system := ruleEngine.NewDefaultActorSystem(&ruleEngine.DefaultActorSystemConfig{
  295. SchedulerPoolSize: 5,
  296. AppDispatcherPoolSize: 4,
  297. TenantDispatcherPoolSize: 4,
  298. RuleEngineDispatcherPoolSize: 4,
  299. })
  300. _ = system.CreateDispatcher(ruleEngine.APP_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  301. _ = system.CreateDispatcher(ruleEngine.TENANT_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  302. _ = system.CreateDispatcher(ruleEngine.RULE_DISPATCHER_NAME, ruleEngine.NewPoolDispatcher(0))
  303. // init services
  304. tenantService := &TenantService{}
  305. ruleChainService := &RuleChainService{}
  306. actorContext := ruleEngine.NewSystemContext(system, ruleEngine.SystemContextServiceConfig{
  307. ClusterService: c.cluster,
  308. RuleChainService: ruleChainService,
  309. TenantService: tenantService,
  310. EventService: NewEventService(),
  311. })
  312. appActor, err := system.CreateRootActor(ruleEngine.APP_DISPATCHER_NAME,
  313. actors.NewAppActorCreator(actorContext))
  314. if err != nil {
  315. return nil, err
  316. }
  317. actorContext.AppActor = appActor
  318. server.Log.Debugln("actor system initialized")
  319. time.Sleep(time.Second * 1)
  320. appActor.Tell(&ruleEngine.AppInitMsg{})
  321. c.actorContext = actorContext
  322. return &ActorSystem{rootActor: appActor}, nil
  323. }
  324. // 启动mq consumers
  325. func (c *Controller) launchConsumer() {
  326. msgs, err := c.consumer.Pop(100 * time.Millisecond)
  327. if err != nil {
  328. server.Log.Error(err)
  329. }
  330. for {
  331. select {
  332. case msg := <-msgs:
  333. ruleEngineMsg := &protocol.Message{}
  334. if err := ruleEngineMsg.Decode(msg.GetData()); err != nil {
  335. fmt.Println("解析消息失败")
  336. }
  337. tenantId := msg.GetHeaders().Get("tenant_id")
  338. if c.actorContext != nil {
  339. c.actorContext.Tell(&ruleEngine.QueueToRuleEngineMsg{
  340. TenantId: string(tenantId),
  341. Message: ruleEngineMsg,
  342. })
  343. }
  344. }
  345. }
  346. }