actions.go 10 KB

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