Ejemplo n.º 1
0
def cursorhandler():
    ''' handle end of cursor movement
	receive data send by dragger.js->finalise->senddata '''
    logger.info("cursor posted:%s" % bottle.request.body.read())
    rec = bottle.request.json
    jd = float(rec['jdtill']) - (900 - float(rec['cursorPos'])) / 800 * float(
        rec['ndays'])
    qids = rec['grQuantIds']
    logger.info("cursor %s at %s " % (rec, prettydate(jd)))
    #logger.info("curs post:%s" % bottle.request.body.read())
    return dict(dd=prettydate(jd), jdtill=jd, evtDescr='curs')
Ejemplo n.º 2
0
def formhandler():
    ''' Handle form submission '''
    tm = time.perf_counter()
    if 'REMOTE_ADDR' in bottle.request.environ:
        ip = bottle.request.environ.get('REMOTE_ADDR')
    else:
        ip = None

    logger.info("==== menu handler from %s =====:\n%s" %
                (ip, bottle.request.body.read()))
    selqs = bottle.request.forms.getall('quantities')
    src = bottle.request.forms.get('source')
    tbcknm = bottle.request.forms.get('tmback')
    cursXpos = bottle.request.forms.get('cursorPos')
    jdtill = bottle.request.forms.get('jdtill')
    evtDescr = bottle.request.forms.get('evtDescr')
    evtData = bottle.request.forms.get('evtData')
    try:
        ndays = next(tb for tb, tup in tmBACKs.items() if tbcknm in tup[0])
    except StopIteration:
        ndays = 5

    jdofs = (plXMARG + plWIDTH -
             int(cursXpos)) / plWIDTH * ndays  # cursor pos giving time offset
    if jdtill:
        jdtill = float(jdtill)  # preserve actual time frame
    else:
        jdtill = julianday()
    jdcursor = jdtill - jdofs
    if evtDescr and evtDescr != 'comment':  # define event at cursor
        root = sys.modules['__main__'].__file__
        logger.info('received event descr %s at jd:%s' % (evtDescr, jdcursor))

        dbStore.setEvtDescription(jdcursor, evtDescr, root=root)
    else:  # place right side at cursor
        jdtill = jdcursor

    if abs(jdtill - julianday()) < ndays / 5.0:
        jdtill = julianday()  # adjust to now when close
    else:
        logger.info("adjusting jd %f with ofs:%f evt:%s" %
                    (jdtill, jdofs, evtDescr))
    statbar = bottle.request.forms.get('statbar')
    logger.info("statbar=%s" % statbar)

    logger.info(
        "menu response(t:%s):qtt=%s src=%s jd=%s ndys=%s cPos=%s evtData=%s" %
        (time.perf_counter() - tm, selqs, src, prettydate(jdtill), tbcknm,
         cursXpos, evtData))
    bottle.response.set_cookie(COOKIE,
                               json.dumps((src, selqs, ndays)),
                               max_age=AN1)
    return bottle.template(TPL, redraw(src, selqs, jdtill, ndays))
Ejemplo n.º 3
0
def tax_grid(jdnow, ndays, gridstep):
    ''' time axis grid locations '''
    utcoff = time.localtime(
    ).tm_gmtoff / 3600 / 24  #[d]  #time.localtime()-time.gmtime()

    if gridstep == 0.0417:  # 1hrs
        gridofs = (jdnow + utcoff) % 0.0417  #[d]
        gridofs = jdnow - int(jdnow)
        gridofs = gridofs % 0.0417
        gridofs *= 24.0  #[hr]
        logger.debug("frac in 1hrs %s utcofs=%s now=%s" %
                     (gridofs, utcoff, prettydate(jdnow)))
    elif gridstep == 0.25:  # 6hrs
        gridofs = (jdnow + utcoff) % 0.25  #[d]
        gridofs *= 4.0  #[6h]
        logger.debug("frac in 6hrs %s utcofs=%s now=%s" %
                     (gridofs, utcoff, prettydate(jdnow)))
    elif gridstep == 7:  # a week
        gridofs = (jdnow + 1.5 + utcoff) % 7  #[d]
        logger.debug("day of week:%s" % gridofs)
        gridofs /= 7  #[w]
    elif int(gridstep) == 30:  # a month
        gridofs = datetime.datetime.fromtimestamp(unixsecond(jdnow))
        logger.debug("date %s hour %s" % (gridofs.day, gridofs.hour))
        gridofs = gridofs.day + gridofs.hour / 24.0  #[d]
        gridofs /= 30.44  #[m]
    else:
        gridofs = jdnow - 0.5 + utcoff  #noon utc to midnight this tz
        gridofs = gridofs / gridstep - int(gridofs / gridstep)

    gridlocs = [
        jdnow - (f + gridofs) * gridstep
        for f in range(int(ndays / gridstep + 0.1))
    ]
    gridlocs.reverse()
    logger.debug("jdnow=%s gridlocs=%s" % (jdnow, gridlocs))
    return gridlocs
Ejemplo n.º 4
0
	def check_quantity(self,tstamp,quantity,val):
		''' filters, validates, averages, checks, quantity results
		 calls accept_result when quantity rules are fullfilled
		 to be called by receive_message  '''
		if quantity not in self._servmap:
			logger.info("unknown quantity:%s val=%s in %s" % (quantity,val,self.manufacturer))
			#self.servmap[quantity] = {'typ':DEVT['unknown']}
			return
		if self.qtype(quantity)>=DEVT['secluded']:	# ignore
			return
		if isinstance(val, collections.Sequence):
			logger.warning('not numeric %d = %s' % (quantity,val))
		if self.qInRng(quantity,val)==False:
			logger.warning("quantity out of range %s" % quantity)
			return
		else:
			self.actual[quantity] = {qVAL:val, qSTMP:tstamp}

		if sampleCollector.signaller:
			if sampleCollector.signaller.checkEvent(quantity, val):  # handle event by polling
				sampleCollector.signaller.signal(quantity, val)
		if self.qIsCounting(quantity): 
			if quantity in self.average and val>0: # only first and pos edge
				self.average[quantity][qVAL] += val
				self.average[quantity][qCNT] +=1
			else:
				self.average[quantity] = [val,1,tstamp]
			self.accept_result(tstamp, quantity)
			logger.info('(%s) cnt val=%s quantity=%s tm=%s since=%.6g' % (quantity,val, self.qname(quantity), prettydate(julianday(tstamp)), self.sinceAccept(quantity)))
		elif quantity in self.average:
			n = self.average[quantity][qCNT]
			avg = self.average[quantity][qVAL] / n
			if (n>=self.minNr and abs(val-avg)>abs(avg*self.minDevPerc/100)) or n>=self.maxNr:
				logger.info('(%s) n=%d avg=%g val=%s quantity=%s devPrc=%g>%g tm=%s since=%.6g' % (quantity,n,avg,val, self.qname(quantity), abs(val-avg)/avg*100 if avg>0 else 0.0, self.minDevPerc, prettydate(julianday(tstamp)), self.sinceAccept(quantity)))
				self.accept_result((tstamp+self.average[quantity][qSTMP])/2, quantity)
				self.average[quantity] = [val,1,tstamp]
			else:
				self.average[quantity][qVAL] += val
				self.average[quantity][qCNT] += 1
				if abs(avg)>0:
					logger.debug('quantity:%d avgCount:%d devperc:%.6g ' % (quantity,self.average[quantity][qCNT], (val-avg)/avg*100) )
		else:  # first avg val
			self.average[quantity] = [val,1,tstamp]
			if self.maxNr<=1:
				self.accept_result(tstamp, quantity)
				logger.info('accepting one val=%s quantity=%s(%s) tm=%s' % (val,self.qname(quantity),quantity, prettydate(julianday(tstamp))))
Ejemplo n.º 5
0
def buildChart(jdats, ydats, selqs, jdtill, ndays):
    ''' build data for svg chart including axes,labels,gridlines,curves,histogram'''
    data = []
    subtitle = []
    ret = dict(title=TITLE,
               ndays=ndays,
               jdtill=jdtill,
               cursorPos=plXMARG + plWIDTH,
               curves=[])

    for jdat, ydat, selq in zip(jdats, ydats, selqs):
        if len(ydat) > 0:
            vmax = max(ydat)
            vmin = min(ydat)
            if vmax <= vmin:
                vmin = vmax - 1
        if selq in DEVT and DEVT[selq] in strokes:
            stroke = strokes[DEVT[selq]]
            symbol = SIsymb[DEVT[selq]]
            vlast = ydat[-1]
            subtitle.append("%s=%.4g %s " % (symbol[0], vlast, symbol[1]))
        else:
            logger.debug("selq %s not in strokes:%s" % (selq, strokes))
            stroke = strokes[0]
        if len(jdat) > 0:
            if selq in DEVT and DEVT[selq] in qCOUNTING:
                vmin = 0
                vmax = int(vmax / 3) * 3 + 3
                crv = buildHistogram(jdat, ydat, ndays, vmax, jdtill - ndays,
                                     vmin)
                qtyp = 1
            else:
                crv = buildCurve(jdat, ydat, ndays, vmax - vmin,
                                 jdtill - ndays, vmin)
                qtyp = 0
            ylbls = buildLbls(vmin, vmax, 4)
            logger.debug("selq:%s,len:%d,col:%s,ylbls:%s" %
                         (selq, len(jdat), stroke, ylbls))
            curve = dict(crv=crv,
                         stroke=stroke,
                         ylbls=ylbls,
                         selq=selq,
                         qtyp=qtyp,
                         legend=selq)
            data.append(curve)
    ret['subtitle'] = ''  #" , ".join(subtitle)
    ret['statbar'] = [
        " dd:%s , %s" % (prettydate(jdtill), " , ".join(subtitle))
    ]
    if len(data) == 0:
        logger.warning('missing chart data:jd:%d yd:%d q:%d' %
                       (len(jdats), len(ydats), len(selqs)))
        ret.update(dict(curves=[], xgrid=[]))
        return ret

    xlbltup = tmBACKs[ndays]
    lblformat = xlbltup[3]
    gridstep = xlbltup[2]
    barwdt = xlbltup[1]
    xscl = plWIDTH / ndays

    gridlocs = tax_grid(jdtill, ndays, gridstep)
    xgrid = [
        round(plXMARG + plWIDTH - (jdtill - jd) * xscl, 1) for jd in gridlocs
    ]
    xlbls = bld_dy_lbls([jd + gridstep / 2 for jd in gridlocs[:-1]], lblformat)

    logger.info("chart upd: ndays=%.4g xlbls=%s xgrid=%s" %
                (ndays, xlbls, xgrid))
    ret.update(dict(title=TITLE, curves=data, xgrid=xgrid, xlbls=xlbls))
    return ret
Ejemplo n.º 6
0
def bld_dy_lbls(jdats, form="{}"):
    ''' date interval labels '''
    if len(jdats) == 0:
        return [""]
    return [prettydate(jd, form) for jd in jdats]