DeviceSensor.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. package Device
  2. import (
  3. "ColdP_server/conf"
  4. "ColdP_server/controllers/lib"
  5. "ColdP_server/logs"
  6. "ColdP_server/models/Account"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/astaxie/beego/cache"
  10. _ "github.com/astaxie/beego/cache/redis"
  11. "github.com/beego/beego/v2/adapter/orm"
  12. orm2 "github.com/beego/beego/v2/client/orm"
  13. _ "github.com/go-sql-driver/mysql"
  14. "log"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // 模板
  20. type DeviceSensor struct {
  21. Id int `orm:"column(ID);size(11);auto;pk"`
  22. T_sn string `orm:"index;size(256);null"` // 设备序列号 KF开头,环境监测主机。 YD开头,温途监测主机
  23. T_id int `orm:"index;size(11);null"` // 传感器编号
  24. T_name string `orm:"size(256);null"` // 标题
  25. T_pid int `orm:"index;size(256);null"` // Account.Company 绑定公司
  26. T_Class string `orm:"size(256);null"` // Device.DeviceClass.Id 设备分类 C1|C2|
  27. T_Notice string `orm:"size(256);null"` // 通知绑定
  28. T_datashow int `orm:"index;size(2);default(1)"` // 0 屏蔽数据展示 1 正常数据展示 (屏蔽后 数据展示无法看到,设备管理中 不受影响)
  29. T_sort int `orm:"index;size(200);default(1)"` // 排序
  30. T_3dview string `orm:"size(256);null"` // 3D 视图ID
  31. T_type int `orm:"index;size(4);null"` // Device.DeviceSensorType 1库房 2移动
  32. // 设备同步参数
  33. T_Dattery int `orm:"size(4);null"` // 电量
  34. T_Site string `orm:"size(200);null"` // GPS
  35. T_monitor int `orm:"index;size(2);null"` // 监控状态 0 未监控 1 监控
  36. T_online int `orm:"index;size(2);default(1)"` // 在线状态 0 未启用 1 在线 2 离线
  37. T_online_s int `orm:"index;size(2);default(0)"` // 在线状态-备用 0 未启用 1 在线 2 离线
  38. T_State int `orm:"index;size(2);default(1)"` // 0 屏蔽 1 正常 (屏蔽后 只有内部管理员才能看到,用户 输入SN\名称 搜索时 也能看到)
  39. CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
  40. UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"` //auto_now 每次 model 保存时都会对时间自动更新
  41. }
  42. type DeviceSensor_Del struct {
  43. T_sn string
  44. T_id int
  45. }
  46. func (t *DeviceSensor) TableName() string {
  47. return "device_sensor" // 数据库名称 // ************** 替换 FormulaList **************
  48. }
  49. // 模板
  50. type DeviceSensor_R struct {
  51. T_sn string // 设备序列号 KF开头,环境监测主机。 YD开头,温途监测主机
  52. T_id int // 传感器编号
  53. T_name string // 标题
  54. T_3dview string // 3D 视图ID
  55. T_sort int // 排序
  56. T_Dattery int // 电量
  57. T_Site string // GPS
  58. T_monitor int // 记录状态
  59. T_online int // 在线状态 1 在线 0 离线
  60. T_online_s int // 在线状态-备用 0 未启用 1 在线 2 离线
  61. T_datashow int // 0 屏蔽数据展示 1 正常数据展示
  62. T_type int // 1库房 2移动
  63. T_DeviceSensorData DeviceData_R // 传感器最新数据
  64. T_DeviceSensorParameter DeviceSensorParameter_R // 设备参数
  65. }
  66. // DeviceSensorData 处理数据生成专用
  67. type DeviceSensorData struct {
  68. T_id int `json:"t_id"`
  69. T_sp string `json:"t_sp"`
  70. T_time string `json:"t_time"`
  71. T_t float64 `json:"t_t"`
  72. T_rh float64 `json:"t_rh"`
  73. T_site string `json:"t_site"`
  74. CreateTime string `json:"create_time"`
  75. }
  76. // 传感器管理
  77. type DeviceSensor_P struct {
  78. T_sn string // 设备序列号 KF开头,环境监测主机。 YD开头,温途监测主机
  79. T_id int // 传感器编号
  80. T_name string // 标题
  81. T_sort int // 排序
  82. T_datashow int // 0 屏蔽数据展示 1 正常数据展示
  83. T_State int // 0 屏蔽 1 正常
  84. // DeviceSensorParameter
  85. T_Tlower *float32 // 温度下限
  86. T_Tupper *float32 // 温度上限
  87. T_RHlower *float32 // 湿度下限
  88. T_RHupper *float32 // 湿度上限
  89. T_enprel *int // 是否启用预警 1开启 0 关闭
  90. T_tprel *float32 // 温度预警下限
  91. T_tpreu *float32 // 温度预警上限
  92. T_hprel *float32 // 湿度预警下限
  93. T_hpreu *float32 // 温度预警上限
  94. T_en *int // en:是否启用传感器,
  95. T_free *int // free:监测点是否为闲置状态(空库,只监测不报警)
  96. }
  97. type DeviceSensor_ struct {
  98. T_sn string // 设备序列号 KF开头,环境监测主机。 YD开头,温途监测主机
  99. T_id int // 传感器编号
  100. T_name string // 标题
  101. }
  102. type DataOld struct {
  103. ID int `json:"ID"`
  104. TSn string `json:"t_sn"`
  105. TId int `json:"t_id"`
  106. TTime string `json:"t_time"`
  107. TT float64 `json:"t_t"`
  108. TRh float64 `json:"t_rh"`
  109. TSite string `json:"t__site"`
  110. TOperation int `json:"t_operation"`
  111. TUuid string `json:"t_uuid"`
  112. CreateTime string `json:"create_time"`
  113. }
  114. var redisCache_DeviceSensor cache.Cache
  115. func init() {
  116. //注册模型
  117. orm.RegisterModel(new(DeviceSensor))
  118. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  119. "redis_DeviceSensor", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  120. fmt.Println(config)
  121. var err error
  122. redisCache_DeviceSensor, err = cache.NewCache("redis", config)
  123. if err != nil || redisCache_DeviceSensor == nil {
  124. errMsg := "failed to init redis"
  125. logs.Error(errMsg, err)
  126. panic(any(errMsg))
  127. }
  128. }
  129. // ---------------- Redis -------------------
  130. // Redis_Device_Set(m.T_sn,m) // Redis 更新缓存
  131. func Redis_DeviceSensor_Set(r DeviceSensor) (err error) {
  132. key := r.T_sn + "|" + strconv.Itoa(r.T_id)
  133. //json序列化
  134. str, err := json.Marshal(r)
  135. if err != nil {
  136. logs.Error(lib.FuncName(), err)
  137. return
  138. }
  139. err = redisCache_DeviceSensor.Put(key, str, 24*time.Hour)
  140. if err != nil {
  141. logs.Error("set key:", key, ",value:", str, err)
  142. }
  143. return
  144. }
  145. func Redis_DeviceSensor_Get(key string) (r DeviceSensor, is bool) {
  146. if redisCache_DeviceSensor.IsExist(key) {
  147. //println("找到key:",key)
  148. v := redisCache_DeviceSensor.Get(key)
  149. err := json.Unmarshal(v.([]byte), &r)
  150. if err != nil {
  151. logs.Error(lib.FuncName(), err)
  152. return DeviceSensor{}, false
  153. }
  154. return r, true
  155. }
  156. return DeviceSensor{}, false
  157. }
  158. func Redis_DeviceSensor_DelK(r DeviceSensor) (err error) {
  159. key := r.T_sn + "|" + strconv.Itoa(r.T_id)
  160. err = redisCache_DeviceSensor.Delete(key)
  161. if err != nil {
  162. logs.Error(lib.FuncName(), err)
  163. }
  164. return
  165. }
  166. // ---------------- 特殊方法 -------------------
  167. /*
  168. func DeviceSensorToDeviceSensor_R(DeviceSensor_ DeviceSensor) (DeviceSensor_r DeviceSensor_R) {
  169. lib.DeviceRealSnMap[DeviceSensor_.T_sn] = 3 // 连续请求 实时数据
  170. DeviceSensor_r.T_sn = DeviceSensor_.T_sn
  171. DeviceSensor_r.T_id = DeviceSensor_.T_id
  172. DeviceSensor_r.T_name = DeviceSensor_.T_name
  173. DeviceSensor_r.T_Site = DeviceSensor_.T_Site
  174. DeviceSensor_r.T_Dattery = DeviceSensor_.T_Dattery
  175. DeviceSensor_r.T_monitor = DeviceSensor_.T_monitor
  176. DeviceSensor_r.T_3dview = DeviceSensor_.T_3dview
  177. DeviceSensor_r.T_type = DeviceSensor_.T_type
  178. DeviceSensor_r.T_sort = DeviceSensor_.T_sort
  179. DeviceSensor_r.T_datashow = DeviceSensor_.T_datashow
  180. DeviceSensor_r.T_Dattery = DeviceSensor_.T_Dattery
  181. DeviceSensor_r.T_online = DeviceSensor_.T_online
  182. DeviceSensor_r.T_online_s = DeviceSensor_.T_online_s
  183. DeviceSensor_r.T_monitor = DeviceSensor_.T_monitor
  184. if DeviceSensor_.T_online == 2 && (DeviceSensor_.T_online_s == 0 || DeviceSensor_.T_online_s == 2) && DeviceSensor_.T_monitor == 1 {
  185. DeviceSensor_r.T_monitor = 2
  186. }
  187. // 最新系统参数
  188. DeviceSensor_r.T_DeviceSensorParameter, _ = Read_DeviceSensorParameter(DeviceSensor_.T_sn, DeviceSensor_.T_id)
  189. // 最新数据
  190. //key_data := DeviceSensor_.T_sn + "|" + strconv.Itoa(DeviceSensor_.T_id)
  191. //DeviceSensor_r.T_DeviceSensorData, _ = RedisDeviceData_Get(key_data)
  192. DeviceData := Read_DeviceData(DeviceSensor_.T_sn, DeviceSensor_.T_id)
  193. device, _ := Read_Device_ByT_sn(DeviceSensor_.T_sn)
  194. DeviceSensor_r.T_DeviceSensorData = DeviceData_ToDeviceData_R(device, DeviceData)
  195. return
  196. }
  197. */
  198. func DeviceSensorToDeviceSensor_(r DeviceSensor) (t DeviceSensor_) {
  199. t.T_sn = r.T_sn
  200. t.T_id = r.T_id
  201. t.T_name = r.T_name
  202. return
  203. }
  204. // ---------------- 特殊方法 -------------------
  205. // 获取列表 - 总数
  206. func Read_DeviceSensor_Num_ByT_sn(T_sn string) int {
  207. o := orm.NewOrm()
  208. // 也可以直接使用 Model 结构体作为表名
  209. qs := o.QueryTable(new(DeviceSensor))
  210. cnt, err := qs.Filter("T_sn", T_sn).Count()
  211. if err != nil {
  212. logs.Error(lib.FuncName(), err)
  213. return 0
  214. }
  215. return int(cnt)
  216. }
  217. /*// 获取列表
  218. func Read_DeviceSensorList(admin_r *Account.Admin, T_pid int, T_sn string, T_name string, T_Class_id, T_datashow, T_type, T_State int, page int, page_z int) (DeviceSensor_r []DeviceSensor_R, cnt int64) {
  219. o := orm.NewOrm()
  220. // 也可以直接使用 Model 结构体作为表名
  221. qs := o.QueryTable(new(DeviceSensor))
  222. var offset int64
  223. if page <= 1 {
  224. offset = 0
  225. } else {
  226. offset = int64((page - 1) * page_z)
  227. }
  228. var r []DeviceSensor
  229. cond := orm.NewCondition()
  230. cond1 := cond.And("T_pid", T_pid)
  231. if T_Class_id > 0 {
  232. T_Class := "C" + strconv.Itoa(T_Class_id) + "|"
  233. fmt.Println("T_Class:", T_Class)
  234. cond1 = cond1.And("T_Class__icontains", T_Class)
  235. }
  236. if T_type > 0 {
  237. cond1 = cond1.And("T_type", T_type)
  238. }
  239. if len(T_sn) > 0 {
  240. cond1 = cond1.And("T_sn__icontains", T_sn)
  241. }
  242. if len(T_name) > 0 {
  243. cond1 = cond1.AndCond(cond.Or("T_name__icontains", T_name).Or("T_sn__icontains", T_name))
  244. }
  245. // 不是内部权限(T_pid>0),T_State=1 0 屏蔽 1 正常
  246. if admin_r.T_pid > 0 || T_State == 1 {
  247. cond1 = cond1.And("T_State", 1)
  248. }
  249. if T_datashow == 1 { // 0 屏蔽数据展示 1 正常数据展示
  250. cond1 = cond1.And("T_datashow", 1)
  251. }
  252. _, err := qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_sort", "T_id").All(&r)
  253. if err != nil {
  254. logs.Error(lib.FuncName(), err)
  255. return
  256. }
  257. cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count()
  258. if err != nil {
  259. logs.Error(lib.FuncName(), err)
  260. return
  261. }
  262. for _, v := range r {
  263. DeviceSensor_r = append(DeviceSensor_r, DeviceSensorToDeviceSensor_R(v))
  264. }
  265. return DeviceSensor_r, cnt
  266. }
  267. */
  268. // 获取
  269. func Read_DeviceSensor_ByT_sn(T_sn string, T_id int) (r DeviceSensor, is bool) {
  270. o := orm.NewOrm()
  271. r = DeviceSensor{T_sn: T_sn, T_id: T_id}
  272. err := o.Read(&r, "T_sn", "T_id") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
  273. if err != nil {
  274. logs.Error(lib.FuncName(), err)
  275. return r, false
  276. }
  277. return r, true
  278. }
  279. // 删除
  280. func Delete_DeviceSensor_ById(T_sn string, T_id int) (err error) {
  281. fmt.Println("Delete_DeviceSensor : T_sn", T_sn, "T_id", T_id)
  282. o := orm.NewOrm()
  283. r := DeviceSensor{T_sn: T_sn, T_id: T_id}
  284. err = o.Read(&r, "T_sn", "T_id") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
  285. if err != nil {
  286. fmt.Println("Delete_DeviceSensor_ById", err)
  287. return err
  288. }
  289. _, err = o.Delete(&DeviceSensor{Id: r.Id})
  290. if err != nil {
  291. logs.Error(lib.FuncName(), err)
  292. return err
  293. }
  294. Redis_DeviceSensor_DelK(r)
  295. return
  296. }
  297. // Get_DeviceSensor_Tid_ByT_sn 获取列表探头列表
  298. func Get_DeviceSensor_Tid_ByT_sn(T_sn string) (r []DeviceSensor) {
  299. o := orm.NewOrm()
  300. // 也可以直接使用 Model 结构体作为表名
  301. qs := o.QueryTable(new(DeviceSensor))
  302. _, err := qs.Filter("t_sn", T_sn).All(&r)
  303. if err != nil {
  304. logs.Error(lib.FuncName(), err)
  305. }
  306. return r
  307. }
  308. // 修改
  309. func Update_DeviceSensor(r DeviceSensor, cols ...string) bool {
  310. o := orm.NewOrm()
  311. num, err := o.Update(&r, cols...)
  312. if err != nil {
  313. logs.Error(lib.FuncName(), err)
  314. return false
  315. }
  316. fmt.Println("Number of records updated in database:", num)
  317. Redis_DeviceSensor_Set(r)
  318. return true
  319. }
  320. // 修改T_Class,替换为""
  321. func DeviceSensor_Bind_T_Class_Del(T_sn string, T_id int, T_Class_id int) (err error) {
  322. o := orm.NewOrm()
  323. v := DeviceSensor{T_sn: T_sn, T_id: T_id}
  324. T_Class := "C" + strconv.Itoa(T_Class_id) + "|"
  325. err = o.Read(&v, "T_sn", "T_id")
  326. if err != nil {
  327. logs.Error(lib.FuncName(), err)
  328. return err
  329. }
  330. v.T_Class = strings.Replace(v.T_Class, T_Class, "", -1)
  331. _, err = o.Update(&v, "T_Class")
  332. if err != nil {
  333. logs.Error(lib.FuncName(), err)
  334. return err
  335. }
  336. Redis_DeviceSensor_Set(v)
  337. return nil
  338. }
  339. // 修改T_Class,追加
  340. func DeviceSensor_Bind_T_Class_Add(T_sn string, T_id int, T_Class_id int) (err error) {
  341. o := orm.NewOrm()
  342. v := DeviceSensor{T_sn: T_sn, T_id: T_id}
  343. T_Class := "C" + strconv.Itoa(T_Class_id) + "|"
  344. err = o.Read(&v, "T_sn", "T_id")
  345. if err != nil {
  346. logs.Error(lib.FuncName(), err)
  347. return err
  348. }
  349. v.T_Class = strings.Replace(v.T_Class, T_Class, "", -1)
  350. v.T_Class = v.T_Class + T_Class
  351. _, err = o.Update(&v, "T_Class")
  352. if err != nil {
  353. logs.Error(lib.FuncName(), err)
  354. return err
  355. }
  356. Redis_DeviceSensor_Set(v)
  357. return nil
  358. }
  359. // 获取 ById
  360. func Read_DeviceSensor_ByTsn_Tid(T_sn string, T_id int) (r DeviceSensor, err error) {
  361. o := orm.NewOrm()
  362. r = DeviceSensor{T_sn: T_sn, T_id: T_id}
  363. err = o.Read(&r, "T_sn", "T_id") // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
  364. if err != nil {
  365. logs.Error(lib.FuncName(), err)
  366. }
  367. return r, err
  368. }
  369. // ReadDeviceSensorByTsnTidTimeRange 获取通过id和时间设备探头数据
  370. func ReadDeviceSensorByTsnTidTimeRange(T_sn string, T_id int, startTime, endTime string) (datas []DeviceSensorData, err error) {
  371. o := orm.NewOrm()
  372. sqlStatement := fmt.Sprintf("select t_id,t_sp,DATE_FORMAT(t_time,'%%Y-%%m-%%d %%H:%%i:%%s') as t_time,t_t,t_rh,DATE_FORMAT(create_time,'%%Y-%%m-%%d %%H:%%i:%%s') as create_time from z_device_data_%s where t_id = %d and t_time between '%s' and '%s'", T_sn, T_id, startTime, endTime)
  373. _, err = o.Raw(sqlStatement).QueryRows(&datas)
  374. return
  375. }
  376. // 获取列表
  377. func Read_DeviceSensor_ByTsn(T_sn string) ([]DeviceSensor, int) {
  378. o := orm.NewOrm()
  379. // 也可以直接使用 Model 结构体作为表名
  380. qs := o.QueryTable(new(DeviceSensor))
  381. var r []DeviceSensor
  382. _, err := qs.Filter("T_sn", T_sn).OrderBy("T_id").All(&r)
  383. if err != nil {
  384. logs.Error(lib.FuncName(), err)
  385. return r, 0
  386. }
  387. cnt, err := qs.Filter("T_sn", T_sn).Count()
  388. if err != nil {
  389. logs.Error(lib.FuncName(), err)
  390. return r, 0
  391. }
  392. return r, int(cnt)
  393. }
  394. // 获取列表
  395. func Read_DeviceSensor_List_T_ClassOr(T_pid int, T_Class_id int, T_sn string, T_name string, T_type int, page int, page_z int) (DeviceSensor_r []DeviceSensor_, cnt int64) {
  396. o := orm.NewOrm()
  397. // 也可以直接使用 Model 结构体作为表名
  398. qs := o.QueryTable(new(DeviceSensor))
  399. var offset int64
  400. if page <= 1 {
  401. offset = 0
  402. } else {
  403. offset = int64((page - 1) * page_z)
  404. }
  405. T_Class := ""
  406. if T_Class_id != 0 {
  407. T_Class = "C" + strconv.Itoa(T_Class_id) + "|"
  408. }
  409. fmt.Println("T_Class:", T_Class)
  410. var r []DeviceSensor
  411. cond := orm.NewCondition()
  412. cond1 := cond.And("T_pid", T_pid).And("T_State", 1).And("T_Class__icontains", T_Class).And("T_sn__icontains", T_sn).Or("T_name__icontains", T_name).And("T_pid", T_pid).And("T_State", 1).And("T_Class__icontains", T_Class) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
  413. if T_type > 0 {
  414. cond1 = cond1.AndCond(cond.And("T_type", T_type))
  415. }
  416. fmt.Printf("分页数据:%d ,%d\n\n\n\n", offset, page_z)
  417. _, err := qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_sort", "T_id").All(&r)
  418. if err != nil {
  419. logs.Error(lib.FuncName(), err)
  420. return
  421. }
  422. cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count()
  423. if err != nil {
  424. logs.Error(lib.FuncName(), err)
  425. return
  426. }
  427. for _, v := range r {
  428. DeviceSensor_r = append(DeviceSensor_r, DeviceSensorToDeviceSensor_(v))
  429. }
  430. return DeviceSensor_r, cnt
  431. }
  432. // 获取列表
  433. func Read_DeviceSensor_List_T_Class(T_pid int, T_Class_id int, T_sn string, T_name string, T_type int, page int, page_z int) (DeviceSensor_r []DeviceSensor_, cnt int64) {
  434. o := orm.NewOrm()
  435. // 也可以直接使用 Model 结构体作为表名
  436. qs := o.QueryTable(new(DeviceSensor))
  437. var offset int64
  438. if page <= 1 {
  439. offset = 0
  440. } else {
  441. offset = int64((page - 1) * page_z)
  442. }
  443. T_Class := ""
  444. if T_Class_id != 0 {
  445. T_Class = "C" + strconv.Itoa(T_Class_id) + "|"
  446. }
  447. fmt.Println("T_Class:", T_Class)
  448. var r []DeviceSensor
  449. cond := orm.NewCondition()
  450. cond1 := cond.And("T_pid", T_pid).And("T_State", 1).And("T_Class__icontains", T_Class).And("T_sn__icontains", T_sn).And("T_name__icontains", T_name) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
  451. if T_type > 0 {
  452. cond1 = cond1.AndCond(cond.And("T_type", T_type))
  453. }
  454. fmt.Printf("分页数据:%d ,%d\n\n\n\n", offset, page_z)
  455. _, err := qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_sort", "T_id").All(&r)
  456. if err != nil {
  457. logs.Error(lib.FuncName(), err)
  458. return
  459. }
  460. cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count()
  461. if err != nil {
  462. logs.Error(lib.FuncName(), err)
  463. return
  464. }
  465. for _, v := range r {
  466. DeviceSensor_r = append(DeviceSensor_r, DeviceSensorToDeviceSensor_(v))
  467. }
  468. return DeviceSensor_r, cnt
  469. }
  470. // 获取列表
  471. func Read_DeviceSensor_ALL_T_sn_T_id_T_Class(T_sn string, T_id int, T_Class_id int) (r []DeviceSensor) {
  472. o := orm.NewOrm()
  473. // 也可以直接使用 Model 结构体作为表名
  474. qs := o.QueryTable(new(DeviceSensor))
  475. T_Class := "C" + strconv.Itoa(T_Class_id) + "|"
  476. _, err := qs.Filter("T_Class__icontains", T_Class).Filter("T_id", T_id).Filter("T_sn", T_sn).All(&r)
  477. if err != nil {
  478. logs.Error(lib.FuncName(), err)
  479. return
  480. }
  481. return r
  482. }
  483. // 获取列表
  484. func Read_DeviceSensor_ALL_List_T_sn(T_sn string) (r []DeviceSensor) {
  485. o := orm.NewOrm()
  486. // 也可以直接使用 Model 结构体作为表名
  487. qs := o.QueryTable(new(DeviceSensor))
  488. _, err := qs.Filter("T_sn", T_sn).All(&r)
  489. if err != nil {
  490. logs.Error(lib.FuncName(), err)
  491. return
  492. }
  493. return r
  494. }
  495. // 获取列表
  496. func Read_DeviceSensor_ALL_Class_Id(T_Class_id int) (r []DeviceSensor) {
  497. o := orm.NewOrm()
  498. // 也可以直接使用 Model 结构体作为表名
  499. qs := o.QueryTable(new(DeviceSensor))
  500. T_Class := "C" + strconv.Itoa(T_Class_id) + "|"
  501. _, err := qs.Filter("T_Class__icontains", T_Class).All(&r)
  502. if err != nil {
  503. logs.Error(lib.FuncName(), err)
  504. return
  505. }
  506. return r
  507. }
  508. func DELETE_DeviceSensor(SN string) bool {
  509. sql := "DELETE FROM `cold`.`device_sensor` WHERE `t_sn` = '" + SN + "' "
  510. o := orm.NewOrm()
  511. _, err := o.Raw(sql).Exec()
  512. if err != nil {
  513. logs.Error(lib.FuncName(), err)
  514. return false
  515. }
  516. return true
  517. }
  518. // 报警策略 -------------------
  519. // 通过T_sn T_id T_Notice_id 获取全部列表
  520. func Read_DeviceSensor_ALL_T_sn_T_id_T_Notice(T_sn string, T_id int, T_Notice_id int) (r []DeviceSensor) {
  521. o := orm.NewOrm()
  522. // 也可以直接使用 Model 结构体作为表名
  523. qs := o.QueryTable(new(DeviceSensor))
  524. T_Notice := "N" + strconv.Itoa(T_Notice_id) + "|"
  525. _, err := qs.Filter("T_Notice__icontains", T_Notice).Filter("T_id", T_id).Filter("T_sn", T_sn).All(&r)
  526. if err != nil {
  527. logs.Error(lib.FuncName(), err)
  528. return
  529. }
  530. return r
  531. }
  532. // 修改T_Notice,替换为""
  533. func DeviceSensor_Bind_T_Notice_Del(T_sn string, T_id int, T_Notice_id int) (err error) {
  534. o := orm.NewOrm()
  535. v := DeviceSensor{T_sn: T_sn, T_id: T_id}
  536. T_Notice := "N" + strconv.Itoa(T_Notice_id) + "|"
  537. err = o.Read(&v, "T_sn", "T_id")
  538. if err != nil {
  539. logs.Error(lib.FuncName(), err)
  540. return
  541. }
  542. v.T_Notice = strings.Replace(v.T_Notice, T_Notice, "", -1)
  543. _, err = o.Update(&v, "T_Notice")
  544. if err != nil {
  545. logs.Error(lib.FuncName(), err)
  546. return
  547. }
  548. Redis_DeviceSensor_Set(v)
  549. return nil
  550. }
  551. // 修改T_Notice,追加
  552. func DeviceSensor_Bind_T_Notice_Add(T_sn string, T_id int, T_Notice_id int) (err error) {
  553. o := orm.NewOrm()
  554. v := DeviceSensor{T_sn: T_sn, T_id: T_id}
  555. T_Notice := "N" + strconv.Itoa(T_Notice_id) + "|"
  556. err = o.Read(&v, "T_sn", "T_id")
  557. if err != nil {
  558. logs.Error(lib.FuncName(), err)
  559. return
  560. }
  561. v.T_Notice = strings.Replace(v.T_Notice, T_Notice, "", -1)
  562. v.T_Notice = v.T_Notice + T_Notice
  563. _, err = o.Update(&v, "T_Notice")
  564. if err != nil {
  565. logs.Error(lib.FuncName(), err)
  566. return
  567. }
  568. Redis_DeviceSensor_Set(v)
  569. return nil
  570. }
  571. // 获取列表
  572. func Read_DeviceSensor_ALL_Notice_Id(T_Notice_id int) (r []DeviceSensor) {
  573. o := orm.NewOrm()
  574. // 也可以直接使用 Model 结构体作为表名
  575. qs := o.QueryTable(new(DeviceSensor))
  576. T_Notice := "N" + strconv.Itoa(T_Notice_id) + "|"
  577. _, err := qs.Filter("T_Notice__icontains", T_Notice).All(&r)
  578. if err != nil {
  579. logs.Error(lib.FuncName(), err)
  580. return
  581. }
  582. return r
  583. }
  584. // 获取列表
  585. func Read_DeviceSensor_List_T_Notice(T_pid int, T_Notice_id int, page int, page_z int, T_sn string, T_name string, T_type int) (DeviceSensor_r []DeviceSensor_, cnt int64) {
  586. o := orm.NewOrm()
  587. // 也可以直接使用 Model 结构体作为表名
  588. qs := o.QueryTable(new(DeviceSensor))
  589. var offset int64
  590. if page <= 1 {
  591. offset = 0
  592. } else {
  593. offset = int64((page - 1) * page_z)
  594. }
  595. T_Notice := ""
  596. if T_Notice_id != 0 {
  597. T_Notice = "N" + strconv.Itoa(T_Notice_id) + "|"
  598. }
  599. fmt.Println("T_Notice:", T_Notice)
  600. var r []DeviceSensor
  601. cond := orm.NewCondition()
  602. cond1 := cond.And("T_pid", T_pid).And("T_State", 1).And("T_Notice__icontains", T_Notice).And("T_sn__icontains", T_sn).And("T_name__icontains", T_name) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
  603. if T_type > 0 {
  604. cond1 = cond1.AndCond(cond.And("T_type", T_type))
  605. }
  606. _, err := qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_sort", "T_id").All(&r)
  607. if err != nil {
  608. logs.Error(lib.FuncName(), err)
  609. return
  610. }
  611. cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count()
  612. if err != nil {
  613. logs.Error(lib.FuncName(), err)
  614. return
  615. }
  616. for _, v := range r {
  617. DeviceSensor_r = append(DeviceSensor_r, DeviceSensorToDeviceSensor_(v))
  618. }
  619. return DeviceSensor_r, cnt
  620. }
  621. // 设备同步参数
  622. func Update_Device_To_DeviceSensor(r_Device Device) bool {
  623. DeviceSensor_list, _ := Read_DeviceSensor_ByTsn(r_Device.T_sn)
  624. for _, v := range DeviceSensor_list {
  625. // 设备同步参数
  626. v.T_Dattery = r_Device.T_Dattery // 电量
  627. v.T_Site = r_Device.T_Site // GPS
  628. v.T_monitor = r_Device.T_monitor // 监控状态 0 未监控 1 监控
  629. v.T_online = r_Device.T_online // 在线状态 0 未启用 1 在线 2 离线
  630. v.T_online_s = r_Device.T_online_s // 在线状态-备用 0 未启用 1 在线 2 离线
  631. v.T_State = r_Device.T_State // 0 屏蔽 1 正常 (屏蔽后 只有内部管理员才能看到,用户 输入SN\名称 搜索时 也能看到)
  632. Update_DeviceSensor(v, "T_Dattery", "T_Site", "T_type", "T_State", "T_monitor", "T_online", "T_online_s")
  633. }
  634. return true
  635. }
  636. // 传感器管理列列表 -------------------
  637. func Read_DeviceSensorManageList(admin_r *Account.Admin, T_pid int, T_name string, T_calss_id, T_en, T_free, T_datashow, T_sort, page, page_z int) (DeviceSensor_p []DeviceSensor_P, cnt int64) {
  638. o := orm.NewOrm()
  639. var maps []DeviceSensor_P
  640. var maps_z []orm2.ParamsList
  641. var offset int
  642. if page <= 1 {
  643. offset = 0
  644. } else {
  645. offset = (page - 1) * page_z
  646. }
  647. sql_WHERE := "t_pid = " + strconv.Itoa(T_pid)
  648. if admin_r.T_pid > 0 {
  649. sql_WHERE += " AND t__state = 1"
  650. }
  651. if len(T_name) > 0 {
  652. sql_WHERE += " AND (ds.t_sn like '%" + T_name + "%' OR t_name like '%" + T_name + "%')"
  653. }
  654. if T_calss_id > 0 {
  655. T_calss := "C" + strconv.Itoa(T_calss_id) + "|"
  656. sql_WHERE += " AND t__class like '%" + T_calss + "%'"
  657. }
  658. if T_en != -1 {
  659. sql_WHERE += " AND t_en = " + strconv.Itoa(T_en)
  660. }
  661. if T_free != -1 {
  662. sql_WHERE += " AND t_free = " + strconv.Itoa(T_free)
  663. }
  664. if T_datashow != -1 {
  665. sql_WHERE += " AND t_datashow =" + strconv.Itoa(T_datashow)
  666. }
  667. sql_ORDER := " ORDER BY t_sort ASC"
  668. if T_sort == 1 {
  669. sql_ORDER = " ORDER BY t_sort DESC"
  670. }
  671. // -------------
  672. sql := "SELECT COUNT(ds.ID) FROM " + "device_sensor ds " +
  673. "LEFT JOIN ( SELECT t_sn AS tsn,t_id AS tid,t_en,t_free " +
  674. "FROM device_sensor_parameter WHERE id IN (SELECT MAX(id) FROM device_sensor_parameter GROUP BY t_sn,t_id)) AS dsp " +
  675. "ON ds.t_sn = dsp.tsn AND ds.t_id = dsp.tid" + " WHERE " + sql_WHERE
  676. fmt.Println(sql)
  677. _, err := o.Raw(sql).ValuesList(&maps_z)
  678. if err != nil {
  679. logs.Error(lib.FuncName(), err)
  680. return DeviceSensor_p, 0
  681. }
  682. if len(maps_z) == 0 {
  683. return DeviceSensor_p, 0
  684. }
  685. //fmt.Println("maps_z;",maps_z[0][0])
  686. sql = "SELECT * FROM device_sensor ds " +
  687. "LEFT JOIN ( SELECT t_sn AS tsn,t_id AS tid,t_en,t_free,t__tlower,t__tupper,t__r_hlower,t__r_hupper,t_enprel,t_tprel,t_tpreu,t_hprel,t_hpreu " +
  688. "FROM device_sensor_parameter WHERE id IN (SELECT MAX(id) FROM device_sensor_parameter GROUP BY t_sn,t_id)) AS dsp " +
  689. "ON ds.t_sn = dsp.tsn AND ds.t_id = dsp.tid " +
  690. "WHERE " + sql_WHERE + sql_ORDER
  691. if page_z != 9999 {
  692. sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z)
  693. }
  694. fmt.Println(sql)
  695. _, err = o.Raw(sql).QueryRows(&maps)
  696. if err != nil {
  697. logs.Error(lib.FuncName(), err)
  698. return
  699. }
  700. key, _ := strconv.ParseInt(maps_z[0][0].(string), 10, 64)
  701. return maps, key
  702. }
  703. // 数据展示菜单下 传感器参数列表
  704. /*
  705. func Read_DeviceSensor_List_For_Data(T_pid int, T_name string, T_Class_id, T_type, T_RealTime int, page int, page_z int) (DeviceSensor_r []DeviceSensor_R, cnt int64) {
  706. o := orm.NewOrm()
  707. // 也可以直接使用 Model 结构体作为表名
  708. qs := o.QueryTable(new(DeviceSensor))
  709. var offset int64
  710. if page <= 1 {
  711. offset = 0
  712. } else {
  713. offset = int64((page - 1) * page_z)
  714. }
  715. var r []DeviceSensor
  716. cond := orm.NewCondition()
  717. cond1 := cond.And("T_pid", T_pid).And("T_State", 1)
  718. if T_Class_id > 0 {
  719. T_Class := "C" + strconv.Itoa(T_Class_id) + "|"
  720. fmt.Println("T_Class:", T_Class)
  721. cond1 = cond1.And("T_Class__icontains", T_Class)
  722. }
  723. if T_type > 0 {
  724. cond1 = cond1.And("T_type", T_type)
  725. }
  726. if len(T_name) == 16 {
  727. cond1 = cond1.And("T_sn", T_name)
  728. } else {
  729. cond1 = cond1.And("T_name__icontains", T_name).And("T_datashow", 1)
  730. }
  731. _, err := qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("T_sort", "T_id").All(&r)
  732. if err != nil {
  733. logs.Error(lib.FuncName(), err)
  734. return
  735. }
  736. cnt, err = qs.SetCond((*orm2.Condition)(cond1)).Count()
  737. if err != nil {
  738. logs.Error(lib.FuncName(), err)
  739. return
  740. }
  741. // 实时数据页面,温度或者湿度不在正常区间,排在最前面
  742. if T_RealTime == 1 {
  743. var DeviceSensor_unusual []DeviceSensor_R
  744. for _, v := range r {
  745. v_r := DeviceSensorToDeviceSensor_R(v)
  746. data := v_r.T_DeviceSensorData
  747. // 温度或者湿度不在正常区间,排在最前面
  748. if data.T_t > data.T_tu || data.T_t < data.T_tl || data.T_rh > data.T_rhu || data.T_rh < data.T_rhl {
  749. DeviceSensor_unusual = append(DeviceSensor_unusual, v_r)
  750. } else {
  751. DeviceSensor_r = append(DeviceSensor_r, v_r)
  752. }
  753. }
  754. DeviceSensor_unusual = append(DeviceSensor_unusual, DeviceSensor_r...)
  755. return DeviceSensor_unusual, cnt
  756. }
  757. for _, v := range r {
  758. DeviceSensor_r = append(DeviceSensor_r, DeviceSensorToDeviceSensor_R(v))
  759. }
  760. return DeviceSensor_r, cnt
  761. }
  762. */
  763. func ToSensorData(tid, tSp, tTime, tSite string, tt, trh float64, createTime string) DeviceSensorData {
  764. num, _ := strconv.ParseInt(tid, 10, 64)
  765. return DeviceSensorData{
  766. int(num),
  767. tSp,
  768. tTime,
  769. tt,
  770. trh,
  771. tSite,
  772. createTime,
  773. }
  774. }
  775. // UpdateDeviceSensorDataTemperatureAndHumidity 更新设备探头数据温湿度
  776. func UpdateDeviceSensorDataTemperatureAndHumidity(sn, id, startTime, endTime string, temperature, humidity float64) {
  777. sqlStatement := fmt.Sprintf("update z_device_data_%s set t_t = t_t + %f , t_rh = t_rh + %f where t_id = '%s' and t_time BETWEEN '%s' and '%s'", sn, temperature, humidity, id, startTime, endTime)
  778. o := orm.NewOrm()
  779. exec, err := o.Raw(sqlStatement).Exec()
  780. if err != nil {
  781. fmt.Println(err.Error())
  782. }
  783. affected, err := exec.RowsAffected()
  784. if err != nil {
  785. fmt.Println(err.Error())
  786. }
  787. fmt.Printf("影响了%d行\n", affected)
  788. }
  789. // SelectDeviceSensorDataListByTimeRange 搜索设备列表通过时间
  790. func SelectDeviceSensorDataListByTimeRange(sn, tId, startTime, endTime string) (list []DeviceSensorData) {
  791. //sqlStatement := fmt.Sprintf("select t_id,t_sp,DATE_FORMAT(t_time,'%%Y-%%m-%%d %%k:%%i:%%s') as t_time,t_t,t_rh,t_site,DATE_FORMAT(create_time,'%%Y-%%m-%%d %%k:%%i:%%s') as create_time from z_device_data_%s where t_id = %s and t_time BETWEEN '%s' AND '%s' ORDER BY t_time ASC", sn, tId, startTime, endTime)
  792. sqlStatement := fmt.Sprintf("select t_id,t_sp,t_time,t_t,t_rh,t_site,create_time from z_device_data_%s where t_id = %s and t_time BETWEEN '%s' AND '%s' ORDER BY t_time ASC", sn, tId, startTime, endTime)
  793. o := orm.NewOrm()
  794. rows, err := o.Raw(sqlStatement).QueryRows(&list)
  795. if err != nil {
  796. fmt.Println(err.Error())
  797. }
  798. fmt.Println("影响行数:", rows)
  799. return
  800. }
  801. // UpdateDeviceSensorDataTemperatureAndHumidityRandom 随机更新
  802. func UpdateDeviceSensorDataTemperatureAndHumidityRandom(sn, id, startTime, endTime string, ttMax, ttMin, trhMax, trhMin int) {
  803. //sql语句
  804. sqlStatement := fmt.Sprintf("update z_device_data_%s set t_t = t_t + Round(FLOOR(%d + RAND() * (%d - %d + 1)) /100.0,1), t_rh = t_rh + Round(FLOOR(%d + RAND() * (%d - %d + 1)) /100.0,1) where t_id = '%s' AND t_time BETWEEN '%s' AND '%s'", sn, ttMin, ttMax, ttMin, trhMin, trhMax, trhMin, id, startTime, endTime)
  805. o := orm.NewOrm()
  806. exec, err := o.Raw(sqlStatement).Exec()
  807. if err != nil {
  808. fmt.Println("执行错误:", sqlStatement)
  809. }
  810. affected, _ := exec.RowsAffected()
  811. fmt.Println("执行更新行数:", affected)
  812. }
  813. // UpdateDeviceSensorData 更新设备探头数据
  814. func UpdateDeviceSensorData(sn, tId string, old, newO DeviceSensorData) {
  815. sqlStatement := fmt.Sprintf("update z_device_data_%s set t_t = %f , t_rh = %f where t_id = %s and t_t = %f and t_rh = %f and t_time= '%s'", sn, newO.T_t, newO.T_rh, tId, old.T_t, old.T_rh, old.T_time)
  816. fmt.Println("执行SQL:", sqlStatement)
  817. o := orm.NewOrm()
  818. exec, err := o.Raw(sqlStatement).Exec()
  819. if err != nil {
  820. fmt.Println("执行错误:", sqlStatement, err.Error())
  821. }
  822. affected, _ := exec.RowsAffected()
  823. fmt.Println("执行更新行数:", affected)
  824. }
  825. // DeleteDeviceSensorDataByTimeRange 删除时间范围内的数据
  826. func DeleteDeviceSensorDataByTimeRange(sn, id, start, end string) {
  827. //把原本的根据创建时间删除更改为更具上传时间删除
  828. sqlStatement := fmt.Sprintf("delete from z_device_data_%s where t_time between '%s' and '%s' and t_id = %s", sn, start, end, id)
  829. //sqlStatement := fmt.Sprintf("delete from z_device_data_%s where create_time between '%s' and '%s' and t_id = %s", sn, start, end, id)
  830. o := orm.NewOrm()
  831. log.Printf("执行SQL:", sqlStatement)
  832. exec, err := o.Raw(sqlStatement).Exec()
  833. if err != nil {
  834. fmt.Println(err.Error())
  835. }
  836. affected, _ := exec.RowsAffected()
  837. fmt.Printf("从%s~%s时间段删除了%d条数据", start, end, affected)
  838. }
  839. // InsertDeviceSensorData 添加设备数据
  840. func InsertDeviceSensorData(sn string, d DeviceSensorData, admin Account.Admin) {
  841. sqlStatement := fmt.Sprintf("insert into z_device_data_%s(t_id,t_sp,t_time,t_t,t_rh,t_site,create_time) value(%d,'%s','%s',%f,%f,'%s','%s')", sn, d.T_id, d.T_sp, d.T_time, d.T_t, d.T_rh, d.T_site, d.CreateTime)
  842. o := orm.NewOrm()
  843. _, err := o.Raw(sqlStatement).Exec()
  844. if err != nil {
  845. fmt.Println(err.Error())
  846. if strings.Contains(err.Error(), "Duplicate entry") {
  847. //已经存在该条目,更新
  848. sqlStatement = fmt.Sprintf("update z_device_data_%s set t_t = %f,t_rh = %f where t_time= '%s' and t_id = %d and t_sp = '%s'", sn, d.T_t, d.T_rh, d.T_time, d.T_id, d.T_sp)
  849. exec, err := o.Raw(sqlStatement).Exec()
  850. if err != nil {
  851. fmt.Println("更新错误:", err.Error())
  852. } else {
  853. affected, _ := exec.RowsAffected()
  854. fmt.Println("修改了", affected, "条")
  855. }
  856. }
  857. } else {
  858. //向DataOld插入数据
  859. sqlStatement = fmt.Sprintf("insert into device_data_old(t_sn,t_id,t_time,t_t,t_rh,t__site,t_operation,t_uuid,create_time) value('%s',%d,'%s',%f,%f,'%s',%d,'%s','%s')", sn, d.T_id, d.T_time, d.T_t, d.T_rh, d.T_site, 2, admin.T_uuid, d.CreateTime)
  860. _, err := o.Raw(sqlStatement).Exec()
  861. if err != nil {
  862. log.Panicln("插入失败:", err.Error())
  863. } else {
  864. fmt.Println("插入成功!")
  865. }
  866. }
  867. }
  868. // ReadDeviceOldBySnTid 读取设备探头记录数据
  869. func ReadDeviceOldBySnTid(sn, tId string) (list []DataOld) {
  870. o := orm.NewOrm()
  871. sqlStatement := fmt.Sprintf("SELECT d.*,a.t_name as t_uuid FROM device_data_old as d LEFT JOIN admin as a on a.t_uuid = d.t_uuid WHERE t_sn = '%s' AND t_id = '%s'", sn, tId)
  872. o.Raw(sqlStatement).QueryRows(&list)
  873. return list
  874. }