def __get_raw_data(self, force_update=False): starttime = int(time.time()) if force_update or starttime - self.__cached_data[ 'last_update'] > terrariumOWFSSensor.__CACHE_TIMEOUT: if self.__port > 0: try: proxy = protocol.proxy(self.__host, self.__port) try: self.__cached_data['temperature'] = float( proxy.read('/{}/temperature'.format( self.__sensor[:-2]))) self.__cached_data['last_update'] = starttime except protocol.OwnetError: pass try: self.__cached_data['humidity'] = float( proxy.read('/{}/humidity'.format( self.__sensor[:-2]))) self.__cached_data['last_update'] = starttime except protocol.OwnetError: pass except Exception as ex: logger.warning( 'OWFS file system is not actve / installed on this device!' )
def main(): assert len(sys.argv) == 2 urlc = urlsplit(sys.argv[1], scheme='owserver', allow_fragments=False) host = urlc.hostname or 'localhost' port = urlc.port or 4304 assert not urlc.path or urlc.path == '/' p = protocol.proxy(host, port, persistent=False) pid = 'unknown' ver = 'unknown' try: pid = int(p.read('/system/process/pid')) ver = p.read('/system/configuration/version').decode() except protocol.OwnetError: pass print(pyownet.__name__, pyownet.__version__, pyownet.__file__) print('proxy_obj: {}'.format(p)) print('server info: pid {}, ver. {}'.format(pid, ver)) freq = 1 << 12 for i in itertools.count(): try: _ = p.dir() except protocol.Error as exc: print('Iteration {0} raised exception: {1}'.format(i, exc)) break None if i % freq else print('Iteration {}'.format(i))
def main(): print(platform.python_implementation(), platform.python_version()) print(platform.system(), platform.release()) print(pyownet.__name__, pyownet.__version__) owp = protocol.proxy(HOST, PORT, flags=protocol.FLG_UNCACHED) print(owp, 'vers.', protocol.bytes2str(owp.read(protocol.PTH_VERSION)) if owp.present(protocol.PTH_VERSION) else 'unknown') signal.signal(signal.SIGALRM, dummy_handler) tic = time.time() signal.setitimer(signal.ITIMER_REAL, A, A) try: count = 0 inter = 0 while count < 10000: count += 1 try: _ = owp.dir() except protocol.Error as exc: (_, val, tb) = sys.exc_info() assert val is exc inter += 1 trs = traceback.extract_tb(tb) print(count, exc, trs[-1][0], trs[-1][1]) time.sleep(random.uniform(0., B)) # can be interrupted except KeyboardInterrupt: print() signal.setitimer(signal.ITIMER_REAL, 0, A) elt = time.time() - tic print('{:d} errors / {:d} calls in {:.1f}s'.format(inter, count, elt))
def main(): assert len(sys.argv) == 2 urlc = urlsplit(sys.argv[1], scheme='owserver', allow_fragments=False) host = urlc.hostname or 'localhost' port = urlc.port or 4304 assert not urlc.path or urlc.path == '/' proxy = protocol.proxy(host, port, verbose=False) pid = -1 ver = '' try: pid = int(proxy.read('/system/process/pid')) ver = proxy.read('/system/configuration/version').decode() except protocol.OwnetError: pass log("{0}, pid={1:d}, {2}".format(proxy, pid, ver)) delta = 60 assert threading.active_count() is 1 started = 0 while threading.active_count() == started + 1: th = threading.Thread(target=worker, args=(proxy, started, ), ) th.start() started += 1 try: sleep(delta) except KeyboardInterrupt: break log('started {0:d} worker threads'.format(started)) log('still waiting for {0:d} worker threads' .format(threading.active_count()-1))
def main(): print(platform.python_implementation(), platform.python_version()) print(platform.system(), platform.release()) print(pyownet.__name__, pyownet.__version__) owp = protocol.proxy(HOST, PORT, flags=protocol.FLG_UNCACHED) print( owp, 'vers.', protocol.bytes2str(owp.read(protocol.PTH_VERSION)) if owp.present(protocol.PTH_VERSION) else 'unknown') signal.signal(signal.SIGALRM, dummy_handler) tic = time.time() signal.setitimer(signal.ITIMER_REAL, A, A) try: count = 0 inter = 0 while count < 10000: count += 1 try: _ = owp.dir() except protocol.Error as exc: (_, val, tb) = sys.exc_info() assert val is exc inter += 1 trs = traceback.extract_tb(tb) print(count, exc, trs[-1][0], trs[-1][1]) time.sleep(random.uniform(0., B)) # can be interrupted except KeyboardInterrupt: print() signal.setitimer(signal.ITIMER_REAL, 0, A) elt = time.time() - tic print('{:d} errors / {:d} calls in {:.1f}s'.format(inter, count, elt))
def load_data(self): data = None if self.__port > 0: data = {} try: proxy = protocol.proxy(self.__host, self.__port) try: data['temperature'] = float( proxy.read('/{}/temperature'.format( self.get_address()))) except protocol.OwnetError: pass try: data['humidity'] = float( proxy.read('/{}/humidity'.format(self.get_address()))) except protocol.OwnetError: pass except Exception as ex: logger.warning( 'OWFS file system is not actve / installed on this device!' ) if data is None: return None return data
def main(): if len(sys.argv) >= 2: args = sys.argv[1:] else: args = ['localhost'] for netloc in args: print('{0:=^33}'.format(netloc)) try: host, port = netloc.split(':', 1) except ValueError: host, port = netloc, 4304 try: proxy = protocol.proxy(host, port) except (protocol.ConnError, protocol.ProtocolError) as err: print(err) continue pid = None ver = None try: pid = int(proxy.read('/system/process/pid')) ver = proxy.read('/system/configuration/version').decode() except protocol.OwnetError: pass print('{0}, pid = {1:d}, ver = {2}'.format(proxy, pid, ver)) print('{0:^17} {1:^7} {2:>7}'.format('id', 'type', 'temp.')) for sensor in proxy.dir(slash=False, bus=False): stype = proxy.read(sensor + '/type').decode() try: temp = float(proxy.read(sensor + '/temperature')) temp = "{0:.2f}".format(temp) except protocol.OwnetError: temp = '' print('{0:<17} {1:<7} {2:>7}'.format(sensor, stype, temp))
def scan_sensors(callback=None): try: proxy = protocol.proxy('localhost', 4304) for sensor in proxy.dir(slash=False, bus=False): stype = proxy.read(sensor + '/type').decode() address = proxy.read(sensor + '/address').decode() try: temp = float(proxy.read(sensor + '/temperature')) yield terrariumOWFSSensor(None, 'temperature', address, callback_indicator=callback) except protocol.OwnetError: pass try: humidity = float(proxy.read(sensor + '/humidity')) yield terrariumOWFSSensor(None, 'humidity', address, callback_indicator=callback) except protocol.OwnetError: pass except Exception as ex: logger.warning( 'OWFS file system is not actve / installed on this device! If this is not correct, try \'i2cdetect -y 1\' to see if device is connected.' )
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 ow server owproxy = ow.proxy(OW_HOST, OW_PORT) while True: # simultaneous temperature conversion owproxy.write("/simultaneous/temperature", "1") # iterate over all sensors for owid, owtopic in SENSORS.items(): logging.debug(("Querying %s : %s") % (owid, owtopic)) try: owtemp = owproxy.read(("/%s/temperature") % (owid)) logging.debug(("Sensor %s : %s") % (owid, owtemp.strip())) MQTTC.publish(owtopic, "{:.1f}".format(float(owtemp.strip()))) except ow.Error: logging.info( "Threw an unknown sensor exception for device %s - %s. Continuing", owid, owname) continue time.sleep(float(POLLINTERVAL) / len(SENSORS))
def __init__(self, owservers=['localhost:4304']): for owserver in owservers: (host, port) = owserver.split(':') owproxy = protocol.proxy(host=host, port=port, persistent=False) timeout = int( owproxy.read('/settings/timeout/volatile', timeout=5).decode('ascii') ) self.owproxy.append(owproxy) if (self.timeout < timeout): self.timeout = timeout
def owbuslist(host='localhost'): from pyownet.protocol import proxy owProxy = proxy() buslist = [] if host == 'localhost': dirs = owProxy.dir() for dir in dirs: buslist.append(str(dir)) return owProxy, buslist
def setUpClass(cls): try: cls.proxy = protocol.proxy( HOST, PORT, persistent=True, ) except protocol.ConnError as exc: raise unittest.SkipTest('no owserver on %s:%s, got:%s' % (HOST, PORT, exc))
def _connect(server): try: if ':' in server: server, port = server.split(':') else: port=4304 log.info("Connecting to %s:%d", server, int(port)) return protocol.proxy(server, int(port)) except Exception as err: log.exception("Failed to retrieve devices from %s:%d: %r", server, int(port), err) raise
def list_sensors(host, port, dir_path): owproxy = protocol.proxy(host=host, port=port) if dir_path is not None: folders = owproxy.dir(dir_path) else: folders = owproxy.dir() for folder in folders: print folder
def main(): assert len(sys.argv) == 2 urlc = urlsplit(sys.argv[1], scheme='owserver', allow_fragments=False) host = urlc.hostname or 'localhost' port = urlc.port or 4304 path = urlc.path or '/' p = proxy(host, port, verbose=True) while True: ret = p.read(path) assert ret, "'%s'" % ret
def test_str(self): # check edge conditions in which _OwnetConnection.__str__ could fail try: p = protocol.proxy(HOST, PORT, persistent=True) except protocol.Error as exc: self.skipTest('no owserver on %s:%s, got:%s' % (HOST, PORT, exc)) p.ping() if p.conn: p.conn.shutdown() str(p.conn) # could fail if not able to determine socket peername else: self.skipTest('unable to create a persistent connection')
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//hostname:port/path') # # parse command line args # args = parser.parse_args() # # parse args.uri and substitute defaults # urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False) assert urlc.fragment == '' if urlc.scheme != 'owserver': parser.error("Invalid URI scheme '{0}:'".format(urlc.scheme)) if urlc.query: parser.error("Invalid URI, query component '?{0}' not allowed" .format(urlc.query)) try: host = urlc.hostname or 'localhost' port = urlc.port or 4304 except ValueError as error: parser.error("Invalid URI: invalid net location '//{0}/'" .format(urlc.netloc)) # # create owserver proxy object # try: owproxy = protocol.proxy(host, port, persistent=True) except protocol.ConnError as error: print("Unable to open connection to '{0}:{1}'\n{2}" .format(host, port, error), file=sys.stderr) sys.exit(1) except protocol.ProtocolError as error: print("Protocol error, '{0}:{1}' not an owserver?\n{2}" .format(host, port, error), file=sys.stderr) sys.exit(1) stress(owproxy, urlc.path)
def sensors(): sensorsdict = {} sensorsdict['/28.B22793050000'] = 'podloga' sensorsdict['/28.858D94050000'] = 'sciana' host, port = "localhost", 4304 proxy = protocol.proxy(host, port) pid = int(proxy.read('/system/process/pid')) ver = proxy.read('/system/configuration/version').decode() for sensor in proxy.dir(slash=False, bus=False): stype = proxy.read(sensor + '/type').decode() if stype == "DS18B20": temp = float(proxy.read(sensor + '/temperature')) temp = "{0:.1f}".format(temp) print(sensorsdict[sensor], sensor, temp)
def temp_connect(self, temp_all): temp_host = temp_all[0] temp_port = temp_all[1] try: self.ow_proxy = protocol.proxy(temp_host, temp_port) except IOError: print("PANIC - cannot connect to sensor's") print('Error class:', sys.exc_info()[0]) print('Error code :', sys.exc_info()[1]) print('host :', temp_host) print('port :', temp_port) sys.exit(2) return ()
def main(): config = get_config() client = InfluxDBClient(config['influxdb']['host'], config['influxdb']['port'], config['influxdb']['user'], config['influxdb']['password'], config['influxdb']['db'] ) while True: for owserver in config['owservers']: try: proxy = protocol.proxy(owserver['owserver_host'], owserver['owserver_port']) except (protocol.ConnError, protocol.ProtocolError) as err: print(err) continue data = [] #for sensor in proxy.dir(slash=False, bus=False): for sensor in owserver['sensors']: stype = proxy.read(sensor['id'] + '/type').decode() try: temp = float(proxy.read(sensor['id'] + '/temperature')) measure = { "measurement": "temperature", "tags": { "region": owserver['region'], "host": owserver['hostname'], "zone": sensor['zone'], "type": stype }, "fields": { "value": temp } } print(measure) temp = "{0:.2f}".format(temp) data.append(measure) except protocol.OwnetError: temp = '' client.write_points(data) time.sleep(300)
def get_readings(self): reading = {} reading['timestamp'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) reading['sensor_id'] = self.sensor_id reading['sensor_name'] = self.sensor_name owproxy = protocol.proxy(host=self.host, port=self.port) # key is one of: 'temperature','humididty','pressure' for key in self.sensors.keys(): try: reading[key] = float(owproxy.read(self.sensors[key]).strip()) except protocol.OwnetError as e: print "Error reading sensor: %s" % (e) return None return reading
def get_RPI_owtemp(host, port): try: owproxy = protocol.proxy(host, port, verbose=DEBUG) except protocol.ConnError as error: print "Error: Unable to open connection to host:port" return null except protocol.ProtocolError as error: print "Protocol error",error return null try: owdir = owproxy.dir(slash=False, bus=False, timeout=TIMEOUT) #print owdir except protocol.OwnetError as error: print "ownet error",error return null except protocol.ProtocolError as error: print "Protocol error getting owdir",error return null sensor_data = {} for sensor in owdir: try: stype = owproxy.read(sensor + '/type', timeout=TIMEOUT).decode() if stype in [ 'DS18S20' , 'DS18B20' ]: data = owproxy.read(sensor+'/temperature', timeout=TIMEOUT) #print "read: %s %.1f" % ( sensor[1:], float(data) ) sensor_data[ sensor[1:] ] = float(data) except protocol.OwnetError as error: print "ownet error",error next except protocol.ProtocolError as error: print "Protocol error",error next return sensor_data
def main(): assert len(sys.argv) == 2 urlc = urlsplit(sys.argv[1], scheme='owserver', allow_fragments=False) host = urlc.hostname or 'localhost' port = urlc.port or 4304 assert not urlc.path or urlc.path == '/' proxy = protocol.proxy(host, port, verbose=False) pid = ver = '' try: pid = int(proxy.read('/system/process/pid')) ver = proxy.read('/system/configuration/version').decode() except protocol.OwnetError: pass log("{0}, pid={1:d}, {2}".format(proxy, pid, ver)) delta = 1 for i in range(MTHR): th = threading.Thread(target=worker, args=(proxy, i, ), ) th.start() time.sleep(1.03*delta) delta *= 2
def main(): assert len(sys.argv) == 2 urlc = urlsplit(sys.argv[1], scheme='owserver', allow_fragments=False) host = urlc.hostname or 'localhost' port = urlc.port or 4304 assert not urlc.path or urlc.path == '/' proxy = protocol.proxy(host, port, verbose=False) pid = -1 ver = '' try: pid = int(proxy.read('/system/process/pid')) ver = proxy.read('/system/configuration/version').decode() except protocol.OwnetError: pass log("{0}, pid={1:d}, {2}".format(proxy, pid, ver)) delta = 60 assert threading.active_count() is 1 started = 0 while threading.active_count() == started + 1: th = threading.Thread( target=worker, args=( proxy, started, ), ) th.start() started += 1 try: sleep(delta) except KeyboardInterrupt: break log('started {0:d} worker threads'.format(started)) log('still waiting for {0:d} worker threads'.format( threading.active_count() - 1))
def _scan_sensors(unit_value_callback=None, trigger_callback=None): try: proxy = protocol.proxy(terrariumOWFSSensor.__HOST, terrariumOWFSSensor.__PORT) for sensor in proxy.dir(slash=False, bus=False): stype = proxy.read(sensor + '/type').decode() address = proxy.read(sensor + '/address').decode() try: temp = float(proxy.read(sensor + '/temperature')) yield terrariumSensor( None, terrariumOWFSSensor.HARDWARE, 'temperature', address, f'{terrariumOWFSSensor.NAME} measuring temperature', unit_value_callback=unit_value_callback, trigger_callback=trigger_callback) except protocol.OwnetError as ex: pass try: humidity = float(proxy.read(sensor + '/humidity')) yield terrariumSensor( None, terrariumOWFSSensor.HARDWARE, 'humidity', address, f'{terrariumOWFSSensor.NAME} measuring humidity', unit_value_callback=unit_value_callback, trigger_callback=trigger_callback) except protocol.OwnetError: pass except Exception as ex: pass
def _load_hardware(self): # For now, we use/depend on the OWFS defaults device = protocol.proxy(self.__HOST, self.__PORT) return device
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//server:port/entity') # optional args for temperature scale parser.set_defaults(t_flags=protocol.FLG_TEMP_C) tempg = parser.add_mutually_exclusive_group() tempg.add_argument('-C', '--Celsius', const=protocol.FLG_TEMP_C, help='Celsius(default) temperature scale', dest='t_flags', action='store_const', ) tempg.add_argument('-F', '--Fahrenheit', const=protocol.FLG_TEMP_F, help='Fahrenheit temperature scale', dest='t_flags', action='store_const', ) tempg.add_argument('-K', '--Kelvin', const=protocol.FLG_TEMP_K, help='Kelvin temperature scale', dest='t_flags', action='store_const', ) tempg.add_argument('-R', '--Rankine', const=protocol.FLG_TEMP_R, help='Rankine temperature scale', dest='t_flags', action='store_const', ) # optional arg for address format fcodes = collections.OrderedDict(( ('f.i', protocol.FLG_FORMAT_FDI), ('fi', protocol.FLG_FORMAT_FI), ('f.i.c', protocol.FLG_FORMAT_FDIDC), ('f.ic', protocol.FLG_FORMAT_FDIC), ('fi.c', protocol.FLG_FORMAT_FIDC), ('fic', protocol.FLG_FORMAT_FIC), )) parser.set_defaults(format='f.i') parser.add_argument('-f', '--format', choices=fcodes, help='format for 1-wire unique serial IDs display') parser.add_argument('--nosys', '--only-sensors', action='store_false', dest='bus', help='do not descend system directories') # # parse command line args # args = parser.parse_args() # # parse args.uri and substitute defaults # urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False) if urlc.scheme != 'owserver': parser.error("Invalid URI scheme '{}:'".format(urlc.scheme)) assert not urlc.fragment if urlc.query: parser.error( "Invalid URI '{}', no query component allowed".format(args.uri)) host = urlc.hostname or 'localhost' port = urlc.port or 4304 # # create owserver proxy object # try: proxy = protocol.proxy( host, port, flags=args.t_flags | fcodes[args.format], persistent=True) except (protocol.ConnError, protocol.ProtocolError) as error: parser.exit(status=1, message=str(error)+'\n') def walk(path): try: if not path.endswith('/'): val = proxy.read(path) print("{:40} {!r}".format(path, val)) else: for entity in proxy.dir(path, bus=args.bus): walk(entity) except protocol.OwnetError as error: print('Unable to walk {}: server says {}'.format(path, error), file=sys.stderr) except protocol.ConnError as error: print('Unable to walk {}: {}'.format(path, error), file=sys.stderr) with proxy: walk(urlc.path)
def setUpClass(cls): try: cls.proxy = protocol.proxy(HOST, PORT, persistent=True, ) except protocol.ConnError as exc: raise unittest.SkipTest('no owserver on %s:%s, got:%s' % (HOST, PORT, exc))
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//hostname:port/path') # optional args for temperature scale parser.set_defaults(t_flags=protocol.FLG_TEMP_C) tempg = parser.add_mutually_exclusive_group() tempg.add_argument( '-C', '--Celsius', const=protocol.FLG_TEMP_C, help='Celsius(default) temperature scale', dest='t_flags', action='store_const', ) tempg.add_argument( '-F', '--Fahrenheit', const=protocol.FLG_TEMP_F, help='Fahrenheit temperature scale', dest='t_flags', action='store_const', ) tempg.add_argument( '-K', '--Kelvin', const=protocol.FLG_TEMP_K, help='Kelvin temperature scale', dest='t_flags', action='store_const', ) tempg.add_argument( '-R', '--Rankine', const=protocol.FLG_TEMP_R, help='Rankine temperature scale', dest='t_flags', action='store_const', ) # optional arg for address format fcodes = collections.OrderedDict(( ('f.i', protocol.FLG_FORMAT_FDI), ('fi', protocol.FLG_FORMAT_FI), ('f.i.c', protocol.FLG_FORMAT_FDIDC), ('f.ic', protocol.FLG_FORMAT_FDIC), ('fi.c', protocol.FLG_FORMAT_FIDC), ('fic', protocol.FLG_FORMAT_FIC), )) parser.set_defaults(format='f.i') parser.add_argument('-f', '--format', choices=fcodes, help='format for 1-wire unique serial IDs display') # optional arg for output format tempg = parser.add_mutually_exclusive_group() tempg.add_argument('--hex', action='store_true', help='write data in hex format') tempg.add_argument('-b', '--binary', action='store_true', help='output binary data') # # parse command line args # args = parser.parse_args() # # parse args.uri and substitute defaults # urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False) assert urlc.fragment == '' if urlc.scheme != 'owserver': parser.error("Invalid URI scheme '{0}:'".format(urlc.scheme)) if urlc.query: parser.error("Invalid URI, query component '?{0}' not allowed".format( urlc.query)) try: host = urlc.hostname or 'localhost' port = urlc.port or 4304 except ValueError as error: parser.error("Invalid URI: invalid net location '//{0}/'".format( urlc.netloc)) # # create owserver proxy object # try: owproxy = protocol.proxy( host, port, flags=args.t_flags | fcodes[args.format], ) except protocol.ConnError as error: print("Unable to open connection to '{0}:{1}'\n{2}".format( host, port, error), file=sys.stderr) sys.exit(1) except protocol.ProtocolError as error: print("Protocol error, '{0}:{1}' not an owserver?\n{2}".format( host, port, error), file=sys.stderr) sys.exit(1) try: if urlc.path.endswith('/'): for path in owproxy.dir(urlc.path, bus=True): print(path) else: data = owproxy.read(urlc.path) if args.binary: if sys.version_info < (3, ): sys.stdout.write(data) else: sys.stdout.buffer.write(data) else: if args.hex: data = hexlify(data) print(data.decode('ascii', errors='backslashreplace')) except protocol.OwnetError as error: print("Ownet error\n{2}".format(host, port, error), file=sys.stderr) sys.exit(1) except protocol.ProtocolError as error: print("Protocol error, '{0}:{1}' buggy?\n{2}".format( host, port, error), file=sys.stderr) sys.exit(1)
def main(): def report(name, res): scale = 1e3 # report times in ms print(' * {:17}'.format(name), end=':') for t in (sorted(res)): print(' {:6.3f} ms'.format(t / number * scale), end=',') print() parser = argparse.ArgumentParser() parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//server:port/entity') parser.add_argument('-n', '--number', type=int, default=20, metavar='N', help='number of executions (default: %(default)s)') parser.add_argument('-r', '--repeat', type=int, default=5, metavar='R', help='repeat count (default: %(default)s)') args = parser.parse_args() urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False) if urlc.scheme != 'owserver': parser.error("Invalid URI scheme '{}:'".format(urlc.scheme)) assert not urlc.fragment if urlc.query: parser.error( "Invalid URI '{}', no query component allowed".format(args.uri)) host = urlc.hostname or 'localhost' port = urlc.port or 4304 path = urlc.path or '/' try: base = protocol.proxy(host, port, persistent=False) except protocol.ConnError as exc: sys.exit('Error connecting to {}:{} {}'.format(host, port, exc)) pid = 'unknown' ver = 'unknown' try: pid = int(base.read(protocol.PTH_PID)) ver = base.read(protocol.PTH_VERSION).decode() except protocol.OwnetError: pass number = args.number repeat = args.repeat print('python : {} {} on {}'.format(platform.python_implementation(), platform.python_version(), platform.platform(terse=True),)) print('{:8s}: {}'.format(pyownet.__name__, pyownet.__version__)) print('owproxy : {}'.format(base)) print('owserver: pid {}, ver. {}'.format(pid, ver)) print('url : {}'.format(urlunsplit(urlc), )) print('samples : {} * {} repetitions'.format(number, repeat)) print() global data, owproxy, hargs data = (b'\x00\x00\x00\x00\x00\x000:\xff\xff\xff\xfe\x00\x00\x00\x00\x00' b'\x00\x04\xd2\x00\x00\x00\xea') hargs = {'payload': 745, 'type': protocol.MSG_READ, 'flags': protocol.FLG_UNCACHED | protocol.FLG_TEMP_C, 'size': 234, 'offset': 52} print('{} core objects'.format(pyownet.__name__)) setup = """ from pyownet.protocol import _FromServerHeader, _ToServerHeader, proxy from __main__ import data, hargs """ stmt = "_FromServerHeader(data)" timer = timeit.Timer(stmt=stmt, setup=setup) res = timer.repeat(number=number, repeat=repeat) report('_FromServerHeader', res) stmt = "_ToServerHeader(**hargs)" timer = timeit.Timer(stmt=stmt, setup=setup) res = timer.repeat(number=number, repeat=repeat) report('_ToServerHeader', res) stmt = "proxy(host='{}', port={})".format(host, port) timer = timeit.Timer(stmt=stmt, setup=setup) res = timer.repeat(number=number, repeat=repeat) report('proxy()', res) setup = "from __main__ import owproxy" stmt = "owproxy.ping()" print(stmt) owproxy = protocol.clone(base, persistent=False) timer = timeit.Timer(stmt=stmt, setup=setup) res = timer.repeat(number=number, repeat=repeat) report('non persistent', res) owproxy = protocol.clone(base, persistent=True) res = timer.repeat(number=number, repeat=repeat) report('persistent', res) setup = "from __main__ import owproxy" if path.endswith('/'): stmt = 'owproxy.dir("{}")'.format(path) else: stmt = 'owproxy.read("{}")'.format(path) owproxy = base assert 'owproxy' in globals() try: eval(stmt, globals(), ) except protocol.OwnetError as err: print(err) sys.exit(1) print(stmt) owproxy = protocol.clone(base, persistent=False) timer = timeit.Timer(stmt=stmt, setup=setup) res = timer.repeat(number=number, repeat=repeat) report('non persistent', res) owproxy = protocol.clone(base, persistent=True) res = timer.repeat(number=number, repeat=repeat) report('persistent', res)
def get_entities(config): """Get a list of entities.""" base_dir = config[CONF_MOUNT_DIR] owhost = config.get(CONF_HOST) owport = config[CONF_PORT] # Ensure type is configured if owhost: conf_type = CONF_TYPE_OWSERVER elif base_dir == DEFAULT_SYSBUS_MOUNT_DIR: conf_type = CONF_TYPE_SYSBUS else: conf_type = CONF_TYPE_OWFS entities = [] device_names = {} if CONF_NAMES in config: if isinstance(config[CONF_NAMES], dict): device_names = config[CONF_NAMES] # We have an owserver on a remote(or local) host/port if conf_type == CONF_TYPE_OWSERVER: _LOGGER.debug("Initializing using %s:%s", owhost, owport) try: owproxy = protocol.proxy(host=owhost, port=owport) devices = owproxy.dir() except protocol.Error as exc: _LOGGER.error("Cannot connect to owserver on %s:%d, got: %s", owhost, owport, exc) devices = [] for device in devices: _LOGGER.debug("Found device: %s", device) family = owproxy.read(f"{device}family").decode() dev_type = "std" if "EF" in family: dev_type = "HobbyBoard" family = owproxy.read(f"{device}type").decode() if family not in hb_info_from_type(dev_type): _LOGGER.warning( "Ignoring unknown family (%s) of sensor found for device: %s", family, device, ) continue for sensor_key, sensor_value in hb_info_from_type( dev_type)[family].items(): if "moisture" in sensor_key: s_id = sensor_key.split("_")[1] is_leaf = int( owproxy.read( f"{device}moisture/is_leaf.{s_id}").decode()) if is_leaf: sensor_key = f"wetness_{s_id}" sensor_id = os.path.split(os.path.split(device)[0])[1] device_file = os.path.join( os.path.split(device)[0], sensor_value) entities.append( OneWireProxy( device_names.get(sensor_id, sensor_id), device_file, sensor_key, owproxy, )) # We have a raw GPIO ow sensor on a Pi elif conf_type == CONF_TYPE_SYSBUS: _LOGGER.debug("Initializing using SysBus") for p1sensor in Pi1Wire().find_all_sensors(): family = p1sensor.mac_address[:2] sensor_id = f"{family}-{p1sensor.mac_address[2:]}" if family not in DEVICE_SUPPORT_SYSBUS: _LOGGER.warning( "Ignoring unknown family (%s) of sensor found for device: %s", family, sensor_id, ) continue device_file = f"/sys/bus/w1/devices/{sensor_id}/w1_slave" entities.append( OneWireDirect( device_names.get(sensor_id, sensor_id), device_file, "temperature", p1sensor, )) if not entities: _LOGGER.error( "No onewire sensor found. Check if dtoverlay=w1-gpio " "is in your /boot/config.txt. " "Check the mount_dir parameter if it's defined") # We have an owfs mounted else: _LOGGER.debug("Initializing using OWFS %s", base_dir) for family_file_path in glob(os.path.join(base_dir, "*", "family")): with open(family_file_path) as family_file: family = family_file.read() if "EF" in family: continue if family in DEVICE_SENSORS: for sensor_key, sensor_value in DEVICE_SENSORS[family].items(): sensor_id = os.path.split( os.path.split(family_file_path)[0])[1] device_file = os.path.join( os.path.split(family_file_path)[0], sensor_value) entities.append( OneWireOWFS( device_names.get(sensor_id, sensor_id), device_file, sensor_key, )) return entities
my_logger.addHandler(handler) count = 2 while count > 1: count = 0 for p in psutil.process_iter(["name"]): if "oneWireBus" in p.name(): count += 1 if count > 2: my_logger.critical( "dziala wiecej niz dwa procesy odczytu temperatury") panic() time.sleep(5) try: owproxy = protocol.proxy(host="127.0.0.1", port=4304) for sensor in sensors: if owproxy.present(sensor[0]): if sensor[1] == 'lazienka_gora' or sensor[1] == 'lazienka_dol': value = (owproxy.read('%stemperature' % sensor[0]).decode('utf-8').strip()) humidity = (owproxy.read( '%shumidity' % sensor[0]).decode('utf-8').strip()) time.sleep(1) sock.sendto(bytes(value, 'utf-8'), (UDP_IP, sensor[2])) time.sleep(1) sock.sendto(bytes(humidity, 'utf-8'), (UDP_IP, sensor[3])) else: value = (owproxy.read('%stemperature10' % sensor[0]).decode('utf-8').strip()) time.sleep(1)
def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument("uri", metavar="URI", nargs="?", default="/", help="[owserver:]//hostname:port/path") # optional args for temperature scale parser.set_defaults(t_flags=protocol.FLG_TEMP_C) tempg = parser.add_mutually_exclusive_group() tempg.add_argument( "-C", "--Celsius", const=protocol.FLG_TEMP_C, help="Celsius(default) temperature scale", dest="t_flags", action="store_const", ) tempg.add_argument( "-F", "--Fahrenheit", const=protocol.FLG_TEMP_F, help="Fahrenheit temperature scale", dest="t_flags", action="store_const", ) tempg.add_argument( "-K", "--Kelvin", const=protocol.FLG_TEMP_K, help="Kelvin temperature scale", dest="t_flags", action="store_const", ) tempg.add_argument( "-R", "--Rankine", const=protocol.FLG_TEMP_R, help="Rankine temperature scale", dest="t_flags", action="store_const", ) # optional arg for address format fcodes = collections.OrderedDict( ( ("f.i", protocol.FLG_FORMAT_FDI), ("fi", protocol.FLG_FORMAT_FI), ("f.i.c", protocol.FLG_FORMAT_FDIDC), ("f.ic", protocol.FLG_FORMAT_FDIC), ("fi.c", protocol.FLG_FORMAT_FIDC), ("fic", protocol.FLG_FORMAT_FIC), ) ) parser.set_defaults(format="f.i") parser.add_argument("-f", "--format", choices=fcodes, help="format for 1-wire unique serial IDs display") # optional arg for output format tempg = parser.add_mutually_exclusive_group() tempg.add_argument("--hex", action="store_true", help="write data in hex format") tempg.add_argument("-b", "--binary", action="store_true", help="output binary data") # # parse command line args # args = parser.parse_args() # # parse args.uri and substitute defaults # urlc = urlsplit(args.uri, scheme="owserver", allow_fragments=False) assert urlc.fragment == "" if urlc.scheme != "owserver": parser.error("Invalid URI scheme '{0}:'".format(urlc.scheme)) if urlc.query: parser.error("Invalid URI, query component '?{0}' not allowed".format(urlc.query)) try: host = urlc.hostname or "localhost" port = urlc.port or 4304 except ValueError as error: parser.error("Invalid URI: invalid net location '//{0}/'".format(urlc.netloc)) # # create owserver proxy object # try: owproxy = protocol.proxy(host, port, flags=args.t_flags | fcodes[args.format]) except protocol.ConnError as error: print("Unable to open connection to '{0}:{1}'\n{2}".format(host, port, error), file=sys.stderr) sys.exit(1) except protocol.ProtocolError as error: print("Protocol error, '{0}:{1}' not an owserver?\n{2}".format(host, port, error), file=sys.stderr) sys.exit(1) try: if urlc.path.endswith("/"): for path in owproxy.dir(urlc.path, bus=True): print(path) else: data = owproxy.read(urlc.path) if args.binary: if sys.version_info < (3,): sys.stdout.write(data) else: sys.stdout.buffer.write(data) else: if args.hex: data = hexlify(data) print(data.decode("ascii", errors="backslashreplace")) except protocol.OwnetError as error: print("Ownet error\n{2}".format(host, port, error), file=sys.stderr) sys.exit(1) except protocol.ProtocolError as error: print("Protocol error, '{0}:{1}' buggy?\n{2}".format(host, port, error), file=sys.stderr) sys.exit(1)
def main(): def report(name, res): scale = 1e3 # report times in ms print('** {:15}'.format(name), end=':') for t in (sorted(res)): print(' {:6.3f} ms'.format(t / number * scale), end=',') print() parser = argparse.ArgumentParser() parser.add_argument('uri', metavar='URI', nargs='?', default='/', help='[owserver:]//server:port/entity') parser.add_argument('-n', '--number', type=int, default=20, metavar='N', help='number of executions (default: %(default)s)') parser.add_argument('-r', '--repeat', type=int, default=5, metavar='R', help='repeat count (default: %(default)s)') args = parser.parse_args() urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False) if urlc.scheme != 'owserver': parser.error("Invalid URI scheme '{}:'".format(urlc.scheme)) assert not urlc.fragment if urlc.query: parser.error( "Invalid URI '{}', no query component allowed".format(args.uri)) host = urlc.hostname or 'localhost' port = urlc.port or 4304 path = urlc.path or '/' print(pyownet.__name__, pyownet.__version__, pyownet.__file__) try: base = protocol.proxy(host, port, persistent=False) except protocol.ConnError as exc: sys.exit('Error connecting to {}:{} {}'.format(host, port, exc)) pid = 'unknown' ver = 'unknown' try: pid = int(base.read('/system/process/pid')) ver = base.read('/system/configuration/version').decode() except protocol.OwnetError: pass print('proxy_obj: {}'.format(base)) print('server info: pid {}, ver. {}'.format(pid, ver)) print() number = args.number repeat = args.repeat setup = "from __main__ import proxy_obj" if path.endswith('/'): stmt = 'proxy_obj.dir("{}")'.format(path) else: stmt = 'proxy_obj.read("{}")'.format(path) print('timeit:\n statement: {}\n number: {}\n repetitions: {}'.format( stmt, number, repeat)) print() global proxy_obj proxy_obj = base assert 'proxy_obj' in globals() try: eval(stmt, globals(), ) except protocol.OwnetError as err: print(err) sys.exit(1) timer = timeit.Timer(stmt=stmt, setup=setup) proxy_obj = protocol.clone(base, persistent=False) res = timer.repeat(number=number, repeat=repeat) report('non persistent', res) proxy_obj = protocol.clone(base, persistent=True) res = timer.repeat(number=number, repeat=repeat) report('persistent', res)
def get_entities(config): """Get a list of entities.""" base_dir = config[CONF_MOUNT_DIR] owhost = config.get(CONF_HOST) owport = config[CONF_PORT] # Ensure type is configured if owhost: conf_type = CONF_TYPE_OWSERVER elif base_dir == DEFAULT_SYSBUS_MOUNT_DIR: conf_type = CONF_TYPE_SYSBUS else: # pragma: no cover # This part of the implementation does not conform to policy regarding 3rd-party libraries, and will not longer be updated. # https://developers.home-assistant.io/docs/creating_platform_code_review/#5-communication-with-devicesservices conf_type = CONF_TYPE_OWFS entities = [] device_names = {} if CONF_NAMES in config: if isinstance(config[CONF_NAMES], dict): device_names = config[CONF_NAMES] # We have an owserver on a remote(or local) host/port if conf_type == CONF_TYPE_OWSERVER: _LOGGER.debug("Initializing using %s:%s", owhost, owport) try: owproxy = protocol.proxy(host=owhost, port=owport) devices = owproxy.dir() except protocol.Error as exc: _LOGGER.error("Cannot connect to owserver on %s:%d, got: %s", owhost, owport, exc) devices = [] for device in devices: _LOGGER.debug("Found device: %s", device) family = owproxy.read(f"{device}family").decode() dev_type = "std" if "EF" in family: dev_type = "HobbyBoard" family = owproxy.read(f"{device}type").decode() if family not in hb_info_from_type(dev_type): _LOGGER.warning( "Ignoring unknown family (%s) of sensor found for device: %s", family, device, ) continue for sensor_key, sensor_value in hb_info_from_type( dev_type)[family].items(): if "moisture" in sensor_key: s_id = sensor_key.split("_")[1] is_leaf = int( owproxy.read( f"{device}moisture/is_leaf.{s_id}").decode()) if is_leaf: sensor_key = f"wetness_{s_id}" sensor_id = os.path.split(os.path.split(device)[0])[1] device_file = os.path.join( os.path.split(device)[0], sensor_value) entities.append( OneWireProxy( device_names.get(sensor_id, sensor_id), device_file, sensor_key, owproxy, )) # We have a raw GPIO ow sensor on a Pi elif conf_type == CONF_TYPE_SYSBUS: _LOGGER.debug("Initializing using SysBus") for p1sensor in Pi1Wire().find_all_sensors(): family = p1sensor.mac_address[:2] sensor_id = f"{family}-{p1sensor.mac_address[2:]}" if family not in DEVICE_SUPPORT_SYSBUS: _LOGGER.warning( "Ignoring unknown family (%s) of sensor found for device: %s", family, sensor_id, ) continue device_file = f"/sys/bus/w1/devices/{sensor_id}/w1_slave" entities.append( OneWireDirect( device_names.get(sensor_id, sensor_id), device_file, "temperature", p1sensor, )) if not entities: _LOGGER.error( "No onewire sensor found. Check if dtoverlay=w1-gpio " "is in your /boot/config.txt. " "Check the mount_dir parameter if it's defined") # We have an owfs mounted else: # pragma: no cover # This part of the implementation does not conform to policy regarding 3rd-party libraries, and will not longer be updated. # https://developers.home-assistant.io/docs/creating_platform_code_review/#5-communication-with-devicesservices _LOGGER.debug("Initializing using OWFS %s", base_dir) _LOGGER.warning( "The OWFS implementation of 1-Wire sensors is deprecated, " "and should be migrated to OWServer (on localhost:4304). " "If migration to OWServer is not feasible on your installation, " "please raise an issue at https://github.com/home-assistant/core/issues/new" "?title=Unable%20to%20migrate%20onewire%20from%20OWFS%20to%20OWServer", ) for family_file_path in glob(os.path.join(base_dir, "*", "family")): with open(family_file_path) as family_file: family = family_file.read() if "EF" in family: continue if family in DEVICE_SENSORS: for sensor_key, sensor_value in DEVICE_SENSORS[family].items(): sensor_id = os.path.split( os.path.split(family_file_path)[0])[1] device_file = os.path.join( os.path.split(family_file_path)[0], sensor_value) entities.append( OneWireOWFS( device_names.get(sensor_id, sensor_id), device_file, sensor_key, )) return entities
logger.addHandler(fh) logger.info( '## Starting 1Wire-Server ####################################################################' ) while True: # read device list with open(path_to_devices + 'devices.json') as json_file: devicelist = json.load(json_file) # outputlist as dict outputlist = {} # connect to owfs owproxy = protocol.proxy(host='192.168.0.17', port=4304) # Enable simultaneous temperature conversation owproxy.write("/simultaneous/temperature", b'1') #ow._put("simultaneous/voltage","1") # read in connected sensor try: sensorlist = owproxy.dir(path='/', slash=False, timeout=0) # loop through sensors and read values for sensor in sensorlist: try: sensorvalues = {} # print('Sensor: ' + sensor) # print('ID: ' + sensor.id)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the one wire Sensors.""" base_dir = config[CONF_MOUNT_DIR] owport = config[CONF_PORT] owhost = config.get(CONF_HOST) if owhost: _LOGGER.debug("Initializing using %s:%s", owhost, owport) else: _LOGGER.debug("Initializing using %s", base_dir) devs = [] device_names = {} if CONF_NAMES in config: if isinstance(config[CONF_NAMES], dict): device_names = config[CONF_NAMES] # We have an owserver on a remote(or local) host/port if owhost: try: owproxy = protocol.proxy(host=owhost, port=owport) devices = owproxy.dir() except protocol.Error as exc: _LOGGER.error("Cannot connect to owserver on %s:%d, got: %s", owhost, owport, exc) devices = [] for device in devices: _LOGGER.debug("Found device: %s", device) family = owproxy.read(f"{device}family").decode() dev_type = "std" if "EF" in family: dev_type = "HobbyBoard" family = owproxy.read(f"{device}type").decode() if family not in hb_info_from_type(dev_type): _LOGGER.warning( "Ignoring unknown family (%s) of sensor found for device: %s", family, device, ) continue for sensor_key, sensor_value in hb_info_from_type( dev_type)[family].items(): if "moisture" in sensor_key: s_id = sensor_key.split("_")[1] is_leaf = int( owproxy.read( f"{device}moisture/is_leaf.{s_id}").decode()) if is_leaf: sensor_key = f"wetness_{id}" sensor_id = os.path.split(os.path.split(device)[0])[1] device_file = os.path.join( os.path.split(device)[0], sensor_value) devs.append( OneWireProxy( device_names.get(sensor_id, sensor_id), device_file, sensor_key, owproxy, )) # We have a raw GPIO ow sensor on a Pi elif base_dir == DEFAULT_MOUNT_DIR: for device_family in DEVICE_SENSORS: for device_folder in glob( os.path.join(base_dir, f"{device_family}[.-]*")): sensor_id = os.path.split(device_folder)[1] device_file = os.path.join(device_folder, "w1_slave") devs.append( OneWireDirect( device_names.get(sensor_id, sensor_id), device_file, "temperature", )) # We have an owfs mounted else: for family_file_path in glob(os.path.join(base_dir, "*", "family")): with open(family_file_path) as family_file: family = family_file.read() if "EF" in family: continue if family in DEVICE_SENSORS: for sensor_key, sensor_value in DEVICE_SENSORS[family].items(): sensor_id = os.path.split( os.path.split(family_file_path)[0])[1] device_file = os.path.join( os.path.split(family_file_path)[0], sensor_value) devs.append( OneWireOWFS( device_names.get(sensor_id, sensor_id), device_file, sensor_key, )) if devs == []: _LOGGER.error("No onewire sensor found. Check if dtoverlay=w1-gpio " "is in your /boot/config.txt. " "Check the mount_dir parameter if it's defined") return add_entities(devs, True)
# logs temperature from OWFS into postgres database # (c) Tomasz Torcz, ISC License import os import psycopg2 import systemd.daemon import time from timeit import default_timer from pyownet.protocol import proxy sleep_seconds = int(os.getenv("WATCHDOG_USEC")) / (2 * (10**6)) + 1 systemd.daemon.notify("STATUS=Opening owserver & DB connection...") try: owproxy = proxy() except Exception as err: print("Error connecting to owserver, sorry: {0}".format(err)) exit(1) try: dbconn = psycopg2.connect("dbname=house_metrics") except Exception as err: print("Error connecting to DB, sorry: {0}".format(err)) exit(2) cur = dbconn.cursor() cur.execute( "PREPARE put_temperature AS INSERT INTO temperatures (datetime, sensor_id, value) VALUES (NOW(), (SELECT id FROM sensors WHERE SN=$1), $2);" )