actions.go 13 KB

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