actions.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 = 3 // 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. span, ctx := opentracing.StartSpanFromContext(context.Background(), "GetDeviceInfoByIdentifier")
  83. defer span.Finish()
  84. ext.SpanKindRPCClient.Set(span)
  85. span.SetTag("identifier", identifier)
  86. err := server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier", identifier, device)
  87. if err != nil {
  88. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  89. return
  90. }
  91. result := DeviceInfoResponse{
  92. Data: DeviceInfoData{
  93. Identifier: device.DeviceIdentifier,
  94. Name: device.DeviceName,
  95. Description: device.DeviceDescription,
  96. Version: device.DeviceVersion,
  97. },
  98. }
  99. r.JSON(http.StatusOK, result)
  100. return
  101. }
  102. func GetDeviceCurrentStatus(device *models.Device, config *productconfig.ProductConfig,
  103. urlparams martini.Params, r render.Render) {
  104. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", device.DeviceIdentifier)
  105. statusargs := rpcs.ArgsGetStatus{
  106. Id: device.DeviceIdentifier,
  107. }
  108. statusreply := rpcs.ReplyGetStatus{}
  109. err := server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.GetStatus", statusargs, &statusreply)
  110. if err != nil {
  111. server.Log.Errorf("get device status error: %v", err)
  112. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  113. return
  114. }
  115. status, err := config.StatusToMap(statusreply.Status)
  116. if err != nil {
  117. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  118. return
  119. }
  120. result := DeviceStatusResponse{
  121. Data: status,
  122. }
  123. r.JSON(http.StatusOK, result)
  124. return
  125. }
  126. // GetDeviceLatestStatus get device latest status
  127. func GetDeviceLatestStatus() {
  128. }
  129. // SetDeviceStatus set device status
  130. func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
  131. urlparams martini.Params, req *http.Request, r render.Render) {
  132. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)
  133. var args interface{}
  134. decoder := json.NewDecoder(req.Body)
  135. err := decoder.Decode(&args)
  136. if err != nil {
  137. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  138. return
  139. }
  140. m, ok := args.(map[string]interface{})
  141. if !ok {
  142. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  143. return
  144. }
  145. status, err := config.MapToStatus(m)
  146. if err != nil {
  147. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  148. return
  149. }
  150. statusargs := rpcs.ArgsSetStatus{
  151. DeviceId: device.RecordId,
  152. Status: status,
  153. }
  154. statusreply := rpcs.ReplySetStatus{}
  155. //opentracing
  156. span, ctx := opentracing.StartSpanFromContext(context.Background(), "SetDeviceStatus")
  157. defer span.Finish()
  158. ext.SpanKindRPCClient.Set(span)
  159. err = server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.SetStatus", statusargs, &statusreply)
  160. if err != nil {
  161. server.Log.Errorf("set devie status error: %v", err)
  162. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  163. return
  164. }
  165. r.JSON(http.StatusOK, Common{})
  166. return
  167. }
  168. // SendCommandToDevice send command to device
  169. /*
  170. {
  171. "deviceCode": "5566",
  172. "subDeviceId": "1",
  173. "data": {
  174. "cmd": "powerControl",
  175. "params": {
  176. "power": 1,
  177. "temp":2
  178. }
  179. }
  180. }
  181. */
  182. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  183. urlparams martini.Params, req *http.Request, r render.Render) {
  184. timeout := req.URL.Query().Get("timeout")
  185. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  186. device.DeviceIdentifier, req.Body, timeout)
  187. var args map[string]interface{}
  188. decoder := json.NewDecoder(req.Body)
  189. err := decoder.Decode(&args)
  190. if err != nil {
  191. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  192. return
  193. }
  194. j := gjson.New(args)
  195. cmdargs := rpcs.ArgsSendCommand{
  196. DeviceId: device.DeviceIdentifier,
  197. SubDevice: j.GetString("subDeviceId"),
  198. WaitTime: uint32(defaultTimeOut),
  199. Params: j.GetMap("data.params"),
  200. Cmd: j.GetString("data.cmd"),
  201. }
  202. cmdreply := rpcs.ReplySendCommand{}
  203. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  204. if err != nil {
  205. server.Log.Errorf("send devie command error: %v", err)
  206. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  207. return
  208. }
  209. r.JSON(http.StatusOK, Common{})
  210. return
  211. }
  212. // AddRule 增加设备规则
  213. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  214. var ruleReq CreateRuleRequest
  215. decoder := json.NewDecoder(req.Body)
  216. err := decoder.Decode(&ruleReq)
  217. if err != nil {
  218. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  219. return
  220. }
  221. rule := &models.Rule{
  222. DeviceID: device.RecordId,
  223. RuleType: ruleReq.Type,
  224. Trigger: ruleReq.Trigger,
  225. Target: ruleReq.Target,
  226. Action: ruleReq.Action,
  227. }
  228. reply := &rpcs.ReplyEmptyResult{}
  229. //opentracing
  230. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  231. defer span.Finish()
  232. ext.SpanKindRPCClient.Set(span)
  233. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  234. if err != nil {
  235. server.Log.Errorf("create device rule error: %v", err)
  236. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  237. return
  238. }
  239. r.JSON(http.StatusOK, Common{})
  240. return
  241. }
  242. func AppAuth(req *http.Request, r render.Render) {
  243. var ruleReq rpcs.ArgsAppAuth
  244. decoder := json.NewDecoder(req.Body)
  245. err := decoder.Decode(&ruleReq)
  246. if err != nil {
  247. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  248. return
  249. }
  250. app := &models.Application{}
  251. err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  252. if err != nil {
  253. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  254. return
  255. }
  256. if app.SecretKey != ruleReq.Secretkey {
  257. // device secret is wrong.
  258. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  259. return
  260. }
  261. token, timeSnap := TokenMaker(app)
  262. result := AppAuthDataResponse{
  263. AccessToken: token,
  264. ExpireAt: timeSnap,
  265. }
  266. r.JSON(http.StatusOK, Common{
  267. Result: result,
  268. })
  269. return
  270. }
  271. func CheckDeviceNetConfig(req *http.Request, r render.Render) {
  272. var params rpcs.ArgsCheckDeviceNetConfig
  273. params.DeviceCode = req.URL.Query().Get("device_code")
  274. params.Md5 = req.URL.Query().Get("md5")
  275. var reply rpcs.ReplyCheckDeviceNetConfig
  276. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.CheckDeviceNetConfig", &params, &reply)
  277. if err != nil {
  278. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  279. return
  280. }
  281. r.JSON(http.StatusOK, Common{
  282. Result: reply.Result,
  283. })
  284. }
  285. func CheckDeviceIsOnline(req *http.Request, r render.Render) {
  286. identifier := req.URL.Query().Get("device_code")
  287. device := &models.Device{}
  288. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindDeviceByIdentifier", identifier, device)
  289. if err != nil {
  290. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  291. return
  292. }
  293. onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
  294. Id: device.DeviceIdentifier,
  295. }
  296. onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
  297. err = server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
  298. if err != nil || onlinereply.ClientIP == "" {
  299. r.JSON(http.StatusOK, Common{
  300. Result: 2,
  301. })
  302. }
  303. r.JSON(http.StatusOK, Common{
  304. Result: 1,
  305. })
  306. }