DataGeneratorController.go 21 KB

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