DeviceData.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. package Device
  2. import (
  3. "ColdP_server/conf"
  4. "ColdP_server/controllers/lib"
  5. "database/sql"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/astaxie/beego/cache"
  9. _ "github.com/astaxie/beego/cache/redis"
  10. "github.com/beego/beego/v2/adapter/orm"
  11. orm2 "github.com/beego/beego/v2/client/orm"
  12. _ "github.com/go-sql-driver/mysql"
  13. "github.com/xuri/excelize/v2"
  14. "log"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // 建表
  20. // var CREATEsql = "CREATE TABLE IF NOT EXISTS `z_device_data_" + SN + " ( " +
  21. var CREATEsql = " ( " +
  22. "`t_id` int(6) NOT NULL," +
  23. "`t_sp` int(6) NOT NULL," +
  24. "`t_time` datetime NOT NULL," +
  25. "`t_t` double(6, 2) NULL DEFAULT NULL," +
  26. "`t_rh` double(6, 2) NULL DEFAULT NULL," +
  27. "`t_site` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL," +
  28. "`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP," +
  29. "PRIMARY KEY (`t_time`, `t_id`) USING BTREE" +
  30. ") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;"
  31. type DeviceData_ struct {
  32. T_id int // 传感器id
  33. T_sp int // 传感器参数id
  34. T_t float32 // 温度
  35. T_rh float32 // 湿度
  36. T_site string // GPS
  37. T_time time.Time // 采集时间
  38. Create_time time.Time //创建时间
  39. }
  40. type DeviceData struct {
  41. T_id string `json:"t_id"`
  42. T_sp string `json:"t_sp"`
  43. T_time string `json:"t_time"`
  44. T_t float64 `json:"t_t"`
  45. T_rh float64 `json:"t_rh"`
  46. T_site sql.NullString `json:"t_site"`
  47. Create_time string `json:"create_time"`
  48. }
  49. type DeviceLists struct {
  50. T_save_t string //系统设置间隔时间
  51. T_warn string // 报警间隔时间
  52. T_tlower float64 // 低温下限
  53. T_tupper float64 // 高温上限
  54. T_r_hlower float64 // 湿度下限
  55. T_r_hupper float64 // 湿度上限
  56. Sn string // sn
  57. }
  58. // 模板
  59. type DeviceData_R struct {
  60. T_sn string `json:"t_sn"` //设备
  61. T_id int `json:"t_id"` // 传感器id
  62. T_sp int `json:"t_sp"` // 传感器参数id
  63. T_name string `json:"t_name"` // 传感器名称
  64. T_t float32 `json:"t_t"` // 温度
  65. T_rh float32 `json:"t_rh"` // 湿度
  66. T_site string `json:"t_site"` // GPS
  67. T_tl float32 `json:"t_tl"` // 温度下限
  68. T_tu float32 `json:"t_tu"` // 温度上限
  69. T_rhl float32 `json:"t_rhl"` // 湿度下限
  70. T_rhu float32 `json:"t_rhu"` // 湿度上限
  71. T_time string `json:"t_time"` // 采集时间
  72. Create_Time string `json:"create_time"`
  73. }
  74. //func (t *DeviceData) TableName() string {
  75. // return "DeviceData" // 数据库名称 // ************** 替换 FormulaList **************
  76. //}
  77. var redis_DeviceData cache.Cache
  78. func init() {
  79. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  80. "redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  81. fmt.Println(config)
  82. var err error
  83. redis_DeviceData, err = cache.NewCache("redis", config)
  84. if err != nil || redis_DeviceData == nil {
  85. errMsg := "failed to init redis"
  86. fmt.Println(errMsg, err)
  87. }
  88. }
  89. func DeviceData_ToDeviceData_R(r DeviceData_, maps map[int]DeviceSensorParameter_M) (t DeviceData_R) {
  90. t.T_id = r.T_id
  91. t.T_t = r.T_t
  92. t.T_rh = r.T_rh
  93. t.T_site = r.T_site
  94. t.T_time = r.T_time.Format("2006-01-02 15:04:05")
  95. t.Create_Time = r.Create_time.Format("2006-01-02 15:04:05")
  96. if sp, ok := maps[r.T_sp]; ok {
  97. t.T_sp = sp.T_sp
  98. t.T_name = sp.T_name
  99. t.T_tl = sp.T_Tlower
  100. t.T_tu = sp.T_Tupper
  101. t.T_rhl = sp.T_RHlower
  102. t.T_rhu = sp.T_RHupper
  103. }
  104. return
  105. }
  106. // ---------------- Redis -------------------
  107. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  108. func RedisDeviceData_Set(key string, r DeviceData_R) (err error) {
  109. if redis_DeviceData.IsExist(key) {
  110. var t DeviceData_R
  111. v := redis_DeviceData.Get(key)
  112. json.Unmarshal(v.([]byte), &t)
  113. tTime, _ := time.Parse("2006-01-02 15:04:05", t.T_time)
  114. rTime, _ := time.Parse("2006-01-02 15:04:05", r.T_time)
  115. if tTime.Unix() > rTime.Unix() {
  116. // 储存的 是最新数据
  117. return
  118. }
  119. }
  120. //json序列化
  121. str, err := json.Marshal(r)
  122. if err != nil {
  123. fmt.Print(err)
  124. return
  125. }
  126. err = redis_DeviceData.Put(key, str, 1*time.Hour)
  127. if err != nil {
  128. fmt.Println("set key:", key, ",value:", str, err)
  129. }
  130. return
  131. }
  132. func RedisDeviceData_Get(key string) (r DeviceData_R, is bool) {
  133. if redis_DeviceData.IsExist(key) {
  134. v := redis_DeviceData.Get(key)
  135. json.Unmarshal(v.([]byte), &r)
  136. return r, true
  137. }
  138. return DeviceData_R{}, false
  139. }
  140. // -------------------------------------------------------
  141. // 创建数据库 Device.CREATE_DeviceData("")
  142. func CREATE_DeviceData(SN string) bool {
  143. sql := "CREATE TABLE IF NOT EXISTS `z_device_data_" + SN + "` " + CREATEsql
  144. o := orm.NewOrm()
  145. _, err := o.Raw(sql).Exec()
  146. if err != nil {
  147. return false
  148. }
  149. return true
  150. }
  151. func DELETE_DeviceDatar(SN string) bool {
  152. timeStr := time.Now().Format("2006_01_02_15_04_05")
  153. //sql := "DROP TABLE z_device_data_" + SN
  154. sql := "ALTER TABLE z_device_data_" + SN + " RENAME TO " + "z_device_data_" + SN + "_dle_" + timeStr + ";"
  155. o := orm.NewOrm()
  156. _, err := o.Raw(sql).Exec()
  157. if err != nil {
  158. return false
  159. }
  160. return true
  161. }
  162. // ---------------- 特殊方法 ------------------
  163. type DeviceData_T struct {
  164. T_id int // ID
  165. T_t float32 // 温度
  166. T_rh float32 // 湿度
  167. T_Site string // GPS
  168. T_time time.Time // 采集时间
  169. }
  170. // 添加
  171. func Add_DeviceData(SN string, v DeviceData_T) bool {
  172. //if(conf.Test_server){
  173. // fmt.Println("Add_DeviceData:",SN , t_name , t_id , t_t , t_rh , t_tl , t_tu , t_rhl , t_rhu , t_site , t_battery , t_time)
  174. // return true
  175. //}
  176. key_time := SN + "|" + strconv.Itoa(v.T_id) + "|" + v.T_time.Format("2006-01-02 15:04:05")
  177. fmt.Println(key_time)
  178. if redis_DeviceData.IsExist(key_time) {
  179. //println("找到key:",key)
  180. return true
  181. }
  182. o := orm.NewOrm()
  183. // 检查 超过时间,查询 数据库
  184. if time.Now().Unix()-v.T_time.Unix() >= 60*40 {
  185. // 查看是否 有记录
  186. var maps_z []orm2.ParamsList
  187. sql_c := "SELECT COUNT(ID) FROM z_device_data_" + SN + " WHERE t_time = '" + v.T_time.Format("2006-01-02 15:04:05") + "' AND t_id = " + strconv.Itoa(v.T_id)
  188. _, err := o.Raw(sql_c).ValuesList(&maps_z)
  189. if err != nil {
  190. return false
  191. }
  192. //fmt.Println("maps_z[0][0]:",maps_z[0][0])
  193. if lib.To_int(maps_z[0][0]) > 0 {
  194. return true
  195. }
  196. }
  197. // 开始插入数据
  198. sql := "INSERT INTO z_device_data_" + SN + " ( `t_id`, `t_t`, `t_rh`, `t_site`, `t_time`) " +
  199. "VALUES (" + strconv.Itoa(v.T_id) + ", " + lib.To_string(v.T_t) + ", " + lib.To_string(v.T_rh) + ", '" + v.T_Site + "'," + v.T_time.Format("2006-01-02 15:04:05") + "')"
  200. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  201. fmt.Println(sql)
  202. res, err := o.Raw(sql).Exec()
  203. if err != nil {
  204. fmt.Println(err)
  205. return false
  206. }
  207. res.RowsAffected()
  208. return true
  209. }
  210. ///---------------
  211. //type DeviceData_ struct {
  212. // T_sn string `orm:"column(t_sn);size(256);null"` // 标题
  213. // T_id int `orm:"column(t_id);size(10);null"` // ID
  214. // T_t float32 `orm:"column(t_t);size(10);null"` // 温度
  215. // T_rh float32 `orm:"column(t_rh);size(10);null"` // 湿度
  216. // T_site string `orm:"column(t_site);type(timestamp);null;"` // GPS
  217. // T_time string `orm:"column(t_time);type(timestamp);null;"` // 采集时间
  218. //}
  219. //type DeviceData_New struct {
  220. // T_name string `orm:"column(t_name);size(256);null"` // 标题
  221. // T_id int `orm:"column(t_id);size(10);null"` // ID
  222. // T_t float32 `orm:"column(t_t);size(10);null"` // 温度
  223. // T_rh float32 `orm:"column(t_rh);size(10);null"` // 湿度
  224. // T_Tlower float32 `orm:"column(t_tl);size(10);null"` // 湿度
  225. // T_Tupper float32 `orm:"column(t_tu);size(10);null"` // 湿度
  226. // T_RHlower float32 `orm:"column(t_rhl);size(10);null"` // 湿度
  227. // T_RHupper float32 `orm:"column(t_rhu);size(10);null"` // 湿度
  228. // T_Site string `orm:"column(t_site);null;"` // GPS
  229. // T_Dattery int `orm:"column(t_dattery);size(10);null"` // 电量
  230. // T_time time.Time `orm:"column(t_time);type(timestamp);null;"` // 采集时间
  231. //}
  232. func Read_DeviceData_ById_List(SN string, T_id int, Time_start_ string, Time_end_ string, page int, page_z int, SParamMap map[int]DeviceSensorParameter_M, sort string) ([]DeviceData_R, int) {
  233. o := orm.NewOrm()
  234. var maps []DeviceData_
  235. var maps_z []orm2.ParamsList
  236. var r []DeviceData_R
  237. var offset int
  238. if page_z == 0 {
  239. page_z = conf.Page_size
  240. }
  241. if page <= 1 {
  242. offset = 0
  243. } else {
  244. offset = (page - 1) * page_z
  245. }
  246. sql_time := ""
  247. if len(Time_start_) > 1 {
  248. sql_time += " t_time >= '" + Time_start_ + "' AND "
  249. }
  250. if len(Time_end_) > 1 {
  251. sql_time += " t_time <= '" + Time_end_ + "' AND "
  252. }
  253. sql := "SELECT COUNT(t_id) FROM z_device_data_" + SN + " WHERE " + sql_time + " t_id = " + strconv.Itoa(T_id)
  254. fmt.Println(sql)
  255. _, err := o.Raw(sql).ValuesList(&maps_z)
  256. if err != nil {
  257. return r, 0
  258. }
  259. if len(maps_z) == 0 {
  260. return r, 0
  261. }
  262. //fmt.Println("maps_z;",maps_z[0][0])
  263. //t_tl,t_tu,t_rhl,t_rhu,
  264. sql = "SELECT t_id,t_sp,t_t,t_rh,t_site,DATE_FORMAT(t_time,'%Y-%m-%d %H:%i:%s') AS t_time,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s') AS create_time FROM z_device_data_" + SN + " WHERE " + sql_time + " t_id = " + strconv.Itoa(T_id) + " ORDER BY t_time " + sort
  265. if page_z != 9999 {
  266. sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z)
  267. }
  268. //fmt.Println(sql)
  269. _, err = o.Raw(sql).QueryRows(&maps)
  270. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  271. key, _ := strconv.Atoi(maps_z[0][0].(string))
  272. fmt.Println("\n\n\n\n\n\n搜索结果:", maps)
  273. for _, v := range maps {
  274. r = append(r, DeviceData_ToDeviceData_R(v, SParamMap))
  275. }
  276. return r, key
  277. }
  278. func Read_SqlRaw(T_SQL string) []orm2.Params {
  279. o := orm.NewOrm()
  280. var lists []orm2.Params
  281. fmt.Println(T_SQL)
  282. o.Raw(T_SQL).Values(&lists)
  283. fmt.Println(T_SQL+":", len(lists))
  284. return lists
  285. }
  286. func Read_SqlRawL(T_SQL string, T_data []string) (string, []orm2.Params) {
  287. o := orm.NewOrm()
  288. var lists []orm2.Params
  289. fmt.Println(T_SQL)
  290. _, err := o.Raw(T_SQL, T_data).Values(&lists)
  291. if err != nil {
  292. return err.Error(), lists
  293. }
  294. return "", lists
  295. }
  296. func Read_DeviceData_By_T_snid_List(T_snid string, Time_start_ string, Time_end_ string, page int, page_z int, sort string) ([]DeviceData_R, int64) {
  297. T_snid_list := strings.Split(T_snid, "|")
  298. var maps []DeviceData_R
  299. var maps_num int64
  300. var offset, offset_z int
  301. for _, v := range T_snid_list {
  302. sn_id := strings.Split(v, ",")
  303. if len(sn_id) == 2 {
  304. SParamMap := Read_DeviceSensorParameter_Map_All(sn_id[0], lib.To_int(sn_id[1]))
  305. r_maps, r_maps_num := Read_DeviceData_ById_List(sn_id[0], lib.To_int(sn_id[1]), Time_start_, Time_end_, 0, 9999, SParamMap, sort)
  306. //for i, _ := range r_maps {
  307. // r_maps[i].T_sn = sn_id[0]
  308. //}
  309. //添加一个sn设备标识
  310. for i := range r_maps {
  311. r_maps[i].T_sn = sn_id[0]
  312. }
  313. maps = append(maps, r_maps...)
  314. maps_num = maps_num + int64(r_maps_num)
  315. fmt.Println("加载数据:", sn_id[0], sn_id[1], r_maps_num)
  316. }
  317. }
  318. if page <= 1 {
  319. offset = 0
  320. } else {
  321. page -= 1
  322. offset = page * page_z
  323. }
  324. offset_z = offset + page_z
  325. if maps_num < int64(offset_z) {
  326. offset_z = int(maps_num)
  327. }
  328. if page_z == 9999 {
  329. fmt.Println("总数据:", maps_num, " 导出")
  330. return maps, maps_num
  331. }
  332. fmt.Println("总数据:", maps_num, " 截取", offset, offset+page_z)
  333. return maps[offset:offset_z], maps_num
  334. }
  335. // DeleteDeviceDataByDeviceDataRList 删除记录
  336. func DeleteDeviceDataByDeviceDataRList(datas []DeviceData_R) {
  337. o := orm.NewOrm()
  338. for _, v := range datas {
  339. _, err := o.Raw(fmt.Sprintf("delete from z_device_data_%s where t_id = ? and t_t = ? and t_rh = ? and t_site = ? and create_time = ?", v.T_sn), v.T_id, v.T_t, v.T_rh, v.T_site, v.Create_Time).Exec()
  340. if err != nil {
  341. fmt.Println(err.Error())
  342. }
  343. }
  344. }
  345. func DeleteDeviceDataByTime(sn, t_id, time_start, time_end string) (sql.Result, error) {
  346. o := orm.NewOrm()
  347. sprintf := fmt.Sprintf("delete from z_device_data_%s where t_id=%s and t_time >= '%s' and t_time <= '%s'", sn, t_id, time_start, time_end)
  348. log.Println(sprintf)
  349. count, err := o.Raw(sprintf).Exec()
  350. if err != nil {
  351. log.Println(err.Error())
  352. return count, err
  353. }
  354. return count, nil
  355. }
  356. // ImportDeviceData 批量导入
  357. func ImportDeviceData(reader *excelize.File, sn string) string {
  358. sheetName := reader.GetSheetName(0)
  359. rows, err := reader.GetRows(sheetName)
  360. o := orm.NewOrm()
  361. if err != nil {
  362. panic(any(err.Error()))
  363. }
  364. values := make([]string, len(rows)-1)
  365. for i, row := range rows {
  366. if i == 0 {
  367. //跳过第一条头部描述
  368. continue
  369. }
  370. // 定义匹配的解析格式
  371. format := row[4]
  372. _, err := time.Parse("2006-01-02 15:04:05", row[4])
  373. if err != nil {
  374. layout := "1/2/06 15:04"
  375. parsedTime, _ := time.Parse(layout, row[4])
  376. year := parsedTime.Year()
  377. if year < 100 {
  378. year += 2000
  379. }
  380. parsedTime = time.Date(year, parsedTime.Month(), parsedTime.Day(), parsedTime.Hour(), parsedTime.Minute(), parsedTime.Second(), parsedTime.Nanosecond(), time.UTC)
  381. format = parsedTime.Format("2006-01-02 15:04:05")
  382. }
  383. isrepeat := Read_DeviceData_Execl_ISREPEAT(sn, format, row[0])
  384. t_sp := Read_device_sensor_parameter(sn, row[0])
  385. if t_sp == "" {
  386. sprintf := fmt.Sprintf("当前sn或探头参数ID不存在:%s,%s", sn, row[0])
  387. return sprintf
  388. }
  389. if isrepeat {
  390. //如果重复就用更新数据
  391. sql := fmt.Sprintf("UPDATE z_device_data_%s SET t_t=%s,t_rh=%s WHERE t_time='%s' AND t_id=%s ", sn, row[1], row[2], format, row[0])
  392. _, err := o.Raw(sql).Exec()
  393. if err != nil {
  394. fmt.Println(err.Error())
  395. return "更新失败"
  396. }
  397. } else {
  398. // t_id,t_t,t_rh,t_time
  399. //传感器 传感器参数ID 温度 湿度 GPS 采集时间 创建时间
  400. parse, _ := time.Parse("2006-01-02 15:04:05", format)
  401. parse = parse.Add(time.Millisecond * 8000)
  402. parse.Format("2006-01-02 15:04:05")
  403. values[i-1] = fmt.Sprintf("(%s,%s,%s,%s,'','%s')", row[0], t_sp, row[1], row[2], format)
  404. sprintf := fmt.Sprintf("insert into z_device_data_%s (t_id,t_sp,t_t,t_rh,t_site,t_time,create_time) values (%s,%s,%s,%s,'%s','%s','%s')", sn, row[0], t_sp, row[1], row[2], row[3], format, parse.Format("2006-01-02 15:04:05"))
  405. log.Println(sprintf)
  406. //执行SQL
  407. _, err := o.Raw(sprintf).Exec()
  408. if err != nil {
  409. fmt.Println("执行失败")
  410. return "请检查表格是否具有重复数据!!!"
  411. }
  412. }
  413. }
  414. //sqlStatement := fmt.Sprintf("insert into z_device_data_%s(t_id,t_sp,t_t,t_rh,t_site,t_time) values %s", sn, strings.Join(values, ","))
  415. //fmt.Println("执行批量导入SQL:", sqlStatement)
  416. return "导入成功"
  417. }
  418. func Read_DeviceData_Execl_ISREPEAT(sn, t_time, t_id string) bool {
  419. o := orm.NewOrm()
  420. var table struct {
  421. T_id string
  422. T_time string
  423. }
  424. sql := fmt.Sprintf("select t_id,t_time from z_device_data_%s where t_time = '%s' and t_id=%s", sn, t_time, t_id)
  425. err := o.Raw(sql).QueryRow(&table)
  426. if err != nil {
  427. fmt.Println(err.Error())
  428. return false
  429. } else {
  430. if table.T_id != "" {
  431. return true
  432. }
  433. }
  434. return false
  435. }
  436. // ExportDeviceData 导出 未完成
  437. /*func ExportDeviceData(sns []string, startTime, endTime string) *os.File {
  438. f, err := os.Create(fmt.Sprintf("[%s]导出数据.zip", time.Now().Format("2006-01-02")))
  439. if err != nil {
  440. fmt.Println(err.Error())
  441. }
  442. z := zip.NewWriter(f)
  443. o := orm.NewOrm()
  444. sqlStatement := "select * from z_device_data_%s where create_time between %s and %s"
  445. title := map[string]string{
  446. "A1": "传感器",
  447. "B1": "传感器参数ID",
  448. "C1": "温度",
  449. "D1": "湿度",
  450. "E1": "GPS",
  451. "F1": "采集时间",
  452. "G1": "创建时间",
  453. }
  454. for _, sn := range sns {
  455. datas := make([]DeviceData_, 0)
  456. sqlNew := fmt.Sprintf(sqlStatement, sn, startTime, endTime)
  457. o.Raw(sqlNew).QueryRows(&datas)
  458. //创建压缩包中的excel
  459. excelT, err := z.Create(fmt.Sprintf("%s.xlsx", sn))
  460. if err != nil {
  461. fmt.Println(err.Error())
  462. }
  463. //创建新的excel
  464. excelNew := excelize.NewFile()
  465. excelNew.NewSheet(sn)
  466. //设置表头
  467. for k, v := range title {
  468. excelNew.SetCellStr(sn, k, v)
  469. }
  470. //设置内容
  471. for i, v := range datas {
  472. }
  473. }
  474. return f
  475. }
  476. */
  477. // Update_DeviceSensorData 更新设备数据
  478. func Update_DeviceSensorData(v DeviceData_R, fieldName, val string) error {
  479. o := orm.NewOrm()
  480. if fieldName == "t__tlower" {
  481. split := strings.Split(val, "|")
  482. i := strings.Split(split[0], "~")
  483. t__tlower := i[0]
  484. t__tupper := i[1]
  485. i2 := strings.Split(split[1], "~")
  486. t__r_hlower := i2[0]
  487. t__r_hupper := i2[1]
  488. sqlStatemt := fmt.Sprintf("update device_sensor_parameter set t__tlower =%s , t__tupper = %s , t__r_hlower = %s , t__r_hupper = %s where id =%d ", t__tlower, t__tupper, t__r_hlower, t__r_hupper, v.T_sp)
  489. //log.Println(sqlStatemt)
  490. _, err := o.Raw(sqlStatemt).Exec()
  491. if err != nil {
  492. return err
  493. }
  494. return nil
  495. } else {
  496. sqlStatemt := fmt.Sprintf("update z_device_data_%s set %s = ? where t_id = ? and t_t = ? and t_rh = ? and t_site = ? and create_time = ?", v.T_sn, fieldName)
  497. log.Println(sqlStatemt)
  498. log.Println("创建时间:", v.Create_Time)
  499. _, err := o.Raw(sqlStatemt, val, v.T_id, v.T_t, v.T_rh, v.T_site, v.Create_Time).Exec()
  500. if err != nil {
  501. return err
  502. }
  503. return nil
  504. }
  505. }
  506. // 复制添加数据
  507. func Copy_DeviceData(T_sn, T_id string, T_Rh, T_T any, T_Site, CreateTime string) {
  508. T_sp := Read_device_sensor_parameter(T_sn, T_id)
  509. o := orm.NewOrm()
  510. sprintf := fmt.Sprintf("insert into z_device_data_%s(t_id,t_sp,t_time,t_t,t_rh,t_site,create_time) values (?,?,?,?,?,?,?)", T_sn)
  511. //log.Println(sprintf)
  512. _, err := o.Raw(sprintf, T_id, T_sp, CreateTime, T_T, T_Rh, T_Site, CreateTime).Exec()
  513. if err != nil {
  514. fmt.Println(err.Error())
  515. }
  516. }
  517. func Read_DeviceData_ById_Year_List(SN string) []orm2.ParamsList {
  518. o := orm.NewOrm()
  519. var maps_z []orm2.ParamsList
  520. //sql = "SELECT t_name,t_t,t_rh,t_tl,t_tu,t_rhl,t_rhu,t_site,DATE_FORMAT(t_time,'%Y-%c-%d %H:%i:%s') AS t_time FROM z_device_data_"+SN+" WHERE "+sql_time+" t_id = "+ strconv.Itoa(T_id) +" ORDER BY t_time DESC "
  521. sql := "SELECT DATE_FORMAT(t_time,\"%m\") AS m ,DATE_FORMAT(t_time,\"%d\") AS d FROM z_device_data_" + SN + " WHERE t_time > '" + strconv.Itoa(time.Now().Year()) + "-0-0 00:00:00' GROUP BY DATE_FORMAT(t_time,\"%m\");"
  522. fmt.Println(sql)
  523. num, err := o.Raw(sql).ValuesList(&maps_z)
  524. if err == nil && num > 0 {
  525. fmt.Println(maps_z[0][0]) // slene
  526. }
  527. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  528. //key,_ := strconv.Atoi(maps_z[0][0].(string))
  529. return maps_z
  530. } //
  531. func Read_DeviceData_ById_Month_List(SN string) []orm2.ParamsList {
  532. o := orm.NewOrm()
  533. var maps_z []orm2.ParamsList
  534. currentTime := time.Now() //获取当前时间,类型是Go的时间类型Time
  535. time_x := currentTime.Format("2006-01") + "-00 00:00:00"
  536. //sql = "SELECT t_name,t_t,t_rh,t_tl,t_tu,t_rhl,t_rhu,t_site,DATE_FORMAT(t_time,'%Y-%c-%d %H:%i:%s') AS t_time FROM z_device_data_"+SN+" WHERE "+sql_time+" t_id = "+ strconv.Itoa(T_id) +" ORDER BY t_time DESC "
  537. sql := "SELECT DATE_FORMAT(t_time,\"%d\") AS d FROM z_device_data_" + SN + " WHERE t_time > '" + time_x + "' GROUP BY DATE_FORMAT(t_time,\"%d\");"
  538. fmt.Println(sql)
  539. o.Raw(sql).ValuesList(&maps_z)
  540. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  541. //key,_ := strconv.Atoi(maps_z[0][0].(string))
  542. return maps_z
  543. }
  544. func Read_device_sensor_parameter(SN, t_id string) string {
  545. o := orm.NewOrm()
  546. var maps_z []orm2.ParamsList
  547. //sql = "SELECT t_name,t_t,t_rh,t_tl,t_tu,t_rhl,t_rhu,t_site,DATE_FORMAT(t_time,'%Y-%c-%d %H:%i:%s') AS t_time FROM z_device_data_"+SN+" WHERE "+sql_time+" t_id = "+ strconv.Itoa(T_id) +" ORDER BY t_time DESC "
  548. sql := "SELECT ID FROM device_sensor_parameter WHERE `t_sn` = '" + SN + "' AND `t_id` = '" + t_id + "' AND `t__state` = '1' ORDER BY `ID` DESC LIMIT 0,2;"
  549. fmt.Println(sql)
  550. list, err := o.Raw(sql).ValuesList(&maps_z)
  551. if err != nil {
  552. return ""
  553. }
  554. if list == 0 {
  555. fmt.Println("没有数据")
  556. return ""
  557. } else {
  558. return maps_z[0][0].(string)
  559. }
  560. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  561. //key,_ := strconv.Atoi(maps_z[0][0].(string))
  562. }
  563. func Read_DeviceData_ById_Day_List(SN string) []orm2.ParamsList {
  564. o := orm.NewOrm()
  565. var maps_z []orm2.ParamsList
  566. currentTime := time.Now() //获取当前时间,类型是Go的时间类型Time
  567. time_x := currentTime.Format("2006-01-02") + " 00:00:00"
  568. //sql = "SELECT t_name,t_t,t_rh,t_tl,t_tu,t_rhl,t_rhu,t_site,DATE_FORMAT(t_time,'%Y-%c-%d %H:%i:%s') AS t_time FROM z_device_data_"+SN+" WHERE "+sql_time+" t_id = "+ strconv.Itoa(T_id) +" ORDER BY t_time DESC "
  569. sql := "SELECT DATE_FORMAT(t_time,\"%H\") AS m FROM z_device_data_" + SN + " WHERE t_time > '" + time_x + "' GROUP BY DATE_FORMAT(t_time,\"%H\");"
  570. fmt.Println(sql)
  571. o.Raw(sql).ValuesList(&maps_z)
  572. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  573. //key,_ := strconv.Atoi(maps_z[0][0].(string))
  574. return maps_z
  575. }
  576. func Read_DeviceData_List_GROUP_BY_t_time(SN string, Time_start_ string, Time_end_ string) []orm2.ParamsList {
  577. o := orm.NewOrm()
  578. var maps_z []orm2.ParamsList
  579. sql_time := ""
  580. if len(Time_start_) > 1 {
  581. sql_time += " t_time >= '" + Time_start_ + "' AND " + " t_time <= '" + Time_end_ + "' "
  582. }
  583. sql := "SELECT DATE_FORMAT(t_time,'%Y-%c-%d %H:%i:%s') AS t_time FROM z_device_data_" + SN + " WHERE " + sql_time + " GROUP BY t_time ORDER BY t_time DESC "
  584. fmt.Println(sql)
  585. o.Raw(sql).ValuesList(&maps_z)
  586. return maps_z
  587. }
  588. // GetCompanyBySn 根据sn查询公司名称
  589. func GetCompanyBySn(sn string) (string, error) {
  590. o := orm.NewOrm()
  591. sqls := fmt.Sprintf("SELECT t_pid FROM `device` WHERE t_sn='%s'", sn)
  592. var TPid string
  593. err := o.Raw(sqls).QueryRow(&TPid)
  594. if err != nil {
  595. return "", err
  596. }
  597. sqlCompany := fmt.Sprintf("SELECT t_name FROM `company` WHERE id='%s'", TPid)
  598. var TName string
  599. err = o.Raw(sqlCompany).QueryRow(&TName)
  600. if err != nil {
  601. return "", err
  602. }
  603. TName = TName + "[" + TPid + "]"
  604. return TName, nil
  605. }