actions.go 13 KB

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