def testEqual(self): s1 = ow.Sensor('/') s2 = ow.Sensor('/') s3 = ow.Sensor(self.config.get('Root', 'sensors').split(' ')[0]) self.failUnlessEqual(s1, s2) self.failIfEqual(s1, s3) self.failIfEqual(s2, s3)
def ReadTemperatures(command, result): # Build a dictonary so that for each sensor id we keep the 1 wire address, the interval required, the time to the next read. # Setting the interval to -ve stops reading for that sensor, setting the interval to zero sets the reading to the maximum rate. deviceId = {} for sensor in GD.SYSTEM_TEMPERATURE_GROUP: deviceId[sensor] = [system.systemControl[sensor].GetAddress(), -1, -1] while 1: # Set the tick timer to 1 second. If we do a 1 wire read we will change this to 0.25 to allow for the 0.75 seconds it takes # to do a 1 wire read!! tickTime = 1 # Every tick time we will scan through every sensor id. for sensor in deviceId: # If we have received a command; load the data. A command is a 2 element tuple. 1st element [0] is the sensor id # 2nd element [1] is the time interval. We will set the time to next read to 1 so that it will be read now. if not command.empty(): commandData = command.get() deviceId[commandData[0]][1] = commandData[1] deviceId[commandData[0]][2] = 1 # Get the address, interval and time to next read for this sensor. address, interval, timeToRead = deviceId[sensor] # Is this sensor active? if interval >= 0: # Build the address string for this senor. address = '/uncached/28.' + address # Initialise temperature to a null string so we can check later if we have read a temperature. sensorTemperature = '' # If interval is zero it is maximum rate so read the sensor. if interval == 0: sensorTemperature = ow.Sensor(address).temperature # Adjust the tick time to try and allow for the 0.75 second delay that occurs doing a 1 wire read. tickTime = 0.25 # If the time to read is not at end decrement it. elif timeToRead > 1: deviceId[sensor][2] -= 1 # The time to read is at the end (1) reload it with the interval and read the sensor. else: deviceId[sensor][2] = interval sensorTemperature = ow.Sensor(address).temperature # Adjust the tick time to try and allow for the 0.75 second delay that occurs doing a 1 wire read. tickTime = 0.25 # If we have we got a temperature and space in the queue for this result send it. If for some reason # there is not space in the queue then this result is going to be discarded. This does not matter as # we will read the temperature again at the next interval time. if sensorTemperature and not result.full(): result.put((sensor, int(float(sensorTemperature)))) # Wait for our tick time time.sleep(tickTime)
def owRead(): global Alive global paging global screen ow.init("/dev/i2c-1") owDevices = ow.Sensor("/") try: while Alive: time.sleep(15) for sensor in c.AllSensors.elements: currSensor = c.AllSensors.elements[sensor] if (currSensor.fields['channel'].translate(None, '. ') == "wire"): try: aDevice = ow.Sensor('/'+currSensor.fields['sensor']) if aDevice: owtemperature = aDevice.__getattr__(currSensor.fields['subsensor']) if owtemperature: if currSensor.fields['formula']: value = float(owtemperature) owtemperature = str(eval(currSensor.fields['formula'])) print (u"Sensor 1Wire-" + currSensor.fields['sensor']+u": " + currSensor.fields['acronym'] + " = " + owtemperature) storeSensor(currSensor,owtemperature) StepValuesUpdate(currSensor, owtemperature) except: traceback.print_exc() except: traceback.print_exc() Alive = False return
def calc_power(): p = tmpclass() pealevool = value = float(ow.Sensor('/28FF461F10140002').temperature11) tagasivool = value = float(ow.Sensor('/28FF981E10140071').temperature11) delta = abs(pealevool - tagasivool) power = delta * 4.2 * 1.1 p.value = "%0.2f" % power p.address = "Power" return p
def testEntryList( self ): for id in self.config.get( 'Root', 'sensors' ).split( ' ' ): c = ow.Sensor( '/' + id ) u = ow.Sensor( '/uncached/' + id ) ce = [ entry for entry in c.entries( ) ] self.failUnlessEqual( ce, c.entryList( ) ) ue = [ entry for entry in u.entries( ) ] self.failUnlessEqual( ue, u.entryList( ) ) self.failUnlessEqual( ce, ue )
def testSensorList( self ): for id in self.config.get( 'Root', 'sensors' ).split( ' ' ): c = ow.Sensor( '/' + id ) u = ow.Sensor( '/uncached/' + id ) cs = [ sensor for sensor in c.sensors( ) ] self.failUnlessEqual( cs, c.sensorList( ) ) us = [ sensor for sensor in u.sensors( ) ] self.failUnlessEqual( us, u.sensorList( ) ) self.failUnlessEqual( cs, us )
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 testCacheUncached( self ): for id in self.config.get( 'Root', 'sensors' ).split( ' ' ): c = ow.Sensor( '/' + id ) u = ow.Sensor( '/uncached/' + id ) self.failUnlessEqual( c._path, u._path ) ce = [ entry for entry in c.entries( ) ] ue = [ entry for entry in u.entries( ) ] self.failUnlessEqual( ce, ue ) cs = [ sensor for sensor in c.sensors( ) ] us = [ sensor for sensor in u.sensors( ) ] self.failUnlessEqual( cs, us )
def _initOW(self): ''' Initiate 1-Wire server (owServer). ''' # Logger localLog = logging.getLogger(self.logPath + "._initOW") localLog.debug("Initiating owServer...") # Init owServer at localhost ow.init('localhost:4304') ow.Sensor('/').useCache(False) localLog.debug("owServer initiated successfully!") self.deviceList = ow.Sensor('/').sensorList() localLog.debug("Device list updated from owServer.")
def __init__(self, log, dev='u', cache=False): """ Create OneWire instance, allowing to use OneWire Network @param dev : device where the interface is connected to, default 'u' for USB """ self.log = log self._sensors = [] self.log.info(u"==> OWFS version : %s" % ow.__version__) try: ow.init(dev) self._cache = cache if cache: self._root = "/" else: self._root = "/uncached/" senseurslist = ow.Sensor("/").sensorList( ) # [Sensor("/10.CF8313020800"), Sensor("/28.A05FD7010000"), Sensor("/26.99E4F1000000"), Sensor("/81.E1BC2C000000")] for senseur in senseurslist: self.log.info( u"==> Senseurs trouvés: %s %s" % (senseur.type, senseur.family + '.' + senseur.id)) except: raise OneWireException( u"### Access to onewire device is not possible: %s" % traceback.format_exc())
def do_scan(self): """ Initiate 1wire bus scanning, check existence in self.scanned join sens with mysensor """ for sens in ow.Sensor("/uncached").sensors(): if not (sens in self.scanned): address = sens.address try: # find sensor in list self.mysenors by address mysensor = next(x for x in self.mysensors if x.address == address) #print "Sensor found " + str(mysensor.circuit) except Exception: #if not found, create new one mysensor = MySensorFabric(address, sens.type, self, interval=15) if mysensor: # notify master process about new sensor self.resultQ.send(mysensor) #mysensor = self.find_mysensor(sens) if mysensor: mysensor.sens = sens self.scanned.add(sens)
def read_sensors(self): sensordata = {} try: ow.init(self.owd.cfg.onewire['controller']) except ow.exNoController: logging.critical("Can't Access Controller") return False try: logging.debug("Reading OneWire Bus") sensors = ow.Sensor("/").sensorList() logging.debug("Done reading OneWire Bus") except Exception as e: logging.warning("Error reading sensors: {0}".format(e)) return False try: for sensor in sensors: if sensor.type != 'DS18B20': sensors.remove(sensor) else: try: tempc = sensor.temperature except Exception: logging.warning("error reading sensor") if tempc == 85: logging.warning("bad temp recieved") else: sensordata[sensor.r_address] = self.c_to_f(tempc) logging.debug(str(sensordata)) except Exception as e: logging.warning("error reading temps: {0}".format(e)) if len(sensordata) == 0: logging.critical("No temps read") return sensordata
def testAttributes(self): for name in sensors: sensor = ow.Sensor(name) family, id = name[1:].split('.') self.failUnlessEqual(family + id, sensor.address[:-2]) #self.failUnlessEqual( config.get( name, 'crc8' ), sensor.crc8 ) self.failUnlessEqual(family, sensor.family) self.failUnlessEqual(id, sensor.id) self.failUnlessEqual('1', sensor.present) self.failUnlessEqual(config.get(name[1:], 'type'), sensor.type) self.failUnlessEqual(hasattr(sensor, 'branch_0'), True) self.failUnlessEqual(hasattr(sensor, 'branch_1'), True) self.failUnlessEqual(hasattr(sensor, 'branch_ALL'), True) self.failUnlessEqual(hasattr(sensor, 'branch_BYTE'), True) self.failUnlessEqual(hasattr(sensor, 'control'), True) #self.failUnlessEqual( hasattr( sensor, 'discharge' ), True ) self.failUnlessEqual(hasattr(sensor, 'event_0'), True) self.failUnlessEqual(hasattr(sensor, 'event_1'), True) self.failUnlessEqual(hasattr(sensor, 'event_ALL'), True) self.failUnlessEqual(hasattr(sensor, 'event_BYTE'), True) self.failUnlessEqual(hasattr(sensor, 'sensed_0'), True) self.failUnlessEqual(hasattr(sensor, 'sensed_1'), True) self.failUnlessEqual(hasattr(sensor, 'sensed_ALL'), True) self.failUnlessEqual(hasattr(sensor, 'sensed_BYTE'), True)
def __init__(self, log, dev = 'u', cache = False): """ Create OneWire instance, allowing to use OneWire Network @param dev : device where the interface is connected to, default 'u' for USB """ self._log = log self._log.info("OWFS version : %s" % ow.__version__) try: ow.init(dev) self._cache = cache if cache == True: self._root = ow.Sensor('/') else: self._root = ow.Sensor('/uncached') except: raise OneWireException("Access to onewire device is not possible. Does your user have the good permissions ? If so, check that you stopped onewire module and you don't have OWFS mounted : %s" % traceback.format_exc())
def _getSensors(): # Connect to owserver ow.init('localhost:4304') # Get sensor list response = ow.Sensor('/').sensorList() # ow clean up #ow.finish() return response
def testSensors(self): #print 'OWSensors.testSensors' sensors = [ str(sensor).split(' - ')[0] for sensor in ow.Sensor('/').sensors() ] sensors.sort() self.failUnlessEqual(sensors, self.sensors)
def scan(port, unit_indicator): # TODO: Wants a callback per sensor here....? starttime = time.time() logger.debug('Start scanning for temperature/humidity sensors') sensor_list = [] if port > 0: try: ow.init(str(port)) sensorsList = ow.Sensor('/').sensorList() for sensor in sensorsList: if 'temperature' in sensor.entryList(): sensor_list.append( terrariumSensor(None, 'owfs', 'temperature', sensor, callback_indicator=unit_indicator)) if 'humidity' in sensor.entryList(): sensor_list.append( terrariumSensor(None, 'owfs', 'humidity', sensor, callback_indicator=unit_indicator)) except ow.exNoController: logger.debug( 'OWFS file system is not actve / installed on this device!' ) pass # Scanning w1 system bus for address in glob.iglob(terrariumSensor.W1_BASE_PATH + '[1-9][0-9]-*'): if not os.path.isfile(address + '/w1_slave'): break data = '' with open(address + '/w1_slave', 'r') as w1data: data = w1data.read() w1data = terrariumSensor.W1_TEMP_REGEX.search(data) if w1data: # Found valid data sensor_list.append( terrariumSensor( None, 'w1', ('temperature' if 't' == w1data.group('type') else 'humidity'), address.replace(terrariumSensor.W1_BASE_PATH, ''), callback_indicator=unit_indicator)) logger.info('Found %d temperature/humidity sensors in %.5f seconds' % (len(sensor_list), time.time() - starttime)) return sensor_list
def write(self,device,pio,value): try: ret = 0 # Ensure we will return a value s = ow.Sensor( '/'+device) gpio = self.pio_map(device,pio) ret = setattr(s,gpio,value) ret = getattr(s,gpio) except: raise OneWireException("Can't access given PIO %s" % gpio) return ret
def __init__(self, dev, log): """ Create OneWire instance, allowing to use OneWire Network @param dev : device where the interface is connected to, default 'u' for USB """ self._log = log try: ow.init(str(dev)) self._root_cached = ow.Sensor('/') self._root_uncached = ow.Sensor('/uncached') except: self._log.error("%s : %s : %s" % (dev, ACCESS_ERROR, traceback.format_exc())) raise OneWireException("%s. See log file for complete trace" % (ACCESS_ERROR)) else: self._cache = True self._root = self._root_cached
def __init__(self, wsMcuFactory, source, outputdir): self.wsMcuFactory = wsMcuFactory #self.sensor = 'ow' self.source = source ow.init(source) self.root = ow.Sensor('/').sensorList() self.hostname = socket.gethostname() # TODO: create outputdir if not existing self.outputdir = outputdir self.reconnectcount = 0
def testBaseAttributes( self ): #print 'OWSensors.testBaseAttributes' for sensor in ow.Sensor( '/' ).sensors( ): name = str( sensor ).split( ' - ' )[ 0 ][ 1: ] family, id = name.split( '.' ) self.failUnlessEqual( family + id, sensor.address[ :-2 ] ) #self.failUnlessEqual( self.config.get( name, 'crc8' ), sensor.crc8 ) self.failUnlessEqual( family, sensor.family ) self.failUnlessEqual( id, sensor.id ) self.failUnlessEqual( self.config.get( name, 'type' ), sensor.type )
def testRootCache( self ): r = ow.Sensor( '/' ) ce = r.entryList( ) cs = r.sensorList( ) r.useCache( False ) ue = r.entryList( ) us = r.sensorList( ) self.failUnlessEqual( cs, us ) self.failUnlessEqual( ue, [ 'alarm', 'simultaneous' ] )
def testAttributes(self): self.failIfEqual(len(sensors), 0) for name in sensors: sensor = ow.Sensor(name) family, id = name[1:].split('.') self.failUnlessEqual(family + id, sensor.address[:-2]) #self.failUnlessEqual( config.get( name, 'crc8' ), sensor.crc8 ) self.failUnlessEqual(family, sensor.family) self.failUnlessEqual(id, sensor.id) self.failUnlessEqual(config.get(name[1:], 'type'), sensor.type)
def info(self): # You can now start using OWFS to access your i2c devices and any connected sensors: # sudo /opt/owfs/bin/owfs --i2c=ALL:ALL --allow_other /mnt/1wire # for details check: https://www.abelectronics.co.uk/kb/article/3/owfs-with-i2c-support-on-raspberry-pi # starting owfs and logging sensors found to file import ow ow.init('localhost:4304') sensorlist = ow.Sensor('/').sensorList() for sensor in sensorlist: log.info("Device found: " + "Type=" + sensor.type + " Family=" + sensor.family + " Address=" + sensor.address + " ID=" + sensor.id)
def report_state(): ow.init('localhost:4304') sensorlist = ow.Sensor('/').sensorList() for sensor in sensorlist: print('Device Found') print('Address: ' + sensor.address) print('Family: ' + sensor.family) print('ID: ' + sensor.id) print('Type: ' + sensor.type) print(' ') ow.finish()
def testCacheSwitch( self ): for id in self.config.get( 'Root', 'sensors' ).split( ' ' ): s = ow.Sensor( '/' + id ) ce = s.entryList( ) cs = s.sensorList( ) s.useCache( False ) ue = s.entryList( ) us = s.sensorList( ) self.failUnlessEqual( ce, ue ) self.failUnlessEqual( cs, us )
def owConnected(self): global owsensorlist try: self.root = ow.Sensor('/').sensorList() if not (self.root == owsensorlist): log.msg('Rereading sensor list') ow.init(self.source) self.root = ow.Sensor('/').sensorList() owsensorlist = self.root self.connectionMade(self.root) self.reconnectcount = 0 except: self.reconnectcount = self.reconnectcount + 1 log.msg('Reconnection event triggered - Number: %d' % self.reconnectcount) time.sleep(2) if self.reconnectcount < 10: self.owConnected() else: print "owConnect: reconnection not possible" self.oneWireInstruments(self.root)
def _sensors(self): import ow self._ensure_connect() sensors = [] try: for s in ow.Sensor('/').sensorList(): if hasattr(s, 'temperature'): sensors.append(TemperatureSensor(s)) if hasattr(s, 'humidity'): sensors.append(HumiditySensor(s)) return sensors except ow.exUnknownSensor as e: logging.warn('Error Reading 1-Wire: {}'.format(e))
def testFindAnyValue( self ): #print 'OWSensors.testFindAnyValue' type_list = { } for id in self.config.get( 'Root', 'sensors' ).split( ' ' ): id_type = self.config.get( id, 'type' ) try: type_list[ id_type ] += 1 except KeyError: type_list[ id_type ] = 1 for id_type in type_list: sensor_list = [ sensor for sensor in ow.Sensor( '/' ).find( type = id_type ) ] self.failUnlessEqual( len( sensor_list ), type_list[ id_type ] )
def __init__(self, _address, _attr, _pm): # def __init__(self, _address, _attr): self._sensor = ow.Sensor(_address) self._attr = _attr self._pm = _pm self._fulladdress = _address + "/" + _attr # initialize as off self._commanded = False self._set(False) # amount of retries self._retries = 4