def main_loop(): """ The main loop in which we stay connected to the broker """ while True: logging.debug(("DeviceList.data is : %s") % (str(DevicesList.data))) item = 0 for device in DevicesList.data: # Split up list into relevant parts for reuse owserver = DevicesList.data[item][0] owport = DevicesList.data[item][1] owpath = DevicesList.data[item][2] owsensortype = DevicesList.data[item][3] logging.debug(("Querying %s on %s:%s") % (owpath, owserver, owport)) # FIXME owserver to come from a list of devices, and their respective servers ow.init(owserver + ":" + owport) ow.error_level(ow.error_level.fatal) ow.error_print(ow.error_print.stderr) # FIXME This possibly needs done for each 1-wire host # Split it off to the connect() function # Enable simultaneous temperature conversion ow._put("/simultaneous/temperature","1") try: # Create sensor object logging.debug(("Trying sensor %s with type %s on %s:%s") % (owpath, owsensortype, owserver, owport)) # sensor = ow.Sensor(owpath) sensordata = ow.owfs_get(owpath + "/" + owsensortype) # sensordata = getattr(sensor, owsensortype) if (owsensortype == 'temperature' and METRICUNITS == '0'): sensordata = (farenheitCon(float(sensordata))) if (owsensortype == 'pressure'): if ("B1-R1-A" in owpath): pressureoffset = ow.owfs_get(owpath + "/gain") sensordata = (float(sensordata) + float(pressureoffset)) * 0.02953 # if (owsensortype == 'illuminance'): # if ("S3-R1-A" in owpath): # solaroffset = ow.owfs_get(owpath + "/gain") # sensordata = float(solaroffset) + float(sensordata) #Query sensor state logging.debug(("Sensor %s : %s") % (owpath, sensordata)) mqttc.publish(MQTT_TOPIC + owpath + "/" + owsensortype, sensordata) item += 1 except ow.exUnknownSensor: logging.debug("Threw an unknown sensor exception for device %s. Continuing", owpath) continue # We only want to poll the sensors occasionally... not every one second that's the default for mqttc.loop time.sleep(POLLINTERVAL)
def run(self): # wait till devices should be announced time.sleep(5) while (True): try: for sensor in root.sensors(): if sensor._type == 'DS18S20' or sensor._type == 'DS18B20' or sensor._type == 'DS2438': temp = round(float(sensor.temperature),1) if sensor._path in sensors: if 'temp' in sensors[sensor._path]: if abs(sensors[sensor._path]['temp'] - temp) > 0.5: client.emitEvent( sensor._path, "event.environment.temperaturechanged", temp, "degC") sensors[sensor._path]['temp'] = temp else: client.emitEvent( sensor._path, "event.environment.temperaturechanged", temp, "degC") sensors[sensor._path]={} sensors[sensor._path]['temp'] = temp if sensor._type == 'DS2438': try: if ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-TL': rawvalue = float(ow.owfs_get('/uncached%s/VAD' % sensor._path )) if rawvalue > 10: rawvalue = 0 lightlevel = int(round(20*rawvalue)) if 'light' in sensors[sensor._path]: if abs(sensors[sensor._path]['light'] - lightlevel) > 5: client.emitEvent( sensor._path, "event.environment.brightnesschanged", lightlevel, "percent") sensors[sensor._path]['light'] = lightlevel else: client.emitEvent( sensor._path, "event.environment.brightnesschanged", lightlevel, "percent") sensors[sensor._path]['light'] = lightlevel if ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-TH': humraw = ow.owfs_get('/uncached%s/humidity' % sensor._path ) humidity = round(float(humraw)) if 'hum' in sensors[sensor._path]: if abs(sensors[sensor._path]['hum'] - humidity) > 2: client.emitEvent( sensor._path, "event.environment.humiditychanged", humidity, "percent") sensors[sensor._path]['hum'] = humidity else: client.emitEvent( sensor._path, "event.environment.humiditychanged", humidity, "percent") sensors[sensor._path]['hum'] = humidity except ow.exUnknownSensor, e: print e if sensor._type == 'DS2406': if sensor.latch_B == '1': sensor.latch_B = '0' sendSensorTriggerEvent(sensor._path, sensor.sensed_B) except ow.exUnknownSensor, e: pass time.sleep(2)
def value_at(self, time_ts): try: altimeter = float(ow.owfs_get('26.C9AABC000000/B1-R1-A/pressure')) return altimeter except ow.exError, e: logerr("Failed attempt to get Barometer data: %s" % ( e)) return None
def value_at(self, time_ts): try: humidity = float(ow.owfs_get('26.378C21010000/HIH4000/humidity')) return humidity except ow.exError, e: logerr("Failed attempt to get inHumid data: %s" % ( e)) return None
def value_at(self, time_ts): try: temp = float(ow.owfs_get('10.25A5A0020800/temperature')) return temp except ow.exError, e: logerr("Failed attempt to get inTemp data: %s" % ( e)) return None
def get(self): try: value = ow.owfs_get(self.path) except ow.exUnknownSensor: value = None value = self.stateType.reduce(value) return self.changeState(value)
def value_at(self, time_ts): """Returns rain and rain rate Various rain rate algorithms are implemented and returned. User can decide which they want and assign it to """ try: rainCnt = int(ow.owfs_get('1D.22AA0D000000/counters.B')) except ow.exError, e: logerr("Failed attempt to get rain data: %s" % ( e)) return None
def aag_winddir(key, path, last_data, ts): """Calculate wind direction for AAG TAI8515 V3 wind instrument. Contributed by Howard Walter, based on oww C implementation.""" w = ow.owfs_get("%s%s" % (path, "/volt.ALL")) wd = w.split(',') wd = [float(x) for x in wd] mx = max(x for x in wd) wd = [x / mx for x in wd] if wd[0] < 0.26: if wd[1] < 0.505: wdir = 11 else: if wd[3] < 0.755: wdir = 13 else: wdir = 12 else: if wd[1] < 0.26: if wd[2] < 0.505: wdir = 9 else: wdir = 10 else: if wd[2] < 0.26: if wd[3] < 0.505: wdir = 7 else: wdir = 8 else: if wd[3] < 0.26: if wd[0] < 0.755: wdir = 5 else: wdir = 6 else: if wd[3] < 0.84: if wd[2] < 0.84: wdir = 15 else: wdir = 14 else: if wd[0] < 0.845: if wd[1] < 0.845: wdir = 3 else: wdir = 4 else: if wd[1] > 0.84: wdir = 0 else: if wd[2] > 0.845: wdir = 2 else: wdir = 1 return 22.5 * wdir
def aag_winddir(key, path, last_data, ts): """Calculate wind direction for AAG TAI8515 V3 wind instrument. Contributed by Howard Walter, based on oww C implementation.""" w = ow.owfs_get("%s%s" % (path, "/volt.ALL")) wd = w.split(',') wd = [float(x) for x in wd] mx = max(x for x in wd) wd = [x/mx for x in wd] if wd[0] < 0.26: if wd[1] < 0.505: wdir = 11 else: if wd[3] < 0.755: wdir = 13 else: wdir = 12 else: if wd[1] < 0.26: if wd[2] < 0.505: wdir = 9 else: wdir = 10 else: if wd[2] < 0.26: if wd[3] < 0.505: wdir = 7 else: wdir = 8 else: if wd[3] < 0.26: if wd[0] < 0.755: wdir = 5 else: wdir = 6 else: if wd[3] < 0.84: if wd[2] < 0.84: wdir = 15 else: wdir = 14 else: if wd[0] < 0.845: if wd[1] < 0.845: wdir = 3 else: wdir = 4 else: if wd[1] > 0.84: wdir = 0 else: if wd[2] > 0.845: wdir = 2 else: wdir = 1 return 22.5 * wdir
def main(): import optparse # Set defaults for logging: weeutil.logger.setup('owfs', {}) #syslog.openlog('wee_owfs', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option("--iface", dest="iface", type=str, metavar="IFACE", help="specify the interface, e.g., u or /dev/ttyS0") parser.add_option('--sensors', dest='sensors', action='store_true', help='display list attached sensors') parser.add_option('--readings', dest='readings', action='store_true', help='display sensor readings') parser.add_option('--reading', dest='reading', type=str, metavar="SENSOR", help='display output of specified sensor') (options, args) = parser.parse_args() if options.version: print("owfs version %s" % DRIVER_VERSION) exit(1) # default to usb for the interface iface = options.iface if options.iface is not None else 'u' if options.sensors: ow.init(iface) traverse(ow.Sensor('/'), identify_sensor) elif options.readings: ow.init(iface) traverse(ow.Sensor('/'), display_sensor_info) elif options.reading: ow.init(iface) print('%s: %s' % (options.reading, ow.owfs_get(options.reading)))
def display_dict(d, level=0): for k in d: if isinstance(d[k], dict): display_dict(d[k], level=level+1) elif k == 'alias': pass elif k.startswith('_'): print '%s%s: %s' % (' '*level, k, d[k]) else: v = 'UNKNOWN' try: v = ow.owfs_get(d[k]) except ow.exError, e: v = 'FAIL: %s' % e print '%s%s: %s' % (' '*level, d[k], v)
def display_dict(d, level=0): for k in d: if isinstance(d[k], dict): display_dict(d[k], level=level + 1) elif k == 'alias': pass elif k.startswith('_'): print('%s%s: %s' % (' ' * level, k, d[k])) else: v = 'UNKNOWN' try: v = ow.owfs_get(d[k]) except ow.exError as e: v = 'FAIL: %s' % e print('%s%s: %s' % (' ' * level, d[k], v))
def __init__(self, parent, name): super(OWDevice, self).__init__(parent, name.strip('/').replace('.', '_')) self.path = parent.path + name if parent.path == '/': self.structure_path = '/structure/%s/' % name.split('.')[0] else: self.structure_path = self.parent.structure_path + name for n in ow.owfs_get(self.path).split(','): if n.endswith('/'): if n.startswith('bus.'): continue OWDevice(self, n) else: OWEntry(self, n)
def readSensor(self, saddress, sprop): """ ow.Sensor don't work with sensor directory be replace by ow.owfs_get """ try: sensor = self._root + saddress + "/" + sprop self.log.info(u"==> Reading sensor '%s'" % sensor) value = ow.owfs_get(str(sensor)).strip() # Ex.: ow.owfs_get('/26.D050E7000000/B1-R1-A/pressure') if ("temperature" in sprop) and value == '85': # Error reading thermometer return 85 ! self.log.error(u"### Sensor '%s', BAD read temperature (85°)" % saddress) return "failed" return value except ow.exUnknownSensor: self.log.error(u"### Sensor '%s' NOT FOUND." % saddress) return "failed" except AttributeError: self.log.error(u"### Sensor '%s', ERROR while reading value." % sensor) return "failed"
def __init__(self,owobj): self._owobj = owobj self._subtype = None if self._owobj.type == 'DS2438': if 'MultiSensor/' in self._owobj._attrs.keys(): self._subtype = ow.owfs_get('%s/MultiSensor/type'%self._owobj._path) if self._subtype == 'MS-TH': self.append(OwSensorMeasure(self,"temperature","temperature")) self.append(OwSensorMeasure(self,"humidity","HIH4000/humidity")) elif self._subtype == 'MS-TL': self.append(OwSensorMeasure(self,"temperature","temperature")) self.append(OwSensorMeasure(self,"light","VAD",20)) else: print "Unknown multi Sensor: %s"%mlttype elif self._owobj.type == 'DS18B20': self.append(OwSensorMeasure(self,"temperature","temperature")) else: print "TODO: manage other sensor:\n\tFamily: "+self._owobj.family+"\n\tType: "+self._owobj.type
def __init__(self, parent, name): self.path = parent.path + name structure = ow.owfs_get(parent.structure_path + name) entryType, index, arraySize, accessMode, size, changebility = structure.split(',')[:-1] index = int(index) if index != 0: self.stateType = Str() elif entryType in ('i', 'u'): self.stateType = Int() elif entryType in ('f', 't', 'g', 'p'): self.stateType = Decimal() elif entryType == 'y': self.stateType = Bool() else: self.stateType = Str() if accessMode in ('ro', 'oo'): self.set = None if accessMode in ('wo', 'oo'): self.get = None super(OWEntry, self).__init__(parent, name.replace('.', '_'))
def __init__(self, parent, name): self.path = parent.path + name structure = ow.owfs_get(parent.structure_path + name) entryType, index, arraySize, accessMode, size, changebility = structure.split( ',')[:-1] index = int(index) if index != 0: self.stateType = Str() elif entryType in ('i', 'u'): self.stateType = Int() elif entryType in ('f', 't', 'g', 'p'): self.stateType = Decimal() elif entryType == 'y': self.stateType = Bool() else: self.stateType = Str() if accessMode in ('ro', 'oo'): self.set = None if accessMode in ('wo', 'oo'): self.get = None super(OWEntry, self).__init__(parent, name.replace('.', '_'))
def main(): import optparse syslog.openlog('wee_owfs', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option("--iface", dest="iface", type=str, metavar="IFACE", help="specify the interface, e.g., u or /dev/ttyS0") parser.add_option('--sensors', dest='sensors', action='store_true', help='display list attached sensors') parser.add_option('--readings', dest='readings', action='store_true', help='display sensor readings') parser.add_option('--reading',dest='reading',type=str,metavar="SENSOR", help='display output of specified sensor') (options, args) = parser.parse_args() if options.version: print "owfs version %s" % DRIVER_VERSION exit(1) # default to usb for the interface iface = options.iface if options.iface is not None else 'u' if options.debug is not None: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) if options.sensors: ow.init(iface) traverse(ow.Sensor('/'), identify_sensor) elif options.readings: ow.init(iface) traverse(ow.Sensor('/'), display_sensor_info) elif options.reading: ow.init(iface) print '%s: %s' % (options.reading, ow.owfs_get(options.reading))
def readSensor(self, saddress, sprop): """ ow.Sensor don't work with sensor directory be replace by ow.owfs_get """ try: sensor = self._root + saddress + "/" + sprop self.log.info(u"==> Reading sensor '%s'" % sensor) value = ow.owfs_get(str(sensor)).strip( ) # Ex.: ow.owfs_get('/26.D050E7000000/B1-R1-A/pressure') if ("temperature" in sprop ) and value == '85': # Error reading thermometer return 85 ! self.log.error(u"### Sensor '%s', BAD read temperature (85°)" % saddress) return "failed" return value except ow.exUnknownSensor: self.log.error(u"### Sensor '%s' NOT FOUND." % saddress) return "failed" except AttributeError: self.log.error(u"### Sensor '%s', ERROR while reading value." % sensor) return "failed"
def main_loop(): logging.debug(("onewire server : %s") % (OW_HOST)) logging.debug((" port : %s") % (str(OW_PORT))) logging.debug(("MQTT broker : %s") % (MQTT_HOST)) logging.debug((" port : %s") % (str(MQTT_PORT))) logging.debug(("pollinterval : %s") % (str(POLLINTERVAL))) logging.debug(("statustopic : %s") % (str(STATUSTOPIC))) logging.debug(("sensors : %s") % (len(SENSORS))) for owid, owtopic in SENSORS.items(): logging.debug((" %s : %s") % (owid, owtopic)) # Connect to the broker and enter the main loop mqtt_connect() # Connect to the broker and enter the main loop ow.init(("%s:%s") % (OW_HOST, str(OW_PORT))) ow.error_level(ow.error_level.fatal) ow.error_print(ow.error_print.stderr) while True: # simultaneous temperature conversion ow._put("/simultaneous/temperature", "1") item = 0 # iterate over all sensors for owid, owtopic in SENSORS.items(): logging.debug(("Querying %s : %s") % (owid, owtopic)) try: owvalue = ow.owfs_get(owid) logging.debug(("Sensor %s : %s") % (owid, owvalue)) MQTTC.publish(owtopic, owvalue) except ow.exUnknownSensor: logging.info( "Threw an unknown sensor exception for device %s - %s. Continuing", owid, owtopic) continue time.sleep(float(POLLINTERVAL) / len(SENSORS))
ow.init( device ) except ow.exNoController: syslog.syslog(syslog.LOG_ERROR, "can't open one wire device, aborting") time.sleep(5) exit(-1) syslog.syslog(syslog.LOG_NOTICE, "reading devices") root = ow.Sensor( '/' ) for sensor in root.sensors(): if sensor._type == 'DS18S20' or sensor._type == 'DS18B20': client.addDevice(sensor._path, "multilevelsensor"); if sensor._type == 'DS2438': try: if ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-TL': client.addDevice(sensor._path, "multilevelsensor"); if ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-TH': client.addDevice(sensor._path, "multilevelsensor"); if ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-T': client.addDevice(sensor._path, "multilevelsensor"); except ow.exUnknownSensor, e: print e if sensor._type == 'DS2406': sensor.PIO_B = '0' sensor.latch_B = '0' sensor.set_alarm = '111' client.addDevice(sensor._path, "switch"); client.addDevice(sensor._path, "binarysensor"); def messageHandler(internalid, content):
def GetValue(self): return float(ow.owfs_get('%s/%s'%(self._parent.GetPath(),self.attr))) * self.ratio
def run(self): # wait till devices should be announced time.sleep(5) while (True): try: for sensor in ROOT.sensors(): if (sensor._type == 'DS18S20' or sensor._type == 'DS18B20' or sensor._type == 'DS2438'): temp = round(float(sensor.temperature), 1) if sensor._path in SENSORS: if 'temp' in SENSORS[sensor._path]: if (abs(SENSORS[sensor._path]['temp'] - temp) > 0.5): CLIENT.emit_event(sensor._path, "event.environment.temperaturechanged", temp, "degC") SENSORS[sensor._path]['temp'] = temp else: CLIENT.emit_event(sensor._path, "event.environment.temperaturechanged", temp, "degC") SENSORS[sensor._path] = {} SENSORS[sensor._path]['temp'] = temp if sensor._type == 'DS2438': try: if (ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-TL'): rawvalue = float(ow.owfs_get('/uncached%s/VAD' % sensor._path)) if rawvalue > 10: rawvalue = 0 lightlevel = int(round(20 * rawvalue)) if 'light' in SENSORS[sensor._path]: if (abs(SENSORS[sensor._path]['light'] - lightlevel) > 5): CLIENT.emit_event(sensor._path + "-brightness", "event.environment.brightnesschanged", lightlevel, "percent") SENSORS[sensor._path]['light'] = lightlevel else: CLIENT.emit_event(sensor._path + "-brightness", "event.environment.brightnesschanged", lightlevel, "percent") SENSORS[sensor._path]['light'] = lightlevel if ow.owfs_get('%s/MultiSensor/type' % sensor._path) == 'MS-TH': humraw = ow.owfs_get('/uncached%s/humidity' % sensor._path) humidity = round(float(humraw)) if 'hum' in SENSORS[sensor._path]: if abs(SENSORS[sensor._path]['hum'] - humidity) > 2: CLIENT.emit_event(sensor._path + "-humidity", "event.environment.humiditychanged", humidity, "percent") SENSORS[sensor._path]['hum'] = humidity else: CLIENT.emit_event(sensor._path + "-humidity", "event.environment.humiditychanged", humidity, "percent") SENSORS[sensor._path]['hum'] = humidity except ow.exUnknownSensor, exception: print exception if sensor._type == 'DS2406': if sensor.latch_B == '1': sensor.latch_B = '0' if sensor.sensed_B == '1': CLIENT.emit_event(sensor._path, "event.security.sensortriggered", 255, "") else: CLIENT.emit_event(sensor._path, "event.security.sensortriggered", 0, "") except ow.exUnknownSensor: pass time.sleep(2)
def get(self, path): import ow as owbinding try: return owbinding.owfs_get(path) except owbinding.exError as e: raise OWError(e)
def value_at(self, time_ts): light = float(ow.owfs_get('26.C29621010000/S3-R1-A/illuminance')) # possible catch needed here return light * 0.4 * 0.7
def get_float(path): sv = ow.owfs_get(path) sv = sv.replace(',','.') v = float(sv) return v
def get_float(path): sv = ow.owfs_get(path) sv = sv.replace(',', '.') v = float(sv) return v
# read in connected sensor sensorlist = ow.Sensor('/').sensorList() #print(sensorlist) # loop through sensors and read values for sensor in sensorlist: try: sensorvalues = {} #print('Family: ' + sensor.family) #print('ID: ' + sensor.id) #print('Type: ' + sensor.type) sensorvalues["name"] = devicelist[sensor.id] if sensor.family == "28": sensorvalues["temperature10"] = ow.owfs_get( "/bus.0/" + sensor.family + "." + sensor.id + "/temperature10") sensorvalues["power"] = ow.owfs_get("/bus.0/" + sensor.family + "." + sensor.id + "/power") elif sensor.family == "26": sensorvalues["VAD"] = ow.owfs_get("/bus.0/" + sensor.family + "." + sensor.id + "/VAD") sensorvalues["VDD"] = ow.owfs_get("/bus.0/" + sensor.family + "." + sensor.id + "/VDD") sensorvalues["vis"] = ow.owfs_get("/bus.0/" + sensor.family + "." + sensor.id + "/vis") sensorvalues["humidity"] = ow.owfs_get("/bus.0/" +
def value_at(self, time_ts): self.MPH_PER_HZ = 2.5 kph_per_hz = self.MPH_PER_HZ * 1.60934400 self.MIN_GUST_SPEED_KPH = 29.63200 # 16 knots self.GUST_VARIATION_SPEED_KPH = 16.68 # 9 knots self.MIN_GUST_SPEED_KPH = 10 # 16 knots self.GUST_VARIATION_SPEED_KPH = 5 # 9 knots return None # NOTE need to read non cached versions for wind # Are the counters shorted, is this for noise, could do clever stuff in here if so wspeedCnt = float(ow.owfs_get('uncached/1D.A4C80D000000/counters.A')) # possible catch needed here # TODO, wee need to read to registers but must ensure we do not get a race condition # OWFS should do this for us if it is configured correctly - check this # Direction is returned on VAD in the range of 5% to 95% of VDD wdir_vdd = float(ow.owfs_get('uncached/26.BE50E7000000/VDD')) # possible catch needed here wdir_vad = float(ow.owfs_get('uncached/26.BE50E7000000/VAD')) # possible catch needed here #logdbg("1WIRE: Inspeed Vortex, Count=%d" % (wspeedCnt)) # TODO Catch wrap round if self._wind_ts is None: self._wind_ts = time_ts logdbg("1WIRE: WindSpeed %s" % self._wind_ts) return None delta = time_ts - self._wind_ts if self._windCnt is None: self._windCnt = wspeedCnt return None cntdelta = wspeedCnt - self._windCnt speed = kph_per_hz * cntdelta/delta logdbg("1WIRE: WindSpeed tdelta %s Cntdelta %s Speed %s" % (delta, cntdelta, speed)) # We need to generate moving averages here but rather than storing speeds for each time instant, if we store the count # then we can do the averaging with just 2 subtractions and a divide rather than a full blown sum all speeds and divide while self.gustpipe and self.gustpipe[0][self.TIME_INDEX] < time_ts - self.GUSTDURATION: _unused = self.gustpipe.popleft() self.gustpipe.append((time_ts, wspeedCnt)) count = len(self.gustpipe) if count < 2: return None delta = self.gustpipe[count-1][self.TIME_INDEX] - self.gustpipe[0][self.TIME_INDEX] cntdelta = self.gustpipe[count-1][1] - self.gustpipe[0][1] gustspeed = kph_per_hz * cntdelta/delta #logdbg("1WIRE: WindSpeed GustSpeed Queue %s" % (self.gustpipe)) logdbg("1WIRE: WindSpeed GustSpeed %s %s %s" % (gustspeed, sum(item[1] for item in self.gustpipe) / count, count)) # NOTE if pipe is less than GUSTDURATION then out speeds are correct but avaraged over the wrong period # Average Speed while self.speedpipe and self.speedpipe[0][self.TIME_INDEX] < time_ts - self.MEANDURATION: _unused = self.speedpipe.popleft() self.speedpipe.append((time_ts, wspeedCnt)) count = len(self.speedpipe) if count < 2: logdbg("1WIRE: WindSpeed Average Pipe is too short for calculation") return None delta = self.speedpipe[count-1][self.TIME_INDEX] - self.speedpipe[0][self.TIME_INDEX] cntdelta = self.speedpipe[count-1][1] - self.speedpipe[0][1] avspeed = kph_per_hz * cntdelta/delta # TODO possible wrap round to protect fore #logdbg("1WIRE: WindSpeed AvSpeed Queue %s" % (self.speedpipe)) logdbg("1WIRE: WindSpeed AvSpeed %s %s %s %s" % (avspeed, self.speedpipe[0][1], self.speedpipe[count-1][1], count)) # NOTE if pipe is less than GUSTDURATION then out speeds are correct but avaraged over the wrong period self._windCnt = wspeedCnt self._wind_ts = time_ts normalised = wdir_vad - 0.05*wdir_vdd # Normalise returned value from 5-95% to 0-90% of VDD if (normalised < 0): logerr("1WIRE: Inspeed e-Vane error, Normalised < 0, VAD=%d, VDD=%d" % (normalise, wdir_vad, wdir_vdd)) direction = None direction = (400 * (normalised))/wdir_vdd if (direction > 360): logerr("1WIRE: Inspeed e-Vane error, Direction > 360, normalised=%d, VDD=%d" % (normalised, wdir_vdd)) direction = None roundeddirection = int(direction + 0.5) gustdirection = roundeddirection logdbg("1WIRE: Rounding WindDir %s %s" % (roundeddirection, direction)) # TODO Next bit is optional if (roundeddirection == 0): roundeddirection = 360 if (avspeed ==0): roundeddirection = 0 if (avspeed ==0): roundeddirection = None if (gustspeed < self.MIN_GUST_SPEED_KPH): gustspeed = None gustdirection = None elif (gustspeed - avspeed < self.GUST_VARIATION_SPEED_KPH): #TODO Careful here what units are 5 in knot mph/kph ?? gustspeed = None gustdirection = None #gustdirection = None #gustspeed = None # Put 16.093440006146921597227828997904 here for 10 mph #avspeed = 16.093440006146921597227828997904 #avspeed = avspeed #roundeddirection = 47 return (avspeed, gustspeed, roundeddirection, gustdirection)
def readBattery(self, sensor, sensortypus): dispatch_url = "http://example.com/" + self.hostname + "/ow#" + sensor.id + "-value" currenttime = datetime.utcnow() filename = datetime.strftime(currenttime, "%Y-%m-%d") actualtime = datetime.strftime(currenttime, "%Y-%m-%dT%H:%M:%S.%f") timestamp = datetime.strftime(currenttime, "%Y-%m-%d %H:%M:%S.%f") outtime = datetime.strftime(currenttime, "%H:%M:%S") packcode = '6hLlLLLf' header = "# MagPyBin %s %s %s %s %s %s %d" % ( sensor.id, '[t1,var1,var2,var3,var4]', '[T,rh,vdd,vad,vis]', '[deg_C,per,V,V,V]', '[1000,100,100,100,1]', packcode, struct.calcsize(packcode)) try: # Extract data #print "Sensor: ", sensor.id, sensortypus try: humidity = float( ow.owfs_get('/uncached%s/HIH4000/humidity' % sensor._path)) except: humidity = float(nan) try: #print "Battery sens: T = ", sensor.temperature temp = float(sensor.temperature) #print "Battery sens: VDD = ", sensor.VDD vdd = float(sensor.VDD) #print "Battery sens: VAD = ", sensor.VAD vad = float(sensor.VAD) #print "Battery sens: vis = ", sensor.vis vis = float(sensor.vis) if sensortypus == "pressure": #print "Pressure [hPa]: ", self.mpxa4100(vad,temp) humidity = self.mpxa4100(vad, temp) except: log.err("OW - readBattery: Could not asign value") # Appending data to buffer which contains pcdate, pctime and sensordata # extract time data datearray = self.timeToArray(timestamp) try: datearray.append(int(temp * 1000)) if humidity < 0: humidity = 9999 datearray.append(int(humidity * 100)) datearray.append(int(vdd * 100)) datearray.append(int(vad * 100)) datearray.append(vis) data_bin = struct.pack(packcode, *datearray) except: log.msg( 'OW - readBattery: Error while packing binary data') pass # File Operations self.dataToFile(sensor.id, filename, data_bin, header) try: evt1 = {'id': 3, 'value': outtime} evt9 = {'id': 1, 'value': timestamp} evt2 = {'id': 30, 'value': temp} if humidity < 100: evt3 = {'id': 33, 'value': humidity} else: evt3 = {'id': 33, 'value': 0} evt5 = {'id': 60, 'value': vdd} evt6 = {'id': 61, 'value': vad} evt7 = {'id': 62, 'value': vis} evt8 = {'id': 99, 'value': 'eol'} except: print("OW - readBattery: Problem assigning values to dict") try: self.wsMcuFactory.dispatch(dispatch_url, evt1) self.wsMcuFactory.dispatch(dispatch_url, evt9) self.wsMcuFactory.dispatch(dispatch_url, evt2) self.wsMcuFactory.dispatch(dispatch_url, evt3) self.wsMcuFactory.dispatch(dispatch_url, evt5) self.wsMcuFactory.dispatch(dispatch_url, evt6) self.wsMcuFactory.dispatch(dispatch_url, evt7) self.wsMcuFactory.dispatch(dispatch_url, evt8) pass except: log.err('OW - readBattery: Unable to parse data at %s' % actualtime) except: log.err( 'OW - readBattery: Lost battery sensor -- reconnecting') global owsensorlist owsensorlist = [] self.owConnected()
def readBattery(self,sensor,sensortypus): dispatch_url = "http://example.com/"+self.hostname+"/ow#"+sensor.id+"-value" currenttime = datetime.utcnow() filename = datetime.strftime(currenttime, "%Y-%m-%d") actualtime = datetime.strftime(currenttime, "%Y-%m-%dT%H:%M:%S.%f") timestamp = datetime.strftime(currenttime, "%Y-%m-%d %H:%M:%S.%f") outtime = datetime.strftime(currenttime, "%H:%M:%S") packcode = '6hLlLLLf' header = "# MagPyBin %s %s %s %s %s %s %d" % (sensor.id, '[t1,var1,var2,var3,var4]', '[T,rh,vdd,vad,vis]', '[deg_C,per,V,V,V]', '[1000,100,100,100,1]', packcode, struct.calcsize(packcode)) try: # Extract data #print "Sensor: ", sensor.id, sensortypus try: humidity = float(ow.owfs_get('/uncached%s/HIH4000/humidity' % sensor._path)) except: humidity = float(nan) try: #print "Battery sens: T = ", sensor.temperature temp = float(sensor.temperature) #print "Battery sens: VDD = ", sensor.VDD vdd = float(sensor.VDD) #print "Battery sens: VAD = ", sensor.VAD vad = float(sensor.VAD) #print "Battery sens: vis = ", sensor.vis vis = float(sensor.vis) if sensortypus == "pressure": #print "Pressure [hPa]: ", self.mpxa4100(vad,temp) humidity = self.mpxa4100(vad,temp) except: log.err("OW - readBattery: Could not asign value") # Appending data to buffer which contains pcdate, pctime and sensordata # extract time data datearray = self.timeToArray(timestamp) try: datearray.append(int(temp*1000)) if humidity < 0: humidity = 9999 datearray.append(int(humidity*100)) datearray.append(int(vdd*100)) datearray.append(int(vad*100)) datearray.append(vis) data_bin = struct.pack(packcode,*datearray) except: log.msg('OW - readBattery: Error while packing binary data') pass # File Operations self.dataToFile(sensor.id, filename, data_bin, header) try: evt1 = {'id': 3, 'value': outtime} evt9 = {'id': 1, 'value': timestamp} evt2 = {'id': 30, 'value': temp} if humidity < 100: evt3 = {'id': 33, 'value': humidity} else: evt3 = {'id': 33, 'value': 0} evt5 = {'id': 60, 'value': vdd} evt6 = {'id': 61, 'value': vad} evt7 = {'id': 62, 'value': vis} evt8 = {'id': 99, 'value': 'eol'} except: print "OW - readBattery: Problem assigning values to dict" try: self.wsMcuFactory.dispatch(dispatch_url, evt1) self.wsMcuFactory.dispatch(dispatch_url, evt9) self.wsMcuFactory.dispatch(dispatch_url, evt2) self.wsMcuFactory.dispatch(dispatch_url, evt3) self.wsMcuFactory.dispatch(dispatch_url, evt5) self.wsMcuFactory.dispatch(dispatch_url, evt6) self.wsMcuFactory.dispatch(dispatch_url, evt7) self.wsMcuFactory.dispatch(dispatch_url, evt8) pass except: log.err('OW - readBattery: Unable to parse data at %s' % actualtime) except: log.err('OW - readBattery: Lost battery sensor -- reconnecting') global owsensorlist owsensorlist = [] self.owConnected()