def POST(self): data = web.input() start = int(data["start"]) length = int(data["length"]) starttime = data['starttime'].replace('/', '').replace( ' ', '').replace(':', '') + '00' endtime = data["endtime"].replace('/', '').replace(' ', '').replace( ':', '') + '00' devid = data['devid'] userid = data['userid'] draw = int(data['draw']) ordernum = int(data['order[0][column]']) orderstyle = data['order[0][dir]'] ids = devid.split(',') result = [] count = 0 for id in ids: #conditions = dict() #conditions['devid'] = id #conditions['time'] = {'$lte':endtime,'$gte':starttime} #maxitem = data_model('devpower_detail').find(conditions=conditions,sort=sort1,limit=1) #minitem = data_model('devpower_detail').find(conditions=conditions,sort=sort2,limit=1) finddata = common.getPowerinfo(id, starttime, endtime) if len(finddata) == 0: continue else: count += 1 temp = [] max = finddata[-1] min = finddata[0] maxW = float('%0.4f' % max['W']) minW = float('%0.4f' % min['W']) maxTime = max['time'] minTime = min['time'] power = maxW - minW power = float('%0.4f' % power) temp.append(id) temp.append(power) temp.append(minW) temp.append(common.strTimeToFormat(minTime)) temp.append(maxW) temp.append(common.strTimeToFormat(maxTime)) result.append(temp) data = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": result } data = json.dumps(data) return data
def getPower_detail(starttime, endtime, devid, start, length, draw): finddata = common.getPowerinfo(devid, starttime, endtime) count = len(finddata) starti = 0 result = dict() resultlist = [] for item in finddata: if starti != start: starti += 1 continue del item["_id"] if "tablename" in item.keys(): del item["tablename"] keys = item.keys() temp = [] for key in keys: if key.lower().find("time") != -1: item[key] = common.strTimeToFormat(item[key]) if isinstance(item[key], dict): item[key] = unparse.dictTostr(item[key]) if key == "_id": item[key] = str(item[key]) temp.append(item[key]) resultlist.append(temp) if len(resultlist) == length: break result = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": resultlist } return result
def getPower(starttime, endtime, devid, type): result = [] sort = [('time', 1)] data = common.getPowerinfo(devid, starttime, endtime) time1 = starttime power = 0 for item in data: temp = {} time2 = item['time'] temp['key'] = common.strTimeToFormat(item['time']) if type == 'power': temp['value'] = float('%0.4f' % (float(item['W']))) result.append(temp) time1 = time2 power = float('%0.4f' % (float(item['W']))) elif type == 'efficiency': a = datetime.datetime.strptime(time2, '%Y%m%d%H%M%S') b = datetime.datetime.strptime(time1, '%Y%m%d%H%M%S') if (a - b).seconds > 600: #两个时间差大于10分钟在这段时间内每隔5分钟填充个0 while b < a: temp1 = {} temp1['key'] = common.strTimeToFormat( b.strftime('%Y%m%d%H%M%S')) temp1['value'] = 0 result.append(temp1) b = b + datetime.timedelta(seconds=600) temp['value'] = int(item['P']) result.append(temp) time1 = time2 a = datetime.datetime.strptime(endtime, '%Y%m%d%H%M%S') b = datetime.datetime.strptime(time1, '%Y%m%d%H%M%S') timeflag = time1[:8] if (a - b).seconds > 600: #两个时间差大于10分钟在这段时间内每隔5分钟填充个0 while b < a: temp1 = {} temp1['key'] = common.strTimeToFormat(b.strftime('%Y%m%d%H%M%S')) if type == 'efficiency': temp1['value'] = 0 elif type == 'power': if b.strftime('%Y%m%d%H%M%S')[:8] == timeflag: temp1['value'] = power else: temp1['value'] = 0 result.append(temp1) b = b + datetime.timedelta(seconds=600) return result
def getCmd_power(starttime, endtime, devid, start, length, draw): conditions = dict() if devid != '': conditions['devid'] = devid if starttime != '': conditions['starttime'] = {'$gte': starttime} if endtime != '': conditions['endtime'] = {'$lte': endtime} sort = [('starttime', 1)] data = data_model('powershowgrid').find(conditions=conditions, sort=sort) result = dict() resultlist = [] count = 0 starti = 0 for item in data: count += len(item['result']) for item in data: for i in item['result']: if starti != start: starti += 1 continue temp = [] temp.append(item['devid']) temp.append(i['temp']) temp.append(i['W']) temp.append(i['P']) temp.append(common.strTimeToFormat(i['time'])) if i['cmd'] == '3001': temp.append('持续状态') elif i['cmd'] == 'devTodo': if i['inst'].startswith('0'): temp.append('关闭') elif i['inst'].startswith('1'): if i['time'] == item['starttime']: temp.append("打开(" + i['inst'] + ")") else: temp.append("调整温度模式(" + i['inst'] + ")") else: if i['actionid'] == '2': temp.append("打开") if i['actionid'] == '0': temp.append("关闭") resultlist.append(temp) if len(resultlist) == length: break if len(resultlist) == length: break result = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": resultlist } return result
def getTemp(starttime, endtime, devid): province = devid.split('_')[0] city = devid.split('_')[1] conditions = dict() conditions['city'] = province conditions['area'] = city conditions['time'] = {'$gte': starttime, '$lte': endtime} sort = [('time', 1)] data = data_model('live.area.temp.history').find(conditions=conditions, sort=sort) result = [] for item in data: if item['temNow'] == '暂无实况': continue temp = {} temp['key'] = common.strTimeToFormat(item['time']) temp['value'] = item['temNow'] result.append(temp) return result
def getCmd(starttime, endtime, devid, start, length, draw): sender = False if devid.startswith('sender_'): devid = devid[7:] sender = True sort = [] sort.append(('acceptTime', pymongo.ASCENDING)) conditions = {} conditions['acceptTime'] = {'$gte': starttime, '$lte': endtime} if sender: pre = devid[:3] stuff = devid[3:] rexexp = '^' + pre + '.*' + stuff + '$' rexexp = re.compile(rexexp) conditions['content.sender'] = rexexp else: conditions['content.devID'] = devid conditions['content.CMD'] = {'$exists': True} conditions['mark'] = {'$ne': 'dev'} result = dict() count = data_model('loger').count(conditions=conditions) findlist = data_model('loger').find(conditions=conditions, sort=sort, limit=length, skip=start) resultlist = [] for item in findlist: print item temp = [] temp.append(devid) temp.append(item["content"]["CMD"]) temp.append(common.strTimeToFormat(item['acceptTime'])) resultlist.append(temp) result = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": resultlist } return result
def POST(self): data = web.input() starttime = data['starttime'] endtime = data['endtime'] type = data['type'] daylist = common.getdaylist(starttime,endtime) if type == 'device': flag = 'info' elif type == 'user': flag = 'user' result = [] for day in daylist: tablename = 'statistic_' + flag + '_' + day count = statistic_model(tablename).count() temp = {'key':'','value':0} temp['key'] = common.strTimeToFormat(day) temp['value'] = count result.append(temp) data = {'result':result} data = json.dumps(data) return data
def getActioninst(starttime, endtime, devid, start, length, draw): conditions = dict() if starttime != '' and endtime != '': conditions['time'] = {'$gte': starttime, '$lte': endtime} sort = [('time', 1)] result = dict() resultlist = [] count = 0 devids = devid.split(',') datalist = [] for id in devids: conditions['devid'] = id data = data_model('devcmd').find(conditions=conditions, sort=sort) count += len(data) action = '' for i in data: if 'actionid' not in i.keys(): actionid = '6' else: actionid = i['actionid'] temp = [] temp.append(i['devid']) temp.append(common.strTimeToFormat(i['time'])) temp.append(i['W']) action, mode, tempi = parseInst(i['inst'], actionid, i['time'], '') temp.append(action) temp.append(mode) temp.append(tempi) resultlist.append(temp) result = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": resultlist } return result
def POST(self, *args): data = web.input() start = int(data["start"]) length = int(data["length"]) userfrom = data['userFrom'] tablename = data["tablename"] draw = int(data['draw']) ordernum = int(data['order[0][column]']) orderstyle = data['order[0][dir]'] conditions = {} keys = [] sort = [] #获取字段名,设定排序条件 first = data_model(tablename).find_one() del first['_id'] if userfrom == "业务持久化存储服务": devid = '' starttime = '' endtime = '' if "devid" in data.keys(): devid = data['devid'] conditions['devid'] = data['devid'] if 'starttime' in data.keys() and 'endtime' in data.keys(): starttime = data['starttime'].replace('/', '').replace( ' ', '').replace(':', '') + '00' endtime = data['endtime'].replace('/', '').replace( ' ', '').replace(':', '') + '00' conditions['time'] = {'$gte': starttime, '$lte': endtime} elif 'starttime' in data.keys(): starttime = data['starttime'].replace('/', '').replace( ' ', '').replace(':', '') + '00' conditions['time'] = {'$gte': starttime} elif 'endtime' in data.keys(): endtime = data['endtime'].replace('/', '').replace( ' ', '').replace(':', '') + '00' conditions['time'] = {'$lte': endtime} keys = first.keys() if tablename == 'powershowgrid': data = dict() data = getCmd_power(starttime, endtime, devid, start, length, draw) data = json.dumps(data) return data elif tablename == 'devpower_detail': data = dict() data = getPower_detail(starttime, endtime, devid, start, length, draw) data = json.dumps(data) return data else: for key in first.keys(): if key == "_id" or key == "tablename": pass else: if key in data.keys( ): #设定查询条件,以%%包围的属于模糊匹配,以‘[’或‘(’开头的属于范围内查找,以‘{}’包围的属于子内容查找,其他请求属于精确匹配 # conditions[key] = data[key] try: value = data[key] if value[0] == '%' or value[-1] == '%': #模糊匹配 pass elif value[0] == '(' or value[0] == '[': list = value.split(':') left = list[0].split(' ') right = list[1].split(' ') if left[1] == '': #<= if right[1] == ')': conditions[key] = {"$lt": right[0]} elif right[1] == ']': conditions[key] = {"$lte": right[0]} elif right[0] == '': #>= if left[0] == '(': conditions[key] = {"$gt": left[1]} elif left[0] == '[': conditions[key] = {"$gte": left[1]} else: #区间 tag_left = '' tag_right = '' if left[0] == '(': tag_left = "$gt" elif left[0] == '[': tag_left = "$gte" if right[1] == ')': tag_right = "$lt" elif right[1] == ']': tag_right = "$lte" conditions[key] = { tag_left: left[1], tag_right: right[0] } elif value[0] == '{' and value[-1] == '}': temp = value.split('{')[1].split('}')[0] list = temp.split(',') for item in list: key_child = item.split(':')[0] value = item.split(':')[1] conditions[key + '.' + key_child] = value else: conditions[key] = data[key] except Exception as e: data = { "draw": draw, "recordsTotal": 0, "recordsFiltered": 0, "aaData": [] } data = json.dumps(data) return data keys.append(key) temp = [] ordercolumn = keys[ordernum] if orderstyle == 'asc': temp.append(ordercolumn) temp.append(pymongo.ASCENDING) sort.append(tuple(temp)) else: temp.append(ordercolumn) temp.append(pymongo.DESCENDING) sort.append(tuple(temp)) count = data_model(tablename).count(conditions=conditions) set = data_model(tablename).find(limit=length, skip=start, sort=sort, conditions=conditions) result = [] for item in set: del item["_id"] if "tablename" in item.keys(): del item["tablename"] keys = item.keys() temp = [] for key in keys: if key.lower().find("time") != -1: item[key] = common.strTimeToFormat(item[key]) if isinstance(item[key], dict): item[key] = unparse.dictTostr(item[key]) if key == "_id": item[key] = str(item[key]) temp.append(item[key]) result.append(temp) data = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": result } data = json.dumps(data) return data
def getActioninfo(starttime, endtime, devid, start, length, draw): conditions = dict() if starttime != '': conditions['starttime'] = {'$gte': starttime} if endtime != '': conditions['endtime'] = {'$lte': endtime} sort = [('starttime', 1)] result = dict() resultlist = [] count = 0 starti = 0 devids = devid.split(',') datalist = [] for id in devids: conditions['devid'] = id data = data_model('powershowgrid').find(conditions=conditions, sort=sort) datalist.append(data) for data in datalist: #处理每个设备 for item in data: #处理某个设备的某一次完整操作 for i in item['result']: if 'actionid' not in i.keys(): i['actionid'] = 'null' if i['cmd'] == '3001': continue if i['inst'].startswith('0') or i['actionid'] == '0': count += 2 #每个结束动作都会有一个小的汇总信息 elif i['inst'].startswith('1') or i['actionid'] == '2': count += 1 if len(data) > 0: count += 1 #最后设备在此查询时间段内会有一个总的汇总信息,若没有操作则没有汇总信息 for data in datalist: if len(data) == 0: continue runtime = 0 power = 0.0 for item in data: stime = item['starttime'] id = item['devid'] for i in item['result']: if i['cmd'] == '3001': continue actionid = i['actionid'] temp = [] temp.append(item['devid']) temp.append(common.strTimeToFormat(i['time'])) temp.append(i['W']) action, mode, tempi = parseInst(i['inst'], actionid, i['time'], stime) temp.append(action) temp.append(mode) temp.append(tempi) resultlist.append(temp) #添加小的汇总信息 finddata = data_model('actioninfo').find(conditions={ 'devid': id, 'starttime': stime }) temp = [] temp.append(id) temp.append(finddata[0]['runtime']) runtime += finddata[0]['runtime'] temp.append(finddata[0]['power']) power += finddata[0]['power'] temp.append('') temp.append('') temp.append('') resultlist.append(temp) #添加总的汇总信息 temp = [] temp.append(id) temp.append(runtime) temp.append(float('%0.4f' % power)) temp.append('') temp.append('') temp.append('') resultlist.append(temp) result = { "draw": draw, "recordsTotal": count, "recordsFiltered": count, "aaData": resultlist } return result
def dealReport(time, month): tablename = 'report_month_%s' % (time) table = 'worktime_' + time devIDlist = data_model(table).find() count = 0 for l in devIDlist: devid = l['_id'] print devid #if devid != '32150609600232212924': # continue finditem = data_model('devID').find_one(conditions={'_id': devid}) if finditem is None: system = '' else: system = finditem.get('system', '') result = dict() finduser = data_model('user_dev').find_one(conditions={'_id': devid}) if finduser is None: print '无用户名' continue else: username = finduser['username'] sender = finduser['sender'] result['_id'] = devid result['username'] = username[-4:] worktime, runtime, index, worktime_pre, starttime, power, power_pre = getWorktime( devid, time) if worktime == 0: #表里无记录说明此设备不是空调类型,不予处理 print "不是空调" continue weatherinfo, city, area = getWeather(devid, time) if city == '' or area == '': #无法确定用户地理信息,不予处理 print '无地理信息' continue #power,power_pre = getPower(devid,time) if power == 0: #查询月份电量为0,说明无工作,不予处理,查询的是devpowerhistory表 print '无电量' continue efficiencyinfo = getEfficiency(devid, time) cityindex = getCityindex(city, area) listtime, listhigh, listlower = getTemperature(city, area, time) data = [] for key in weatherinfo.keys(): temp = dict() temp['name'] = key temp['value'] = weatherinfo[key] data.append(temp) result['weather'] = {'key': weatherinfo.keys(), 'value': data} result['power'] = power result['power_pre'] = power_pre result['cityindex'] = cityindex result['efficiency'] = efficiencyinfo result['temperature'] = { 'time': listtime, 'lower': listlower, 'high': listhigh } result['worktime'] = worktime result['runtime'] = runtime result['index'] = index result['starttime'] = common.strTimeToFormat(starttime) year1 = int(time[:4]) month1 = int(time[4:6]) if month1 == 1: month2 = 12 year2 = year - 1 else: month2 = month1 - 1 year2 = year1 day1 = calendar.monthrange(year1, month1)[1] day2 = calendar.monthrange(year2, month2)[1] avgpower = float(power) / day1 avgpower = float('%0.3f' % avgpower) if power_pre == 0: avgpower_pre = 0 else: avgpower_pre = float(power_pre) / day2 avgpower_pre = float('%0.3f' % avgpower_pre) result['powerinfo'] = { 'now': [float('%0.3f' % power), avgpower], 'pre': [float('%0.3f' % power_pre), avgpower_pre] } data_model(tablename).insert(result) count += 1 # finditem = data_model('user_dev').find_one(conditions={'_id':devid}) # if finditem is None: # pass # else: if system == '': findloger = data_model('loger').find_one( conditions={'content.devID': devid}) if findloger is None: system = 'LV_1' else: system = findloger.get('system', 'LV_1') # sender = finditem['sender'] # username = finditem['username'] findname = data_model('devCurrInfo').find_one( conditions={'deviceId': devid}) if findname is None: name = '设备' + devid[:15][-4:] else: name = findname.get('devName', '设备' + devid[:15][-4:]) content = '%s %s年%d月份使用情况汇总' % (name, time[:4], month) url = 'http://%s/report/month?month=%s&devid=%s' % ( server, time, common.encrypt(15, devid)) data_model('month_report_test').insert({ 'devid': devid, 'month': time, 'sender': sender, 'url': url, 'username': username, 'content': content, 'system': system }) print count print 'OK'