actions.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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.RecordId,
  107. }
  108. statusreply := rpcs.ReplyGetStatus{}
  109. //opentracing
  110. span, ctx := opentracing.StartSpanFromContext(context.Background(), "GetDeviceCurrentStatus")
  111. defer span.Finish()
  112. ext.SpanKindRPCClient.Set(span)
  113. err := server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.GetStatus", statusargs, &statusreply)
  114. if err != nil {
  115. server.Log.Errorf("get devie status error: %v", err)
  116. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  117. return
  118. }
  119. status, err := config.StatusToMap(statusreply.Status)
  120. if err != nil {
  121. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  122. return
  123. }
  124. result := DeviceStatusResponse{
  125. Data: status,
  126. }
  127. r.JSON(http.StatusOK, result)
  128. return
  129. }
  130. // GetDeviceLatestStatus get device latest status
  131. func GetDeviceLatestStatus() {
  132. }
  133. // SetDeviceStatus set device status
  134. func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
  135. urlparams martini.Params, req *http.Request, r render.Render) {
  136. server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)
  137. var args interface{}
  138. decoder := json.NewDecoder(req.Body)
  139. err := decoder.Decode(&args)
  140. if err != nil {
  141. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  142. return
  143. }
  144. m, ok := args.(map[string]interface{})
  145. if !ok {
  146. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  147. return
  148. }
  149. status, err := config.MapToStatus(m)
  150. if err != nil {
  151. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  152. return
  153. }
  154. statusargs := rpcs.ArgsSetStatus{
  155. DeviceId: device.RecordId,
  156. Status: status,
  157. }
  158. statusreply := rpcs.ReplySetStatus{}
  159. //opentracing
  160. span, ctx := opentracing.StartSpanFromContext(context.Background(), "SetDeviceStatus")
  161. defer span.Finish()
  162. ext.SpanKindRPCClient.Set(span)
  163. err = server.RPCCallByName(ctx, rpcs.ControllerName, "Controller.SetStatus", statusargs, &statusreply)
  164. if err != nil {
  165. server.Log.Errorf("set devie status error: %v", err)
  166. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  167. return
  168. }
  169. r.JSON(http.StatusOK, Common{})
  170. return
  171. }
  172. // SendCommandToDevice send command to device
  173. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  174. urlparams martini.Params, req *http.Request, r render.Render) {
  175. timeout := req.URL.Query().Get("timeout")
  176. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  177. device.DeviceIdentifier, req.Body, timeout)
  178. var args map[string]interface{}
  179. decoder := json.NewDecoder(req.Body)
  180. err := decoder.Decode(&args)
  181. if err != nil {
  182. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  183. return
  184. }
  185. j := gjson.New(args)
  186. cmdargs := rpcs.ArgsSendCommand{
  187. DeviceId: device.DeviceIdentifier,
  188. SubDevice: j.GetString("subDeviceId"),
  189. WaitTime: uint32(defaultTimeOut),
  190. Params: j.GetMap("data.params"),
  191. Cmd: j.GetString("data.cmd"),
  192. }
  193. cmdreply := rpcs.ReplySendCommand{}
  194. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  195. if err != nil {
  196. server.Log.Errorf("send devie command error: %v", err)
  197. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  198. return
  199. }
  200. r.JSON(http.StatusOK, Common{})
  201. return
  202. }
  203. // AddRule 增加设备规则
  204. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  205. var ruleReq CreateRuleRequest
  206. decoder := json.NewDecoder(req.Body)
  207. err := decoder.Decode(&ruleReq)
  208. if err != nil {
  209. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  210. return
  211. }
  212. rule := &models.Rule{
  213. DeviceID: device.RecordId,
  214. RuleType: ruleReq.Type,
  215. Trigger: ruleReq.Trigger,
  216. Target: ruleReq.Target,
  217. Action: ruleReq.Action,
  218. }
  219. reply := &rpcs.ReplyEmptyResult{}
  220. //opentracing
  221. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  222. defer span.Finish()
  223. ext.SpanKindRPCClient.Set(span)
  224. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  225. if err != nil {
  226. server.Log.Errorf("create device rule error: %v", err)
  227. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  228. return
  229. }
  230. r.JSON(http.StatusOK, Common{})
  231. return
  232. }
  233. func AppAuth(req *http.Request, r render.Render) {
  234. var ruleReq rpcs.ArgsAppAuth
  235. decoder := json.NewDecoder(req.Body)
  236. err := decoder.Decode(&ruleReq)
  237. if err != nil {
  238. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  239. return
  240. }
  241. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AppAuth")
  242. defer span.Finish()
  243. ext.SpanKindRPCClient.Set(span)
  244. app := &models.Application{}
  245. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  246. if err != nil {
  247. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  248. return
  249. }
  250. if app.SecretKey != ruleReq.Secretkey {
  251. // device secret is wrong.
  252. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  253. return
  254. }
  255. token, timeSnap := TokenMaker(app)
  256. result := AppAuthDataResponse{
  257. AccessToken: token,
  258. ExpireAt: timeSnap,
  259. }
  260. r.JSON(http.StatusOK, Common{
  261. Result: result,
  262. })
  263. return
  264. }