actions.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/gogf/gf/encoding/gjson"
  7. "sparrow/pkg/productconfig"
  8. "sparrow/pkg/rpcs"
  9. "github.com/opentracing/opentracing-go/ext"
  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. err = server.RPCCallByName(context.Background(), rpcs.MQTTAccessName, "Access.Upgrade", args, &reply)
  144. if err != nil {
  145. server.Log.Errorf("设备OTA升级失败:", err)
  146. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  147. return
  148. }
  149. r.JSON(http.StatusOK, Common{})
  150. return
  151. }
  152. // SetDeviceStatus set device status
  153. func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
  154. urlparams martini.Params, req *http.Request, r render.Render) {
  155. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)
  156. var args interface{}
  157. decoder := json.NewDecoder(req.Body)
  158. err := decoder.Decode(&args)
  159. if err != nil {
  160. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  161. return
  162. }
  163. m, ok := args.(map[string]interface{})
  164. if !ok {
  165. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  166. return
  167. }
  168. status, err := config.MapToStatus(m)
  169. if err != nil {
  170. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  171. return
  172. }
  173. statusargs := rpcs.ArgsSetStatus{
  174. DeviceId: device.RecordId,
  175. Status: status,
  176. }
  177. statusreply := rpcs.ReplySetStatus{}
  178. //opentracing
  179. span, ctx := opentracing.StartSpanFromContext(context.Background(), "SetDeviceStatus")
  180. defer span.Finish()
  181. ext.SpanKindRPCClient.Set(span)
  182. err = server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.SetStatus", statusargs, &statusreply)
  183. if err != nil {
  184. server.Log.Errorf("set devie status error: %v", err)
  185. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  186. return
  187. }
  188. r.JSON(http.StatusOK, Common{})
  189. return
  190. }
  191. // SendCommandToDevice send command to device
  192. /*
  193. {
  194. "deviceCode": "5566",
  195. "subDeviceId": "1",
  196. "data": {
  197. "cmd": "powerControl",
  198. "params": {
  199. "power": 1,
  200. "temp":2
  201. }
  202. }
  203. }
  204. */
  205. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  206. urlparams martini.Params, req *http.Request, r render.Render) {
  207. timeout := req.URL.Query().Get("timeout")
  208. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  209. device.DeviceIdentifier, req.Body, timeout)
  210. var args map[string]interface{}
  211. decoder := json.NewDecoder(req.Body)
  212. err := decoder.Decode(&args)
  213. if err != nil {
  214. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  215. return
  216. }
  217. j := gjson.New(args)
  218. cmdargs := rpcs.ArgsSendCommand{
  219. DeviceId: device.DeviceIdentifier,
  220. SubDevice: j.GetString("subDeviceId"),
  221. WaitTime: uint32(defaultTimeOut),
  222. Params: j.GetMap("data.params"),
  223. Cmd: j.GetString("data.cmd"),
  224. }
  225. cmdreply := rpcs.ReplySendCommand{}
  226. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  227. if err != nil {
  228. server.Log.Errorf("send devie command error: %v", err)
  229. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  230. return
  231. }
  232. r.JSON(http.StatusOK, Common{})
  233. return
  234. }
  235. func SendCommandToDeviceV2(device *models.Device, config *productconfig.ProductConfig,
  236. urlparams martini.Params, req *http.Request, r render.Render) {
  237. timeout := req.URL.Query().Get("timeout")
  238. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  239. device.DeviceIdentifier, req.Body, timeout)
  240. var args map[string]interface{}
  241. decoder := json.NewDecoder(req.Body)
  242. err := decoder.Decode(&args)
  243. if err != nil {
  244. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  245. return
  246. }
  247. j := gjson.New(args)
  248. cmdargs := rpcs.ArgsSendCommand{
  249. DeviceId: device.DeviceIdentifier,
  250. SubDevice: j.GetString("subDeviceId"),
  251. WaitTime: uint32(defaultTimeOut),
  252. Params: j.GetMap("data.params"),
  253. Cmd: j.GetString("data.cmd"),
  254. }
  255. cmdreply := rpcs.ReplySendCommand{}
  256. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommandV2", cmdargs, &cmdreply)
  257. if err != nil {
  258. server.Log.Errorf("send devie command error: %v", err)
  259. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  260. return
  261. }
  262. r.JSON(http.StatusOK, Common{})
  263. return
  264. }
  265. // AddRule 增加设备规则
  266. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  267. var ruleReq CreateRuleRequest
  268. decoder := json.NewDecoder(req.Body)
  269. err := decoder.Decode(&ruleReq)
  270. if err != nil {
  271. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  272. return
  273. }
  274. rule := &models.Rule{
  275. DeviceID: device.RecordId,
  276. RuleType: ruleReq.Type,
  277. Trigger: ruleReq.Trigger,
  278. Target: ruleReq.Target,
  279. Action: ruleReq.Action,
  280. }
  281. reply := &rpcs.ReplyEmptyResult{}
  282. //opentracing
  283. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  284. defer span.Finish()
  285. ext.SpanKindRPCClient.Set(span)
  286. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  287. if err != nil {
  288. server.Log.Errorf("create device rule error: %v", err)
  289. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  290. return
  291. }
  292. r.JSON(http.StatusOK, Common{})
  293. return
  294. }
  295. func AppAuth(req *http.Request, r render.Render) {
  296. var ruleReq rpcs.ArgsAppAuth
  297. decoder := json.NewDecoder(req.Body)
  298. err := decoder.Decode(&ruleReq)
  299. if err != nil {
  300. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  301. return
  302. }
  303. app := &models.Application{}
  304. err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  305. if err != nil {
  306. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  307. return
  308. }
  309. if app.SecretKey != ruleReq.Secretkey {
  310. // device secret is wrong.
  311. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  312. return
  313. }
  314. token, timeSnap := TokenMaker(app)
  315. result := AppAuthDataResponse{
  316. AccessToken: token,
  317. ExpireAt: timeSnap,
  318. }
  319. r.JSON(http.StatusOK, Common{
  320. Result: result,
  321. })
  322. return
  323. }
  324. func CheckDeviceNetConfig(req *http.Request, r render.Render) {
  325. var params rpcs.ArgsCheckDeviceNetConfig
  326. params.DeviceCode = req.URL.Query().Get("device_code")
  327. params.Md5 = req.URL.Query().Get("md5")
  328. var reply rpcs.ReplyCheckDeviceNetConfig
  329. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.CheckDeviceNetConfig", &params, &reply)
  330. if err != nil {
  331. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  332. return
  333. }
  334. r.JSON(http.StatusOK, Common{
  335. Result: reply.Result,
  336. })
  337. }
  338. func CheckDeviceIsOnline(req *http.Request, r render.Render) {
  339. identifier := req.URL.Query().Get("device_code")
  340. device := &models.Device{}
  341. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier", identifier, device)
  342. if err != nil {
  343. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  344. return
  345. }
  346. onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
  347. Id: device.DeviceIdentifier,
  348. }
  349. onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
  350. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
  351. if err != nil || onlinereply.ClientIP == "" {
  352. r.JSON(http.StatusOK, Common{
  353. Result: 2,
  354. })
  355. }
  356. r.JSON(http.StatusOK, Common{
  357. Result: 1,
  358. })
  359. }
  360. func SubmitSceneTask(req *http.Request, r render.Render) {
  361. var ruleReq rpcs.ArgsSubmitTask
  362. decoder := json.NewDecoder(req.Body)
  363. err := decoder.Decode(&ruleReq)
  364. if err != nil {
  365. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  366. return
  367. }
  368. reply := rpcs.ReplySubmitTask{}
  369. server.Log.Debugf("submit sceneTask %v", ruleReq)
  370. err = server.RPCCallByName(nil, rpcs.SceneAccessServiceName, "SceneService.SubmitTask", ruleReq, &reply)
  371. if err != nil {
  372. server.Log.Errorf("submit sceneTask error: %v", err)
  373. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  374. return
  375. }
  376. r.JSON(http.StatusOK, Common{})
  377. return
  378. }
  379. func SubmitTaskLifecycle(req *http.Request, r render.Render) {
  380. var ruleReq rpcs.ArgsSubmitTaskLifecycle
  381. decoder := json.NewDecoder(req.Body)
  382. err := decoder.Decode(&ruleReq)
  383. if err != nil {
  384. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  385. return
  386. }
  387. reply := rpcs.ReplySubmitTask{}
  388. err = server.RPCCallByName(nil, rpcs.SceneAccessServiceName, "SceneService.SubmitTaskLifecycle", ruleReq, &reply)
  389. if err != nil {
  390. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  391. server.Log.Errorf("submit taskLifecycle error: %v", err)
  392. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  393. return
  394. }
  395. r.JSON(http.StatusOK, Common{})
  396. return
  397. }