123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675 |
- package Device
- import (
- "ColdP_server/conf"
- "ColdP_server/controllers/lib"
- "database/sql"
- "encoding/json"
- "fmt"
- "github.com/astaxie/beego/cache"
- _ "github.com/astaxie/beego/cache/redis"
- "github.com/beego/beego/v2/adapter/orm"
- orm2 "github.com/beego/beego/v2/client/orm"
- _ "github.com/go-sql-driver/mysql"
- "github.com/xuri/excelize/v2"
- "log"
- "strconv"
- "strings"
- "time"
- )
- // 建表
- // var CREATEsql = "CREATE TABLE IF NOT EXISTS `z_device_data_" + SN + " ( " +
- var CREATEsql = " ( " +
- "`t_id` int(6) NOT NULL," +
- "`t_sp` int(6) NOT NULL," +
- "`t_time` datetime NOT NULL," +
- "`t_t` double(6, 2) NULL DEFAULT NULL," +
- "`t_rh` double(6, 2) NULL DEFAULT NULL," +
- "`t_site` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL," +
- "`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP," +
- "PRIMARY KEY (`t_time`, `t_id`) USING BTREE" +
- ") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;"
- type DeviceData_ struct {
- T_id int // 传感器id
- T_sp int // 传感器参数id
- T_t float32 // 温度
- T_rh float32 // 湿度
- T_site string // GPS
- T_time time.Time // 采集时间
- Create_time time.Time //创建时间
- }
- type DeviceData struct {
- T_id string `json:"t_id"`
- T_sp string `json:"t_sp"`
- T_time string `json:"t_time"`
- T_t float64 `json:"t_t"`
- T_rh float64 `json:"t_rh"`
- T_site sql.NullString `json:"t_site"`
- Create_time string `json:"create_time"`
- }
- type DeviceLists struct {
- T_save_t string //系统设置间隔时间
- T_warn string // 报警间隔时间
- T_tlower float64 // 低温下限
- T_tupper float64 // 高温上限
- T_r_hlower float64 // 湿度下限
- T_r_hupper float64 // 湿度上限
- Sn string // sn
- }
- // 模板
- type DeviceData_R struct {
- T_sn string `json:"t_sn"` //设备
- T_id int `json:"t_id"` // 传感器id
- T_sp int `json:"t_sp"` // 传感器参数id
- T_name string `json:"t_name"` // 传感器名称
- T_t float32 `json:"t_t"` // 温度
- T_rh float32 `json:"t_rh"` // 湿度
- T_site string `json:"t_site"` // GPS
- T_tl float32 `json:"t_tl"` // 温度下限
- T_tu float32 `json:"t_tu"` // 温度上限
- T_rhl float32 `json:"t_rhl"` // 湿度下限
- T_rhu float32 `json:"t_rhu"` // 湿度上限
- T_time string `json:"t_time"` // 采集时间
- Create_Time string `json:"create_time"`
- }
- //func (t *DeviceData) TableName() string {
- // return "DeviceData" // 数据库名称 // ************** 替换 FormulaList **************
- //}
- var redis_DeviceData cache.Cache
- func init() {
- config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
- "redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
- fmt.Println(config)
- var err error
- redis_DeviceData, err = cache.NewCache("redis", config)
- if err != nil || redis_DeviceData == nil {
- errMsg := "failed to init redis"
- fmt.Println(errMsg, err)
- }
- }
- func DeviceData_ToDeviceData_R(r DeviceData_, maps map[int]DeviceSensorParameter_M) (t DeviceData_R) {
- t.T_id = r.T_id
- t.T_t = r.T_t
- t.T_rh = r.T_rh
- t.T_site = r.T_site
- t.T_time = r.T_time.Format("2006-01-02 15:04:05")
- t.Create_Time = r.Create_time.Format("2006-01-02 15:04:05")
- if sp, ok := maps[r.T_sp]; ok {
- t.T_sp = sp.T_sp
- t.T_name = sp.T_name
- t.T_tl = sp.T_Tlower
- t.T_tu = sp.T_Tupper
- t.T_rhl = sp.T_RHlower
- t.T_rhu = sp.T_RHupper
- }
- return
- }
- // ---------------- Redis -------------------
- // Redis_Set(m.T_sn,m) // Redis 更新缓存
- func RedisDeviceData_Set(key string, r DeviceData_R) (err error) {
- if redis_DeviceData.IsExist(key) {
- var t DeviceData_R
- v := redis_DeviceData.Get(key)
- json.Unmarshal(v.([]byte), &t)
- tTime, _ := time.Parse("2006-01-02 15:04:05", t.T_time)
- rTime, _ := time.Parse("2006-01-02 15:04:05", r.T_time)
- if tTime.Unix() > rTime.Unix() {
- // 储存的 是最新数据
- return
- }
- }
- //json序列化
- str, err := json.Marshal(r)
- if err != nil {
- fmt.Print(err)
- return
- }
- err = redis_DeviceData.Put(key, str, 1*time.Hour)
- if err != nil {
- fmt.Println("set key:", key, ",value:", str, err)
- }
- return
- }
- func RedisDeviceData_Get(key string) (r DeviceData_R, is bool) {
- if redis_DeviceData.IsExist(key) {
- v := redis_DeviceData.Get(key)
- json.Unmarshal(v.([]byte), &r)
- return r, true
- }
- return DeviceData_R{}, false
- }
- // -------------------------------------------------------
- // 创建数据库 Device.CREATE_DeviceData("")
- func CREATE_DeviceData(SN string) bool {
- sql := "CREATE TABLE IF NOT EXISTS `z_device_data_" + SN + "` " + CREATEsql
- o := orm.NewOrm()
- _, err := o.Raw(sql).Exec()
- if err != nil {
- return false
- }
- return true
- }
- func DELETE_DeviceDatar(SN string) bool {
- timeStr := time.Now().Format("2006_01_02_15_04_05")
- //sql := "DROP TABLE z_device_data_" + SN
- sql := "ALTER TABLE z_device_data_" + SN + " RENAME TO " + "z_device_data_" + SN + "_dle_" + timeStr + ";"
- o := orm.NewOrm()
- _, err := o.Raw(sql).Exec()
- if err != nil {
- return false
- }
- return true
- }
- // ---------------- 特殊方法 ------------------
- type DeviceData_T struct {
- T_id int // ID
- T_t float32 // 温度
- T_rh float32 // 湿度
- T_Site string // GPS
- T_time time.Time // 采集时间
- }
- // 添加
- func Add_DeviceData(SN string, v DeviceData_T) bool {
- //if(conf.Test_server){
- // 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)
- // return true
- //}
- key_time := SN + "|" + strconv.Itoa(v.T_id) + "|" + v.T_time.Format("2006-01-02 15:04:05")
- fmt.Println(key_time)
- if redis_DeviceData.IsExist(key_time) {
- //println("找到key:",key)
- return true
- }
- o := orm.NewOrm()
- // 检查 超过时间,查询 数据库
- if time.Now().Unix()-v.T_time.Unix() >= 60*40 {
- // 查看是否 有记录
- var maps_z []orm2.ParamsList
- 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)
- _, err := o.Raw(sql_c).ValuesList(&maps_z)
- if err != nil {
- return false
- }
- //fmt.Println("maps_z[0][0]:",maps_z[0][0])
- if lib.To_int(maps_z[0][0]) > 0 {
- return true
- }
- }
- // 开始插入数据
- sql := "INSERT INTO z_device_data_" + SN + " ( `t_id`, `t_t`, `t_rh`, `t_site`, `t_time`) " +
- "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") + "')"
- // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
- fmt.Println(sql)
- res, err := o.Raw(sql).Exec()
- if err != nil {
- fmt.Println(err)
- return false
- }
- res.RowsAffected()
- return true
- }
- ///---------------
- //type DeviceData_ struct {
- // T_sn string `orm:"column(t_sn);size(256);null"` // 标题
- // T_id int `orm:"column(t_id);size(10);null"` // ID
- // T_t float32 `orm:"column(t_t);size(10);null"` // 温度
- // T_rh float32 `orm:"column(t_rh);size(10);null"` // 湿度
- // T_site string `orm:"column(t_site);type(timestamp);null;"` // GPS
- // T_time string `orm:"column(t_time);type(timestamp);null;"` // 采集时间
- //}
- //type DeviceData_New struct {
- // T_name string `orm:"column(t_name);size(256);null"` // 标题
- // T_id int `orm:"column(t_id);size(10);null"` // ID
- // T_t float32 `orm:"column(t_t);size(10);null"` // 温度
- // T_rh float32 `orm:"column(t_rh);size(10);null"` // 湿度
- // T_Tlower float32 `orm:"column(t_tl);size(10);null"` // 湿度
- // T_Tupper float32 `orm:"column(t_tu);size(10);null"` // 湿度
- // T_RHlower float32 `orm:"column(t_rhl);size(10);null"` // 湿度
- // T_RHupper float32 `orm:"column(t_rhu);size(10);null"` // 湿度
- // T_Site string `orm:"column(t_site);null;"` // GPS
- // T_Dattery int `orm:"column(t_dattery);size(10);null"` // 电量
- // T_time time.Time `orm:"column(t_time);type(timestamp);null;"` // 采集时间
- //}
- 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) {
- o := orm.NewOrm()
- var maps []DeviceData_
- var maps_z []orm2.ParamsList
- var r []DeviceData_R
- var offset int
- if page_z == 0 {
- page_z = conf.Page_size
- }
- if page <= 1 {
- offset = 0
- } else {
- offset = (page - 1) * page_z
- }
- sql_time := ""
- if len(Time_start_) > 1 {
- sql_time += " t_time >= '" + Time_start_ + "' AND "
- }
- if len(Time_end_) > 1 {
- sql_time += " t_time <= '" + Time_end_ + "' AND "
- }
- sql := "SELECT COUNT(t_id) FROM z_device_data_" + SN + " WHERE " + sql_time + " t_id = " + strconv.Itoa(T_id)
- fmt.Println(sql)
- _, err := o.Raw(sql).ValuesList(&maps_z)
- if err != nil {
- return r, 0
- }
- if len(maps_z) == 0 {
- return r, 0
- }
- //fmt.Println("maps_z;",maps_z[0][0])
- //t_tl,t_tu,t_rhl,t_rhu,
- 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
- if page_z != 9999 {
- sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(page_z)
- }
- //fmt.Println(sql)
- _, err = o.Raw(sql).QueryRows(&maps)
- //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
- key, _ := strconv.Atoi(maps_z[0][0].(string))
- fmt.Println("\n\n\n\n\n\n搜索结果:", maps)
- for _, v := range maps {
- r = append(r, DeviceData_ToDeviceData_R(v, SParamMap))
- }
- return r, key
- }
- func Read_SqlRaw(T_SQL string) []orm2.Params {
- o := orm.NewOrm()
- var lists []orm2.Params
- fmt.Println(T_SQL)
- o.Raw(T_SQL).Values(&lists)
- fmt.Println(T_SQL+":", len(lists))
- return lists
- }
- func Read_SqlRawL(T_SQL string, T_data []string) (string, []orm2.Params) {
- o := orm.NewOrm()
- var lists []orm2.Params
- fmt.Println(T_SQL)
- _, err := o.Raw(T_SQL, T_data).Values(&lists)
- if err != nil {
- return err.Error(), lists
- }
- return "", lists
- }
- 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) {
- T_snid_list := strings.Split(T_snid, "|")
- var maps []DeviceData_R
- var maps_num int64
- var offset, offset_z int
- for _, v := range T_snid_list {
- sn_id := strings.Split(v, ",")
- if len(sn_id) == 2 {
- SParamMap := Read_DeviceSensorParameter_Map_All(sn_id[0], lib.To_int(sn_id[1]))
- 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)
- //for i, _ := range r_maps {
- // r_maps[i].T_sn = sn_id[0]
- //}
- //添加一个sn设备标识
- for i := range r_maps {
- r_maps[i].T_sn = sn_id[0]
- }
- maps = append(maps, r_maps...)
- maps_num = maps_num + int64(r_maps_num)
- fmt.Println("加载数据:", sn_id[0], sn_id[1], r_maps_num)
- }
- }
- if page <= 1 {
- offset = 0
- } else {
- page -= 1
- offset = page * page_z
- }
- offset_z = offset + page_z
- if maps_num < int64(offset_z) {
- offset_z = int(maps_num)
- }
- if page_z == 9999 {
- fmt.Println("总数据:", maps_num, " 导出")
- return maps, maps_num
- }
- fmt.Println("总数据:", maps_num, " 截取", offset, offset+page_z)
- return maps[offset:offset_z], maps_num
- }
- // DeleteDeviceDataByDeviceDataRList 删除记录
- func DeleteDeviceDataByDeviceDataRList(datas []DeviceData_R) {
- o := orm.NewOrm()
- for _, v := range datas {
- _, 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()
- if err != nil {
- fmt.Println(err.Error())
- }
- }
- }
- func DeleteDeviceDataByTime(sn, t_id, time_start, time_end string) (sql.Result, error) {
- o := orm.NewOrm()
- 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)
- log.Println(sprintf)
- count, err := o.Raw(sprintf).Exec()
- if err != nil {
- log.Println(err.Error())
- return count, err
- }
- return count, nil
- }
- // ImportDeviceData 批量导入
- func ImportDeviceData(reader *excelize.File, sn string) string {
- sheetName := reader.GetSheetName(0)
- rows, err := reader.GetRows(sheetName)
- o := orm.NewOrm()
- if err != nil {
- panic(any(err.Error()))
- }
- values := make([]string, len(rows)-1)
- for i, row := range rows {
- if i == 0 {
- //跳过第一条头部描述
- continue
- }
- // 定义匹配的解析格式
- format := row[4]
- _, err := time.Parse("2006-01-02 15:04:05", row[4])
- if err != nil {
- layout := "1/2/06 15:04"
- parsedTime, _ := time.Parse(layout, row[4])
- year := parsedTime.Year()
- if year < 100 {
- year += 2000
- }
- parsedTime = time.Date(year, parsedTime.Month(), parsedTime.Day(), parsedTime.Hour(), parsedTime.Minute(), parsedTime.Second(), parsedTime.Nanosecond(), time.UTC)
- format = parsedTime.Format("2006-01-02 15:04:05")
- }
- isrepeat := Read_DeviceData_Execl_ISREPEAT(sn, format, row[0])
- t_sp := Read_device_sensor_parameter(sn, row[0])
- if t_sp == "" {
- sprintf := fmt.Sprintf("当前sn或探头参数ID不存在:%s,%s", sn, row[0])
- return sprintf
- }
- if isrepeat {
- //如果重复就用更新数据
- 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])
- _, err := o.Raw(sql).Exec()
- if err != nil {
- fmt.Println(err.Error())
- return "更新失败"
- }
- } else {
- // t_id,t_t,t_rh,t_time
- //传感器 传感器参数ID 温度 湿度 GPS 采集时间 创建时间
- parse, _ := time.Parse("2006-01-02 15:04:05", format)
- parse = parse.Add(time.Millisecond * 8000)
- parse.Format("2006-01-02 15:04:05")
- values[i-1] = fmt.Sprintf("(%s,%s,%s,%s,'','%s')", row[0], t_sp, row[1], row[2], format)
- 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"))
- log.Println(sprintf)
- //执行SQL
- _, err := o.Raw(sprintf).Exec()
- if err != nil {
- fmt.Println("执行失败")
- return "请检查表格是否具有重复数据!!!"
- }
- }
- }
- //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, ","))
- //fmt.Println("执行批量导入SQL:", sqlStatement)
- return "导入成功"
- }
- func Read_DeviceData_Execl_ISREPEAT(sn, t_time, t_id string) bool {
- o := orm.NewOrm()
- var table struct {
- T_id string
- T_time string
- }
- 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)
- err := o.Raw(sql).QueryRow(&table)
- if err != nil {
- fmt.Println(err.Error())
- return false
- } else {
- if table.T_id != "" {
- return true
- }
- }
- return false
- }
- // ExportDeviceData 导出 未完成
- /*func ExportDeviceData(sns []string, startTime, endTime string) *os.File {
- f, err := os.Create(fmt.Sprintf("[%s]导出数据.zip", time.Now().Format("2006-01-02")))
- if err != nil {
- fmt.Println(err.Error())
- }
- z := zip.NewWriter(f)
- o := orm.NewOrm()
- sqlStatement := "select * from z_device_data_%s where create_time between %s and %s"
- title := map[string]string{
- "A1": "传感器",
- "B1": "传感器参数ID",
- "C1": "温度",
- "D1": "湿度",
- "E1": "GPS",
- "F1": "采集时间",
- "G1": "创建时间",
- }
- for _, sn := range sns {
- datas := make([]DeviceData_, 0)
- sqlNew := fmt.Sprintf(sqlStatement, sn, startTime, endTime)
- o.Raw(sqlNew).QueryRows(&datas)
- //创建压缩包中的excel
- excelT, err := z.Create(fmt.Sprintf("%s.xlsx", sn))
- if err != nil {
- fmt.Println(err.Error())
- }
- //创建新的excel
- excelNew := excelize.NewFile()
- excelNew.NewSheet(sn)
- //设置表头
- for k, v := range title {
- excelNew.SetCellStr(sn, k, v)
- }
- //设置内容
- for i, v := range datas {
- }
- }
- return f
- }
- */
- // Update_DeviceSensorData 更新设备数据
- func Update_DeviceSensorData(v DeviceData_R, fieldName, val string) error {
- o := orm.NewOrm()
- if fieldName == "t__tlower" {
- split := strings.Split(val, "|")
- i := strings.Split(split[0], "~")
- t__tlower := i[0]
- t__tupper := i[1]
- i2 := strings.Split(split[1], "~")
- t__r_hlower := i2[0]
- t__r_hupper := i2[1]
- 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)
- //log.Println(sqlStatemt)
- _, err := o.Raw(sqlStatemt).Exec()
- if err != nil {
- return err
- }
- return nil
- } else {
- 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)
- log.Println(sqlStatemt)
- log.Println("创建时间:", v.Create_Time)
- _, err := o.Raw(sqlStatemt, val, v.T_id, v.T_t, v.T_rh, v.T_site, v.Create_Time).Exec()
- if err != nil {
- return err
- }
- return nil
- }
- }
- // 复制添加数据
- func Copy_DeviceData(T_sn, T_id string, T_Rh, T_T any, T_Site, CreateTime string) {
- T_sp := Read_device_sensor_parameter(T_sn, T_id)
- o := orm.NewOrm()
- 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)
- //log.Println(sprintf)
- _, err := o.Raw(sprintf, T_id, T_sp, CreateTime, T_T, T_Rh, T_Site, CreateTime).Exec()
- if err != nil {
- fmt.Println(err.Error())
- }
- }
- func Read_DeviceData_ById_Year_List(SN string) []orm2.ParamsList {
- o := orm.NewOrm()
- var maps_z []orm2.ParamsList
- //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 "
- 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\");"
- fmt.Println(sql)
- num, err := o.Raw(sql).ValuesList(&maps_z)
- if err == nil && num > 0 {
- fmt.Println(maps_z[0][0]) // slene
- }
- //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
- //key,_ := strconv.Atoi(maps_z[0][0].(string))
- return maps_z
- } //
- func Read_DeviceData_ById_Month_List(SN string) []orm2.ParamsList {
- o := orm.NewOrm()
- var maps_z []orm2.ParamsList
- currentTime := time.Now() //获取当前时间,类型是Go的时间类型Time
- time_x := currentTime.Format("2006-01") + "-00 00:00:00"
- //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 "
- 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\");"
- fmt.Println(sql)
- o.Raw(sql).ValuesList(&maps_z)
- //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
- //key,_ := strconv.Atoi(maps_z[0][0].(string))
- return maps_z
- }
- func Read_device_sensor_parameter(SN, t_id string) string {
- o := orm.NewOrm()
- var maps_z []orm2.ParamsList
- //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 "
- 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;"
- fmt.Println(sql)
- list, err := o.Raw(sql).ValuesList(&maps_z)
- if err != nil {
- return ""
- }
- if list == 0 {
- fmt.Println("没有数据")
- return ""
- } else {
- return maps_z[0][0].(string)
- }
- //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
- //key,_ := strconv.Atoi(maps_z[0][0].(string))
- }
- func Read_DeviceData_ById_Day_List(SN string) []orm2.ParamsList {
- o := orm.NewOrm()
- var maps_z []orm2.ParamsList
- currentTime := time.Now() //获取当前时间,类型是Go的时间类型Time
- time_x := currentTime.Format("2006-01-02") + " 00:00:00"
- //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 "
- 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\");"
- fmt.Println(sql)
- o.Raw(sql).ValuesList(&maps_z)
- //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
- //key,_ := strconv.Atoi(maps_z[0][0].(string))
- return maps_z
- }
- func Read_DeviceData_List_GROUP_BY_t_time(SN string, Time_start_ string, Time_end_ string) []orm2.ParamsList {
- o := orm.NewOrm()
- var maps_z []orm2.ParamsList
- sql_time := ""
- if len(Time_start_) > 1 {
- sql_time += " t_time >= '" + Time_start_ + "' AND " + " t_time <= '" + Time_end_ + "' "
- }
- 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 "
- fmt.Println(sql)
- o.Raw(sql).ValuesList(&maps_z)
- return maps_z
- }
- // GetCompanyBySn 根据sn查询公司名称
- func GetCompanyBySn(sn string) (string, error) {
- o := orm.NewOrm()
- sqls := fmt.Sprintf("SELECT t_pid FROM `device` WHERE t_sn='%s'", sn)
- var TPid string
- err := o.Raw(sqls).QueryRow(&TPid)
- if err != nil {
- return "", err
- }
- sqlCompany := fmt.Sprintf("SELECT t_name FROM `company` WHERE id='%s'", TPid)
- var TName string
- err = o.Raw(sqlCompany).QueryRow(&TName)
- if err != nil {
- return "", err
- }
- TName = TName + "[" + TPid + "]"
- return TName, nil
- }
|