DataGeneratorController.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. package controllers
  2. import (
  3. "ColdP_server/controllers/lib"
  4. "ColdP_server/logs"
  5. "ColdP_server/models/Company"
  6. "ColdP_server/models/Device"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/beego/beego/v2/adapter/orm"
  10. beego "github.com/beego/beego/v2/server/web"
  11. "github.com/xuri/excelize/v2"
  12. "io"
  13. "log"
  14. "math/rand"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. type DataGeneratorController struct {
  20. beego.Controller
  21. }
  22. // GeneratorHtml 获取页面
  23. func (c *DataGeneratorController) GeneratorHtml() {
  24. b_, admin := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  25. if !b_ {
  26. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  27. c.ServeJSON()
  28. return
  29. }
  30. classList := Company.Read_CompanyClass_All(admin.T_pid, "")
  31. c.Data["Class_List"] = classList
  32. //确认状态为登录状态后
  33. c.TplName = "Data/GeneratorData2.html"
  34. }
  35. // DeviceSensorData 获取对应设备探头数据
  36. func (c *DataGeneratorController) DeviceSensorData() {
  37. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  38. if !b_ {
  39. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  40. c.ServeJSON()
  41. return
  42. }
  43. startTime := c.GetString("startTime")
  44. endTime := c.GetString("endTime")
  45. sns := make([][]string, 0)
  46. json.Unmarshal([]byte(c.GetString("sns")), &sns)
  47. type Temp struct {
  48. Sn []string `json:"sn"`
  49. Data []Device.DeviceSensorData `json:"data"`
  50. }
  51. datas := make([]Temp, 0)
  52. for _, sn := range sns {
  53. //sn = [sn,探头id]
  54. id, _ := strconv.ParseInt(sn[1], 10, 63)
  55. v, err := Device.ReadDeviceSensorByTsnTidTimeRange(sn[0], int(id), startTime, endTime)
  56. if err != nil {
  57. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取设备探头错误!"}
  58. c.ServeJSON()
  59. return
  60. }
  61. datas = append(datas, Temp{sn, v})
  62. }
  63. c.Data["json"] = lib.JSONS{Code: 200, Msg: "获取数据成功", Data: datas}
  64. c.ServeJSON()
  65. }
  66. // UpdateFix 更新固定值
  67. func (c *DataGeneratorController) UpdateFix() {
  68. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  69. if !b_ {
  70. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  71. c.ServeJSON()
  72. return
  73. }
  74. //1.解析数据
  75. var body = c.Ctx.Request.Body
  76. defer body.Close()
  77. type T struct {
  78. FixTemperature string `json:"fixTemperature"`
  79. FixHumidity string `json:"fixHumidity"`
  80. Sns [][2]string `json:"sns"`
  81. Data []int64 `json:"data"`
  82. }
  83. var temp = T{}
  84. bytes, _ := io.ReadAll(body)
  85. json.Unmarshal(bytes, &temp)
  86. fmt.Println("解析后:", temp.Data[0])
  87. //2.得到数据进行统一设置访问修改
  88. humidity, _ := strconv.ParseFloat(temp.FixHumidity, 64)
  89. temperature, _ := strconv.ParseFloat(temp.FixTemperature, 64)
  90. //开始时间到结束时间
  91. startTime := time.UnixMilli(temp.Data[0]).Format("2006-01-02 15:04:05")
  92. endTime := time.UnixMilli(temp.Data[1]).Format("2006-01-02 15:04:05")
  93. //3.循环更新数据
  94. for _, v := range temp.Sns {
  95. sn := v[0]
  96. tId := v[1]
  97. Device.UpdateDeviceSensorDataTemperatureAndHumidity(sn, tId, startTime, endTime, temperature, humidity)
  98. }
  99. //4.反馈成功
  100. c.Data["json"] = lib.JSONS{200, "调整固定偏移值成功!", nil}
  101. c.ServeJSON()
  102. }
  103. // ProportionalScaling 等比缩放
  104. func (c *DataGeneratorController) ProportionalScaling() {
  105. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  106. if !b_ {
  107. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  108. c.ServeJSON()
  109. return
  110. }
  111. //1.解析数据
  112. var body = c.Ctx.Request.Body
  113. defer body.Close()
  114. type T struct {
  115. FixTemperature string `json:"fixTemperature"`
  116. FixHumidity string `json:"fixHumidity"`
  117. Sns [][2]string `json:"sns"`
  118. Data []int64 `json:"data"`
  119. }
  120. var temp = T{}
  121. bytes, _ := io.ReadAll(body)
  122. json.Unmarshal(bytes, &temp)
  123. fmt.Println("解析后:", temp.Data[0])
  124. //2.得到数据进行统一设置访问修改
  125. humidity, _ := strconv.ParseFloat(temp.FixHumidity, 64)
  126. temperature, _ := strconv.ParseFloat(temp.FixTemperature, 64)
  127. if temperature == 0 || humidity == 0 {
  128. temperature = 1
  129. humidity = 1
  130. }
  131. //开始时间到结束时间
  132. startTime := time.UnixMilli(temp.Data[0]).Format("2006-01-02 15:04:05")
  133. endTime := time.UnixMilli(temp.Data[1]).Format("2006-01-02 15:04:05")
  134. //3.循环更新数据
  135. for _, v := range temp.Sns {
  136. sn := v[0]
  137. tId := v[1]
  138. Device.ProportionalScaling(sn, tId, startTime, endTime, temperature, humidity)
  139. }
  140. //4.反馈成功
  141. c.Data["json"] = lib.JSONS{200, "调整固定偏移值成功!", nil}
  142. c.ServeJSON()
  143. }
  144. // Delete 删除
  145. func (c *DataGeneratorController) Delete() {
  146. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  147. if !b_ {
  148. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  149. c.ServeJSON()
  150. return
  151. }
  152. //1.解析数据
  153. var body = c.Ctx.Request.Body
  154. defer body.Close()
  155. type T struct {
  156. Sns [][2]string `json:"sns"`
  157. Data []int64 `json:"data"`
  158. }
  159. var temp = T{}
  160. bytes, _ := io.ReadAll(body)
  161. json.Unmarshal(bytes, &temp)
  162. fmt.Println("解析后:", temp.Data[0])
  163. //开始时间到结束时间
  164. startTime := time.UnixMilli(temp.Data[0]).Format("2006-01-02 15:04:05")
  165. endTime := time.UnixMilli(temp.Data[1]).Format("2006-01-02 15:04:05")
  166. //3.循环更新数据
  167. for _, v := range temp.Sns {
  168. sn := v[0]
  169. tId := v[1]
  170. Device.DeleteDeviceSensorDataByTimeRange(sn, tId, startTime, endTime)
  171. }
  172. //4.反馈成功
  173. c.Data["json"] = lib.JSONS{200, "调整固定偏移值成功!", nil}
  174. c.ServeJSON()
  175. }
  176. // UpdateRand 更新随机值
  177. func (c *DataGeneratorController) UpdateRand() {
  178. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  179. if !b_ {
  180. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  181. c.ServeJSON()
  182. return
  183. }
  184. //解析请求参数
  185. body := c.Ctx.Request.Body
  186. defer body.Close()
  187. bytes, _ := io.ReadAll(body)
  188. type T struct {
  189. TemperatureMin int `json:"temperatureMin"`
  190. TemperatureMax int `json:"temperatureMax"`
  191. HumidityMax int `json:"humidityMax"`
  192. HumidityMin int `json:"humidityMin"`
  193. Sns [][2]string `json:"sns"`
  194. Data []int64 `json:"data"`
  195. }
  196. var t = T{}
  197. json.Unmarshal(bytes, &t)
  198. fmt.Println("requestJSON: ", t, "原始json:", string(bytes))
  199. //开始时间到结束时间
  200. startTime := time.UnixMilli(t.Data[0]).Format("2006-01-02 15:04:05")
  201. endTime := time.UnixMilli(t.Data[1]).Format("2006-01-02 15:04:05")
  202. for _, v := range t.Sns {
  203. sn := v[0]
  204. tId := v[1]
  205. Device.UpdateDeviceSensorDataTemperatureAndHumidityRandom(sn, tId, startTime, endTime, t.TemperatureMax, t.TemperatureMin, t.HumidityMax, t.HumidityMin)
  206. }
  207. //反馈成功
  208. c.Data["json"] = lib.JSONS{200, "调整随机偏移值成功!", nil}
  209. c.ServeJSON()
  210. return
  211. }
  212. // CopyFromPosition 数据拷贝
  213. func (c *DataGeneratorController) CopyFromPosition() {
  214. b_, admin := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  215. if !b_ {
  216. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  217. c.ServeJSON()
  218. return
  219. }
  220. var body = c.Ctx.Request.Body
  221. defer body.Close()
  222. bytes, _ := io.ReadAll(body)
  223. type T struct {
  224. CopyPosition string `json:"copyPosition"`
  225. Sns [][2]string `json:"sns"`
  226. Data []int64 `json:"data"`
  227. }
  228. t := T{}
  229. json.Unmarshal(bytes, &t)
  230. //开始时间 和结束时间,插入的时间范围
  231. fmt.Println(t)
  232. copyTime, _ := time.Parse("2006-01-02 15:04:05", t.CopyPosition)
  233. startTime := time.UnixMilli(t.Data[0]).Format("2006-01-02 15:04:05")
  234. endTime := time.UnixMilli(t.Data[1]).Format("2006-01-02 15:04:05")
  235. for _, v := range t.Sns {
  236. sn := v[0]
  237. tId := v[1]
  238. list := Device.SelectDeviceSensorDataListByTimeRange(sn, tId, startTime, endTime)
  239. saveTime := Device.ReadDeviceParameterByTsn(sn).T_saveT
  240. ct := copyTime
  241. go func(list []Device.DeviceSensorData, sn string, saveTime int) {
  242. for _, d := range list {
  243. d.T_time = ct.Format("2006-01-02 15:04:05")
  244. d.CreateTime = ct.Format("2006-01-02 15:04:05")
  245. Device.InsertDeviceSensorData(sn, d, admin)
  246. ct = ct.Add(time.Second * time.Duration(saveTime))
  247. }
  248. }(list, sn, saveTime)
  249. }
  250. c.Data["json"] = lib.JSONS{200, "数据复制已提交后台处理!", nil}
  251. c.ServeJSON()
  252. return
  253. }
  254. // RepairSensorData 数据补漏
  255. func (c *DataGeneratorController) RepairSensorData() {
  256. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  257. if !b_ {
  258. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  259. c.ServeJSON()
  260. return
  261. }
  262. sns := make([][2]string, 0)
  263. timeRange := make([]int64, 0)
  264. json.Unmarshal([]byte(c.GetString("sns")), &sns)
  265. json.Unmarshal([]byte(c.GetString("data")), &timeRange)
  266. start := time.UnixMilli(timeRange[0]).Format("2006-01-02 15:04:05")
  267. end := time.UnixMilli(timeRange[1]).Format("2006-01-02 15:04:05")
  268. num := 0
  269. for _, v := range sns {
  270. listdevices, lists := Listdevices(v[0], v[1], start, end)
  271. num = normal(listdevices, lists.T_save_t, lists.T_warn, lists.Sn, lists.T_tlower, lists.T_tupper, lists.T_r_hlower, lists.T_r_hupper)
  272. }
  273. //for _, v := range sns {
  274. // sn := v[0]
  275. // tId := v[1]
  276. // saveTime := Device.ReadDeviceParameterByTsn(sn).T_saveT
  277. // list := Device.SelectDeviceSensorDataListByTimeRange(sn, tId, start, end)
  278. //
  279. // for i := 0; i < len(list)-1; i++ {
  280. // current := list[i].T_time
  281. // next := list[i+1].T_time
  282. // ct, _ := time.Parse("2006-01-02 15:04:05 +0800 CST", current)
  283. // //format := cts.Format("2006-01-02 15:04:05")
  284. // //ct, _ := time.Parse("2006-01-02 15:04:05", format)
  285. //
  286. // n, _ := time.Parse("2006-01-02 15:04:05 +0800 CST", next)
  287. // //nsfmt := ns.Format("2006-01-02 15:04:05")
  288. // //n, _ := time.Parse("2006-01-02 15:04:05", nsfmt)
  289. // interval := n.Unix() - ct.Unix()
  290. // logs.Debug("时间间隔:", interval)
  291. // fmt.Println("当前:", current, "下一个:", next)
  292. // if int(interval) > saveTime {
  293. // ttInterval := list[i+1].T_t - list[i].T_t
  294. // ttt := list[i].T_t // 温度临时变量
  295. // trhInterval := list[i+1].T_rh - list[i].T_rh
  296. // trht := list[i].T_rh //湿度临时变量
  297. // count := int(interval) / saveTime
  298. // num += count
  299. // for k := 0; k < count; k++ {
  300. // t := ct.Format("2006-01-02 15:04:05") //时间临时变量
  301. // ttt += ttInterval / float64(count)
  302. // trht += trhInterval / float64(count)
  303. // Device.InsertDeviceSensorData(sn, Device.DeviceSensorData{
  304. // list[i].T_id,
  305. // list[i].T_sp,
  306. // t,
  307. // lib.Decimal(ttt),
  308. // lib.Decimal(trht),
  309. // list[i].T_site,
  310. // list[i].CreateTime,
  311. // }, admin)
  312. // ct = ct.Add(time.Second * time.Duration(saveTime))
  313. // }
  314. // }
  315. // }
  316. //
  317. //}
  318. c.Data["json"] = lib.JSONS{200, fmt.Sprintf("补漏完成!共补漏%d条数据", num), nil}
  319. c.ServeJSON()
  320. return
  321. }
  322. func Listdevices(sn, t_id, startTime, endTime string) ([]Device.DeviceData, Device.DeviceLists) {
  323. var deviceslist Device.DeviceLists
  324. sql := fmt.Sprintf("SELECT * FROM z_device_data_%s WHERE t_id=%s and t_time BETWEEN '%s' AND '%s';", sn, t_id, startTime, endTime)
  325. deviceslist.Sn = sn
  326. var devices []Device.DeviceData
  327. o := orm.NewOrm()
  328. queryRows, err := o.Raw(sql).QueryRows(&devices)
  329. if err != nil {
  330. log.Fatal(queryRows, err)
  331. return devices, deviceslist
  332. }
  333. sqls := fmt.Sprintf("SELECT t_save_t,t_warn FROM device_parameter WHERE t_sn='%s' ORDER BY update_time DESC LIMIT 1", sn)
  334. deviceSensorParameter := fmt.Sprintf("SELECT t__tlower,t__tupper,t__r_hlower,t__r_hupper FROM device_sensor_parameter WHERE t_sn='%s' and t__state=1 and t_id = '%s' ORDER BY update_time DESC LIMIT 1", sn, t_id)
  335. var save_t string
  336. var t_warn string
  337. err = o.Raw(sqls).QueryRow(&save_t, &t_warn)
  338. deviceslist.T_save_t = save_t
  339. deviceslist.T_warn = t_warn
  340. if err != nil {
  341. log.Fatal(err)
  342. return devices, deviceslist
  343. }
  344. err = o.Raw(deviceSensorParameter).QueryRow(&deviceslist.T_tlower, &deviceslist.T_tupper, &deviceslist.T_r_hlower, &deviceslist.T_r_hupper)
  345. if err != nil {
  346. log.Fatal(err)
  347. return devices, deviceslist
  348. }
  349. return devices, deviceslist
  350. }
  351. // 正常情况下补漏数据
  352. func normal(devices []Device.DeviceData, t_save_t, t_warn, sn string, t_tlower, t_tupper, t_r_hlower, t_r_hupper float64) int {
  353. num := 0
  354. timeFormat := "2006-01-02 15:04:05 -0700 MST"
  355. Format := "2006-01-02 15:04:05"
  356. floatSave, _ := strconv.ParseFloat(t_save_t, 64)
  357. newOrm := orm.NewOrm()
  358. for i := 0; i < len(devices)-1; i++ {
  359. t1, err := time.Parse(timeFormat, devices[i].T_time)
  360. if err != nil {
  361. log.Println("解析时间失败:", err)
  362. continue
  363. }
  364. t2, err := time.Parse(timeFormat, devices[i+1].T_time)
  365. if err != nil {
  366. log.Println("解析时间失败:", err)
  367. continue
  368. }
  369. timeDiff := t2.Sub(t1).Seconds()
  370. if timeDiff > floatSave {
  371. fmt.Printf("时间差大于系统设置时间:%s 和 %s\n", devices[i].T_time, devices[i+1].T_time)
  372. numInserts := int(timeDiff / floatSave)
  373. ttInterval := devices[i+1].T_t - devices[i].T_t
  374. ttt := devices[i].T_t // 温度临时变量
  375. trhInterval := devices[i+1].T_rh - devices[i].T_rh
  376. trht := devices[i].T_rh //湿度临时变量
  377. for j := 1; j <= numInserts-1; j++ {
  378. t := t1.Truncate(time.Minute)
  379. newTime := t.Add(time.Duration(j*int(floatSave)) * time.Second)
  380. //T_T, T_Rh := IsNotWarn(devices, t_tlower, t_tupper, t_r_hlower, t_r_hupper)
  381. ttt += ttInterval / float64(numInserts)
  382. trht += trhInterval / float64(numInserts)
  383. devi := Device.DeviceData{
  384. T_id: devices[i].T_id,
  385. T_sp: devices[i].T_sp,
  386. T_time: newTime.Format(Format),
  387. //T_t: T_T,
  388. T_t: lib.Decimal(ttt),
  389. T_rh: lib.Decimal(trht),
  390. T_site: devices[i].T_site,
  391. Create_time: newTime.Format(Format),
  392. }
  393. insertSql := fmt.Sprintf("INSERT INTO z_device_data_%s (t_id, t_sp, t_time, t_t, t_rh, t_site, create_time) VALUES (?, ?, ?, ?, ?, ?, ?)", sn)
  394. log.Println(insertSql)
  395. _, err := newOrm.Raw(insertSql, devi.T_id, devi.T_sp, devi.T_time, devi.T_t, devi.T_rh, devi.T_site.String, devi.Create_time).Exec()
  396. if err != nil {
  397. log.Println("插入新时间点失败:", err)
  398. return 0
  399. }
  400. num++
  401. log.Println("sn:", sn, "补漏数据:", devi, " 插入时间点:", newTime.Format(timeFormat))
  402. }
  403. }
  404. }
  405. return num
  406. }
  407. // 判断是否在预警范围内,并且返回在预警内的值
  408. func IsNotWarn(deviceDatas []Device.DeviceData, t_tlower, t_tupper, t_r_hlower, t_r_hupper float64) (T_T, T_Rh float64) {
  409. for i, _ := range deviceDatas {
  410. if i == len(deviceDatas)-1 {
  411. break // 最后一个元素没有下一个元素,直接跳过
  412. }
  413. if !(deviceDatas[i].T_t < t_tlower || deviceDatas[i].T_t > t_tupper || deviceDatas[i].T_rh < t_r_hlower || deviceDatas[i].T_rh > t_r_hupper) {
  414. if deviceDatas[i].T_rh != 0 {
  415. T_Rh = deviceDatas[i].T_rh + rand.Float64()*0.1
  416. }
  417. T_T = deviceDatas[i].T_t + rand.Float64()*0.1
  418. if T_T >= deviceDatas[i+1].T_t {
  419. T_T = deviceDatas[i].T_t // 如果新温度值不小于下一个设备数据的温度值,则使用当前设备数据的温度值
  420. }
  421. if i > 0 && deviceDatas[i-1].T_t > deviceDatas[i+1].T_t {
  422. T_T -= 0.1
  423. if T_T < t_tlower {
  424. T_T = t_tlower
  425. }
  426. }
  427. T_Rh = deviceDatas[i].T_rh
  428. return T_T, T_Rh
  429. }
  430. }
  431. return 0, 0
  432. }
  433. func (c *DataGeneratorController) RepairAllSensorData() {
  434. b_, admin := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  435. if !b_ {
  436. // 用户验证逻辑省略
  437. }
  438. o := orm.NewOrm()
  439. deviceList := []Device.Device{}
  440. var err error
  441. _, err = o.QueryTable(new(Device.Device)).
  442. Filter("T_model__in", []string{"BX200GSE", "MD100", "MD200G", "BX100", "KF100", "MD300G"}).
  443. Filter("T_state", 1).
  444. //Filter("T_pid", 80).
  445. Filter("T_sn", "kf861693223539284").
  446. All(&deviceList)
  447. if err != nil {
  448. logs.Error("获取设备列表失败", err)
  449. return
  450. }
  451. start := "2024.05.14 00:00:00"
  452. end := time.Now().Format("2006-01-02 15:04:05")
  453. // 初始化Excel文件
  454. f := excelize.NewFile()
  455. // 创建工作表
  456. sheetName := "RepairLog"
  457. f.NewSheet(sheetName)
  458. // 设置列标题
  459. f.SetCellValue(sheetName, "A1", "设备序列号")
  460. f.SetCellValue(sheetName, "B1", "传感器ID")
  461. f.SetCellValue(sheetName, "C1", "补漏起始时间")
  462. f.SetCellValue(sheetName, "D1", "补漏结束时间")
  463. f.SetCellValue(sheetName, "E1", "补漏数据量")
  464. row := 2 // 从第二行开始记录数据
  465. totalRows := 0 // 总的补漏条数
  466. for _, device := range deviceList {
  467. deviceSensorList := []Device.DeviceSensor{}
  468. _, err = o.QueryTable(new(Device.DeviceSensor)).Filter("T_sn", device.T_sn).All(&deviceSensorList)
  469. if err != nil {
  470. logs.Error(lib.FuncName(), err)
  471. continue
  472. }
  473. num := map[int]int{} // 用于存储每个传感器ID补漏的数量
  474. startTime := map[int]string{} // 用于存储每个传感器ID补漏的起始时间
  475. endTime := map[int]string{} // 用于存储每个传感器ID补漏的结束时间
  476. for _, v := range deviceSensorList {
  477. sn := v.T_sn
  478. itoa := strconv.Itoa(v.T_id)
  479. saveTime := Device.ReadDeviceParameterByTsn(sn).T_saveT
  480. list := Device.SelectDeviceSensorDataListByTimeRange(sn, itoa, start, end)
  481. // 确定每个传感器ID补漏的起始时间和结束时间
  482. for i := 0; i < len(list)-1; i++ {
  483. current := list[i].T_time
  484. next := list[i+1].T_time
  485. ct, _ := time.Parse("2006-01-02 15:04:05 +0800 CST", current)
  486. n, _ := time.Parse("2006-01-02 15:04:05 +0800 CST", next)
  487. interval := n.Unix() - ct.Unix()
  488. if int(interval) > saveTime {
  489. ttInterval := list[i+1].T_t - list[i].T_t
  490. ttt := list[i].T_t // 温度临时变量
  491. trhInterval := list[i+1].T_rh - list[i].T_rh
  492. trht := list[i].T_rh //湿度临时变量
  493. count := int(interval) / saveTime
  494. num[v.T_id] += count
  495. for k := 0; k < count; k++ {
  496. t := ct.Add(time.Duration(k) * time.Duration(saveTime) * time.Second).Format("2006-01-02 15:04:05") //时间临时变量
  497. ttt += ttInterval / float64(count)
  498. trht += trhInterval / float64(count)
  499. Device.InsertDeviceSensorData(sn, Device.DeviceSensorData{
  500. list[i].T_id,
  501. list[i].T_sp,
  502. t,
  503. lib.Decimal(ttt),
  504. lib.Decimal(trht),
  505. list[i].T_site,
  506. list[i].CreateTime,
  507. }, admin)
  508. logs.Println(t)
  509. }
  510. // 更新起始时间和结束时间
  511. if _, ok := startTime[v.T_id]; !ok {
  512. startTime[v.T_id] = ct.Format("2006-01-02 15:04:05")
  513. }
  514. endTime[v.T_id] = ct.Add(time.Duration(count-1) * time.Duration(saveTime) * time.Second).Format("2006-01-02 15:04:05")
  515. }
  516. }
  517. }
  518. // 记录每个设备及其每个传感器ID的数据
  519. for sensorID, count := range num {
  520. if count > 0 { // 只记录补漏数量大于0的数据
  521. f.SetCellValue(sheetName, fmt.Sprintf("A%d", row), device.T_sn)
  522. f.SetCellValue(sheetName, fmt.Sprintf("B%d", row), sensorID)
  523. f.SetCellValue(sheetName, fmt.Sprintf("C%d", row), startTime[sensorID])
  524. f.SetCellValue(sheetName, fmt.Sprintf("D%d", row), endTime[sensorID])
  525. f.SetCellValue(sheetName, fmt.Sprintf("E%d", row), count)
  526. row++
  527. totalRows += count
  528. }
  529. }
  530. //time.Sleep(time.Second * 1)
  531. }
  532. // 在最后一行记录总的补漏条数
  533. f.SetCellValue(sheetName, fmt.Sprintf("A%d", row), "总补漏条数")
  534. f.SetCellValue(sheetName, fmt.Sprintf("B%d", row), totalRows)
  535. // 保存Excel文件
  536. if err := f.SaveAs("repair_log.xlsx"); err != nil {
  537. logs.Error("保存Excel文件失败", err)
  538. return
  539. }
  540. c.Data["json"] = lib.JSONS{200, fmt.Sprintf("所有设备补漏完成!"), nil}
  541. c.ServeJSON()
  542. return
  543. }
  544. // DataSensorDataSmooth 数据平滑
  545. func (c *DataGeneratorController) DataSensorDataSmooth() {
  546. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  547. if !b_ {
  548. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  549. c.ServeJSON()
  550. return
  551. }
  552. var (
  553. sns [][2]string
  554. timeRange []int64
  555. tRange float64
  556. hRange float64
  557. )
  558. json.Unmarshal([]byte(c.GetString("sns")), &sns)
  559. json.Unmarshal([]byte(c.GetString("data")), &timeRange)
  560. tRange, _ = c.GetFloat("tRange")
  561. hRange, _ = c.GetFloat("hRange")
  562. start := time.UnixMilli(timeRange[0]).Format("2006-01-02 15:04:05")
  563. end := time.UnixMilli(timeRange[1]).Format("2006-01-02 15:04:05")
  564. fmt.Println(tRange, hRange)
  565. var count int
  566. for _, v := range sns {
  567. sn := v[0]
  568. id := v[1]
  569. list := Device.SelectDeviceSensorDataListByTimeRange(sn, id, start, end)
  570. for i := 1; i < len(list); i++ {
  571. n := list[i-1]
  572. old := list[i]
  573. newO := list[i]
  574. //变化差
  575. var tInterval = old.T_t - n.T_t
  576. var hInterval = old.T_rh - n.T_rh
  577. fmt.Println("温度:", n.T_t, "温度next:", old.T_t, "差值:", n.T_t-old.T_t)
  578. if tRange != 0 {
  579. if tInterval > tRange {
  580. newO.T_t = n.T_t + tRange
  581. } else if tInterval < -tRange {
  582. newO.T_t = n.T_t - tRange
  583. }
  584. }
  585. if hRange != 0 {
  586. if hInterval > hRange {
  587. newO.T_rh = n.T_rh + hRange
  588. } else if hInterval < -hRange {
  589. newO.T_rh = n.T_rh - hRange
  590. }
  591. }
  592. if old != newO {
  593. fmt.Println("原始数据:", old, "新数据:", newO)
  594. list[i] = newO
  595. newO.T_t = lib.Decimal(newO.T_t)
  596. newO.T_rh = lib.Decimal(newO.T_rh)
  597. Device.UpdateDeviceSensorData(sn, id, old, newO)
  598. count++
  599. }
  600. }
  601. }
  602. c.Data["json"] = lib.JSONS{200, "操作成功处理" + fmt.Sprint(count) + "条数据", nil}
  603. c.ServeJSON()
  604. }
  605. // DataSensorDataTrend 数据趋势
  606. func (c *DataGeneratorController) DataSensorDataTrend() {
  607. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  608. if !b_ {
  609. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  610. c.ServeJSON()
  611. return
  612. }
  613. //获取数据
  614. timeRange := make([]int64, 0)
  615. sns := make([][2]string, 0)
  616. json.Unmarshal([]byte(c.GetString("data")), &timeRange)
  617. json.Unmarshal([]byte(c.GetString("sns")), &sns)
  618. start := time.UnixMilli(timeRange[0]).Format("2006-01-02 15:04:05")
  619. end := time.UnixMilli(timeRange[1]).Format("2006-01-02 15:04:05")
  620. for _, v := range sns {
  621. sn := v[0]
  622. tId := v[1]
  623. list := Device.SelectDeviceSensorDataListByTimeRange(sn, tId, start, end)
  624. first := list[0]
  625. last := list[len(list)-1]
  626. ttInterval := (last.T_t - first.T_t) / float64(len(list)-2)
  627. trhInterval := (last.T_rh - first.T_rh) / float64(len(list)-2)
  628. if len(list) < 3 {
  629. continue
  630. }
  631. for i, d := range list[1 : len(list)-1] {
  632. old := list[i]
  633. if ttInterval != 0 {
  634. d.T_t = list[0].T_t + float64(i+1)*ttInterval
  635. }
  636. if trhInterval != 0 {
  637. d.T_rh = list[0].T_rh + float64(i+1)*trhInterval
  638. }
  639. if d != old {
  640. d.T_t = lib.Decimal(d.T_t)
  641. d.T_rh = lib.Decimal(d.T_rh)
  642. Device.UpdateDeviceSensorData(sn, tId, old, d)
  643. }
  644. }
  645. }
  646. c.Data["json"] = lib.JSONS{200, "设置平滑操作成功", nil}
  647. c.ServeJSON()
  648. return
  649. }
  650. // ImportSensorData 导入数据
  651. func (c *DataGeneratorController) ImportSensorData() {
  652. b_, admin := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  653. if !b_ {
  654. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  655. c.ServeJSON()
  656. return
  657. }
  658. //读取文件
  659. file, _, err := c.GetFile("file")
  660. if err != nil {
  661. fmt.Println("读取form文件失败", err.Error())
  662. }
  663. //解析文件
  664. read, err := excelize.OpenReader(file)
  665. if err != nil {
  666. fmt.Println("解析错误:", err.Error())
  667. }
  668. rows, err := read.GetRows("data")
  669. if err != nil {
  670. fmt.Println("解析excel错误", err.Error())
  671. }
  672. values := make([][]string, 0)
  673. for _, row := range rows[1:] {
  674. //t_id t_sp t_time t_t t_rh t_site create_time
  675. values = append(values, row)
  676. }
  677. //添加操作
  678. sns := strings.Split(c.GetString("sn"), "|")
  679. for _, v := range sns {
  680. for _, ev := range values {
  681. temperature, _ := strconv.ParseFloat(ev[4], 64)
  682. humidty, _ := strconv.ParseFloat(ev[5], 64)
  683. temperature = lib.Decimal(temperature)
  684. humidty = lib.Decimal(humidty)
  685. data := Device.ToSensorData(strings.Split(v, ",")[1], ev[1], ev[2], ev[3], temperature, humidty, ev[6])
  686. Device.InsertDeviceSensorData(strings.Split(v, ",")[0], data, admin)
  687. }
  688. }
  689. c.Data["json"] = lib.JSONS{200, "导入数据成功!", nil}
  690. c.ServeJSON()
  691. return
  692. }