actions.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. var args rpcs.ArgsDeviceUpgrade
  135. args.DeviceId = param.DeviceId
  136. args.SudDeviceId = param.SubDeviceId
  137. args.Url = param.Url
  138. args.Md5 = param.MD5
  139. args.Version = param.Version
  140. args.FileSize = param.FileSize
  141. var reply rpcs.ReplyEmptyResult
  142. err = server.RPCCallByName(context.Background(), rpcs.MQTTAccessName, "Access.Upgrade", args, &reply)
  143. if err != nil {
  144. server.Log.Errorf("设备OTA升级失败:", err)
  145. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  146. return
  147. }
  148. r.JSON(http.StatusOK, Common{})
  149. return
  150. }
  151. // SetDeviceStatus set device status
  152. func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
  153. urlparams martini.Params, req *http.Request, r render.Render) {
  154. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)
  155. var args interface{}
  156. decoder := json.NewDecoder(req.Body)
  157. err := decoder.Decode(&args)
  158. if err != nil {
  159. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  160. return
  161. }
  162. m, ok := args.(map[string]interface{})
  163. if !ok {
  164. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  165. return
  166. }
  167. status, err := config.MapToStatus(m)
  168. if err != nil {
  169. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  170. return
  171. }
  172. statusargs := rpcs.ArgsSetStatus{
  173. DeviceId: device.RecordId,
  174. Status: status,
  175. }
  176. statusreply := rpcs.ReplySetStatus{}
  177. //opentracing
  178. span, ctx := opentracing.StartSpanFromContext(context.Background(), "SetDeviceStatus")
  179. defer span.Finish()
  180. ext.SpanKindRPCClient.Set(span)
  181. err = server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.SetStatus", statusargs, &statusreply)
  182. if err != nil {
  183. server.Log.Errorf("set devie status error: %v", err)
  184. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  185. return
  186. }
  187. r.JSON(http.StatusOK, Common{})
  188. return
  189. }
  190. // SendCommandToDevice send command to device
  191. /*
  192. {
  193. "deviceCode": "5566",
  194. "subDeviceId": "1",
  195. "data": {
  196. "cmd": "powerControl",
  197. "params": {
  198. "power": 1,
  199. "temp":2
  200. }
  201. }
  202. }
  203. */
  204. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  205. urlparams martini.Params, req *http.Request, r render.Render) {
  206. timeout := req.URL.Query().Get("timeout")
  207. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  208. device.DeviceIdentifier, req.Body, timeout)
  209. var args map[string]interface{}
  210. decoder := json.NewDecoder(req.Body)
  211. err := decoder.Decode(&args)
  212. if err != nil {
  213. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  214. return
  215. }
  216. j := gjson.New(args)
  217. cmdargs := rpcs.ArgsSendCommand{
  218. DeviceId: device.DeviceIdentifier,
  219. SubDevice: j.GetString("subDeviceId"),
  220. WaitTime: uint32(defaultTimeOut),
  221. Params: j.GetMap("data.params"),
  222. Cmd: j.GetString("data.cmd"),
  223. }
  224. cmdreply := rpcs.ReplySendCommand{}
  225. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  226. if err != nil {
  227. server.Log.Errorf("send devie command error: %v", err)
  228. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  229. return
  230. }
  231. r.JSON(http.StatusOK, Common{})
  232. return
  233. }
  234. // AddRule 增加设备规则
  235. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  236. var ruleReq CreateRuleRequest
  237. decoder := json.NewDecoder(req.Body)
  238. err := decoder.Decode(&ruleReq)
  239. if err != nil {
  240. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  241. return
  242. }
  243. rule := &models.Rule{
  244. DeviceID: device.RecordId,
  245. RuleType: ruleReq.Type,
  246. Trigger: ruleReq.Trigger,
  247. Target: ruleReq.Target,
  248. Action: ruleReq.Action,
  249. }
  250. reply := &rpcs.ReplyEmptyResult{}
  251. //opentracing
  252. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  253. defer span.Finish()
  254. ext.SpanKindRPCClient.Set(span)
  255. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  256. if err != nil {
  257. server.Log.Errorf("create device rule error: %v", err)
  258. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  259. return
  260. }
  261. r.JSON(http.StatusOK, Common{})
  262. return
  263. }
  264. func AppAuth(req *http.Request, r render.Render) {
  265. var ruleReq rpcs.ArgsAppAuth
  266. decoder := json.NewDecoder(req.Body)
  267. err := decoder.Decode(&ruleReq)
  268. if err != nil {
  269. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  270. return
  271. }
  272. app := &models.Application{}
  273. err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  274. if err != nil {
  275. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  276. return
  277. }
  278. if app.SecretKey != ruleReq.Secretkey {
  279. // device secret is wrong.
  280. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  281. return
  282. }
  283. token, timeSnap := TokenMaker(app)
  284. result := AppAuthDataResponse{
  285. AccessToken: token,
  286. ExpireAt: timeSnap,
  287. }
  288. r.JSON(http.StatusOK, Common{
  289. Result: result,
  290. })
  291. return
  292. }
  293. func CheckDeviceNetConfig(req *http.Request, r render.Render) {
  294. var params rpcs.ArgsCheckDeviceNetConfig
  295. params.DeviceCode = req.URL.Query().Get("device_code")
  296. params.Md5 = req.URL.Query().Get("md5")
  297. var reply rpcs.ReplyCheckDeviceNetConfig
  298. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.CheckDeviceNetConfig", &params, &reply)
  299. if err != nil {
  300. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  301. return
  302. }
  303. r.JSON(http.StatusOK, Common{
  304. Result: reply.Result,
  305. })
  306. }
  307. func CheckDeviceIsOnline(req *http.Request, r render.Render) {
  308. identifier := req.URL.Query().Get("device_code")
  309. device := &models.Device{}
  310. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier", identifier, device)
  311. if err != nil {
  312. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  313. return
  314. }
  315. onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
  316. Id: device.DeviceIdentifier,
  317. }
  318. onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
  319. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
  320. if err != nil || onlinereply.ClientIP == "" {
  321. r.JSON(http.StatusOK, Common{
  322. Result: 2,
  323. })
  324. }
  325. r.JSON(http.StatusOK, Common{
  326. Result: 1,
  327. })
  328. }