34 import os, string, tempfile, types, sys, time
58 def __init__(self,dateFormat, colNum, firstTs, beg=None, end=None, time=None, ):
75 if dateFormat ==
'diff':
76 secs=P2Query.fromInterval(beg)
77 self.
beg = datetime.datetime.now()
78 self.
beg = int(self.beg.strftime(
"%s")) + secs
80 self.
beg=datetime.strptime(beg,dateFormat)
81 self.
beg = int(self.beg.strftime(
"%s"))
86 self.
end=datetime.datetime.now()
87 self.
end = int(self.end.strftime(
"%s"))
89 if dateFormat ==
'diff':
90 secs=P2Query.fromInterval(end)
91 self.
end = datetime.datetime.now()
92 self.
end = int(self.end.strftime(
"%s")) + secs
94 self.
end=datetime.strptime(end,dateFormat)
95 self.
end = int(self.end.strftime(
"%s"))
99 secs=P2Query.fromInterval(time)
101 if beg ==
None and not end ==
None:
102 self.
beg = self.
end + secs
104 elif end ==
None and not beg ==
None:
105 self.
end = self.
beg + secs
109 logger.critical(
'End date is smaller than begin date')
125 unit = interval[len(interval)-1]
126 secs=int(interval[:-1])
137 logger.critical(
'Invalid time interval : '+time)
150 for (ts,vals)
in content:
160 if timestamp
not in self.
datas:
163 return self.
datas[timestamp]
175 return self.datas.keys();
186 argsShort = {
'b' :
'begin',
'e' :
'end',
't' :
'time',
'f' :
'format',
'd':
'data',
'n':
'num',
'y':
'yaxe',
's':
'style',
'c':
'color',
'l':
'label',
'sc':
'scale',
'a':
'add' }
188 argsToNone = [
'begin',
'end',
'time']
212 firstTs = self.db.getFirst()
214 for query
in queries:
216 args = P2Datas.queryToDict(query, queryArgSep)
217 self.qArgs.append(args)
218 if 'format' not in args:
219 print >> sys.stderr,
'Error, no date format specified in query '+query
221 elif 'num' not in args:
222 print >> sys.stderr,
'Error no data id number specified in query '+query
223 self.queries.append(
P2Query(args[
'format'], args[
'num'], firstTs, args[
'begin'],args[
'end'],args[
'time']))
225 diff = curq.getEnd() - curq.getBeg()
230 base = [curq.getBeg(),curq.getEnd()]
232 if base[0] != curq.getBeg()
or base[1] != curq.getEnd():
244 spl = query.split(sep)
247 spl2 = s.split(
'=',1)
249 if name
in P2Datas.argsShort:
250 name = P2Datas.argsShort[name]
253 for n
in P2Datas.argsToNone:
269 if len(dataList) != 48:
270 logger.warning(
'Data as not the waited length ('+str(len(dataList))+
' \''+data[1]+
'\'')
273 content.append([data[0],dataList])
276 for query
in queries:
277 query.setContent(content)
286 datas = self.db.getData(self.
queries[0].getBeg(),self.
queries[0].getEnd())
287 P2Datas.fillQuery(datas,self.
queries)
290 """The goal is to look for queries with same begin and end
291 to make only one db query per group"""
292 for i
in range(len(self.
queries)):
296 for j
in range(i,len(self.
queries)):
301 datas = self.db.getData(self.
queries[i].getBeg(),self.
queries[i].getEnd())
306 P2Datas.fillQuery(datas, tofill)
323 for i
in range(len(self.
queries)):
324 self.tmpfile.append(tempfile.NamedTemporaryFile(
'w+b',-1,
'pyP2gnuplotdatas'))
335 trange = sorted(self.
queries[0].getKeys())
346 for i
in range(len(self.
queries)):
353 ts = ts + query.getBeg()
362 scale = args[
'scale']
365 val = query.getVal(ts)
372 dataBuff+=sep+str(float(val)*float(scale)+float(add))
375 tmpfd[i].write(str(ts)+
' '+str(float(val)*float(scale)+float(add))+
'\n')
382 outfd.write(str(ts)+dataBuff+
'\n');
393 for i
in range(len(self.
queries)):
405 res +=
'"'+self.
tmpfile[i].name+
'" using 1:2 '
408 label = args[
'label']+
' '
410 label =
colNames()[int(args[
'num'])]+
' '
418 scale = args[
'scale']
424 label +=
'*'+str(scale)
431 style = args[
'style']
435 if 'yaxe' in args
and args[
'yaxe'] ==
'2':
441 res +=
'title "'+label+
'" '
442 res +=
' with '+style+
' '
444 res +=
'lt rgb "'+args[
'color']+
'" '
447 logger.debug(
'Plot command : '+res)
463 outFmt =
'%d-%m %H:%M'
466 return (inFmt,outFmt)
478 def data2List(timestamp, data, dateFormat="%Y/%m/%d_%H:%M:%S
"):
480 date = datetime.datetime.fromtimestamp(float(timestamp))
483 res.append(date.strftime(dateFormat))
489 for i
in range(0,len(data),2):
490 res.append(data[i]*0x100+data[i+1])
497 if res[16] & 0x8000 != 0:
499 res[16] = res[16] - ( 1 << 16 )
517 res.append(
"Date et heure")
522 res.append(
"Temp chaudiere")
523 res.append(
"Temp fumee")
524 res.append(
"Temp gaz brules")
525 res.append(
"Puissance momentanee")
526 res.append(
"Ventil. depart")
527 res.append(
"Ventil. air combustion")
528 res.append(
"Alimentation")
529 res.append(
"O2 residuel")
530 res.append(
"Regulation O2")
531 res.append(
"Pellets restants (kg)")
533 res.append(
"Temp exterieur")
534 res.append(
"Temp consigne depart 1")
535 res.append(
"Temp depart 1")
538 res.append(
"Demarages")
539 res.append(
"Duree fonctionnement (h)")
540 res.append(
"Temp tableau")
541 res.append(
"Consigne temp chaudiere")
554 if len(dataList) == 48:
555 res.append(
data2List(data[0], dataList ))
557 return json.dumps(res)
566 def csvDump(dbname, filename = '-', header = True, sep="; "):
575 fdout = open(filename,
"w+")
580 for i
in range(len(hnames)):
581 fdout.write(hnames[i])
582 if i < len(hnames)-1:
586 datas = db.getLastData()
588 for (timestamp,data)
in datas:
599 while len(ts) == 0
or len(data) == 0:
600 lfile = open(lfname,
"r")
601 ts = lfile.readline().strip("\n")
602 data = lfile.readline().strip(
"\n")
606 for i
in range(len(hnames)):
607 sys.stdout.write(hnames[i])
608 if i < len(hnames)-1:
609 sys.stdout.write(sep)
610 sys.stdout.write(
"\n")
622 if len(dataList) != 48:
624 logger.warning(
"Bad data length "+str(len(dataList))+
" : '"+(str(timestamp)+
" "+data)+
"'")
626 dataNums =
data2List(timestamp, dataList)
627 for i
in range(len(dataNums)):
628 fdout.write(str(dataNums[i]))
629 if i < len(dataNums)-1: