package timetask import ( "dust-monitor/errors" "dust-monitor/model" "dust-monitor/util" "encoding/json" "fmt" "time" ) // 获取天表中已有的最大时间 func getLastMaxDay(sn string) (string, error) { sql := fmt.Sprintf("select * from \"%s\" order by time desc limit 1", sn) dbname := "dust_monitor_2031" array := []DustInfo{} _, err := model.Query(sql, dbname, &array) if err != nil { return "", errors.DataBaseError } if len(array) == 0 { return "", nil } t := util.ParseTime(array[0].Time).Add(8*time.Hour) ret := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location()) return ret.Format(layout), nil } // 获取未入库的天数据 func getUnwritedDayData(start string, end string, sn string) ([]DustInfo, error) { sql := fmt.Sprintf("SELECT mean(*) FROM \"%s\"", sn) whereArray := []string{} if start != "" { whereArray = append(whereArray, fmt.Sprintf("time >= '%s'", start)) } if end != "" { whereArray = append(whereArray, fmt.Sprintf("time < '%s'", end)) } where := "" for _, v := range whereArray { if where == "" { where = fmt.Sprintf("where %s", v) continue } where = fmt.Sprintf("%s and %s", where, v) } sql = fmt.Sprintf("%s %s GROUP BY time(1d) tz('Asia/Shanghai')", sql, where) array := []DustInfoMean{} dbname := "dust_monitor_2011" _, err := model.Query(sql, dbname, &array) if err != nil { return nil, errors.DataBaseError } if len(array) == 0 { return nil, nil } ret := make([]DustInfo, len(array)) for i, v := range array { item := DustInfo{ Time:v.Time, Pm25Avg:v.Pm25Avg, Pm10Avg:v.Pm10Avg, W01Avg:v.W01Avg, W03:v.W03, W02Avg:v.W02Avg, P01Avg:v.P01Avg, TspAvg:v.TspAvg, T01Avg:v.T01Avg, H01Avg:v.H01Avg, R01Avg:v.R01Avg, Lat:v.Lat, Lng:v.Lng, B03Avg:v.B03Avg, } ret[i] = item } return ret, nil } // 写入天数据 func writeDayData(sn string, data []DustInfo) error { if len(data) == 0 { return nil } bytes, _ := json.Marshal(data) array := []map[string]interface{}{} json.Unmarshal(bytes, &array) tarray := make([]time.Time, len(array)) for i, v := range array { ti, ok := v["time"] if !ok { return errors.ParamsError } str, ok := ti.(string) if !ok { return errors.ParamsError } t := util.ParseTime(str) tarray[i] = t delete(array[i], "time") } tags := map[string]string{ "sn":sn, } return model.WriteDustDatas(sn, tags, array, tarray, "2031") } func handleDustDay(start string, end string, sn string) { lastMaxTime, err := getLastMaxDay(sn) if err != nil { return } if lastMaxTime == "" { start = "" } else { tmpStart := util.ParseTime(lastMaxTime) tmpStart = tmpStart.Add(24 *time.Hour) if tmpStart.Unix() > util.ParseTime(start).Unix() { return } start = tmpStart.Format(layout) } datas, err := getUnwritedDayData(start, end, sn) if err != nil { return } writeDayData(sn, datas) }