actions.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "sparrow/pkg/productconfig"
  7. "sparrow/pkg/rpcs"
  8. "strings"
  9. "github.com/gogf/gf/encoding/gjson"
  10. "github.com/opentracing/opentracing-go/ext"
  11. "github.com/opentracing/opentracing-go"
  12. "net/http"
  13. "sparrow/pkg/models"
  14. "sparrow/pkg/server"
  15. "github.com/go-martini/martini"
  16. "github.com/martini-contrib/render"
  17. )
  18. const (
  19. ErrOK = 0
  20. ErrSystemFault = 10001
  21. ErrProductNotFound = 10002
  22. ErrDeviceNotFound = 10003
  23. ErrDeviceNotOnline = 10004
  24. ErrWrongRequestFormat = 10005
  25. ErrWrongProductConfig = 10006
  26. ErrWrongQueryFormat = 10007
  27. ErrAccessDenied = 10008
  28. ErrIllegalityAction = 10009 //非法操作
  29. ErrWrongSecret = 10010 //
  30. )
  31. var (
  32. // ErrBadRequestString 参数不全错误
  33. errBadRequestString = errors.New("请求参数不全")
  34. errIllegalityString = errors.New("非法操作")
  35. )
  36. const (
  37. defaultTimeOut = 0 // seconds
  38. )
  39. func renderError(code int, err error) Common {
  40. result := Common{}
  41. result.Code = code
  42. result.Message = err.Error()
  43. server.Log.Error(err.Error())
  44. return result
  45. }
  46. func done(result interface{}) Common {
  47. return Common{
  48. Code: ErrOK,
  49. Message: "success",
  50. Result: result,
  51. }
  52. }
  53. // GetDeviceInfoByKey get device info with device key
  54. func GetDeviceInfoByKey(params martini.Params, req *http.Request, r render.Render) {
  55. key := req.URL.Query().Get("device_key")
  56. server.Log.Printf("ACTION GetDeviceInfoByKey, key:: %v", key)
  57. device := &models.Device{}
  58. span, ctx := opentracing.StartSpanFromContext(context.Background(), "GetDeviceInfoByKey")
  59. defer span.Finish()
  60. ext.SpanKindRPCClient.Set(span)
  61. span.SetTag("device_key", key)
  62. err := server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.ValidateDevice", key, device)
  63. if err != nil {
  64. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  65. return
  66. }
  67. result := DeviceInfoResponse{
  68. Data: DeviceInfoData{
  69. Identifier: device.DeviceIdentifier,
  70. Name: device.DeviceName,
  71. Description: device.DeviceDescription,
  72. Version: device.DeviceVersion,
  73. },
  74. }
  75. r.JSON(http.StatusOK, result)
  76. return
  77. }
  78. // GetDeviceInfoByIdentifier get device info with device identifier
  79. func GetDeviceInfoByIdentifier(urlparams martini.Params, r render.Render) {
  80. identifier := urlparams["identifier"]
  81. server.Log.Printf("ACTION GetDeviceInfoByIdentifier, identifier:: %v", identifier)
  82. device := &models.Device{}
  83. err := server.RPCCallByName(context.Background(), rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier2", identifier, device)
  84. if err != nil {
  85. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  86. return
  87. }
  88. result := DeviceInfoResponse{
  89. Data: DeviceInfoData{
  90. Identifier: device.DeviceIdentifier,
  91. Name: device.DeviceName,
  92. Description: device.DeviceDescription,
  93. Version: device.DeviceVersion,
  94. },
  95. }
  96. r.JSON(http.StatusOK, result)
  97. return
  98. }
  99. func GetDeviceCurrentStatus(device *models.Device, config *productconfig.ProductConfig,
  100. urlparams martini.Params, r render.Render) {
  101. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", device.DeviceIdentifier)
  102. // 1. 触发设备上报状态(下发指令,不等待返回)
  103. triggerArgs := rpcs.ArgsGetStatus{Id: device.DeviceIdentifier}
  104. triggerReply := rpcs.ReplyGetStatus{}
  105. err := server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.GetStatus", triggerArgs, &triggerReply)
  106. if err != nil {
  107. server.Log.Errorf("trigger device status error: %v", err)
  108. }
  109. // 2. 从 DeviceManager 获取实际存储的状态数据
  110. args := rpcs.ArgsGetStatus{Id: device.DeviceIdentifier}
  111. reply := rpcs.ReplyStatus{}
  112. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceStatus", args, &reply)
  113. if err != nil {
  114. server.Log.Errorf("获取设备状态数据失败: %v", err)
  115. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  116. return
  117. }
  118. if reply.Status == "" {
  119. r.JSON(http.StatusOK, DeviceStatusResponse{Data: map[string]interface{}{}})
  120. return
  121. }
  122. // 3. 解析 JSON 字符串
  123. var status map[string]interface{}
  124. if err := json.Unmarshal([]byte(reply.Status), &status); err != nil {
  125. server.Log.Errorf("解析设备状态数据失败: %v", err)
  126. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  127. return
  128. }
  129. r.JSON(http.StatusOK, DeviceStatusResponse{Data: status})
  130. return
  131. }
  132. func GetDeviceStatusByFields(device *models.Device, config *productconfig.ProductConfig,
  133. urlparams martini.Params, req *http.Request, r render.Render) {
  134. server.Log.Printf("ACTION GetDeviceStatusByFields, identifier:: %v", device.DeviceIdentifier)
  135. fieldsParam := req.URL.Query().Get("fields")
  136. if fieldsParam == "" {
  137. r.JSON(http.StatusOK, renderError(ErrWrongQueryFormat, errBadRequestString))
  138. return
  139. }
  140. requestFields := strings.Split(fieldsParam, ",")
  141. // 触发设备上报状态
  142. triggerArgs := rpcs.ArgsGetStatus{Id: device.DeviceIdentifier}
  143. triggerReply := rpcs.ReplyGetStatus{}
  144. err := server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.GetStatus", triggerArgs, &triggerReply)
  145. if err != nil {
  146. server.Log.Errorf("trigger device status error: %v", err)
  147. }
  148. // 从 DeviceManager 获取实际存储的状态数据
  149. args := rpcs.ArgsGetStatus{Id: device.DeviceIdentifier}
  150. reply := rpcs.ReplyStatus{}
  151. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceStatus", args, &reply)
  152. if err != nil {
  153. server.Log.Errorf("获取设备状态数据失败: %v", err)
  154. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  155. return
  156. }
  157. if reply.Status == "" {
  158. r.JSON(http.StatusOK, DeviceStatusFieldResponse{Data: *gjson.New("")})
  159. return
  160. }
  161. // 解析 JSON 字符串
  162. var status map[string]interface{}
  163. if err := json.Unmarshal([]byte(reply.Status), &status); err != nil {
  164. server.Log.Errorf("解析设备状态数据失败: %v", err)
  165. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  166. return
  167. }
  168. // 按指定字段过滤
  169. j := gjson.New("")
  170. for _, field := range requestFields {
  171. if val, ok := status[field]; ok {
  172. _ = j.Set(field, val)
  173. }
  174. }
  175. r.JSON(http.StatusOK, DeviceStatusFieldResponse{Data: *j})
  176. return
  177. }
  178. // GetDeviceLatestStatus get device latest status
  179. func GetDeviceLatestStatus() {
  180. }
  181. // DeviceUpgrade 设备OTA升级
  182. func DeviceUpgrade(device *models.Device, urlparams martini.Params, req *http.Request, r render.Render) {
  183. var param DeviceUpgradeReq
  184. decoder := json.NewDecoder(req.Body)
  185. err := decoder.Decode(&param)
  186. if err != nil {
  187. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  188. return
  189. }
  190. server.Log.Infof("设备OTA升级:%s, %s", param.DeviceId, param.Version)
  191. //var args rpcs.ArgsDeviceUpgrade
  192. //args.DeviceId = param.DeviceId
  193. //args.SudDeviceId = param.SubDeviceId
  194. //args.Url = param.Url
  195. //args.Md5 = param.MD5
  196. //args.Version = param.Version
  197. //args.FileSize = param.FileSize
  198. var reply rpcs.ReplyEmptyResult
  199. args := rpcs.ArgsSendCommand{
  200. DeviceId: param.DeviceId,
  201. SubDevice: param.SubDeviceId,
  202. Cmd: "devUpgrade",
  203. Params: map[string]interface{}{
  204. "md5": param.MD5,
  205. "url": param.Url,
  206. "version": param.Version,
  207. "file_size": param.FileSize,
  208. },
  209. }
  210. err = server.RPCCallByName(nil, rpcs.ControllerName, "Controller.SendCommand", args, &reply)
  211. //err = server.RPCCallByName(context.Background(), rpcs.MQTTAccessName, "Access.Upgrade", args, &reply)
  212. if err != nil {
  213. server.Log.Errorf("设备OTA升级失败:", err)
  214. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  215. return
  216. }
  217. r.JSON(http.StatusOK, Common{})
  218. return
  219. }
  220. // SetDeviceStatus set device status
  221. func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
  222. urlparams martini.Params, req *http.Request, r render.Render) {
  223. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)
  224. var args interface{}
  225. decoder := json.NewDecoder(req.Body)
  226. err := decoder.Decode(&args)
  227. if err != nil {
  228. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  229. return
  230. }
  231. m, ok := args.(map[string]interface{})
  232. if !ok {
  233. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  234. return
  235. }
  236. status, err := config.MapToStatus(m)
  237. if err != nil {
  238. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  239. return
  240. }
  241. statusargs := rpcs.ArgsSetStatus{
  242. DeviceId: device.RecordId,
  243. Status: status,
  244. }
  245. statusreply := rpcs.ReplySetStatus{}
  246. //opentracing
  247. span, ctx := opentracing.StartSpanFromContext(context.Background(), "SetDeviceStatus")
  248. defer span.Finish()
  249. ext.SpanKindRPCClient.Set(span)
  250. err = server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.SetStatus", statusargs, &statusreply)
  251. if err != nil {
  252. server.Log.Errorf("set devie status error: %v", err)
  253. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  254. return
  255. }
  256. r.JSON(http.StatusOK, Common{})
  257. return
  258. }
  259. // SendCommandToDevice send command to device
  260. /*
  261. {
  262. "deviceCode": "5566",
  263. "subDeviceId": "1",
  264. "data": {
  265. "cmd": "powerControl",
  266. "params": {
  267. "power": 1,
  268. "temp":2
  269. }
  270. }
  271. }
  272. */
  273. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  274. urlparams martini.Params, req *http.Request, r render.Render) {
  275. timeout := req.URL.Query().Get("timeout")
  276. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  277. device.DeviceIdentifier, req.Body, timeout)
  278. var args map[string]interface{}
  279. decoder := json.NewDecoder(req.Body)
  280. err := decoder.Decode(&args)
  281. if err != nil {
  282. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  283. return
  284. }
  285. j := gjson.New(args)
  286. cmdargs := rpcs.ArgsSendCommand{
  287. DeviceId: device.DeviceIdentifier,
  288. SubDevice: j.GetString("subDeviceId"),
  289. WaitTime: uint32(defaultTimeOut),
  290. Params: j.GetMap("data.params"),
  291. Cmd: j.GetString("data.cmd"),
  292. }
  293. cmdreply := rpcs.ReplySendCommand{}
  294. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  295. if err != nil {
  296. server.Log.Errorf("send devie command error: %v", err)
  297. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  298. return
  299. }
  300. r.JSON(http.StatusOK, Common{})
  301. return
  302. }
  303. func SendCommandToDeviceV2(device *models.Device, config *productconfig.ProductConfig,
  304. urlparams martini.Params, req *http.Request, r render.Render) {
  305. timeout := req.URL.Query().Get("timeout")
  306. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  307. device.DeviceIdentifier, req.Body, timeout)
  308. var args map[string]interface{}
  309. decoder := json.NewDecoder(req.Body)
  310. err := decoder.Decode(&args)
  311. if err != nil {
  312. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  313. return
  314. }
  315. j := gjson.New(args)
  316. cmdargs := rpcs.ArgsSendCommand{
  317. DeviceId: device.DeviceIdentifier,
  318. SubDevice: j.GetString("subDeviceId"),
  319. WaitTime: uint32(defaultTimeOut),
  320. Params: j.GetMap("data.params"),
  321. Cmd: j.GetString("data.cmd"),
  322. }
  323. cmdreply := rpcs.ReplySendCommand{}
  324. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommandV2", cmdargs, &cmdreply)
  325. if err != nil {
  326. server.Log.Errorf("send devie command error: %v", err)
  327. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  328. return
  329. }
  330. r.JSON(http.StatusOK, Common{})
  331. return
  332. }
  333. // AddRule 增加设备规则
  334. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  335. var ruleReq CreateRuleRequest
  336. decoder := json.NewDecoder(req.Body)
  337. err := decoder.Decode(&ruleReq)
  338. if err != nil {
  339. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  340. return
  341. }
  342. rule := &models.Rule{
  343. DeviceID: device.RecordId,
  344. RuleType: ruleReq.Type,
  345. Trigger: ruleReq.Trigger,
  346. Target: ruleReq.Target,
  347. Action: ruleReq.Action,
  348. }
  349. reply := &rpcs.ReplyEmptyResult{}
  350. //opentracing
  351. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  352. defer span.Finish()
  353. ext.SpanKindRPCClient.Set(span)
  354. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  355. if err != nil {
  356. server.Log.Errorf("create device rule error: %v", err)
  357. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  358. return
  359. }
  360. r.JSON(http.StatusOK, Common{})
  361. return
  362. }
  363. func AppAuth(req *http.Request, r render.Render) {
  364. var ruleReq rpcs.ArgsAppAuth
  365. decoder := json.NewDecoder(req.Body)
  366. err := decoder.Decode(&ruleReq)
  367. if err != nil {
  368. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  369. return
  370. }
  371. app := &models.Application{}
  372. err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  373. if err != nil {
  374. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  375. return
  376. }
  377. if app.SecretKey != ruleReq.Secretkey {
  378. // device secret is wrong.
  379. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  380. return
  381. }
  382. token, timeSnap := TokenMaker(app)
  383. result := AppAuthDataResponse{
  384. AccessToken: token,
  385. ExpireAt: timeSnap,
  386. }
  387. r.JSON(http.StatusOK, Common{
  388. Result: result,
  389. })
  390. return
  391. }
  392. func CheckDeviceNetConfig(req *http.Request, r render.Render) {
  393. var params rpcs.ArgsCheckDeviceNetConfig
  394. params.DeviceCode = req.URL.Query().Get("device_code")
  395. params.Md5 = req.URL.Query().Get("md5")
  396. var reply rpcs.ReplyCheckDeviceNetConfig
  397. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.CheckDeviceNetConfig", &params, &reply)
  398. if err != nil {
  399. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  400. return
  401. }
  402. r.JSON(http.StatusOK, Common{
  403. Result: reply.Result,
  404. })
  405. }
  406. func CheckDeviceIsOnline(req *http.Request, r render.Render) {
  407. identifier := req.URL.Query().Get("device_code")
  408. device := &models.Device{}
  409. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier", identifier, device)
  410. if err != nil {
  411. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  412. return
  413. }
  414. onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
  415. Id: device.DeviceIdentifier,
  416. }
  417. onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
  418. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
  419. if err != nil || onlinereply.ClientIP == "" {
  420. r.JSON(http.StatusOK, Common{
  421. Result: 2,
  422. })
  423. }
  424. r.JSON(http.StatusOK, Common{
  425. Result: 1,
  426. })
  427. }
  428. func SubmitSceneTask(req *http.Request, r render.Render) {
  429. var ruleReq rpcs.ArgsSubmitTask
  430. decoder := json.NewDecoder(req.Body)
  431. err := decoder.Decode(&ruleReq)
  432. if err != nil {
  433. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  434. return
  435. }
  436. reply := rpcs.ReplySubmitTask{}
  437. server.Log.Debugf("submit sceneTask %v", ruleReq)
  438. err = server.RPCCallByName(nil, rpcs.SceneAccessServiceName, "SceneService.SubmitTask", ruleReq, &reply)
  439. if err != nil {
  440. server.Log.Errorf("submit sceneTask error: %v", err)
  441. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  442. return
  443. }
  444. r.JSON(http.StatusOK, Common{})
  445. return
  446. }
  447. func SubmitTaskLifecycle(req *http.Request, r render.Render) {
  448. var ruleReq rpcs.ArgsSubmitTaskLifecycle
  449. decoder := json.NewDecoder(req.Body)
  450. err := decoder.Decode(&ruleReq)
  451. if err != nil {
  452. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  453. return
  454. }
  455. reply := rpcs.ReplySubmitTask{}
  456. err = server.RPCCallByName(nil, rpcs.SceneAccessServiceName, "SceneService.SubmitTaskLifecycle", ruleReq, &reply)
  457. if err != nil {
  458. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  459. server.Log.Errorf("submit taskLifecycle error: %v", err)
  460. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  461. return
  462. }
  463. r.JSON(http.StatusOK, Common{})
  464. return
  465. }
  466. func SubmitSceneAction(req *http.Request, r render.Render) {
  467. var ruleReq rpcs.ArgsSubmitSceneAction
  468. decoder := json.NewDecoder(req.Body)
  469. err := decoder.Decode(&ruleReq)
  470. if err != nil {
  471. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  472. return
  473. }
  474. reply := rpcs.ReplySubmitSceneAction{}
  475. err = server.RPCCallByName(nil, rpcs.SceneServiceName, "SceneService.SubmitAction", ruleReq, &reply)
  476. if err != nil {
  477. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  478. server.Log.Errorf("submit scene-manager error: %v", err)
  479. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  480. return
  481. }
  482. r.JSON(http.StatusOK, Common{})
  483. return
  484. }