DataGeneratorController.go 24 KB

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