actions.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. //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 device 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. /*
  174. {
  175. "deviceCode": "5566",
  176. "subDeviceId": "1",
  177. "data": {
  178. "cmd": "powerControl",
  179. "params": {
  180. "power": 1,
  181. "temp":2
  182. }
  183. }
  184. }
  185. */
  186. func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
  187. urlparams martini.Params, req *http.Request, r render.Render) {
  188. timeout := req.URL.Query().Get("timeout")
  189. server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
  190. device.DeviceIdentifier, req.Body, timeout)
  191. var args map[string]interface{}
  192. decoder := json.NewDecoder(req.Body)
  193. err := decoder.Decode(&args)
  194. if err != nil {
  195. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  196. return
  197. }
  198. j := gjson.New(args)
  199. cmdargs := rpcs.ArgsSendCommand{
  200. DeviceId: device.DeviceIdentifier,
  201. SubDevice: j.GetString("subDeviceId"),
  202. WaitTime: uint32(defaultTimeOut),
  203. Params: j.GetMap("data.params"),
  204. Cmd: j.GetString("data.cmd"),
  205. }
  206. cmdreply := rpcs.ReplySendCommand{}
  207. err = server.RPCCallByName(context.Background(), rpcs.ControllerName, "Controller.SendCommand", cmdargs, &cmdreply)
  208. if err != nil {
  209. server.Log.Errorf("send devie command error: %v", err)
  210. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  211. return
  212. }
  213. r.JSON(http.StatusOK, Common{})
  214. return
  215. }
  216. // AddRule 增加设备规则
  217. func AddRule(device *models.Device, req *http.Request, r render.Render) {
  218. var ruleReq CreateRuleRequest
  219. decoder := json.NewDecoder(req.Body)
  220. err := decoder.Decode(&ruleReq)
  221. if err != nil {
  222. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  223. return
  224. }
  225. rule := &models.Rule{
  226. DeviceID: device.RecordId,
  227. RuleType: ruleReq.Type,
  228. Trigger: ruleReq.Trigger,
  229. Target: ruleReq.Target,
  230. Action: ruleReq.Action,
  231. }
  232. reply := &rpcs.ReplyEmptyResult{}
  233. //opentracing
  234. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AddRule")
  235. defer span.Finish()
  236. ext.SpanKindRPCClient.Set(span)
  237. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.CreateRule", rule, reply)
  238. if err != nil {
  239. server.Log.Errorf("create device rule error: %v", err)
  240. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  241. return
  242. }
  243. r.JSON(http.StatusOK, Common{})
  244. return
  245. }
  246. func AppAuth(req *http.Request, r render.Render) {
  247. var ruleReq rpcs.ArgsAppAuth
  248. decoder := json.NewDecoder(req.Body)
  249. err := decoder.Decode(&ruleReq)
  250. if err != nil {
  251. r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
  252. return
  253. }
  254. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AppAuth")
  255. defer span.Finish()
  256. ext.SpanKindRPCClient.Set(span)
  257. app := &models.Application{}
  258. err = server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.FindApplicationByAppKey", ruleReq, app)
  259. if err != nil {
  260. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("invalid secret key")))
  261. return
  262. }
  263. if app.SecretKey != ruleReq.Secretkey {
  264. // device secret is wrong.
  265. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong application secret")))
  266. return
  267. }
  268. token, timeSnap := TokenMaker(app)
  269. result := AppAuthDataResponse{
  270. AccessToken: token,
  271. ExpireAt: timeSnap,
  272. }
  273. r.JSON(http.StatusOK, Common{
  274. Result: result,
  275. })
  276. return
  277. }