actions.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/gogf/gf/encoding/gjson"
  7. "github.com/opentracing/opentracing-go/ext"
  8. "sparrow/pkg/productconfig"
  9. "sparrow/pkg/rpcs"
  10. "strings"
  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. statusargs := rpcs.ArgsGetStatus{
  103. Id: device.DeviceIdentifier,
  104. }
  105. statusreply := rpcs.ReplyGetStatus{}
  106. err := server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.GetStatus", statusargs, &statusreply)
  107. if err != nil {
  108. server.Log.Errorf("get device status error: %v", err)
  109. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  110. return
  111. }
  112. status, err := config.StatusToMap(statusreply.Status)
  113. if err != nil {
  114. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  115. return
  116. }
  117. result := DeviceStatusResponse{
  118. Data: status,
  119. }
  120. r.JSON(http.StatusOK, result)
  121. return
  122. }
  123. func GetDeviceStatusByFields(device *models.Device, config *productconfig.ProductConfig,
  124. urlparams martini.Params, req *http.Request, r render.Render) {
  125. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", device.DeviceIdentifier)
  126. fieldsParam := req.URL.Query().Get("fields")
  127. if fieldsParam == "" {
  128. r.JSON(http.StatusOK, renderError(ErrWrongQueryFormat, errBadRequestString))
  129. return
  130. }
  131. // 解析字段列表
  132. requestFields := strings.Split(fieldsParam, ",")
  133. statusargs := rpcs.ArgsGetStatus{
  134. Id: device.DeviceIdentifier,
  135. }
  136. statusreply := rpcs.ReplyGetStatus{}
  137. err := server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.GetStatus", statusargs, &statusreply)
  138. if err != nil {
  139. server.Log.Errorf("get device status error: %v", err)
  140. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  141. return
  142. }
  143. status, err := config.StatusToMap(statusreply.Status)
  144. if err != nil {
  145. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  146. return
  147. }
  148. j := gjson.New("")
  149. for _, v := range requestFields {
  150. _ = j.Set(v, status[v])
  151. }
  152. result := DeviceStatusFieldResponse{
  153. Data: *j,
  154. }
  155. r.JSON(http.StatusOK, result)
  156. return
  157. }
  158. // GetDeviceLatestStatus get device latest status
  159. func GetDeviceLatestStatus() {
  160. }
  161. // DeviceUpgrade 设备OTA升级
  162. func DeviceUpgrade(device *models.Device, urlparams martini.Params, req *http.Request, r render.Render) {
  163. var param DeviceUpgradeReq
  164. decoder := json.NewDecoder(req.Body)
  165. err := decoder.Decode(&param)
  166. if err != nil {
  167. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  168. return
  169. }
  170. server.Log.Infof("设备OTA升级:%s, %s", param.DeviceId, param.Version)
  171. //var args rpcs.ArgsDeviceUpgrade
  172. //args.DeviceId = param.DeviceId
  173. //args.SudDeviceId = param.SubDeviceId
  174. //args.Url = param.Url
  175. //args.Md5 = param.MD5
  176. //args.Version = param.Version
  177. //args.FileSize = param.FileSize
  178. var reply rpcs.ReplyEmptyResult
  179. args := rpcs.ArgsSendCommand{
  180. DeviceId: param.DeviceId,
  181. SubDevice: param.SubDeviceId,
  182. Cmd: "devUpgrade",
  183. Params: map[string]interface{}{
  184. "md5": param.MD5,
  185. "url": param.Url,
  186. "version": param.Version,
  187. "file_size": param.FileSize,
  188. },
  189. }
  190. err = server.RPCCallByName(nil, rpcs.ControllerName, "Controller.SendCommand", args, &reply)
  191. //err = server.RPCCallByName(context.Background(), rpcs.MQTTAccessName, "Access.Upgrade", args, &reply)
  192. if err != nil {
  193. server.Log.Errorf("设备OTA升级失败:", err)
  194. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  195. return
  196. }
  197. r.JSON(http.StatusOK, Common{})
  198. return
  199. }
  200. // SetDeviceStatus set device status
  201. func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
  202. urlparams martini.Params, req *http.Request, r render.Render) {
  203. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)
  204. var args interface{}
  205. decoder := json.NewDecoder(req.Body)
  206. err := decoder.Decode(&args)
  207. if err != nil {
  208. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  209. return
  210. }
  211. m, ok := args.(map[string]interface{})
  212. if !ok {
  213. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  214. return
  215. }
  216. status, err := config.MapToStatus(m)
  217. if err != nil {
  218. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  219. return
  220. }
  221. statusargs := rpcs.ArgsSetStatus{
  222. DeviceId: device.RecordId,
  223. Status: status,
  224. }
  225. statusreply := rpcs.ReplySetStatus{}
  226. //opentracing
  227. span, ctx := opentracing.StartSpanFromContext(context.Background(), "SetDeviceStatus")
  228. defer span.Finish()
  229. ext.SpanKindRPCClient.Set(span)
  230. err = server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.SetStatus", statusargs, &statusreply)
  231. if err != nil {
  232. server.Log.Errorf("set devie status error: %v", err)
  233. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  234. return
  235. }
  236. r.JSON(http.StatusOK, Common{})
  237. return
  238. }
  239. // SendCommandToDevice send command to device
  240. /*
  241. {
  242. "deviceCode": "5566",
  243. "subDeviceId": "1",
  244. "data": {
  245. "cmd": "powerControl",
  246. "params": {
  247. "power": 1,
  248. "temp":2
  249. }
  250. }
  251. }
  252. */
  253. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  254. urlparams martini.Params, req *http.Request, r render.Render) {
  255. timeout := req.URL.Query().Get("timeout")
  256. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  257. device.DeviceIdentifier, req.Body, timeout)
  258. var args map[string]interface{}
  259. decoder := json.NewDecoder(req.Body)
  260. err := decoder.Decode(&args)
  261. if err != nil {
  262. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  263. return
  264. }
  265. j := gjson.New(args)
  266. cmdargs := rpcs.ArgsSendCommand{
  267. DeviceId: device.DeviceIdentifier,
  268. SubDevice: j.GetString("subDeviceId"),
  269. WaitTime: uint32(defaultTimeOut),
  270. Params: j.GetMap("data.params"),
  271. Cmd: j.GetString("data.cmd"),
  272. }
  273. cmdreply := rpcs.ReplySendCommand{}
  274. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  275. if err != nil {
  276. server.Log.Errorf("send devie command error: %v", err)
  277. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  278. return
  279. }
  280. r.JSON(http.StatusOK, Common{})
  281. return
  282. }
  283. func SendCommandToDeviceV2(device *models.Device, config *productconfig.ProductConfig,
  284. urlparams martini.Params, req *http.Request, r render.Render) {
  285. timeout := req.URL.Query().Get("timeout")
  286. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  287. device.DeviceIdentifier, req.Body, timeout)
  288. var args map[string]interface{}
  289. decoder := json.NewDecoder(req.Body)
  290. err := decoder.Decode(&args)
  291. if err != nil {
  292. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  293. return
  294. }
  295. j := gjson.New(args)
  296. cmdargs := rpcs.ArgsSendCommand{
  297. DeviceId: device.DeviceIdentifier,
  298. SubDevice: j.GetString("subDeviceId"),
  299. WaitTime: uint32(defaultTimeOut),
  300. Params: j.GetMap("data.params"),
  301. Cmd: j.GetString("data.cmd"),
  302. }
  303. cmdreply := rpcs.ReplySendCommand{}
  304. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommandV2", cmdargs, &cmdreply)
  305. if err != nil {
  306. server.Log.Errorf("send devie command error: %v", err)
  307. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  308. return
  309. }
  310. r.JSON(http.StatusOK, Common{})
  311. return
  312. }
  313. // AddRule 增加设备规则
  314. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  315. var ruleReq CreateRuleRequest
  316. decoder := json.NewDecoder(req.Body)
  317. err := decoder.Decode(&ruleReq)
  318. if err != nil {
  319. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  320. return
  321. }
  322. rule := &models.Rule{
  323. DeviceID: device.RecordId,
  324. RuleType: ruleReq.Type,
  325. Trigger: ruleReq.Trigger,
  326. Target: ruleReq.Target,
  327. Action: ruleReq.Action,
  328. }
  329. reply := &rpcs.ReplyEmptyResult{}
  330. //opentracing
  331. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  332. defer span.Finish()
  333. ext.SpanKindRPCClient.Set(span)
  334. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  335. if err != nil {
  336. server.Log.Errorf("create device rule error: %v", err)
  337. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  338. return
  339. }
  340. r.JSON(http.StatusOK, Common{})
  341. return
  342. }
  343. func AppAuth(req *http.Request, r render.Render) {
  344. var ruleReq rpcs.ArgsAppAuth
  345. decoder := json.NewDecoder(req.Body)
  346. err := decoder.Decode(&ruleReq)
  347. if err != nil {
  348. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  349. return
  350. }
  351. app := &models.Application{}
  352. err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  353. if err != nil {
  354. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  355. return
  356. }
  357. if app.SecretKey != ruleReq.Secretkey {
  358. // device secret is wrong.
  359. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  360. return
  361. }
  362. token, timeSnap := TokenMaker(app)
  363. result := AppAuthDataResponse{
  364. AccessToken: token,
  365. ExpireAt: timeSnap,
  366. }
  367. r.JSON(http.StatusOK, Common{
  368. Result: result,
  369. })
  370. return
  371. }
  372. func CheckDeviceNetConfig(req *http.Request, r render.Render) {
  373. var params rpcs.ArgsCheckDeviceNetConfig
  374. params.DeviceCode = req.URL.Query().Get("device_code")
  375. params.Md5 = req.URL.Query().Get("md5")
  376. var reply rpcs.ReplyCheckDeviceNetConfig
  377. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.CheckDeviceNetConfig", &params, &reply)
  378. if err != nil {
  379. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  380. return
  381. }
  382. r.JSON(http.StatusOK, Common{
  383. Result: reply.Result,
  384. })
  385. }
  386. func CheckDeviceIsOnline(req *http.Request, r render.Render) {
  387. identifier := req.URL.Query().Get("device_code")
  388. device := &models.Device{}
  389. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier", identifier, device)
  390. if err != nil {
  391. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  392. return
  393. }
  394. onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
  395. Id: device.DeviceIdentifier,
  396. }
  397. onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
  398. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
  399. if err != nil || onlinereply.ClientIP == "" {
  400. r.JSON(http.StatusOK, Common{
  401. Result: 2,
  402. })
  403. }
  404. r.JSON(http.StatusOK, Common{
  405. Result: 1,
  406. })
  407. }
  408. func SubmitSceneTask(req *http.Request, r render.Render) {
  409. var ruleReq rpcs.ArgsSubmitTask
  410. decoder := json.NewDecoder(req.Body)
  411. err := decoder.Decode(&ruleReq)
  412. if err != nil {
  413. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  414. return
  415. }
  416. reply := rpcs.ReplySubmitTask{}
  417. server.Log.Debugf("submit sceneTask %v", ruleReq)
  418. err = server.RPCCallByName(nil, rpcs.SceneAccessServiceName, "SceneService.SubmitTask", ruleReq, &reply)
  419. if err != nil {
  420. server.Log.Errorf("submit sceneTask error: %v", err)
  421. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  422. return
  423. }
  424. r.JSON(http.StatusOK, Common{})
  425. return
  426. }
  427. func SubmitTaskLifecycle(req *http.Request, r render.Render) {
  428. var ruleReq rpcs.ArgsSubmitTaskLifecycle
  429. decoder := json.NewDecoder(req.Body)
  430. err := decoder.Decode(&ruleReq)
  431. if err != nil {
  432. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  433. return
  434. }
  435. reply := rpcs.ReplySubmitTask{}
  436. err = server.RPCCallByName(nil, rpcs.SceneAccessServiceName, "SceneService.SubmitTaskLifecycle", ruleReq, &reply)
  437. if err != nil {
  438. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  439. server.Log.Errorf("submit taskLifecycle error: %v", err)
  440. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  441. return
  442. }
  443. r.JSON(http.StatusOK, Common{})
  444. return
  445. }
  446. func SubmitSceneAction(req *http.Request, r render.Render) {
  447. var ruleReq rpcs.ArgsSubmitSceneAction
  448. decoder := json.NewDecoder(req.Body)
  449. err := decoder.Decode(&ruleReq)
  450. if err != nil {
  451. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  452. return
  453. }
  454. reply := rpcs.ReplySubmitSceneAction{}
  455. err = server.RPCCallByName(nil, rpcs.SceneServiceName, "SceneService.SubmitAction", ruleReq, &reply)
  456. if err != nil {
  457. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  458. server.Log.Errorf("submit scene-manager error: %v", err)
  459. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  460. return
  461. }
  462. r.JSON(http.StatusOK, Common{})
  463. return
  464. }