Exemple #1
0
 def RemoveCallbacks(self):
     """Remove callback function for all digital devices"""
     devices = manager.getDeviceList()
     for device in devices:
         sensor = instance.deviceInstance(device['name'])
         if 'DigitalSensor' in device['type'] and hasattr(sensor, 'removeCallback'):
             sensor.removeCallback()
Exemple #2
0
    def RemoveSensor(self, name):
        """Remove an existing sensor/actuator

        Args:
            name: Name of sensor to remove

        Returns:
            True for success, False otherwise.
        """
        bVal = False
        try:
            if self.pluginManager.is_plugin(name):
                return self.pluginManager.disable(name)
            sensorRemove = name
            try:
                sensor = instance.deviceInstance(sensorRemove)
                if hasattr(sensor, 'removeCallback'):
                    sensor.removeCallback()
            except: 
                pass
            with self.sensorMutex:
                retValue = manager.removeDevice(sensorRemove)
            info('Remove device returned: {}'.format(retValue))
            if retValue[0] == 200:
                bVal = True
        except:
            exception("Remove sensor failed")
            bVal = False
        return bVal
Exemple #3
0
 def setGPIOInstance(self):
     if not self.gpio:
         if self.gpioname != "GPIO":
             self.gpio = instance.deviceInstance(self.gpioname)
         else:
             self.gpio = GPIO()
         if self.gpio:
             self.gpio.setFunction(self.channel, GPIO.IN)
Exemple #4
0
    def __init__(self, altitude=0, external=None):
        self.altitude = toint(altitude)
        if isinstance(external, str):
            self.external = deviceInstance(external)
        else:
            self.external = external

        if self.external != None and not isinstance(self.external,
                                                    Temperature):
            raise Exception("external must be a Temperature sensor")
Exemple #5
0
 def InitCallbacks(self):
     """Set callback function for any digital devices that support them"""
     devices = manager.getDeviceList()
     for device in devices:
         sensor = instance.deviceInstance(device['name'])
         if 'DigitalSensor' in device['type'] and hasattr(sensor, 'setCallback'):
             debug('Set callback for {}'.format(sensor))
             sensor.setCallback(self.OnSensorChange, device)
             if not self.realTimeMonitorRunning:
                 ThreadPool.Submit(self.RealTimeMonitor)
Exemple #6
0
 def SensorsInfo(self):
     """Return a list with current sensor states for all enabled sensors"""
     manager.deviceDetector()
     devices = manager.getDeviceList()
     sensors_info = []
     if devices is None:
         return sensors_info
     for device in devices:
         sensor = instance.deviceInstance(device['name'])
         if 'enabled' not in device or device['enabled'] == 1:
             sensor_types = {'Temperature': {'function': 'getCelsius', 'data_args': {'type': 'temp', 'unit': 'c'}},
                             'Humidity': {'function': 'getHumidityPercent', 'data_args': {'type': 'rel_hum', 'unit': 'p'}},
                             'Pressure': {'function': 'getPascal', 'data_args': {'type': 'bp', 'unit': 'pa'}},
                             'Luminosity': {'function': 'getLux', 'data_args': {'type': 'lum', 'unit': 'lux'}},
                             'Distance': {'function': 'getCentimeter', 'data_args': {'type': 'prox', 'unit': 'cm'}},
                             'ServoMotor': {'function': 'readAngle', 'data_args': {'type': 'analog_actuator'}},
                             'DigitalSensor': {'function': 'read', 'data_args': {'type': 'digital_sensor', 'unit': 'd'}},
                             'DigitalActuator': {'function': 'read', 'data_args': {'type': 'digital_actuator', 'unit': 'd'}},
                             'AnalogSensor': {'function': 'readFloat', 'data_args': {'type': 'analog_sensor'}},
                             'AnalogActuator': {'function': 'readFloat', 'data_args': {'type': 'analog_actuator'}}}
             # extension_types = {'ADC': {'function': 'analogReadAllFloat'},
             #                     'DAC': {'function': 'analogReadAllFloat'},
             #                     'PWM': {'function': 'pwmWildcard'},
             #                     'GPIOPort': {'function': 'wildcard'}}
             for device_type in device['type']:
                 try:
                     display_name = device['description']
                 except:
                     display_name = None
                 if device_type in sensor_types:
                     try:
                         sensor_type = sensor_types[device_type]
                         func = getattr(sensor, sensor_type['function'])
                         if len(device['type']) > 1:
                             channel = '{}:{}'.format(device['name'], device_type.lower())
                         else:
                             channel = device['name']
                         value = self.CallDeviceFunction(func)
                         cayennemqtt.DataChannel.add(sensors_info, cayennemqtt.DEV_SENSOR, channel, value=value, name=display_name, **sensor_type['data_args'])
                         if 'DigitalActuator' == device_type and value in (0, 1):
                             manager.updateDeviceState(device['name'], value)
                     except:
                         exception('Failed to get sensor data: {} {}'.format(device_type, device['name']))
                 # else:
                 #     try:
                 #         extension_type = extension_types[device_type]
                 #         func = getattr(sensor, extension_type['function'])
                 #         values = self.CallDeviceFunction(func)
                 #         for pin, value in values.items():
                 #             cayennemqtt.DataChannel.add(sensors_info, cayennemqtt.DEV_SENSOR, device['name'] + ':' + str(pin), cayennemqtt.VALUE, value, name=display_name)
                 #     except:
                 #         exception('Failed to get extension data: {} {}'.format(device_type, device['name']))
     info('Sensors info: {}'.format(sensors_info))
     return sensors_info
Exemple #7
0
    def SensorCommand(self, command, sensorId, channel, value):
        """Execute sensor/actuator command

        Args:
            command: Type of command to execute
            sensorId: Sensor id
            channel: Pin/channel on device, None if there is no channel
            value: Value to use for setting the sensor state

        Returns:
            Command specific return value on success, False on failure
        """
        result = False
        info('SensorCommand: {}, sensor {}, channel {}, value {}'.format(command, sensorId, channel, value))
        try:
            if self.pluginManager.is_plugin(sensorId, channel):
                return self.pluginManager.write_value(sensorId, channel, value)
            commands = {'integer': {'function': 'write', 'value_type': int},
                        'value': {'function': 'write', 'value_type': int},
                        'function': {'function': 'setFunctionString', 'value_type': str},
                        'angle': {'function': 'writeAngle', 'value_type': float},
                        'float': {'function': 'writeFloat', 'value_type': float},
                        'volt': {'function': 'writeVolt', 'value_type': float}}
            with self.sensorMutex:
                if sensorId in self.disabledSensors:
                    info('Sensor disabled')
                    return result
                sensor = instance.deviceInstance(sensorId)
                if not sensor:
                    info('Sensor not found')
                    return result
                if command in commands:
                    device = instance.DEVICES[sensorId]
                    info('Sensor found: {}'.format(device))
                    func = getattr(sensor, commands[command]['function'])
                    value = commands[command]['value_type'](value)
                    if channel:
                        result = self.CallDeviceFunction(func, int(channel), value)
                    else:
                        result = self.CallDeviceFunction(func, value)
                    if 'DigitalActuator' in device['type']:
                        manager.updateDeviceState(sensorId, value)
                    return result
                warn('Command not implemented: {}'.format(command))
                return result
        except Exception:
            exception('SensorCommand failed')
        return result
Exemple #8
0
 def setADCInstance(self):
     if not self.adc:
         self.adc = instance.deviceInstance(self.adcname)
         info(" setADCInstance  self.adcname={} self.adc={}".format(
             self.adcname, self.adc))
Exemple #9
0
 def SensorCommand(self, commandType, sensorName, sensorType, driverClass,
                   method, channel, value):
     retVal = False
     info(
         'SensorCommand: {} SensorName {} SensorType {} DriverClass {} Method {} Channel {} Value {}'
         .format(commandType, sensorName, sensorType, driverClass, method,
                 channel, value))
     try:
         self.AddRefresh()
         debug('')
         actuators = ('GPIOPort', 'ServoMotor', 'AnalogActuator',
                      'LoadSensor', 'PiFaceDigital', 'DistanceSensor',
                      'Thermistor', 'Photoresistor', 'LightDimmer',
                      'LightSwitch', 'DigitalSensor', 'DigitalActuator',
                      'MotorSwitch', 'RelaySwitch', 'ValveSwitch',
                      'MotionSensor')
         gpioExtensions = ('GPIOPort', 'PiFaceDigital')
         if driverClass is None:
             hashKey = self.SHA_Calc_str(sensorName + sensorType)
         else:
             hashKey = self.SHA_Calc_str(sensorName + driverClass)
         with self.sensorMutex:
             if hashKey in self.disabledSensors:
                 return retVal
             sensor = instance.deviceInstance(sensorName)
             if not sensor:
                 info('Sensor not found')
                 return retVal
             if (sensorType in actuators) or (driverClass in actuators):
                 if sensorType in gpioExtensions or driverClass in gpioExtensions:
                     if commandType == 'integer' or commandType == 'value':
                         retVal = str(
                             self.CallDeviceFunction(
                                 sensor.write, int(channel), int(value)))
                         return retVal
                 else:
                     if commandType == 'integer':
                         retVal = str(
                             self.CallDeviceFunction(
                                 sensor.write, int(value)))
                         return retVal
                 if commandType == 'function':
                     retVal = str(
                         self.CallDeviceFunction(sensor.setFunctionString,
                                                 channel, value))
                     return retVal
                 if commandType == 'angle':
                     retVal = self.CallDeviceFunction(
                         sensor.writeAngle, value)
                     return retVal
                 if commandType == 'float':
                     retVal = self.CallDeviceFunction(
                         sensor.writeFloat, float(value))
                     return retVal
             if commandType == 'integer':
                 retVal = float(
                     self.CallDeviceFunction(sensor.write, int(channel),
                                             int(value)))
                 return retVal
             if commandType == 'float':
                 retVal = float(
                     self.CallDeviceFunction(sensor.writeFloat,
                                             int(channel), float(value)))
                 return retVal
             if commandType == 'volt':
                 retVal = float(
                     self.CallDeviceFunction(sensor.writeVolt, int(channel),
                                             float(value)))
                 return retVal
             if commandType == 'angle':
                 retVal = float(
                     self.CallDeviceFunction(sensor.writeAngle,
                                             int(channel), float(value)))
                 return retVal
             warn('Command not implemented: ' + commandType)
             return retVal
     except Exception as ex:
         exception('SensorCommand failed with: ' + str(ex))
         pass
     finally:
         #looks like this breaks actuators refresh by updating and not sending data changed
         #then refresh never comes for the specific sensor
         #ThreadPool.SubmitParam(self.Monitor, hashKey)
         return retVal
Exemple #10
0
 def SensorsInfo(self):
     with self.sensorMutex:
         devices = self.GetDevices()
         debug(
             str(time()) + ' Got devices info ' +
             str(self.sensorsRefreshCount))
         if devices is None:
             return {}
         for value in devices:
             sensor = instance.deviceInstance(value['name'])
             if 'enabled' not in value or value['enabled'] == 1:
                 sleep(SENSOR_INFO_SLEEP)
                 try:
                     if value['type'] == 'Temperature':
                         value['Celsius'] = self.CallDeviceFunction(
                             sensor.getCelsius)
                         value['Fahrenheit'] = self.CallDeviceFunction(
                             sensor.getFahrenheit)
                         value['Kelvin'] = self.CallDeviceFunction(
                             sensor.getKelvin)
                     if value['type'] == 'Pressure':
                         value['Pascal'] = self.CallDeviceFunction(
                             sensor.getPascal)
                     if value['type'] == 'Luminosity':
                         value['Lux'] = self.CallDeviceFunction(
                             sensor.getLux)
                     if value['type'] == 'Distance':
                         value['Centimeter'] = self.CallDeviceFunction(
                             sensor.getCentimeter)
                         value['Inch'] = self.CallDeviceFunction(
                             sensor.getInch)
                     if value['type'] in ('ADC', 'DAC', 'PWM'):
                         value['channelCount'] = self.CallDeviceFunction(
                             sensor.analogCount)
                         value['maxInteger'] = self.CallDeviceFunction(
                             sensor.analogMaximum)
                         value['resolution'] = self.CallDeviceFunction(
                             sensor.analogResolution)
                         value['allInteger'] = self.CallDeviceFunction(
                             sensor.analogReadAll)
                         value['allVolt'] = self.CallDeviceFunction(
                             sensor.analogReadAllVolt)
                         value['allFloat'] = self.CallDeviceFunction(
                             sensor.analogReadAllFloat)
                         if value['type'] in ('DAC'):
                             value['vref'] = self.CallDeviceFunction(
                                 sensor.analogReference)
                     if value['type'] == 'PWM':
                         value['channelCount'] = self.CallDeviceFunction(
                             sensor.pwmCount)
                         value['maxInteger'] = self.CallDeviceFunction(
                             sensor.pwmMaximum)
                         value['resolution'] = self.CallDeviceFunction(
                             sensor.pwmResolution)
                         value['all'] = self.CallDeviceFunction(
                             sensor.pwmWildcard)
                     if value['type'] == 'Humidity':
                         value['float'] = self.CallDeviceFunction(
                             sensor.getHumidity)
                         value['percent'] = self.CallDeviceFunction(
                             sensor.getHumidityPercent)
                     if value['type'] == 'PiFaceDigital':
                         value['all'] = self.CallDeviceFunction(
                             sensor.readAll)
                     if value['type'] in ('DigitalSensor',
                                          'DigitalActuator'):
                         value['value'] = self.CallDeviceFunction(
                             sensor.read)
                     if value['type'] == 'GPIOPort':
                         value['channelCount'] = self.CallDeviceFunction(
                             sensor.digitalCount)
                         value['all'] = self.CallDeviceFunction(
                             sensor.wildcard)
                     if value['type'] == 'AnalogSensor':
                         value['integer'] = self.CallDeviceFunction(
                             sensor.read)
                         value['float'] = self.CallDeviceFunction(
                             sensor.readFloat)
                         value['volt'] = self.CallDeviceFunction(
                             sensor.readVolt)
                     if value['type'] == 'ServoMotor':
                         value['angle'] = self.CallDeviceFunction(
                             sensor.readAngle)
                     if value['type'] == 'AnalogActuator':
                         value['float'] = self.CallDeviceFunction(
                             sensor.readFloat)
                 except:
                     exception("Sensor values failed: " + value['type'] +
                               " " + value['name'])
             try:
                 if 'hash' in value:
                     value['sensor'] = value['hash']
                     del value['hash']
             except KeyError:
                 pass
         if self.currentSensorsInfo:
             del self.currentSensorsInfo
             self.currentSensorsInfo = None
         self.currentSensorsInfo = devices
         devices = None
     if self.sensorsRefreshCount == 0:
         info('System sensors info at start ' +
              str(self.currentSensorsInfo))
     debug(('New sensors info retrieved: {}').format(
         self.sensorsRefreshCount))
     logJson('Sensors Info updated: ' + str(self.currentSensorsInfo))
     return self.currentSensorsInfo
Exemple #11
0
 def setADCInstance(self):
     if not self.adc:
         self.adc = instance.deviceInstance(self.adcname)
Exemple #12
0
 def setPWMInstance(self):
     if not self.pwm:
         self.pwm = instance.deviceInstance(self.pwmname)
Exemple #13
0
 def setADCInstance(self):
     if not self.adc:
         self.adc = instance.deviceInstance(self.adcname)
         if not self.adc:
             self.adc = self.pluginManager.get_plugin_by_id(self.adcname)