channels.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. package system
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "time"
  6. "dashoo.cn/backend/api/business/actions"
  7. "dashoo.cn/backend/api/business/authcode"
  8. "dashoo.cn/backend/api/business/device"
  9. "dashoo.cn/backend/api/business/trigger"
  10. "dashoo.cn/backend/api/business/triggerhistory"
  11. "dashoo.cn/backend/api/business/userchannels"
  12. . "dashoo.cn/backend/api/controllers"
  13. "dashoo.cn/labsop"
  14. "dashoo.cn/models"
  15. "dashoo.cn/utils"
  16. )
  17. // 动作接口说明
  18. type ChannelsController struct {
  19. BaseController
  20. }
  21. type MyResponse struct {
  22. Results []MyResult `json:"results,omitempty"`
  23. Err string `json:"err,omitempty"`
  24. }
  25. type MyResult struct {
  26. Series []models.Row `json:"series"`
  27. Err string `json:"err,omitempty"`
  28. }
  29. type ChannelLast struct {
  30. Temp string
  31. Hum string
  32. Vol string
  33. Rssi string
  34. Time string
  35. O2 string
  36. Co2 string
  37. Power string
  38. Supply string
  39. Signal string
  40. DState int //设备状态 1在线,2离线
  41. LiquidLevel string //液位
  42. }
  43. type ChannelModel struct {
  44. Title string `json:"title"`
  45. Serial string `json:"serial"`
  46. TagCode string `json:"tagCode"`
  47. DeviceState string `json:"devicestate"`
  48. About string `json:"about"`
  49. }
  50. type AdjuModel struct {
  51. CalibrationValue string `json:"temp"`
  52. CalibrationHumidity string `json:"hum"`
  53. CalibrationCO2 string `json:"co2"`
  54. CalibrationO2 string `json:"o2"`
  55. }
  56. type Triggerwaringhistory struct {
  57. Items []triggerhistory.Trigger_History `json:"items"` //数据列表
  58. }
  59. type ChannelDataModel struct {
  60. Value [][]float64
  61. GroupValue []float64
  62. }
  63. type SortDataModel struct {
  64. ChannelIds string
  65. }
  66. // @Title 设备列表
  67. // @Description 设备列表
  68. // @Success 200 {object} business.device.DeviceChannels
  69. // @router /list [get]
  70. func (this *ChannelsController) List() {
  71. page := this.GetPageInfoForm()
  72. svc := device.GetDeviceService(utils.DBE)
  73. svcuc := userchannels.GetUserChannelService(utils.DBE)
  74. channelid := svcuc.GetChannelids(utils.ToStr(this.User.Id))
  75. Uid := utils.ToStr(this.User.Id)
  76. where := " (a.CreateUserId=" + utils.ToStr(this.User.Id) + " or a.Id in (" + strings.Join(channelid, ",") + ")) and a.DataItem in (" + ChannelItem_Sensor + ") "
  77. keyword := this.GetString("keyword")
  78. if keyword != "" {
  79. where = where + " and (a.Title like '%" + keyword + "%' or a.TagCode like '%" + keyword + "%' or a.Serial like '%" + keyword + "%')"
  80. }
  81. cstate := this.GetString("cstate")
  82. if cstate != "" {
  83. if cstate == "1" {
  84. where = where + " and a.ChannelState in (1,0)"
  85. } else {
  86. where = where + " and a.ChannelState=" + cstate
  87. }
  88. }
  89. total, devices := svc.GetPagingEntitiesWithOrderSearch(page.CurrentPage, page.Size, "c.sortcode, a.CreateOn desc", where, Uid)
  90. var datainfo DataInfo
  91. datainfo.Items = devices
  92. datainfo.CurrentItemCount = total
  93. this.Data["json"] = &datainfo
  94. this.ServeJSON()
  95. }
  96. // @Title 设备列表
  97. // @Description 设备列表
  98. // @Success 200 {object} business.device.DeviceChannels
  99. // @router /bblist [get]
  100. func (this *ChannelsController) BBList() {
  101. var list []device.Device
  102. svc := device.GetDeviceService(utils.DBE)
  103. svc.GetEntities(&list, " CreateUserId="+utils.ToStr(this.User.Id)+" and DataItem="+Device_Box+" order by CreateOn desc")
  104. this.Data["json"] = &list
  105. this.ServeJSON()
  106. }
  107. // @Title 采集数据
  108. // @Description 采集数据,修改为由接口取数
  109. // @Param serial path string true "设备SN"
  110. // @Success 200 {object} coldcloud.DatapointColdCloud
  111. // @Failure 403 :serial 为空
  112. // @router /datavalue/:serial [get]
  113. func (this *ChannelsController) DataValue() {
  114. serial := this.Ctx.Input.Param(":serial")
  115. svcauthcode := authcode.GetAuthCodeService(utils.DBE)
  116. var aclist []authcode.AuthCode
  117. whereac := " AccCode='" + this.User.AccCode + "'"
  118. aclist = svcauthcode.GetList(" Id desc limit 1 ", whereac)
  119. var errinfo ErrorInfo
  120. if len(aclist) == 0 {
  121. errinfo.Message = "请需要先设置授权码"
  122. errinfo.Code = -2
  123. this.Data["json"] = &errinfo
  124. this.ServeJSON()
  125. return
  126. }
  127. keystr := aclist[0].AuthCode
  128. //调接口获取sensors
  129. var sresponse MyResponse
  130. if keystr != "" {
  131. channel_id := "c" + serial
  132. strurl := utils.Cfg.MustValue("server", "dataapiurl") + "/channels/" + channel_id + "/datapoints"
  133. json.Unmarshal(ApiKeyRequest(strurl, "GET", keystr, nil), &sresponse)
  134. }
  135. // lastdata, err := GetChannelLast(serial)
  136. var data ChannelLast
  137. if len(sresponse.Results) > 0 && len(sresponse.Results[0].Series) > 0 &&
  138. len(sresponse.Results[0].Series[0].Values) > 0 {
  139. cols, arrs := sresponse.Results[0].Series[0].Columns, sresponse.Results[0].Series[0].Values
  140. vl := len(arrs)
  141. if vl == 1 {
  142. indextemp := utils.SliceIndexOf(cols, "temperature")
  143. timeindex := utils.SliceIndexOf(cols, "time")
  144. if indextemp > -1 {
  145. valuef, _ := arrs[0][indextemp].(float64)
  146. data.Temp = utils.ToStr(utils.FloatPoint(valuef, 2))
  147. }
  148. if timeindex > -1 {
  149. valuef, _ := arrs[0][timeindex].(float64)
  150. data.Time = time.Unix(int64(valuef), 0).Format("2006-01-02 15:04:05")
  151. }
  152. }
  153. // data.Temp = utils.ToStr(lastdata.Temperature)
  154. // data.Hum = utils.ToStr(lastdata.Humidity)
  155. // data.Vol = utils.ToStr(lastdata.Voltage)
  156. // data.Rssi = utils.ToStr(lastdata.RSSI)
  157. // data.O2 = utils.ToStr(lastdata.O2)
  158. // data.Co2 = utils.ToStr(lastdata.Co2)
  159. // data.Power = utils.ToStr(lastdata.ElectricalPower)
  160. // data.Supply = utils.ToStr(lastdata.ElectricalSupply)
  161. // data.Signal = utils.ToStr(lastdata.SimSignal)
  162. // data.LiquidLevel = utils.ToStr(lastdata.LiquidLevel)
  163. // data.Time = lastdata.Time.Format("2006-01-02 15:04:05")
  164. // if (time.Now().Unix() - 3600*int64(5)) < lasttimeint {
  165. // data.DState = 1
  166. // } else {
  167. // data.DState = 2
  168. // }
  169. }
  170. this.Data["json"] = &data
  171. this.ServeJSON()
  172. }
  173. // @Title 验证采集设备序列号
  174. // @Description 采集数据
  175. // @Param code path string true "设备SN"
  176. // @Success 200 {object} ErrorInfo
  177. // @Failure 403 :code 为空
  178. // @router /validcode/:code [get]
  179. func (this *ChannelsController) ValidCode() {
  180. code := this.Ctx.Input.Param(":code")
  181. var errinfo ErrorInfo
  182. var entity device.Channels
  183. strUrl := utils.Cfg.MustValue("server", "apiurl") + "/channels/serial?serial=" + code
  184. json.Unmarshal(Apiget(strUrl), &entity)
  185. if entity.Code != "" && DeviceItemContainint(ChannelItem_Sensor, entity.DataItem) {
  186. errinfo.Message = "验证通过!"
  187. errinfo.Code = 0
  188. } else {
  189. errinfo.Message = "传感器序列号不存在!"
  190. errinfo.Code = -1
  191. }
  192. this.Data["json"] = &errinfo
  193. this.ServeJSON()
  194. }
  195. // @Title 创建传感器
  196. // @Description 创建传感器
  197. // @Param body body business.device.DeviceChannels "传感器信息"
  198. // @Success 200 {object} controllers.Request
  199. // @router / [post]
  200. func (this *ChannelsController) AddChannel() {
  201. var model ChannelModel
  202. var jsonblob = this.Ctx.Input.RequestBody
  203. json.Unmarshal(jsonblob, &model)
  204. var errinfo ErrorInfo
  205. var channel device.Channels
  206. u, p := this.GetuAndp()
  207. channel.About = model.About
  208. channel.DeviceState, _ = utils.StrTo(model.DeviceState).Int()
  209. channel.Serial = model.Serial
  210. channel.TagCode = model.TagCode
  211. channel.Title = model.Title
  212. svc := device.GetDeviceService(utils.DBE)
  213. var entity device.Channels
  214. strUrl := utils.Cfg.MustValue("server", "apiurl") + "/channels/serial?serial=" + channel.Serial
  215. json.Unmarshal(Apiget(strUrl), &entity)
  216. var devices device.Device
  217. //取缓存数据,如果是半小时内的数据就自动获取bbmac
  218. lastdata, err := GetChannelLast(channel.Serial)
  219. if lasttimeint := lastdata.Time.Unix(); err == nil && time.Now().Unix()-lasttimeint <= 30*60 {
  220. strUrl = utils.Cfg.MustValue("server", "apiurl") + "/devices/serial?serial=" + lastdata.BBMac
  221. json.Unmarshal(Apiget(strUrl), &devices)
  222. //判断如果box未开通记录到数据库
  223. if devices.Id == 0 {
  224. notopen := device.Device_NotOpen{Serial: lastdata.BBMac, CSerial: channel.Serial}
  225. svc.InsertEntity(&notopen)
  226. }
  227. }
  228. if !DeviceItemContainint(Device_Box, devices.DataItem) {
  229. devices = device.Device{}
  230. }
  231. if svc.VerifyChannel(entity.Code) {
  232. errinfo.Message = "传感器已存在!"
  233. errinfo.Code = -1
  234. this.Data["json"] = &errinfo
  235. this.ServeJSON()
  236. return
  237. } else {
  238. api_wdid := devices.Id
  239. if !svc.VerifyDevice(devices.Id) && api_wdid > 0 {
  240. devices.Wdid = devices.Id
  241. devices.Id = 0
  242. devices.Serial = devices.Serial
  243. devices.CreateUserId, _ = utils.StrTo(this.User.Id).Int()
  244. devices.CreateBy = this.User.Realname
  245. devices.Dtype = 1
  246. svc.InsertEntity(&devices)
  247. strUrl = utils.Cfg.MustValue("server", "apiurl") + "/devices/soursedevice/" + utils.ToStr(api_wdid) + "?u=" + u + "&p=" + p + "&sourse=coldchain&account=" + this.GetAccode() + "&accountname=" + this.User.Realname
  248. Apipost(strUrl, "PUT", nil)
  249. }
  250. if channel.Title == "" {
  251. channel.Title = entity.Title
  252. }
  253. if channel.Tags == "" {
  254. channel.Tags = entity.Tags
  255. }
  256. if channel.About == "" {
  257. channel.About = entity.About
  258. }
  259. cdid := svc.GetDIdBySerial(devices.Serial)
  260. if cdid == 0 {
  261. channel.DId = devices.Id
  262. } else {
  263. channel.DId = cdid
  264. }
  265. channel.Code = entity.Code
  266. channel.CreateUserId, _ = utils.StrTo(this.User.Id).Int()
  267. channel.CreateBy = this.User.Realname
  268. //2015-4-21增加设备类型(区分普通传感器和blackbox) zh
  269. channel.DataItem = entity.DataItem
  270. _, err := svc.InsertEntity(&channel)
  271. if err == nil {
  272. strUrl = utils.Cfg.MustValue("server", "apiurl") + "/channels/" + entity.Code + "?u=" + u + "&p=" + p
  273. Apipost(strUrl, "PUT", channel)
  274. strUrl = utils.Cfg.MustValue("server", "apiurl") + "/channels/sourse/" + entity.Code + "?u=" + u + "&p=" + p + "&sourse=coldchain&account=" + this.GetAccode() + "&accountname=" + this.User.Realname
  275. Apipost(strUrl, "PUT", channel)
  276. //判断是否需要反写传感器对应关系到waterdrop
  277. if api_wdid != entity.DId && api_wdid > 0 {
  278. strUrl = utils.Cfg.MustValue("server", "apiurl") + "/channels/updatedevice/" + entity.Code + "?u=" + u + "&p=" + p + "&did=" + utils.ToStr(api_wdid)
  279. Apipost(strUrl, "PUT", nil)
  280. }
  281. //去查有没有blackbox被绑定
  282. var channeldevice1 device.Channels
  283. has := svc.GetEntity(&channeldevice1, " Did= "+utils.ToStr(svc.GetBlackBoxIdByCode(channel.Code))+" and DataItem=1 and Serial= '"+devices.Serial+"' ")
  284. if !has {
  285. var channeldevice device.Channels
  286. strUrl := utils.Cfg.MustValue("server", "apiurl") + "/channels/serial?serial=" + devices.Serial //查询
  287. json.Unmarshal(Apiget(strUrl), &channeldevice)
  288. if channeldevice.Code != "" && DeviceItemContainint(ChannelItem_Box, channeldevice.DataItem) {
  289. channeldevice.DId = channel.DId
  290. var channeldevicedb device.Channels
  291. channeldevicedb.Title = channeldevice.Title
  292. channeldevicedb.Code = channeldevice.Code
  293. channeldevicedb.Serial = channeldevice.Serial
  294. channeldevicedb.Tags = channeldevice.Tags
  295. channeldevicedb.DId = channeldevice.DId
  296. channeldevicedb.DataItem = channeldevice.DataItem
  297. channeldevicedb.CreateUserId, _ = utils.StrTo(this.User.Id).Int()
  298. channeldevicedb.CreateBy = this.User.Realname
  299. svc.InsertEntity(&channeldevicedb) //添加到冷云
  300. //绑定
  301. strUrl = utils.Cfg.MustValue("server", "apiurl") + "/channels/sourse/" + channeldevice.Code + "?u=" + u + "&p=" + p + "&sourse=coldchain&account=" + this.GetAccode() + "&accountname=" + this.User.Realname
  302. Apipost(strUrl, "PUT", nil)
  303. }
  304. }
  305. errinfo.Message = "保存成功!"
  306. errinfo.Code = 0
  307. this.Data["json"] = &errinfo
  308. this.ServeJSON()
  309. return
  310. } else {
  311. errinfo.Message = "保存失败!" + utils.AlertProcess(err.Error())
  312. errinfo.Code = -2
  313. this.Data["json"] = &errinfo
  314. this.ServeJSON()
  315. return
  316. }
  317. }
  318. }
  319. // @Title 编辑传感器
  320. // @Description 编辑传感器
  321. // @Param code path string true "需要修改的传感器编号"
  322. // @Param body body business.device.DeviceChannels "传感器信息"
  323. // @Success 200 {object} ErrorInfo
  324. // @router /:code [put]
  325. func (this *ChannelsController) EditChannel() {
  326. code := this.Ctx.Input.Param(":code")
  327. var errinfo ErrorInfo
  328. if code == "" {
  329. errinfo.Message = "操作失败!请求信息不完整"
  330. errinfo.Code = -2
  331. this.Data["json"] = &errinfo
  332. this.ServeJSON()
  333. return
  334. }
  335. code = "c" + code
  336. var model ChannelModel
  337. var jsonblob = this.Ctx.Input.RequestBody
  338. json.Unmarshal(jsonblob, &model)
  339. var channel device.Channels
  340. u, p := this.GetuAndp()
  341. channel.About = model.About
  342. channel.DeviceState, _ = utils.StrTo(model.DeviceState).Int()
  343. channel.Serial = model.Serial
  344. channel.TagCode = model.TagCode
  345. channel.Title = model.Title
  346. var channelempty device.Channels
  347. svc := device.GetDeviceService(utils.DBE)
  348. channel.ModifiedUserId, _ = utils.StrTo(this.User.Id).Int()
  349. channel.ModifiedBy = this.User.Realname
  350. var cols []string = []string{"Title", "Tags", "TagCode", "DeviceState", "About", "VisitLevel", "ModifiedUserId", "ModifiedBy"}
  351. err := svc.UpdateEntityAndBackupByCols(svc.GetIdByCode(code), &channel, &channelempty, cols, utils.ToStr(this.User.Id), this.User.Realname)
  352. if err == nil {
  353. // code := "c" + this.GetString("Serial")
  354. // enabled := this.GetString("alertor")
  355. // //修改报警设置状态
  356. // if code != "" && enabled != "" {
  357. // var status Status
  358. // u, p := this.GetuAndp()
  359. // strUrl := utils.Cfg.MustValue("server", "apiurl") + "/triggers/enabled?code=" + code + "&enabled=" + enabled + "&u=" + u + "&p=" + p
  360. // json.Unmarshal(Apipost(strUrl, "PUT", nil), &status)
  361. // //修改时报警状态的日志
  362. // var entity AllalarmLog_Log
  363. // title := channel.Title
  364. // svc1 := device.GetDeviceService(utils.DBE)
  365. // entity.Code = strings.Replace(code, "c", "", 1)
  366. // entity.Title = title
  367. // entity.Enabled, _ = utils.StrTo(enabled).Int()
  368. // svc1.InsertUpdateLog(0, &entity, utils.ToStr(this.User.Id), this.User.Realname, AllalarmLogTName)
  369. // }
  370. //修改缓存中设备状态
  371. cachevalue, _ := labsop.GetBoxCacheValue(channel.Serial)
  372. cachevalue.DeviceState = channel.DeviceState
  373. labsop.UpdateBoxChcheValue(channel.Serial, cachevalue)
  374. // //更新地理信息到device
  375. // if channel.DId > 0 {
  376. // var devicemodel device.Device
  377. // devicemodel.Id = channel.DId
  378. // devicemodel.Local = channel.Local
  379. // devicemodel.Latitude = channel.Latitude
  380. // devicemodel.Longitude = channel.Longitude
  381. // var devicecols []string = []string{"Longitude", "Latitude", "Local"}
  382. // svc.UpdateEntityByIdCols(devicemodel.Id, &devicemodel, devicecols)
  383. // }
  384. strUrl := utils.Cfg.MustValue("server", "apiurl") + "/channels/" + code + "?u=" + u + "&p=" + p
  385. Apipost(strUrl, "PUT", channel)
  386. errinfo.Message = "保存成功!"
  387. errinfo.Code = 0
  388. this.Data["json"] = &errinfo
  389. this.ServeJSON()
  390. } else {
  391. errinfo.Message = "保存失败!" + utils.AlertProcess(err.Error())
  392. errinfo.Code = -1
  393. this.Data["json"] = &errinfo
  394. this.ServeJSON()
  395. }
  396. }
  397. // @Title 删除传感器
  398. // @Description 删除传感器
  399. // @Param code path string true "需要删除的传感器编号"
  400. // @Success 200 {object} ErrorInfo
  401. // @Failure 403 :code 为空
  402. // @router /:code [delete]
  403. func (this *ChannelsController) Delete() {
  404. code := this.Ctx.Input.Param(":code")
  405. var errinfo ErrorInfo
  406. if code == "" {
  407. errinfo.Message = "操作失败!请求信息不完整"
  408. errinfo.Code = -3
  409. this.Data["json"] = &errinfo
  410. this.ServeJSON()
  411. return
  412. }
  413. code = "c" + code
  414. var triggerlist []trigger.Trigger
  415. u, p := this.GetuAndp()
  416. strUrl := utils.Cfg.MustValue("server", "apiurl") + "/triggers/?cid=" + code + "&u=" + u + "&p=" + p
  417. json.Unmarshal(Apiget(strUrl), &triggerlist)
  418. if len(triggerlist) > 0 {
  419. errinfo.Message = "操作失败!请先删除该设备的报警设置!"
  420. errinfo.Code = -4
  421. this.Data["json"] = &errinfo
  422. this.ServeJSON()
  423. return
  424. }
  425. var entity device.Channels
  426. var devices device.Device
  427. var devicesempty device.Device
  428. var entityempty device.Channels
  429. svc := device.GetDeviceService(utils.DBE)
  430. cid := svc.GetIdByCode(code)
  431. has := svc.GetEntityById(cid, &entity)
  432. if has {
  433. //冷云数据校准值记录到缓存,清除
  434. cachevalue, _ := labsop.GetBoxCacheValue(entity.Serial)
  435. cachevalue.CalibrationValue = 0
  436. cachevalue.CalibrationHumidity = 0
  437. cachevalue.CalibrationCO2 = 0
  438. cachevalue.CalibrationO2 = 0
  439. cachevalue.DeviceState = 0
  440. labsop.UpdateBoxChcheValue(entity.Serial, cachevalue)
  441. err := svc.DeleteEntityAndBackup(cid, &entity, &entityempty, utils.ToStr(this.User.Id), this.User.Username)
  442. if err == nil {
  443. //删除权限
  444. svcchannels := userchannels.GetUserChannelService(utils.DBE)
  445. svcchannels.ClearBBChannel(cid)
  446. //取消waterdrop绑定状态
  447. strUrl := utils.Cfg.MustValue("server", "apiurl") + "/channels/unbingding/" + code + "?u=" + u + "&p=" + p
  448. Apipost(strUrl, "PUT", nil)
  449. //删除设备
  450. cnum := svc.GetChannelsCount(" DataItem in (" + ChannelItem_Sensor + ") and DId=" + utils.ToStr(entity.DId))
  451. if cnum <= 0 {
  452. //取消waterdrop绑定状态
  453. wdid := svc.GetWDidByDid(entity.DId)
  454. strUrldevice := utils.Cfg.MustValue("server", "apiurl") + "/devices/unbingding/" + utils.ToStr(wdid) + "?u=" + u + "&p=" + p
  455. Apipost(strUrldevice, "PUT", nil)
  456. svc.DeleteEntityAndBackup(entity.DId, &devices, &devicesempty, utils.ToStr(this.User.Id), this.User.Username)
  457. var channeldevice device.Channels
  458. haschannel := svc.GetEntity(&channeldevice, " DataItem=1 and DId="+utils.ToStr(entity.DId))
  459. if haschannel {
  460. svc.DeleteEntityAndBackup(channeldevice.Id, &channeldevice, &entityempty, utils.ToStr(this.User.Id), this.User.Username)
  461. cstrUrl := utils.Cfg.MustValue("server", "apiurl") + "/channels/unbingding/" + channeldevice.Code + "?u=" + u + "&p=" + p
  462. Apipost(cstrUrl, "PUT", nil)
  463. }
  464. }
  465. errinfo.Message = "删除成功!"
  466. errinfo.Code = 0
  467. this.Data["json"] = &errinfo
  468. this.ServeJSON()
  469. } else {
  470. errinfo.Message = "删除失败!" + utils.AlertProcess(err.Error())
  471. errinfo.Code = -1
  472. this.Data["json"] = &errinfo
  473. this.ServeJSON()
  474. }
  475. } else {
  476. errinfo.Message = "删除失败!"
  477. errinfo.Code = -2
  478. this.Data["json"] = &errinfo
  479. this.ServeJSON()
  480. }
  481. }
  482. // @Title 验证报警器权限
  483. // @Description 验证报警器权限
  484. // @Success 200 {object} ErrorInfo
  485. // @router /validalert [get]
  486. func (this *ChannelsController) ValidAlert() {
  487. wdid := this.GetString("ids")
  488. serial := this.GetString("serial")
  489. wdids := strings.Split(wdid, ",")
  490. var errinfo ErrorInfo
  491. errinfo.Message = "验证通过!"
  492. errinfo.Code = 0
  493. svc := actions.GetActionsService(utils.DBE)
  494. for _, v := range wdids {
  495. action := svc.GetByWdid(v)
  496. if action.AItem == 4 {
  497. code := "c" + serial
  498. selectstr := ""
  499. lastdata, err := GetChannelLast("calert" + action.SPara4)
  500. if err == nil && lastdata.Time.Unix() > 0 {
  501. selectstr = lastdata.RequestData
  502. }
  503. if !utils.SliceContains(strings.Split(selectstr, ","), code) {
  504. errinfo.Message = "报警器(" + action.AName + ")未关联此设备"
  505. errinfo.Code = -1
  506. break
  507. }
  508. }
  509. }
  510. this.Data["json"] = &errinfo
  511. this.ServeJSON()
  512. }
  513. // @Title 获取校准数据
  514. // @Description 获取校准数据
  515. // @Param serial path string true "设备SN"
  516. // @Success 200 {object} AdjuModel
  517. // @Failure 403 :serial 为空
  518. // @router /adjudata/:serial [get]
  519. func (this *ChannelsController) GetAdjuData() {
  520. svc := device.GetDeviceService(utils.DBE)
  521. var entity device.Channels
  522. svc.GetEntity(&entity, "Serial='"+this.Ctx.Input.Param(":serial")+"'")
  523. this.Data["json"] = &entity
  524. this.ServeJSON()
  525. }
  526. // @Title 校准数据
  527. // @Description 校准数据
  528. // @Param serial path string true "设备SN"
  529. // @Success 200 {object} ErrorInfo
  530. // @Failure 403 :serial 为空
  531. // @router /adjudata/:serial [put]
  532. func (this *ChannelsController) SaveAdjuData() {
  533. serial := this.Ctx.Input.Param(":serial")
  534. var errinfo ErrorInfo
  535. if serial == "" {
  536. errinfo.Message = "操作失败!请求信息不完整"
  537. errinfo.Code = -2
  538. this.Data["json"] = &errinfo
  539. this.ServeJSON()
  540. return
  541. }
  542. code := "c" + serial
  543. var model AdjuModel
  544. var jsonblob = this.Ctx.Input.RequestBody
  545. json.Unmarshal(jsonblob, &model)
  546. var channel device.Channels
  547. var channelempty device.Channels
  548. svc := device.GetDeviceService(utils.DBE)
  549. channel.CalibrationValue, _ = utils.StrTo(model.CalibrationValue).Float32()
  550. channel.CalibrationHumidity, _ = utils.StrTo(model.CalibrationHumidity).Float32()
  551. channel.CalibrationCO2, _ = utils.StrTo(model.CalibrationCO2).Float32()
  552. channel.CalibrationO2, _ = utils.StrTo(model.CalibrationO2).Float32()
  553. channel.ModifiedUserId, _ = utils.StrTo(this.User.Id).Int()
  554. channel.ModifiedBy = this.User.Realname
  555. var cols []string = []string{"CalibrationValue", "CalibrationHumidity", "CalibrationCO2", "CalibrationO2", "ModifiedUserId", "ModifiedBy"}
  556. err := svc.UpdateEntityAndBackupByCols(svc.GetIdByCode(code), &channel, &channelempty, cols, utils.ToStr(this.User.Id), this.User.Realname)
  557. if err == nil {
  558. //冷云数据校准值记录到缓存
  559. cachevalue, _ := labsop.GetBoxCacheValue(serial)
  560. cachevalue.CalibrationValue = channel.CalibrationValue
  561. cachevalue.CalibrationHumidity = channel.CalibrationHumidity
  562. cachevalue.CalibrationCO2 = channel.CalibrationCO2
  563. cachevalue.CalibrationO2 = channel.CalibrationO2
  564. labsop.UpdateBoxChcheValue(serial, cachevalue)
  565. errinfo.Message = "校准成功!"
  566. errinfo.Code = 0
  567. this.Data["json"] = &errinfo
  568. this.ServeJSON()
  569. } else {
  570. errinfo.Message = "校准失败!" + utils.AlertProcess(err.Error())
  571. errinfo.Code = -1
  572. this.Data["json"] = &errinfo
  573. this.ServeJSON()
  574. }
  575. }
  576. // @Title 历史采集数据
  577. // @Description 历史采集数据
  578. // @Param serial path string true "设备SN"
  579. // @Success 200 {object} coldcloud.DatapointColdCloud
  580. // @Failure 403 :serial 为空
  581. // @router /historydatavalue/:serial [get]
  582. func (this *ChannelsController) HistoryDataValue() {
  583. dataitem := this.GetString("_dataitem")
  584. serial := this.Ctx.Input.Param(":serial")
  585. cid := "c" + serial
  586. startint, _ := this.GetInt64("_start")
  587. endint, _ := this.GetInt64("_end")
  588. // client := labsop.GetLabSopClient(this.GetupdbAndHost())
  589. svcauthcode := authcode.GetAuthCodeService(utils.DBE)
  590. var aclist []authcode.AuthCode
  591. whereac := " AccCode='" + this.User.AccCode + "'"
  592. aclist = svcauthcode.GetList(" Id desc limit 1 ", whereac)
  593. if len(aclist) == 0 {
  594. this.Data["json"] = ChannelDataModel{}
  595. this.ServeJSON()
  596. return
  597. }
  598. valuedata, datagroup := this.ChannelManageview(aclist[0].AuthCode, cid, dataitem, startint/1000-1, endint/1000+1)
  599. this.Data["json"] = ChannelDataModel{valuedata, datagroup}
  600. this.ServeJSON()
  601. }
  602. func (this *ChannelsController) ChannelManageview(authcode, code, dataitem string, start, end int64) ([][]float64, []float64) {
  603. //调接口获取sensors
  604. var sresponse MyResponse
  605. channel_id := code
  606. strurl := utils.Cfg.MustValue("server", "dataapiurl") + "/channels/" + channel_id + "/datapoints"
  607. strurl += "?start=" + utils.ToStr(start) + "&end=" + utils.ToStr(end)
  608. json.Unmarshal(ApiKeyRequest(strurl, "GET", authcode, nil), &sresponse)
  609. var arrvs [][]float64
  610. if len(sresponse.Results) > 0 && len(sresponse.Results[0].Series) > 0 &&
  611. len(sresponse.Results[0].Series[0].Values) > 0 {
  612. cols, arrs := sresponse.Results[0].Series[0].Columns, sresponse.Results[0].Series[0].Values
  613. vl := len(arrs)
  614. indextemp := utils.SliceIndexOf(cols, "temperature")
  615. timeindex := utils.SliceIndexOf(cols, "time")
  616. voltageindex := utils.SliceIndexOf(cols, "voltage")
  617. if indextemp > -1 && timeindex > -1 && voltageindex > -1 {
  618. //历史数据
  619. for x, y := 0, vl; x < y; x++ {
  620. valuetempf, _ := arrs[x][indextemp].(float64)
  621. valuetimef, _ := arrs[x][timeindex].(float64)
  622. valuevolf, _ := arrs[x][voltageindex].(float64)
  623. arr := []float64{valuetimef * 1000, valuetempf, valuevolf}
  624. arrvs = append(arrvs, arr)
  625. }
  626. }
  627. }
  628. var arrgroup []float64
  629. return arrvs, arrgroup
  630. }
  631. // @Title 设备排序
  632. // @Description 设备排序
  633. // @Success 200 {object} ErrorInfo
  634. // @router /sortsave [put]
  635. func (this *ChannelsController) SaveSort() {
  636. var model SortDataModel
  637. var jsonblob = this.Ctx.Input.RequestBody
  638. json.Unmarshal(jsonblob, &model)
  639. channelId := strings.Split(model.ChannelIds, ",")
  640. var channelsSort device.ChannelsSort
  641. svc := device.GetDeviceService(utils.DBE)
  642. channelsSort.UserId, _ = utils.StrTo(this.User.Id).Int()
  643. svc.DeleteEntity(&channelsSort)
  644. channelsSort.CreateUserId = channelsSort.UserId
  645. channelsSort.CreateBy = this.User.Realname
  646. channelsSort.ModifiedUserId = channelsSort.UserId
  647. channelsSort.ModifiedBy = this.User.Realname
  648. for i, j := 0, len(channelId)-1; i < j; i++ {
  649. channelsSort.ChannelId, _ = utils.StrTo(channelId[i]).Int()
  650. channelsSort.SortCode = i
  651. svc.InsertEntity(&channelsSort)
  652. }
  653. var errinfo ErrorInfo
  654. errinfo.Message = "保存成功!"
  655. errinfo.Code = 0
  656. this.Data["json"] = &errinfo
  657. this.ServeJSON()
  658. }