Пример #1
0
    def __init__(self, engine, config_dict):
        """
        interface: Where to find the one-wire sensors.  Options include
        u, /dev/ttyS0
        [Required. Default is u (usb)]

        sensor_map: Associate sensor values with database fields.
        [Required]

        sensor_type: Indicates how data should be processed before saving.
        [Optional. Default is gauge]
        """
        super(OWFSService, self).__init__(engine, config_dict)

        d = config_dict.get('OWFS', {})
        self.sensor_map = d['sensor_map']
        self.sensor_type = d.get('sensor_type', {})
        self.interface = d.get('interface', 'u')
        self.unit_system = d.get('unit_system', 'METRIC').lower()
        self.binding = d.get('binding', 'archive')
        self.last_data = {}
        self.units = weewx.US if self.unit_system == 'us' else weewx.METRIC

        loginf('service version is %s' % DRIVER_VERSION)
        loginf('binding is %s' % self.binding)
        loginf('interface is %s' % self.interface)
        loginf('sensor map is %s' % self.sensor_map)
        loginf('sensor type map is %s' % self.sensor_type)
        loginf('sensor unit system is %s' % self.unit_system)

        ow.init(self.interface)
        if self.binding == 'loop':
            self.bind(weewx.NEW_LOOP_PACKET, self.handle_new_loop)
        else:
            self.bind(weewx.NEW_ARCHIVE_RECORD, self.handle_new_archive)
Пример #2
0
    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())
Пример #3
0
 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
Пример #4
0
 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
Пример #5
0
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
Пример #6
0
    def __init__(self, engine, config_dict):
        """interface: Where to find the one-wire sensors.
        Options include  u, /dev/ttyS0
        [Required. Default is u (usb)]

        sensor_map: Associate sensor values with database fields.
        [Required]

        sensor_type: Indicates how data should be processed before saving.
        [Optional. Default is gauge]
        """
        super(OWFSService, self).__init__(engine, config_dict)

        d = config_dict.get('OWFS', {})
        self.sensor_map = d['sensor_map']
        self.sensor_type = d.get('sensor_type', {})
        self.interface = d.get('interface', 'u')
        self.unit_system = d.get('unit_system', 'METRIC').lower()
        self.binding = d.get('binding', 'archive')
        self.last_data = {}
        self.units = weewx.US if self.unit_system == 'us' else weewx.METRIC

        log.info('service version is %s', DRIVER_VERSION)
        log.info('binding is %s', self.binding)
        log.info('interface is %s', self.interface)
        log.info('sensor map is %s', self.sensor_map)
        log.info('sensor type map is %s', self.sensor_type)
        log.info('sensor unit system is %s', self.unit_system)

        #ow.init(self.interface.encode())
        ow.init(self.interface)
        if self.binding == 'loop':
            self.bind(weewx.NEW_LOOP_PACKET, self.handle_new_loop)
        else:
            self.bind(weewx.NEW_ARCHIVE_RECORD, self.handle_new_archive)
Пример #7
0
def _getSensors():
    # Connect to owserver
    ow.init('localhost:4304')
    # Get sensor list
    response = ow.Sensor('/').sensorList()
    # ow clean up
    #ow.finish()
    return response
Пример #8
0
def init():
    """ Wrapper of ow library init() function, hard linked to owserver."""
    # check if owserver is currently running
    try:
        subprocess.check_output(['pgrep', 'owserver'])
        ow.init('localhost:4304')
    except subprocess.CalledProcessError:
        raise ow.exError('owserver not running')
Пример #9
0
def _getSensors():
  # Connect to owserver
  ow.init('localhost:4304')
  # Get sensor list
  response = ow.Sensor('/').sensorList()
  # ow clean up
  #ow.finish()
  return response
Пример #10
0
    def run(self):
        """ Main loop of the subprocess
            Every scan_interval initiate bus scanning
            Peridocally scan 1wire sensors, else sleep
        """
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        ow.init(self.bus)
        logger.info("Entering OWW loop with PID {}".format(os.getpid()))

        while True:  # If no sensors are in cache
            if self.scan_interval != 0: self.do_scan()  # Do initial scan
            if len(self.mysensors) > 0:
                break

            if self.taskQ.poll(20):  # Wait 20 second for CMD from main loop
                #CMD from main loop
                cmd = self.taskQ.recv()
                self.do_command(cmd)

        mysensor = min(self.mysensors, key=lambda x: x.time
                       )  # Find sensor with min time (all se to 0 as default)

        scan_time = time.time() + self.scan_interval  # Plan next scan

        while True:  # "Main loop"

            if self.scan_interval != 0:
                t1 = time.time()
                if t1 >= scan_time:  # Is time to scan the bus
                    self.do_scan()
                    scan_time = t1 + self.scan_interval  # Plan next scan

            try:  # Read values from selected sensor
                t1 = time.time()
                mysensor.read_val_from_sens(
                    mysensor.sens)  # Read temperature from DS thermometer
                mysensor.lost = False  # Readout was successful
                mysensor.readtime = t1  # Store last read time - UNUSED NOW, redundant to mysensor.time
                if self.resultQ:
                    # send measurement into result queue
                    self.resultQ.send((mysensor.circuit, mysensor.value))
            except (ow.exUnknownSensor, AttributeError):
                if not mysensor.lost:  # Catch the edge
                    mysensor.set_lost()
                    self.resultQ.send(
                        (mysensor.circuit,
                         mysensor.lost))  # Send info about lost to the queue
            mysensor.time = t1 + mysensor.calc_interval()
            mysensor = min(self.mysensors, key=lambda x: x.time)
            t1 = time.time()
            sleep_time = 0 if mysensor.time < t1 else mysensor.time - t1
            while self.taskQ.poll(sleep_time) is True:
                #commands from master
                cmd = self.taskQ.recv()
                self.do_command(cmd)
                mysensor = min(self.mysensors, key=lambda x: x.time)
                t1 = time.time()
                sleep_time = 0 if mysensor.time < t1 else mysensor.time - t1
Пример #11
0
    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
Пример #12
0
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)
Пример #13
0
	def init(self):
		try:
			ow.init('localhost:4304')
			return True				
		except Exception, e:
			print (strftime("[%H:%M:%S]: EXCEPTION ", localtime()) + traceback.format_exc())

			if self.logger:
				self.logger.error((strftime("[%H:%M:%S]: EXCEPTION ", localtime()) + traceback.format_exc()), exc_info=True)
		  		return False		        
Пример #14
0
 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
Пример #15
0
 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
Пример #16
0
 def test_get_all(self):
     """Ensure _get_all gets all sensors """
     ow.init('--tester=28,28,28,28')
     OWSensor.initialized_connection_type = '--tester=28,28,28,28'
     sensors = {}
     expected_sensors = {'28.000028D70200': '/28.000028D70200',
                         '28.000028D70300': '/28.000028D70300',
                         '28.000028D70000': '/28.000028D70000',
                         '28.000028D70100': '/28.000028D70100'}
     OWSensor._get_all(ow.Sensor('/'), sensors)
     self.assertEqual(sensors, expected_sensors)
Пример #17
0
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()
Пример #18
0
 def do_reset(self):
     logger.debug("Invoked reset of 1W master")
     try:
         with ModbusClient('127.0.0.1') as client: # Send request to local unipi-tcp in simple sync mode
             ret = client.write_coil(1001, True, unit=1)
             time.sleep(0.2)
             ret = client.write_coil(1001, False, unit=1)
         ow.finish()
         time.sleep(0.05)
         ow.init(self.bus)
     except (ConnectionException):
         pass
Пример #19
0
 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)
Пример #20
0
    def __init__(self):
        # log init
        logging.basicConfig(filename = tempfile.gettempdir() + '/smarty.log', format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s]  %(message)s', level = logging.DEBUG)

        logging.info('Daemon start')
        
        # ow init
        try: 
            logging.info('1-wire network init owserver')
            ow.init('localhost:4444')
        except:
            logging.error('1-wire network init')
            sys.exit(0)
Пример #21
0
    def run(self):
        """ Main loop 
            Every scan_interval initiate bus scanning
            Peridocally scan 1wire sensors, else sleep
        """
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        # apigpio.mainprog = 0
        # for i in range(25):
        # try:
        # if not (i in (0,1,2,self.taskQ.fileno(), self.resultQ.fileno())):
        #         os.close(i)
        #   except Exception, E:
        #     print str(E)
        ow.init(self.bus)
        print "Entering 1wire loop"
        self.do_scan()
        while len(self.mysensors) == 0:
            if self.taskQ.poll(20):
                #commands from master
                cmd = self.taskQ.recv()
                self.do_command(cmd)
            self.do_scan()

        scan_time = time.time() + self.scan_interval
        mysensor = min(self.mysensors, key=lambda x: x.time)
        while True:
            t1 = time.time()
            #if t1 <= scan_time: 
            if t1 >= scan_time:
                self.do_scan()
                t1 = time.time()
                scan_time = t1 + self.scan_interval
            try:
                mysensor.read_val_from_sens(mysensor.sens)
                mysensor.lost = False
                mysensor.readtime = t1
                if self.resultQ:
                    # send measurement into result queue
                    self.resultQ.send((mysensor.circuit, mysensor.value))
            except (ow.exUnknownSensor, AttributeError):
                if not mysensor.lost:
                    mysensor.set_lost()
                    self.resultQ.send((mysensor.circuit, mysensor.lost))
            mysensor.time = t1 + mysensor.calc_interval()
            mysensor = min(self.mysensors, key=lambda x: x.time)
            t1 = time.time()
            if mysensor.time > t1:
                if self.taskQ.poll(mysensor.time - t1):
                    #commands from master
                    cmd = self.taskQ.recv()
                    self.do_command(cmd)
Пример #22
0
    def run(self):
        """ Main loop 
            Every scan_interval initiate bus scanning
            Peridocally scan 1wire sensors, else sleep
        """
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        # apigpio.mainprog = 0
        # for i in range(25):
        # try:
        # if not (i in (0,1,2,self.taskQ.fileno(), self.resultQ.fileno())):
        #         os.close(i)
        #   except Exception, E:
        #     print str(E)
        ow.init(self.bus)
        logger.debug("Entering 1wire loop")
        self.do_scan()
        while len(self.mysensors) == 0:
            if self.taskQ.poll(20):
                #commands from master
                cmd = self.taskQ.recv()
                self.do_command(cmd)
            self.do_scan()

        scan_time = time.time() + self.scan_interval
        mysensor = min(self.mysensors, key=lambda x: x.time)
        while True:
            t1 = time.time()
            #if t1 <= scan_time: 
            if t1 >= scan_time:
                self.do_scan()
                t1 = time.time()
                scan_time = t1 + self.scan_interval
            try:
                mysensor.read_val_from_sens(mysensor.sens)
                mysensor.lost = False
                mysensor.readtime = t1
                if self.resultQ:
                    # send measurement into result queue
                    self.resultQ.send((mysensor.circuit, mysensor.value))
            except (ow.exUnknownSensor, AttributeError):
                if not mysensor.lost:
                    mysensor.set_lost()
                    self.resultQ.send((mysensor.circuit, mysensor.lost))
            mysensor.time = t1 + mysensor.calc_interval()
            mysensor = min(self.mysensors, key=lambda x: x.time)
            t1 = time.time()
            if mysensor.time > t1:
                if self.taskQ.poll(mysensor.time - t1):
                    #commands from master
                    cmd = self.taskQ.recv()
                    self.do_command(cmd)
Пример #23
0
    def __init__(self, config):
        # We only support 'owserver' temperature sensors at the moment
        # For example DS18B20 connected directly or over DS2482 I2C-to-1wire bridge
        assert(config['mode'] == 'owserver')
        
        # Load the probe aliases
        aliases = config.get('aliases', '{}')
        self.aliases = json.loads(aliases)

        # Connect to the server and list probes
        ow.init(config['server'])

        # Enumerate all sensors
        self.sensors = ow.Sensor('/').sensorList()
Пример #24
0
    def __init__(self, **stn_dict):
        """Initialize the simulator

        # TODO Some of this next stuff is redundant as it come from Simulator
        NAMED ARGUMENTS:
        
        interface: Where to find the one-wire sensors.  Options include
        u, /dev/ttyS0
        [Required. Default is u (usb)]
        

        loop_interval: The time (in seconds) between emitting LOOP packets. [Optional. Default is 2.5]

        start_time: The start (seed) time for the generator in unix epoch time [Optional. If 'None',
                    or not present, then the present time will be used.]

        resume_time: The start time for the loop. [Optional. If 'None',
                     or not present, then start_time will be used].


        """

        logdbg("Station 1WIRE created")
        self.interface         = stn_dict.get('interface', 'u')
        self.LOOP_INTERVAL = float(stn_dict.get('loop_interval', 1))
        self.RAIN_INTERVAL = float(stn_dict.get('rain_interval', 30))
        self.OTHERS_INTERVAL = float(stn_dict.get('rain_interval', 30))
        
        # No start time specified. We are in realtime mode.
        self.real_time = True
        start_ts = self.the_time = time.time()

        #self.mode = stn_dict['mode']
        
        self.wind = WindSpeed()
        self.rain = RainCount()

        self.last_rain_time = time.time()
        self.last_other_time = time.time()

        # The following doesn't make much meteorological sense, but it is easy to program!
        self.observations = {'outTemp'    : inTemp(),
                             'inTemp'     : inTemp(),
                             'barometer'  : Barometer(),
                             'outHumidity': inHumid(),
                             'inHumidity' : inHumid(),
                             'radiation'  : Solar(),
                             'maxInstantRadiation' : MaxSolar()}
                             
        ow.init(self.interface)
Пример #25
0
def sensors(request):

    slist = []
    message = ''
    sensors = []
    
    if request.method == 'POST' and 'add_sensor' in request.POST:
        #save sensor
        
        if utils.add_sensor(request.POST['sensor_address'], request.POST['sensor_alias'], int(request.POST['sensor_family']), request.POST['sensor_service']):        
            #d = dict(request=request, slist=slist, message=message)
            return redirect('/sensors/')
        else:
            message = 'sensor save error'        
            d = dict(request=request, slist=slist, message=message)
            return render_to_response('web/sensors.html', d, context_instance=RequestContext(request))    
    
    
    try:
        ow.init(utils.owserver)
        sensors = ow.Sensor('/').sensorList()
        
        for s in sensors:
            
            exist = utils.get_sensor(s.address)
            
            if int(s.family) == 28:
                if exist:
                    slist.append({'address': s.address, 'family': s.family, 'temperature': s.temperature, 'alias': exist.alias})
                else:
                    slist.append({'address': s.address, 'family': s.family, 'temperature': s.temperature})
                
            elif int(s.family) == 29:
                if exist:
                    slist.append({'address': s.address, 'family': s.family, 'PIO_ALL': s.PIO_ALL, 'alias': exist.alias})
                else:
                    slist.append({'address': s.address, 'family': s.family, 'PIO_ALL': s.PIO_ALL})
            
            else:
                slist.append({'address': s.address, 'family': s.family})
   
    except:
        message = 'OWserver error'
    
   
    
    d = dict(request=request, slist=slist, message=message, sensors=sensors)
    
    return render_to_response('web/sensors.html', d, context_instance=RequestContext(request))
Пример #26
0
  def scan(port):
    if port > 0:
      try:
        ow.init(str(port));
        sensorsList = ow.Sensor('/').sensorList()
        for sensor in sensorsList:
          if 'temperature' in sensor.entryList():
            yield(sensor,'temperature')

          if 'humidity' in sensor.entryList():
            yield(sensor,'humidity')

      except ow.exNoController:
        logger.debug('OWFS file system is not actve / installed on this device!')
        pass
Пример #27
0
    def setUp( self ):
        #print 'OWSensors.setup'
        if not os.path.exists( 'owtest.ini' ):
            raise IOError, 'owtest.ini'

        self.config = ConfigParser.ConfigParser( )
        self.config.read( 'owtest.ini' )

        ow.init( self.config.get( 'General', 'interface' ) )

        self.entries = self.config.get( 'Root', 'entries' ).split( ' ' )
        self.entries.sort( )

        self.sensors = [ '/' + name for name in self.config.get( 'Root', 'sensors' ).split( ' ' ) ]
        self.sensors.sort( )
Пример #28
0
    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.")
Пример #29
0
  def __login(self):
    if (self.__getConfig().getOnewire().getHostname() != None and self.__getConfig().getOnewire().getPort() != None):
	
      ow.init(("%s:%s") % (self.__getConfig().getOnewire().getHostname(), str(self.__getConfig().getOnewire().getPort())));
      ow.error_level(ow.error_level.fatal);
      ow.error_print(ow.error_print.stderr);
	  
      for path, value in self.__getConfig().getOnewire().getInitDevices().items():
        try:
          ow._put(path, value);
        except ow.exUnknownSensor:
          logging.error("unknown sensor for deviceId \"%s\" and topic \"%s\"", temp.getId(), temp.getPath());
	
      return True;
	  
    return False;
Пример #30
0
    def _temperature_loop(self):
        ow.init(self._location)
        sensorlist = ow.Sensor('/').sensorList()

        while True:
            for ow_sensor in sensorlist:
                for IOPoint in self._config.keys():
                    try:
                        if ow_sensor.alias in self._config[IOPoint]:
                            self._temperature_dict[IOPoint] = ow_sensor.temperature

                    except Exception as e:
                        log.exception('An error occurred while obtaining sensor temperature: ' + str(IOPoint))
                        log.exception(e)
                        raise
            time.sleep(self._loop_time)
Пример #31
0
 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())
Пример #32
0
 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):
        self._pm = waterHelpers.PowerMeter()
        self._leds = waterHelpers.Leds()

        self._gpios = {}
        self._buttonCallbacks = {}

        ow.init('localhost:4304')
        self._sensors = ow.Sensor("/uncached").sensorList()

        self._buspower = False
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(relp, GPIO.OUT)

        self._regButton(16, self.togglePower)
        self._leds.regCallback(11, self.powerState)

        self._regButton(19, self.stop)
Пример #34
0
def read_sensor(sensor):
    """
    Read the sensor

    :param sensor: sensor to read
    """
    ow.init('localhost:4304')

    sensor['value'] = ''
    sensor['error'] = ''
    try:
        sensor_1w = ow.Sensor(str('/%s' % sensor['address']))
    except Exception:
        app.logger.warn('Could not read sensor %s : %s', sensor['name'],
                        sys.exc_info()[1])
        sensor['error'] = 'Could not read sensor'
    else:
        sensor['value'] = '{:.2f}'.format(float(sensor_1w.temperature))
Пример #35
0
 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
Пример #36
0
def get_informations(device):
    info = { "device" : False,
             "device_type" : device,
             "1w_devices" : []}
    try:
        ow.init(device)             # initialize ow
        info['device'] = True
        
    except: 
        print(u"### No device found on 1-wire device '%s':  %s" % (device, traceback.format_exc()))
        pass

    if info['device'] == True:
        try:
            for device in ow.Sensor("/").find(all = True):    #.find(type = "DS18B20"):
                info['1w_devices'].append({"type" : device.type, "id" : device.family + '.' + device.id})
        except Exception as error:
            info['1w_devices'].append({"type" : "EXCEPTION ERROR", "id" : error})
    return info
Пример #37
0
def get_informations():
    info = { "device" : False,
             "device_model" : None,
             "1w_devices" : []}
    try:
        ow.init("u") # initialize USB
        info['device_model'] = "usb"
        info['device'] = True
        
    except: 
        pass

    if info['device'] == True:
        try:
            for device in ow.Sensor("/").find(all = True):    #.find(type = "DS18B20"):
                info['1w_devices'].append({"type" : device.type, "id" : device.family + '.' + device.id})
        except Exception as error:
            info['1w_devices'].append({"type" : "EXCEPTION ERROR", "id" : error})
    return info
Пример #38
0
  def scan(port,config): # TODO: Wants a callback per sensor here....?
    sensors = []
    try:
      ow.init(str(port));
      sensorsList = ow.Sensor('/').sensorList()
      for sensor in sensorsList:
        sensor_config = {}
        if 'temperature' in sensor.entryList():
          sensor_id = md5(b'' + sensor.address + 'temperature').hexdigest()
          if sensor_id in config:
            sensor_config = config[sensor_id]

          sensors.append(terrariumSensor( sensor_id,
                                          'temperature',
                                          sensor,
                                          sensor_config['name'] if 'name' in sensor_config else '',
                                          sensor_config['alarm_min'] if 'alarm_min' in sensor_config else 0,
                                          sensor_config['alarm_max'] if 'alarm_max' in sensor_config else 0,
                                          sensor_config['min'] if 'min' in sensor_config else 0,
                                          sensor_config['max'] if 'max' in sensor_config else 100))

        if 'humidity' in sensor.entryList():
          sensor_id = md5(b'' + sensor.address + 'humidity').hexdigest()
          if sensor_id in config:
            sensor_config = config[sensor_id]

          sensors.append(terrariumSensor(sensor_id,
                                        'humidity',
                                        sensor,
                                        sensor_config['name'] if 'name' in sensor_config else '',
                                        sensor_config['alarm_min'] if 'alarm_min' in sensor_config else 0,
                                        sensor_config['alarm_max'] if 'alarm_max' in sensor_config else 0,
                                        sensor_config['min'] if 'min' in sensor_config else 0,
                                        sensor_config['max'] if 'max' in sensor_config else 100))

    except ow.exNoController:
      message = '1 Wire file system is not actve / installed on this device!'
      print message
      pass

    return sensors
Пример #39
0
    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(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())
Пример #40
0
def main_loop():
    """
    main loop 
    """
    logging.debug(("ow.init (%s:%s)") % (args.server, args.port))
    ow.init(("%s:%s") % (args.server, args.port))
    ow.error_level(ow.error_level.fatal)
    ow.error_print(ow.error_print.stderr)
    logging.debug(("Querying %s") % (args.sensor_id))
    try:
        # Create sensor object
        sensor = ow.Sensor(args.sensor_id)
        # Query sensor state
        owtemp = float(sensor.temperature)
        logging.debug(("Sensor %s : %s") % (args.sensor_id, owtemp))

        # Check critical
        if owtemp < args.crit_low or owtemp > args.crit_high:
            # CRITICAL - 24,58 C |temp=24,58;25:35;15:55;0;120
            print(("CRITICAL - %.2f C|temp=%.2f;%s:%s;%s:%s") %
                  (owtemp, owtemp, args.warn_low, args.warn_high,
                   args.crit_low, args.crit_high))
            sys.exit(2)
        elif owtemp < args.warn_low or owtemp > args.warn_high:
            # WARNING - 24,58 C |temp=24,58;25:35;15:55;0;120
            print(("WARNING - %.2f C|temp=%.2f;%s:%s;%s:%s") %
                  (owtemp, owtemp, args.warn_low, args.warn_high,
                   args.crit_low, args.crit_high))
            sys.exit(1)
        else:
            # OK - 24,58 C |temp=24,58;25:35;15:55;0;120
            print(("OK - %.2f C|temp=%.2f;%s:%s;%s:%s") %
                  (owtemp, owtemp, args.warn_low, args.warn_high,
                   args.crit_low, args.crit_high))
            sys.exit(0)

    except ow.exUnknownSensor:
        logging.info("CRITICAL - Sensor %s not found", args.sensor_id)
        print("CRITICAL - Sensor %s not found" % args.sensor_id)
        sys.exit(3)
Пример #41
0
def get_temperature():
    path = os.path.realpath(os.path.dirname(__file__))
    dbname = "database.rrd"
    image = "image.png"
    fullpath = "%s/%s" % (path, dbname)
    fullimage = "%s/%s" % (path, image)
        
    if os.path.isfile(fullpath):

	ow.init('localhost:4444')
	sensors = ow.Sensor("/").sensorList()
	metric1 = sensors[0].temperature
	metric2 = sensors[1].temperature
	metric3 = sensors[2].temperature
	    
	ret = rrd_update(fullpath, 'N:%s:%s:%s' % (metric1, metric2, metric3))
	
	ret = rrdtool.graph(fullimage, "--start", "0", "--vertical-label=Temperature",
	     "-w 500",
	     "DEF:t1=/home/nc/tt/timecard/database.rrd:metric1:LAST",
	     "DEF:t2=/home/nc/tt/timecard/database.rrd:metric2:LAST",
	     "DEF:t3=/home/nc/tt/timecard/database.rrd:metric3:LAST",
	     "LINE2:t1#006633:metric 1\\r",
	     "GPRINT:t1:LAST:Average temperature\: %1.0lf ",
	     "COMMENT:\\n",
	     "LINE2:t2#0000FF:metric 2\\r",
	     "GPRINT:t2:LAST:Average temperature\: %1.0lf ",
	     "COMMENT:\\n",
	     "LINE2:t3#0073E6:metric 3\\r",
	     "GPRINT:t3:LAST:Average temperature\: %1.0lf",
	     "COMMENT:\\n")
	     	     
    else:
	
	ret = rrdtool.create(fullpath, "--step", "300",
	    "DS:metric1:GAUGE:600:U:U",
	    "DS:metric2:GAUGE:600:U:U",
	    "DS:metric3:GAUGE:600:U:U",
	    "RRA:LAST:0.5:1:576")
Пример #42
0
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]
            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
                sensor = ow.Sensor(owpath)

                # Query sensor state
                logging.debug(("Sensor %s : %s") % (owpath, sensor.temperature))
                mqttc.publish(MQTT_TOPIC + owpath, sensor.temperature)
                item += 1

            except ow.exUnknownSensor:
                logging.info("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)
Пример #43
0
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 list(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 list(SENSORS.items()):
            logging.debug(("Querying %s : %s") % (owid, owtopic))
            try:
                sensor = ow.Sensor(owid)
                owtemp = sensor.temperature
                logging.debug(("Sensor %s : %s") % (owid, owtemp))
                MQTTC.publish(owtopic, owtemp)

            except ow.exUnknownSensor:
                logging.info(
                    "Threw an unknown sensor exception for device %s - %s. Continuing",
                    owid, owname)
                continue

            time.sleep(float(POLLINTERVAL) / len(SENSORS))
Пример #44
0
        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)
Пример #45
0
 def read(self):
     
     # Check to see if the one-wire server is running.  If not, start it.
     if not self.start_server_if_needed():
         # no owserver, so no readings
         return []
     
     ts = int(time.time())   # same timestamp used for all readings
     readings = []
     
     # loop across all sensors, reading the ones that appear in the target
     # list defined above.
     ow.init('localhost:4304')
     for sensor in ow.Sensor('/').sensorList():
         if sensor.type in TARGET_SENSORS:
             attr, rd_type, conv_func = TARGET_SENSORS[sensor.type]
             sensor.useCache(False)
             val = float(getattr(sensor, attr))
             if conv_func:
                 val = conv_func(val)
             readings.append((ts, f'{sensor.family}.{sensor.id}', val, rd_type))
     
     return readings
Пример #46
0
    def __init__(self, **stn_dict):
        """Initialize the driver.

        interface: Where to find the one-wire sensors.  Options include
        u, /dev/ttyS0
        [Required. Default is u (usb)]

        sensor_map: Associate sensor values with database fields.
        [Required]

        sensor_type: Indicate how data should be processed before saving.
        [Optional. Default is gauge]

        polling_interval: How often to poll for data, in seconds.
        [Optional. Default is 10]

        unit_system: The unit system the data are assumed to be in.  Can
        be one of 'METRIC' or 'US'.  This assumes that all sensors are
        reporting data in the same unit system.
        [Optional. Default is METRIC]
        """
        self.sensor_map = stn_dict['sensor_map']
        self.sensor_type = stn_dict.get('sensor_type', {})
        self.interface = stn_dict.get('interface', 'u')
        self.polling_interval = int(stn_dict.get('polling_interval', 10))
        self.unit_system = stn_dict.get('unit_system', 'METRIC').lower()
        self.last_data = {}
        self.units = weewx.US if self.unit_system == 'us' else weewx.METRIC

        log.info('driver version is %s', DRIVER_VERSION)
        log.info('interface is %s', self.interface)
        log.info('sensor map is %s', self.sensor_map)
        log.info('sensor type map is %s', self.sensor_type)
        log.info('polling interval is %s', str(self.polling_interval))
        log.info('sensor unit system is %s', self.unit_system)
        #ow.init(self.interface.encode())
        ow.init(self.interface)
Пример #47
0
    def __init__(self, **stn_dict) :
        """Initialize the driver.

        interface: Where to find the one-wire sensors.  Options include
        u, /dev/ttyS0
        [Required. Default is u (usb)]

        sensor_map: Associate sensor values with database fields.
        [Required]

        sensor_type: Indicate how data should be processed before saving.
        [Optional. Default is gauge]

        polling_interval: How often to poll for data, in seconds.
        [Optional. Default is 10]

        unit_system: The unit system the data are assumed to be in.  Can
        be one of 'METRIC' or 'US'.  This assumes that all sensors are
        reporting data in the same unit system.
        [Optional. Default is METRIC]
        """
        self.sensor_map = stn_dict['sensor_map']
        self.sensor_type = stn_dict.get('sensor_type', {})
        self.interface = stn_dict.get('interface', 'u')
        self.polling_interval = int(stn_dict.get('polling_interval', 10))
        self.unit_system = stn_dict.get('unit_system', 'METRIC').lower()
        self.last_data = {}
        self.units = weewx.US if self.unit_system == 'us' else weewx.METRIC

        loginf('driver version is %s' % DRIVER_VERSION)
        loginf('interface is %s' % self.interface)
        loginf('sensor map is %s' % self.sensor_map)
        loginf('sensor type map is %s' % self.sensor_type)
        loginf('polling interval is %s' % str(self.polling_interval))
        loginf('sensor unit system is %s' % self.unit_system)
        ow.init(self.interface)
Пример #48
0
    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))
Пример #49
0
DEVICE = agoclient.get_config_option("owfs", "device", "/dev/usbowfs")


# route stderr to syslog
class LogErr:
    def write(self, data):
        syslog.syslog(syslog.LOG_ERR, data)

syslog.openlog(sys.argv[0], syslog.LOG_PID, syslog.LOG_DAEMON)
# sys.stderr = LogErr()

SENSORS = {}

syslog.syslog(syslog.LOG_NOTICE, "agoowfs.py startup")
try:
    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.add_device(_sensor._path, "multilevelsensor")
    if _sensor._type == 'DS2438':
        try:
            if ow.owfs_get('%s/MultiSensor/type' % _sensor._path) == 'MS-TL':
Пример #50
0
	def init(self):
		if self._init == True:
			return
		ow.init( self['OWFS']['port'] )
		self._init = True
Пример #51
0
 def setUp( self ):
     ow.init( config.get( 'General', 'interface' ) )
Пример #52
0
device = agoclient.getConfigOption("owfs", "device", "/dev/usbowfs")

# route stderr to syslog
class LogErr:
        def write(self, data):
                syslog.syslog(syslog.LOG_ERR, data)

syslog.openlog(sys.argv[0], syslog.LOG_PID, syslog.LOG_DAEMON)
# sys.stderr = LogErr()

sensors = {}

syslog.syslog(syslog.LOG_NOTICE, "agoowfs.py startup")
try:
	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':
Пример #53
0
 def testImport( self ):
     #print 'OWLoad.testImport'
     import ow
     ow.init( self.config.get( 'General', 'interface' ) )
     s = ow.Sensor( '/' )
Пример #54
0
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
::EOH

Print the address and type of all sensors on a 1-wire network.
"""


import sys
import ow


def tree( sensor ):
    print '%7s - %s' % ( sensor._type, sensor._path )
    for next in sensor.sensors( ):
        if next._type in [ 'DS2409', ]:
            tree( next )
        else:
            print '%7s - %s' % ( next._type, next._path )


if __name__ == "__main__":
    if len( sys.argv ) == 1:
        print 'usage: tree.py u|serial_port_path|localhost:4304'
        sys.exit( 1 )
    else:
        ow.init( sys.argv[ 1 ] )
        tree( ow.Sensor( '/' ) )
Пример #55
0
import xml.etree.ElementTree as ET # for loading config
from cosmSender import CosmSender

#########################################
#            CONSTANTS                  #
#########################################

configTree = ET.parse("config.xml") # load config from config file
API_KEY    = configTree.findtext("apikey") # Your Pachube API Key
FEED       = configTree.findtext("feed")   # Your Pachube Feed number

##################
# OWFS           #
##################

ow.init( 'u' )

# We're accessing the 1-wire bus directly from python but
# if you want to use owserver:
# ow.init( 'localhost:3030' ) # /opt/owfs/bin/owserver -p 3030 -u -r

sensors = ow.Sensor("/").sensorList()


dataStreamDefaults = {
    "unit": {
        "type"  : "derivedSI",
        "label" : "degree Celsius",
        "symbol": u"\u00B0C"}
    }
Пример #56
0
DEVICE = agoclient.get_config_option("owfs", "device", "/dev/usbowfs")


# route stderr to syslog
class LogErr:
    def write(self, data):
        syslog.syslog(syslog.LOG_ERR, data)

syslog.openlog(sys.argv[0], syslog.LOG_PID, syslog.LOG_DAEMON)
# sys.stderr = LogErr()

SENSORS = {}

syslog.syslog(syslog.LOG_NOTICE, "agoowfs.py startup")
try:
    ow.init(str(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.add_device(_sensor._path, "temperaturesensor")
    if _sensor._type == 'DS2438':
        try:
            if ow.owfs_get('%s/MultiSensor/type' % _sensor._path) == 'MS-TL':