コード例 #1
0
    def set_valve(self, valve_name, sample):
        """
            Called when any tank valve channel changes its status. XBIB LED 
            channel corresponding to the valve must change too.
        """

        if valve_name == VALVE_IN:
            if self.input_valve_channel == None:
                try:
                    self.input_valve_channel = \
                        self.cm.channel_database_get().channel_get(
                                                           self.input_valve)
                except:
                    raise TankError("Channel %s does not exist" %
                                    self.input_valve)
            val = Boolean(self.input_valve_channel.get().value,
                          style=STYLE_ONOFF)
            if sample.value != val:
                self.input_valve_channel.set(
                    Sample(0, Boolean(sample.value, style=STYLE_ONOFF)))
        else:
            if self.output_valve_channel == None:
                try:
                    self.output_valve_channel = \
                        self.cm.channel_database_get().channel_get(
                                                           self.output_valve)
                except:
                    raise TankError("Channel %s does not exist" %
                                    self.output_valve)
            val = Boolean(self.output_valve_channel.get().value,
                          style=STYLE_ONOFF)
            if sample.value != val:
                self.output_valve_channel.set(
                    Sample(0, Boolean(sample.value, style=STYLE_ONOFF)))
コード例 #2
0
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services

        ## Local State Variables:
        self.__response_buffer = ""
        self.__request_events = []
        self.__request_retry_events = []

        from core.tracing import get_tracer
        self.__tracer = get_tracer(name)

        ## Settings Table Definition:
        settings_list = [
            Setting(
                name='poll_rate_sec', type=int, required=False,
                default_value=5,
                verify_function=lambda x: x >= 0),
            Setting(
                name='bus_id', type=int, required=False,
                default_value=0,
                verify_function=lambda x: x >= 0),
        ]

        ## Channel Properties Definition:
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(name="strength", type=int,
                initial=Sample(timestamp=0, value=0, unit="%"),
                perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP),

            ChannelSourceDeviceProperty(name="target_detected", type=Boolean,
                initial=Sample(timestamp=0,
                    value=Boolean(False, style=STYLE_YESNO)),
                perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP),

            ChannelSourceDeviceProperty(name="error_flag", type=Boolean,
                initial=Sample(timestamp=0,
                    value=Boolean(False, style=STYLE_YESNO)),
                perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP),

            ChannelSourceDeviceProperty(name="range", type=int,
                initial=Sample(timestamp=0, value=0, unit="in"),
                perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP),

            ChannelSourceDeviceProperty(name="temperature", type=float,
                initial=Sample(timestamp=0, value=0.0, unit="C"),
                perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        ## Initialize the DeviceBase interface:
        DeviceBase.__init__(self, self.__name, self.__core,
                                settings_list, property_list)

        ## Initialize the serial interface:
        Serial.__init__(self, 0, 19200, timeout = 0)
コード例 #3
0
    def __verify_power_setting(self, power):
        # The power option is ONLY supported on the X3 product.
        # So assume power is always on, and is intended to be always on.
        # Only do real checking for the False case.
        if power == Boolean(True, style = STYLE_ONOFF):
            return True
        elif power == Boolean(False, style=STYLE_ONOFF):
            if get_platform_name() == 'digix3':
                return True
            else:
                self.__tracer.error("Turning IO power off " +
                                    "on this device is not supported!")
                return False

        return False
コード例 #4
0
ファイル: xbee_rpm.py プロジェクト: bernhara/DigiGateway4Raph
    def _set_initial_power_state(self):
        '''
        set the initial power state (if set as "same")

        This needs to be outside of the start method, because
        it requires active communication with the device.

        Returns True on success, False on failure.
        '''
        # Retrieve current state from device for channel
        d4 = self._xbee_manager.xbee_device_ddo_get_param(
            self._extended_address, 'd4')

        d4 = struct.unpack('B', d4)[0]

        if d4 == POWER_ON:
            state = True

            # Treat as having just been turned on for shut-off
            self.__power_on_time = digitime.time()
        elif d4 == POWER_OFF:
            state = False
        else:
            self._tracer.warning('Unrecognized initial power_on state '
                                 '<%s>!\nNot touching "power_on" property.' %
                                 d4)
            return False

        self.property_set("power_on",
                          Sample(0, str(Boolean(state, style=STYLE_ONOFF))))
        return True
コード例 #5
0
 def __handle_debug(self, value):
     '''
     handle a call from the channel
     '''
     value = Boolean(value.value)
     self.property_set('debug_mode', Sample(0, value=value, unit='bool'))
     self.set_debug_mode(value)
コード例 #6
0
    def __init__(self, name, core_services):
        settings_list = [
            Setting(name='debug_sleep_time',
                    type=int,
                    required=False,
                    default_value=50,
                    verify_function=lambda x: 10 <= x <= 14400000),
            Setting(name='debug_wake_time',
                    type=int,
                    required=False,
                    default_value=20000,
                    verify_function=lambda x: 69 <= x <= 3600000),
        ]

        property_list = [
            ChannelSourceDeviceProperty(name='debug_mode',
                                        type=Boolean,
                                        initial=Sample(timestamp=0,
                                                       value=Boolean(False),
                                                       unit='bool'),
                                        perms_mask=DPROP_PERM_GET
                                        | DPROP_PERM_SET,
                                        options=DPROP_OPT_AUTOTIMESTAMP,
                                        set_cb=self.__handle_debug),
        ]

        # network debug mode flag
        self.__debug = False
        self.__debug_lock = threading.RLock()

        DigiMeshDeviceManager.__init__(self, name, core_services,
                                       settings_list, property_list)
コード例 #7
0
    def message_indication(self, buf):
        self._tracer.calls("message indication.")

        self.__response_buffer += buf

        if len(self.__response_buffer) < 6:
            # Response may have been fragmented, so wait for more pieces
            self._tracer.debug("Received incomplete data")
            return

        # we have our response, move state to IDLE
        self.__mode = self.MODE_IDLE

        dct = self.__sensor.ind_status_3(buf)
        if self._tracer.debug:
            self._tracer.debug('parsed ind: %s', str(dct))

        now = digitime.time()
        if dct.has_key('error'):
            # then the indication failed
            self.__response_buffer = ""

        else:
            # Update our channels:
            self.__rsp_cnt += 1
            self.property_set("strength", Sample(now, dct['strength'], "%"))
            self.property_set(
                "target_detected",
                Sample(now, Boolean(dct['target_detected'], STYLE_YESNO)))
            self.property_set(
                "error_flag",
                Sample(now, Boolean(dct['sensor_error'], STYLE_YESNO)))
            self.property_set("range", Sample(now, dct['range'], "in"))
            self.property_set("temperature",
                              Sample(now, dct['temperature'], "C"))

            if self._tracer.info:
                self._tracer.info("temp=%0.1fC range=%0.1fin strength=%d%%",
                                  dct['temperature'], dct['range'],
                                  dct['strength'])

        self.update_availability(now)
        return
コード例 #8
0
    def __init__(self, name, core_services, property_list):
        self.__name = name
        self.__core = core_services
        self.__property_list = property_list

        from core.tracing import get_tracer
        self._tracer = get_tracer(name)

        ## Local State Variables:
        self.__xbee_manager = None

        self.sensor = None

        # Settings
        #
        # xbee_device_manager: must be set to the name of an XBeeDeviceManager
        #                      instance.
        # extended_address: the extended address of the XBee Watchport Sensor
        #                   device you would like to monitor.
        # sleep: True/False setting which determines if we should put the
        #        device to sleep between samples.
        # sample_rate_ms: the sample rate of the XBee adapter.
        # enable_low_battery: Force an adapter to enable support for
        #                     battery-monitor pin.
        #                     It should be only enabled if adapter is using
        #                     internal batteries. Optional, Off by default.

        settings_list = [
            Setting(
                name='sleep', type=bool, required=False,
                default_value=False),
            Setting(
                name='sample_rate_ms', type=int, required=True,
                default_value=60000,
                verify_function=lambda x: x >= 0 and x <= CYCLIC_SLEEP_EXT_MAX_MS),

            # This setting is provided for advanced users, it is not required:
            Setting(
                name='awake_time_ms', type=int, required=False,
                default_value=5000,
                verify_function=lambda x: x >= 0 and x <= 0xffff),
            Setting(
                name='enable_low_battery', type=Boolean, required=False,
                default_value=Boolean("Off", STYLE_ONOFF)),
        ]

        ## Channel Properties Definition:
        __property_list_internal = [

        ]
        property_list.extend(__property_list_internal)

        ## Initialize the XBeeBase interface:
        XBeeBase.__init__(self, self.__name, self.__core,
                                settings_list, property_list)
コード例 #9
0
    def set_valve(self, valve_name, sample):
        """
            Change the value of the given valve. Save the status of the 
            valve internally for the level calculation method.
        """

        if valve_name == VALVE_IN:
            if sample.value == Boolean(False, style=STYLE_ONOFF):
                self.valve_in_status = False
            else:
                self.valve_in_status = True
        else:
            if sample.value == Boolean(False, style=STYLE_ONOFF):
                self.valve_out_status = False
            else:
                self.valve_out_status = True

        # Set the corresponding valve channel with the given sample value
        self.property_set(valve_name,
                          Sample(0, Boolean(sample.value, style=STYLE_ONOFF)))
コード例 #10
0
    def upload_now(self, sample, snapshot):
        '''
        Force a snapshot/samples upload now.
        '''
        if snapshot:
            channel = 'upload_snapshot'
        else:
            channel = 'upload_samples'

        if sample:
            self.property_set(channel, Sample(value=Boolean(False)))
            self.__upload_data(force=snapshot)
コード例 #11
0
ファイル: xbee_rpm.py プロジェクト: bernhara/DigiGateway4Raph
    def start(self):

        self._tracer.calls("XBeeRPM.start()")

        # init self._xbee_manager and self._extended_address
        # register ourself with our Xbee manager
        # create the self.running_indication callback
        XBeeBase.pre_start(self)

        # Create a callback specification for our device address, endpoint
        # Digi XBee profile and sample cluster id:
        self._xbee_manager.register_sample_listener(self,
                                                    self._extended_address,
                                                    self.sample_indication)

        # Create a DDO configuration block for this device:
        xbee_ddo_cfg = XBeeConfigBlockDDO(self._extended_address)

        # Configure pins DI1 .. DI3 for analog input:
        for io_pin in ['D1', 'D2', 'D3']:
            xbee_ddo_cfg.add_parameter(io_pin, 2)

        # Get the extended address of the device:
        default_state = SettingsBase.get_setting(self, 'default_state')

        if default_state != 'same':
            # Configure pin DI4 for digital output, default state setting:
            self.prop_set_power_control(
                Sample(0, str(Boolean(default_state, STYLE_ONOFF))))
        else:
            self.property_set('power_on', Sample(0, UNKNOWN_POWER_STATE))

        # Configure the IO Sample Rate:
        sample_rate = SettingsBase.get_setting(self, 'sample_rate_ms')
        xbee_ddo_cfg.add_parameter('IR', sample_rate)

        # new method for mesh health monitoring
        self.set_data_update_rate_seconds(sample_rate / 1000)

        # Handle subscribing the devices output to a named channel,
        # if configured to do so:
        power_on_source = SettingsBase.get_setting(self, 'power_on_source')
        if power_on_source is not None:
            cm = self._core.get_service('channel_manager')
            cp = cm.channel_publisher_get()
            cp.subscribe(power_on_source, self.update_power_state)

        # Register this configuration block with the XBee Device Manager:
        self._xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg)

        # we've no more to config, indicate we're ready to configure.
        return XBeeBase.start(self)
コード例 #12
0
ファイル: xbee_RCS.py プロジェクト: bernhara/DigiGateway4Raph
    def serial_receive(self, buf, addr):
        # Parse the I/O sample:
        self.__tracer.debug("serialReceive:%s", repr(buf))
        # Update channels:
        self.property_set("serialReceive", Sample(0, buf, ""))

        d = self._parse_return_message(buf)

        if d.has_key("T"):
            self.property_set("current_temp",
                              Sample(0, value=int(d["T"]), unit="F"))
        if d.has_key("SP"):
            self.property_set("set_point_temp",
                              Sample(0, value=int(d["SP"]), unit="F"))
        if d.has_key("SPH"):
            self.property_set("set_point_high_temp",
                              Sample(0, value=int(d["SPH"]), unit="F"))
        if d.has_key("SPC"):
            samp = Sample(0, value=int(d["SPC"]), unit="F")
            self.property_set("set_point_low_temp", samp)
        if d.has_key("M"):
            self.property_set("mode", \
                Sample(0, value=d["M"], unit="o/h/c/a"))
        if d.has_key("FM"):
            self.property_set(
                "fan",
                Sample(0, value=Boolean(bool(int(d["FM"])),
                                        style=STYLE_ONOFF)))

        # This next bit deciedes the 'state' of the thermostat.
        # Similar to 'mode', but depends on the set points and temperature
        if(self.property_get("mode").value == 'Cool' and
            self.property_get("set_point_low_temp").value <\
            self.property_get("current_temp").value):
            c = 'Cool'
        elif(self.property_get("mode").value == 'Heat' and \
            self.property_get("set_point_high_temp").value >\
                self.property_get("current_temp").value):
            c = 'Heat'
        else:
            c = 'Off'

        self.property_set("state", Sample(0, value=c, unit="o/h/c/a"))
コード例 #13
0
ファイル: xbee_rpm.py プロジェクト: bernhara/DigiGateway4Raph
    def prop_set_power_control(self, bool_sample):
        '''
        Set the power on the device and the power_on property.
        '''
        power_on = Boolean(bool_sample.value, style=STYLE_ONOFF)
        if power_on:
            ddo_io_value = POWER_ON
            self.__power_on_time = digitime.time()
        else:
            ddo_io_value = POWER_OFF

        try:
            self._xbee_manager.xbee_device_ddo_set_param(
                self._extended_address, 'D4', ddo_io_value, apply=True)
            self.property_set("power_on", Sample(0, str(power_on)))
            if self._tracer.info():
                self._tracer.info('Power going %r at %s', power_on,
                                  digitime.asctime())
        except:
            self._tracer.debug(traceback.format_exc())
コード例 #14
0
    def prop_set_led(self, led_name, sample):

        self._tracer.calls("XBeeXBIB.prop_set_led(%s, %s)", led_name, sample)

        now = digitime.time()

        ddo_io_value = 0  # I/O high impedance
        if sample.value:
            ddo_io_value = 4  # I/O sinking

        led_io = LED_IO_MAP[led_name]

        self._extended_address = SettingsBase.get_setting(
            self, "extended_address")

        # we want to allow the exception to propogate to the caller
        self._xbee_manager.xbee_device_ddo_set_param(self._extended_address,
                                                     led_io,
                                                     ddo_io_value,
                                                     apply=True)
        val = Boolean(sample.value, style=STYLE_ONOFF)
        self.property_set(led_name, Sample(now, val))
        self._tracer.info('%s is now %r', led_name, val)
コード例 #15
0
    def start(self):

        # Fetch the XBee Manager name from the Settings Manager:
        xbee_manager_name = SettingsBase.get_setting(self,
                                                     "xbee_device_manager")
        dm = self.__core.get_service("device_driver_manager")
        self.__xbee_manager = dm.instance_get(xbee_manager_name)

        # Register ourselves with the XBee Device Manager instance:
        self.__xbee_manager.xbee_device_register(self)

        # Create a callback specification that calls back this driver when
        # our device has left the configuring state and has transitioned
        # to the running state:
        xbdm_running_event_spec = XBeeDeviceManagerRunningEventSpec()
        xbdm_running_event_spec.cb_set(self.running_indication)
        self.__xbee_manager.xbee_device_event_spec_add(
            self, xbdm_running_event_spec)

        extended_address = None

        my_address = ':'.join(
            ["%02x" % ord(b) for b in ''.join(gw_extended_address_tuple())])
        my_address = '[' + my_address + ']!'

        # Create a callback specification for our device address, endpoint
        # Digi XBee profile and sample cluster id:
        xbdm_rx_event_spec = XBeeDeviceManagerRxEventSpec()
        xbdm_rx_event_spec.cb_set(self.sample_indication)
        xbdm_rx_event_spec.match_spec_set((my_address, 0xe8, 0xc105, 0x92),
                                          (False, True, True, True))
        self.__xbee_manager.xbee_device_event_spec_add(self,
                                                       xbdm_rx_event_spec)

        # Create a DDO configuration block for this device:
        xbee_ddo_cfg = XBeeConfigBlockDDO(extended_address)

        # Get the gateway's extended address:
        gw_xbee_sh, gw_xbee_sl = gw_extended_address_tuple()

        # Set the destination for I/O samples to be the gateway:
        xbee_ddo_cfg.add_parameter('DH', gw_xbee_sh)
        xbee_ddo_cfg.add_parameter('DL', gw_xbee_sl)

        # Configure pins DIO0 .. DIO3 for digital input:
        pr = 0xe1  # DIO0-3 pullups off, all else on
        ic = 0

        for io_pin in range(4):
            dir = SettingsBase.get_setting(self,
                                           'channel%d_dir' % (io_pin + 1))
            dir = dir.lower()

            # Enable input on all pins:
            xbee_ddo_cfg.add_parameter(self.DIO_CONTROL_LINES[io_pin], 3)

            # Build our change detection mask for all io pins:
            ic |= 1 << self.INPUT_CHANNEL_TO_PIN[io_pin]

            if dir == 'in':
                # Disable sinking driver output:
                pass

            elif dir == 'out':
                # Create the output channel for this IO pin:
                self.add_property(
                    ChannelSourceDeviceProperty(
                        name='channel%d_output' % (io_pin+1), type=bool,
                        initial=Sample(timestamp=0, value=False, unit='bool'),
                        perms_mask=(DPROP_PERM_GET|DPROP_PERM_SET),
                        options=DPROP_OPT_AUTOTIMESTAMP,
                        set_cb=lambda sample, io=io_pin: \
                                self.set_output(sample, io) )
                    )

                # Set initial value of output to low:
                digihw.configure_channel(io_pin, self.DIO_MODE_OUTPUT_LOW)

                # If set, subscribe to the channel that drives our output logic:
                source = SettingsBase.get_setting(
                    self, 'channel%d_source' % (io_pin + 1))

                if len(source):
                    if source == "True":
                        sample = Sample(digitime.time(),
                                        Boolean(True, style=STYLE_TF))
                        self.set_output(sample, io_pin)
                    elif source == "False":
                        sample = Sample(digitime.time(),
                                        Boolean(False, style=STYLE_TF))
                        self.set_output(sample, io_pin)
                    else:
                        cm = self.__core.get_service("channel_manager")
                        cp = cm.channel_publisher_get()
                        cp.subscribe(
                            source,
                            lambda chan, io=io_pin: self.update(chan, io))

        # Enable I/O line monitoring on pins DIO0 .. DIO3 &
        # enable change detection on DIO11:
        #
        # 0x   8    0    0
        #   1000 0000 0000 (b)
        #   DDDD DDDD DDDD
        #   IIII IIII IIII
        #   OOOO OOOO OOOO
        #   1198 7654 3210
        #   10
        #
        xbee_ddo_cfg.add_parameter('IC', ic)

        # Disable any periodic I/O sampling:
        xbee_ddo_cfg.add_parameter('IR', 0)

        # Register this configuration block with the XBee Device Manager:
        self.__xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg)

        # Indicate that we have no more configuration to add:
        self.__xbee_manager.xbee_device_configure(self)

        return True
コード例 #16
0
    def __init__(self, name, core_services):

        # these variables created by DeviceBase
        # self._name, self._core, self._tracer

        self.__stopevent = core_services
        self.__subscribed_channels = []

        # key: channel name
        # val: duple (type, list of samples from that channel)
        self.__upload_queue = {}
        self._stats_file = StatsFile()
        TRACER.debug("initial statsfile: %s", self._stats_file)

        self.channel_blacklist = (''.join((name, '.upload_samples')), ''.join(
            (name, '.upload_snapshot')))

        self.__entry_lock = threading.Lock()
        self.__sample_count = 0
        self.__sample_sync = digitime.time()

        chm = core_services.get_service("channel_manager")
        self.__cp = chm.channel_publisher_get()
        self.__cdb = chm.channel_database_get()

        self.methods = {
            DBF_11: self.__make_xml,
            DBF_FULL: self.__make_full_xml,
            DBF_COMPACT: self.__make_compact_xml
        }

        # Properties
        # ----------
        # upload_now: Boolean which forces an upload now if set to true.
        #     It automatically resets to false.

        # Settings
        # --------
        # initial_upload: is the number of seconds before the first initial
        #     upload.  If it is not specified, initial upload is disabled.
        #     The initial upload is handled before normal interval and
        #     sample_threshold processing. If you set the initial upload
        #     for 600 (10 minutes), after ten minutes, the first samples
        #     will be uploaded. Then normal processing will occur.
        #
        # interval: is the maximum interval in seconds that this
        #     module waits before sending all collected samples
        #     to the Device Cloud Database. This timer can be reset
        #     by three different methods:
        #         1) forced upload (by setting "update_now" channel to True)
        #         2) interval upload
        #         3) sample upload
        #     The timer is reset *even if these methods fail*.
        #     If interval is equal to 0, the feature is disabled.
        #
        # sample_threshold: is the mininum number of samples required before
        #     sending data to the Device Cloud Database.  If it is equal to
        #     0, the feature is disabled.
        #
        # collection: is the collection on the database where the data will
        #     be stored.
        #
        # file_count: the number of unique files we will keep on Device Cloud
        #             (and/or locally in the case of upload failure).
        #
        # filename: the name of the xml file we will push to Device Cloud, with
        #     a number appended to the end (cycling from 1 to file_count)
        #
        # legacy_time_format:
        #     use the old, non-iso format that idigi_db used
        #
        # channels: is the list of channels the module is subscribed to.
        #     If no channels are listed, all channels are subscribed to.
        #     Wildcards '*' and '?' are supported in channel names.
        #
        # upload_control: a DIA channel reference to enable or suppress uploading.
        #     String which can be None or a channel (ie "driver0.channel1").
        #     The channel should hold a boolean value. If None or the channel
        #     has a True value, then uploading takes place. If the channel is
        #     false, uploading is paused (and samples are *NOT* saved).
        #
        # compact_xml: (when set to True) will produce output XML with the
        #     information stored as attributes to the sample node instead of
        #     separately tagged, resulting in smaller XML output.
        #
        # upload_time_zero: when False, suppress upload of samples with a
        #     timestamp of 0 (1970-01-01 00:00:00). this defaults to False
        #
        # trigger_snapshot: a DIA channel reference to trigger a one-shot
        #     upload of all normal channels.

        settings_list = [
            Setting(
                name='initial_upload', type=int, required=False,
                default_value=0),
            Setting(
                name='interval', type=int, required=False,
                default_value=0),
            Setting(
                name='snapshot_interval', type=int, required=False,
                default_value=0),
            Setting(
                name='sample_threshold', type=int, required=False,
                default_value=0),
            Setting(
                name='collection', type=str, required=False,
                default_value=''),
            Setting(
                name="channels", type=list, required=False,
                default_value=[]),
            Setting(
                name='file_count', type=int, required=False,
                default_value=20),
            Setting(
                name='filename', type=str, required=False,
                default_value="upload"),
            Setting(
                name='upload_type', type=bool, required=False,
                default_value=True),
            Setting(
                name='legacy_time_format', type=bool, required=False,
                default_value=False),
            Setting(
                name='upload_control', type=str, required=False,
                default_value=ALWAYS_ON),
            # backwards compatibility:
            # use 'idigi_db_full' or 'idigi_db_compact'
            # as arguments to be backwards compatible with either old style
            Setting(
                name='compatibility', type=str, required=False,
                default_value=DBF_11, verify_function=lambda x: \
                x == DBF_FULL or x == DBF_COMPACT or x == DBF_11),

            Setting(
                name='upload_time_zero', type=bool, required=False,
                default_value=False),

            Setting(
                name='trigger_snapshot', type=str, required=False),
            ]

        ## Channel Properties Definition:
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(
                name='upload_snapshot',
                type=Boolean,
                perms_mask=DPROP_PERM_SET | DPROP_PERM_REFRESH,
                options=(DPROP_OPT_AUTOTIMESTAMP | DPROP_OPT_DONOTDUMPDATA),
                initial=Sample(value=Boolean(False)),
                set_cb=lambda x: self.upload_now(x, snapshot=True)),
            ChannelSourceDeviceProperty(
                name='upload_samples',
                type=Boolean,
                perms_mask=DPROP_PERM_SET | DPROP_PERM_REFRESH,
                options=(DPROP_OPT_AUTOTIMESTAMP | DPROP_OPT_DONOTDUMPDATA),
                initial=Sample(value=Boolean(False)),
                set_cb=lambda x: self.upload_now(x, snapshot=False)),
        ]

        DeviceBase.__init__(self, name, core_services, settings_list,
                            property_list)

        self.__stopevent = threading.Event()

        # Event to use for notification of meeting the sample threshold
        self.__threshold_event = threading.Event()

        # event for enabled/disabled signalling
        self.__enabled = threading.Event()
        self.__control_initialized = False

        threading.Thread.__init__(self, name=name)
        threading.Thread.setDaemon(self, True)
コード例 #17
0
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services

        ## Local State Variables:
        self.__xbee_aio_driver = None
        self.__xbee_dio_driver = None

        self.__analog_channels = []
        self.__digital_channels = []

        from core.tracing import get_tracer
        self.__tracer = get_tracer(name)

        ## Settings Table Definition:

        settings_list = [
            Setting(name = 'power', type = Boolean, required = False,
                    default_value = Boolean("On", STYLE_ONOFF),
                    verify_function = self.__verify_power_setting),
            Setting(name = 'sample_rate_ms', type = int, required = False,
                   default_value = 60000,
                   verify_function = lambda x: x >= 100 and x <= 6000000),
            Setting(name = 'calibration_rate_ms', type = int, required = False,
                   default_value = 900000,
                   verify_function = lambda x: x >= 0),
        ]

        ## Channel Properties Definition:
        property_list = []

        # Dynamically create the rest of our settings based on what the device supports.
        for ch in range(0, self.IO_MAX_CHANNELS):

            # Attempt to get the channel type.
            # If we try to go beyond the amount of supported channels,
            # we will get a ValueError exception.  If we do, stop our loop.
            try:
                type = digihw.get_channel_type(ch)
                
            except ValueError:
                # we'll hit this once we go past valid count since we support 10
                # channels, but likely device like X4H only has 4
                # traceback.print_exc()
                break
                
            except:
                traceback.print_exc()

            if type == self.IO_TYPE_ANALOG:
                self.__tracer.info("Detected IO channel %d is Analog", 
                                        ch + 1)
                self.__analog_channels.append(ch)

                settings_list.append(Setting(
                    name = 'channel%d_mode' % (ch + 1), 
                    type=str, required=False,
                    verify_function = _verify_aio_channel_mode,
                    default_value = self.LOCAL_AIO_MODE_TENV))

            elif type == self.IO_TYPE_DIGITAL:
                self.__tracer.info("Detected IO channel %d is Digital", 
                                        ch + 1)
                self.__digital_channels.append(ch)

                settings_list.append(Setting(
                    name = 'channel%d_dir' % (ch + 1), type = str,
                    required=False,
                    default_value='in'))
                settings_list.append(Setting(
                    name = 'channel%d_source' % (ch + 1), type = str,
                    required = False,
                    default_value=''))
                    
            else:
                raise "Unknown IO hardware type channel %d, is %d" % \
                            ((ch + 1), type)

        # Finally, on some platforms, the AIO and DIO support is done by
        # the XBee radio inside the unit.
        #
        # If this is the case, we will need to also have the
        # 'xbee_device_manager' setting provided to us as well.
        if get_platform_name() == 'digix3':
            settings_list.append(Setting(name='xbee_device_manager',
                                         type = str, required = True))
            self.__xbee_aio_driver = self.__xbee_dio_driver = \
                                     XBeeLocalIO(self, core_services,
                                         self.__analog_channels,
                                         self.__digital_channels)
        elif get_platform_name() == 'digiconnect':
            settings_list.append(Setting(name='xbee_device_manager',
                                         type = str, required = True))
            self.__xbee_aio_driver = self.__xbee_dio_driver = \
                                     XBeeLocalIO(self, core_services,
                                         self.__analog_channels,
                                         self.__digital_channels)

        ## Initialize the DeviceBase interface:
        DeviceBase.__init__(self, self.__name, self.__core,
                                settings_list, property_list)
コード例 #18
0
    def __init__(self, name, core_services, set_in=None, prop_in=None):
        """\
            Initialize an XBee Wall Router instance.

            Parameters:
                * name - The name of the XBee Wall Router instance.
                * core - The Core services instance.
                * set_in - settings from a derived class
                * prop_in - properties from a derived class

        """

        # DeviceBase will create:
        #   self._name, self._core, self._tracer,
        # XBeeBase will create:
        #   self._xbee_manager, self._extended_address

        # Settings
        #
        # sleep: True/False setting which determines if we should put the
        #        device to sleep between samples.
        # sample_rate_ms: the sample rate of the XBee adapter.
        # power: True/False setting to enable/disable the power output
        #        on terminal 6 of the adapter.
        #
        # raw_value: On/Off; On makes output sample raw binary, Off for scaled
        #            output.  Defaults to Off/False.
        # zero_clamp: min raw binary setting to call zero; if zero is disabled,
        #             else forces low values to zero.
        # channel1_mode: Operating input mode for pin 1 of the adapter.
        #                Must be a string value comprised of one of
        #                the following:
        #                "TenV" - 0-10v input available on any channel.
        #                "CurrentLoop" - 0-20 mA current loop available on
        #                                any channel.
        #                "Differential" - +/- 2.4a differential current mode
        #                                 enabled on channel1 & channel2 or
        #                                 channel3 & channel4.
        # channel2_mode: Operating input mode for pin 2 of the adapter.
        #                See channel1_mode for valid setting information.
        # channel3_mode: Operating input mode for pin 3 of the adapter.
        #                See channel1_mode for valid setting information.
        # channel4_mode: Operating input mode for pin 4 of the adapter.
        #                See channel1_mode for valid setting information.
        # awake_time_ms: How many milliseconds should the device remain
        #                awake after waking from sleep.
        # sample_predelay: How long, in milliseconds, to wait after waking
        #                  up from sleep before taking a sample from the
        #                  inputs.
        # enable_low_battery: Force an adapter to enable support for
        #                     battery-monitor pin.
        #                     It should be only enabled if adapter is using
        #                     internal batteries. Optional, Off by default.
        settings_list = [
            Setting(
                name='sleep', type=bool, required=False,
                default_value=False),
            Setting(
                name='sample_rate_ms', type=int, required=False,
                default_value=60000,
                verify_function=lambda x: x >= 0 and \
                                x <= CYCLIC_SLEEP_EXT_MAX_MS),
            Setting(
                name='power', type=Boolean, required=False,
                default_value=Boolean("On", STYLE_ONOFF)),
            Setting(
                name='raw_value', type=Boolean, required=False,
                default_value=Boolean("Off", STYLE_ONOFF)),
            Setting(
                name='zero_clamp', type=int, required=False,
                default_value=0, verify_function=lambda x: x >= 0),
            Setting(
                name=self.CHN_MODE_NAME[0], type=str, required=False,
                verify_function=_verify_channel_mode,
                default_value=AIO_MODE_TENV),
            Setting(
                name=self.CHN_MODE_NAME[1], type=str, required=False,
                verify_function=_verify_channel_mode,
                default_value=AIO_MODE_TENV),
            Setting(
                name=self.CHN_MODE_NAME[2], type=str, required=False,
                verify_function=_verify_channel_mode,
                default_value=AIO_MODE_TENV),
            Setting(
                name=self.CHN_MODE_NAME[3], type=str, required=False,
                verify_function=_verify_channel_mode,
                default_value=AIO_MODE_TENV),

            # These settings are provided for advanced users, they are
            # not required:
            Setting(
                name='awake_time_ms', type=int, required=False,
                default_value=5000,
                verify_function=lambda x: x >= 0 and x <= 0xffff),
            Setting(
                name='sample_predelay', type=int, required=False,
                default_value=1000,
                verify_function=lambda x: x >= 0 and x <= 0xffff),
            Setting(
                name='enable_low_battery', type=Boolean, required=False,
                default_value=Boolean("Off", STYLE_ONOFF)),
        ]
        # Add our settings_list entries into the settings passed to us.
        set_in = self.merge_settings(set_in, settings_list)

        ## Channel Properties Definition:
        property_list = [
            ChannelSourceDeviceProperty(name=self.CHN_VALUE_NAME[0],
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="V",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name=self.CHN_VALUE_NAME[1],
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="V",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name=self.CHN_VALUE_NAME[2],
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="V",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name=self.CHN_VALUE_NAME[3],
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="V",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        # Add our property_list entries into the properties passed to us.
        prop_in = self.merge_properties(prop_in, property_list)

        ## Initialize the XBeeBase interface:
        XBeeBase.__init__(self, name, core_services, set_in, prop_in)

        self._tracer.calls("XBeeAIO.__init__()")
コード例 #19
0
    def __init__(self, name, core_services, set_in=None, prop_in=None):
        """\
            Initialize an XBee Wall Router instance.

            Parameters:
                * name - The name of the XBee Wall Router instance.
                * core - The Core services instance.
                * set_in - settings from a derived class
                * prop_in - properties from a derived class

        """

        # DeviceBase will create:
        #   self._name, self._core, self._tracer,
        # XBeeBase will create:
        #   self._xbee_manager, self._extended_address

        ## Settings Table Definition:

        settings_list = [
            Setting(
                name='sleep_ms', type=int, required=False,
                default_value=self.DEF_SLEEP_MS,
                verify_function=lambda x: x >= 0 and \
                                x <= CYCLIC_SLEEP_EXT_MAX_MS),
            Setting(name="led1_source", type=str, required=False),
            Setting(name="led2_source", type=str, required=False),
            Setting(name="led3_source", type=str, required=False),
            # This setting is provided for advanced users:
            Setting(
                name='awake_time_ms', type=int, required=False,
                default_value=self.DEF_AWAKE_MS,
                verify_function=lambda x: x >= 0 and x <= 0xffff),
        ]
        # Add our settings_list entries into the settings passed to us.
        set_in = self.merge_settings(set_in, settings_list)

        ## Channel Properties Definition:
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(name="sw1",
                                        type=bool,
                                        initial=Sample(timestamp=0,
                                                       value=False),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="sw2",
                                        type=bool,
                                        initial=Sample(timestamp=0,
                                                       value=False),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="sw3",
                                        type=bool,
                                        initial=Sample(timestamp=0,
                                                       value=False),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="sw4",
                                        type=bool,
                                        initial=Sample(timestamp=0,
                                                       value=False),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            # gettable and settable properties
            ChannelSourceDeviceProperty(
                name="led1",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.prop_set_led("led1", sample)),
            ChannelSourceDeviceProperty(
                name="led2",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.prop_set_led("led2", sample)),
            ChannelSourceDeviceProperty(
                name="led3",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.prop_set_led("led3", sample)),
        ]
        # Add our property_list entries into the properties passed to us.
        prop_in = self.merge_properties(prop_in, property_list)

        ## Initialize the XBeeBase interface:
        XBeeBase.__init__(self, name, core_services, set_in, prop_in)

        self._tracer.calls("XBeeXBIB.__init__()")
コード例 #20
0
    def message_indication(self, buf, addr):
        self.__tracer.debug("message indication.")
        self.__response_buffer += buf

        if len(self.__response_buffer) < 6:
            # We may need to just give the network a bit more time
            # but just in case, reschedule the retry event now:
            self.__reschedule_retry_watchdog()
            return

        bus_id = 0
        strength = 0.00
        target_detected = False
        error_flag = False
        range = 0
        temperature = 0
        checksum_good = False

        response = self.__response_buffer[0:6]
        self.__response_buffer = self.__response_buffer[6:]
        response = struct.unpack("6B", response)

        # Parse the response packet:

        bus_id = response[0]

        b = (response[1] & 0xf0) >> 4
        strength_tab = { 0x1: 25, 0x2: 50, 0x3: 75, 0x4: 100 }
        if b in strength_tab:
            strength = strength_tab[b]
        else:
            strength = 0

        b = (response[1] & 0xf)
        if (b & 0x8):
            target_detected = True
#	    if (b & 0x4):
#		vout_mode = True
#	    if (b & 0x2):
#		switch_mode = True
        if (b & 0x1):
            error_flag = True

        range = ((response[3] << 8) | response[2]) / 128
        temperature = (response[4] * 0.48876) - 50

        if (sum(response[0:5]) % 256 == response[5]):
            checksum_good = True

        if not checksum_good:
            # Ick!  The RS-485 reply packets may not been packetized
            # in the proper sequence.  Flush the buffer.
            self.__response_buffer = ""
        else:
            # Update our channels:
            self.property_set("strength", Sample(0, strength, "%"))
            self.property_set("target_detected",
                Sample(0, Boolean(target_detected, STYLE_YESNO)))
            self.property_set("error_flag",
                Sample(0, Boolean(error_flag, STYLE_YESNO)))
            self.property_set("range", Sample(0, range, "in"))
            self.property_set("temperature", Sample(0, temperature, "C"))
            self.__tracer.debug("temp=%0.1fC range=%0.1fin strength=%d%%",
                temperature, range, strength)

        # Schedule our next poll:
        self.__schedule_request()
        # Reschedule retry watchdog:
        self.__reschedule_retry_watchdog()
コード例 #21
0
    def __init__(self, name, core_services):

        ## These will be created by XBeeSerial
        # self._name = name
        # self._core = core_services
        # self._tracer = get_tracer(name)
        # self._xbee_manager = None
        # self._extended_address = None

        ## Local State Variables:
        self.__response_buffer = ""
        self.__request_event = None
        self.__mode = self.MODE_IDLE
        self.__req_cnt = 0
        self.__rsp_cnt = 0
        self.__sensor = None

        ## Over-ride our parent's settings
        self.DEF_BAUDRATE = 19200
        self.DEF_PARITY = 'none'
        self.DEF_STOPBITS = 1
        self.DEF_HWFLOW = '485'

        ## Settings Table Definition:
        settings_list = [
            Setting(name='poll_rate_sec',
                    type=int,
                    required=False,
                    default_value=5,
                    verify_function=lambda x: x >= 1),
            Setting(name='bus_id',
                    type=int,
                    required=False,
                    default_value=1,
                    verify_function=lambda x: x >= 0),
        ]

        ## Channel Properties Definition:
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(name="strength",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       value=0,
                                                       unit="%"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="target_detected",
                                        type=Boolean,
                                        initial=Sample(timestamp=0,
                                                       value=Boolean(
                                                           False,
                                                           style=STYLE_YESNO)),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="error_flag",
                                        type=Boolean,
                                        initial=Sample(timestamp=0,
                                                       value=Boolean(
                                                           False,
                                                           style=STYLE_YESNO)),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="range",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       value=0.0,
                                                       unit="in"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="temperature",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       value=0.0,
                                                       unit="C"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="availability",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       value=0.0,
                                                       unit="prc"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        ## Initialize the DeviceBase interface:
        ## Initialize the XBeeSerial interface:
        XBeeSerial.__init__(self, name, core_services, settings_list,
                            property_list)

        self._tracer.calls("MassaM300.__init__()")
コード例 #22
0
ファイル: xbee_rpm.py プロジェクト: bernhara/DigiGateway4Raph
    def sample_indication(self, buf, addr):

        self._tracer.calls("XBeeRPM.sample_indication()")

        # save time of last data, plus we want ALL of the samples to have
        # exact same timestamp (leaving 0 means some may be 1 second newer)
        self._last_timestamp = digitime.time()

        # new method for mesh health monitoring
        self.set_time_of_last_data(self._last_timestamp)

        # if we haven't gotten initial state yet, ask for it
        if self.property_get('power_on').value == UNKNOWN_POWER_STATE:
            if not self._set_initial_power_state():
                self._tracer.warning('Power state unknown, ignoring '
                                     'sample indication.')
                return

        # Parse the I/O sample:
        io_sample = parse_is(buf)

        # Calculate channel values:
        light_mv, temperature_mv, current_mv = \
            map(lambda cn: sample_to_mv(io_sample[cn]),
                ('AD1', 'AD2', 'AD3'))
        light = round(light_mv, 0)
        if light < 0:
            # clamp to be zero or higher
            light = 0

        power_state = Boolean(self.property_get("power_on").value,
                              style=STYLE_ONOFF)

        # TODO: CRA Max could you remove this offset code?  Change to
        # clip at 0.
        if not power_state:
            self.offset = current_mv * (157.0 / 47.0)
            if self.offset >= 600.0:
                # Probably a current spike from flipping the power relay
                self.offset = 520.0

        current = round((current_mv * (157.0 / 47.0) - self.offset) \
                        / 180.0 * 0.7071, 3)

        pf_adj = self.get_power_factor()
        # compute powerfactor adjusted current
        if 1.0 >= pf_adj and 0.0 <= pf_adj:
            current *= pf_adj

        if current <= 0.05:
            # Clip the noise at the bottom of this sensor:
            current = 0.0
        temperature = (temperature_mv - 500.0) / 10.0
        # self-heating correction
        temperature = (temperature - 4.0) - \
                      (0.017 * current ** 2 + 0.631 * current)

        if SettingsBase.get_setting(self, "degf"):
            temperature = (temperature * 1.8) + 32.0
            units = 'F'
        else:
            units = 'C'

        temperature = round(temperature, 2)

        # Update channels:
        self.property_set("light",
                          Sample(self._last_timestamp, light, "brightness"))
        self.property_set("temperature",
                          Sample(self._last_timestamp, temperature, units))
        self.property_set("current", Sample(self._last_timestamp, current,
                                            "A"))

        ## Check if sample has information about the power state
        if io_sample.has_key('AD4'):
            ## Define it as a boolean
            compare_state = Boolean(io_sample['AD4'], style=STYLE_ONOFF)

            ## compare to current power_state
            if not compare_state == power_state:
                ## It's different, set the power state to the new value
                self._tracer.warning("Power state was: %s, but now it is: %s" %
                                     (power_state, compare_state))
                self._tracer.warning("Returning power state to: %s" %
                                     (power_state))

                self.prop_set_power_control(Sample(0, str(power_state)))

        if self._tracer.info():
            self._tracer.info('Power:%r light:%d %0.1f%s %0.2fA', power_state,
                              light, temperature, units, current)

        # check the realtime clock and compare to the last power_on_time
        # turn off if the idle_off_setting has been met or exceeded
        idle_off_setting = SettingsBase.get_setting(self, "idle_off_seconds")
        if (power_state and idle_off_setting > 0):
            if ((digitime.time() - self.__power_on_time) \
                >= idle_off_setting):
                power_on_state_bool = self.property_get("power_on")
                power_on_state_bool.value = False
                self.prop_set_power_control(power_on_state_bool)
                self._tracer.debug('Idle Off True')
コード例 #23
0
ファイル: xbee_rpm.py プロジェクト: bernhara/DigiGateway4Raph
    def __init__(self, name, core_services, set_in=None, prop_in=None):

        # DeviceBase will create:
        #   self._name, self._core, self._tracer,
        # XBeeBase will create:
        #   self._xbee_manager, self._extended_address

        ## XBeeBase manages these settings:
        #   xbee_device_manager: the name of an XBeeDeviceManager instance.
        #   extended_address:    the extended address of the XBee device you
        #                            would like to monitor.

        ## Local State Variables:
        self._last_timestamp = 0
        self.offset = 520.0
        self.__power_on_time = 0

        # Settings
        #
        # xbee_device_manager: must be set to the name of an
        #                      XBeeDeviceManager instance.
        # extended_address: the extended address of the XBee device you
        #                   would like to monitor.
        # sample_rate_ms: the sample rate of the XBee SmartPlug.
        # default_state: "On"/"Off"/"Same", if "On" the plug will default to
        #                being switched on.
        # idle_off_seconds: Number of seconds to go by before forcing
        #                   power off.
        #                   If not set the value defauts to 0, which means
        #                   the device never idles out.
        # power_on_source: optional setting; string name of a Boolean
        #                  "device.channel" to be used as the state.  For
        #                  example, if set to the name of a channel which
        #                  changes value from False to True, the SmartPlug
        #                  would change from being off to on.
        # pf_adjustment: optional setting; floating point value between
        #                0 and 1, that is used to adjust the current
        #                output given a known power factor.
        #                defaults to 1 (i.e no adjustment)
        #                Note: The unit cannot determine the pf,
        #                it is strictly a user supplied value.
        # device_profile: optional setting; string value corresponding
        #                 to a preset pf_adjustment value.
        #                 These values are by not intended to be precise;
        #                 they are only estimates.
        #                 For a list of valid device_profile settings see the
        #                 check_profiles() function in the driver source.

        settings_list = [
            Setting(name='sample_rate_ms',
                    type=int,
                    required=False,
                    default_value=self.DEF_SAMPLE_MS,
                    verify_function=lambda x: x > 0 and x < 0xffff),
            Setting(name='default_state',
                    type=str,
                    required=False,
                    default_value=self.DEF_STATE,
                    parser=lambda s: s.lower(),
                    verify_function=lambda s: s in initial_states),
            Setting(name='idle_off_seconds',
                    type=int,
                    required=False,
                    default_value=self.DEF_IDLE_OFF,
                    verify_function=lambda x: x >= 0),
            Setting(name="power_on_source", type=str, required=False),
            Setting(name="pf_adjustment",
                    type=float,
                    required=False,
                    default_value=self.DEF_PF,
                    verify_function=lambda i: 0 < i and i <= 1.0),
            Setting(name="device_profile", type=str, required=False),
            Setting(name="degf",
                    type=bool,
                    required=False,
                    default_value=self.DEF_DEGF),
        ]

        # Add our settings_list entries into the settings passed to us.
        set_in = self.merge_settings(set_in, settings_list)

        ## Channel Properties Definition:
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(name="light",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="brightness",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="temperature",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="C",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="current",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       unit="A",
                                                       value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(
                name="power_on",
                type=str,
                initial=Sample(timestamp=0,
                               value=str(Boolean(True, style=STYLE_ONOFF))),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=self.prop_set_power_control),
        ]

        # Add our property_list entries into the properties passed to us.
        prop_in = self.merge_properties(prop_in, property_list)

        ## Initialize the XBeeBase interface:
        XBeeBase.__init__(self, name, core_services, set_in, prop_in)

        self._tracer.calls("XBeeRPM.__init__()")
コード例 #24
0
ファイル: xbee_dio.py プロジェクト: bernhara/DigiGateway4Raph
    def __init__(self, name, core_services, set_in=None, prop_in=None):
        """\
            Initialize an XBee Wall Router instance.

            Parameters:
                * name - The name of the XBee Wall Router instance.
                * core - The Core services instance.
                * set_in - settings from a derived class
                * prop_in - properties from a derived class

        """

        # DeviceBase will create:
        #   self._name, self._core, self._tracer,
        # XBeeBase will create:
        #   self._xbee_manager, self._extended_address

        # Settings
        #
        # sleep: True/False setting which determines if we should put the
        #        device to sleep between samples.
        # sleep_time_ms: If set for sleep, specifies the length of time that
        #                the module will sleep after a period of awake_time_ms
        #                each cycle.
        # sample_rate_ms: If set, then value is loaded into IR to
        #                 cause period data updated regardless of
        #                 change.  Also, if non-zero then samples are
        #                 always updated (timestamp refreshed)
        #                 even if there was no change.
        #                 (Is Optional, defaults to 0/off, valid range 0-60000)
        # power: True/False setting to enable/disable the power output
        #        on terminal 6 of the adapter.
        # channel1_dir: Operating I/O mode for pin 1 of the adapter.
        #               Must be a string value comprised of one of the
        #               following:
        #                   "In" - pin is configured to be an input.
        #                   "Out" - pin is configured to be an output.
        # channel2_dir: Operating I/O mode for pin 2 of the adapter.
        #               See channel1_dir for valid setting information.
        # channel3_dir: Operating I/O mode for pin 3 of the adapter.
        #               See channel1_dir for valid setting information.
        # channel4_dir: Operating I/O mode for pin 4 of the adapter.
        #               See channel1_dir for valid setting information.
        # channel1_source: If channel1_dir is configured as an output, this
        #                  option setting may be specified to a
        #                  "device.channel" channel name.  The Boolean value
        #                  of this channel will specify to logic state for
        #                  pin 1 on the adapter.
        # channel2_source: Configures output value source channel for pin 2
        #                  of the adapter.
        #                  See channel1_source setting information.
        # channel3_source: Configures output value source channel for pin 3
        #                  of the adapter.
        #                  See channel1_source setting information.
        # channel4_source: Configures output value source channel for pin 4
        #                  of the adapter.
        #                   See channel1_source setting information.
        # awake_time_ms: How many milliseconds should the device remain
        #                awake after waking from sleep.
        # sample_predelay: How long, in milliseconds, to wait after waking
        #                  up from sleep before taking a sample from the
        #                  inputs.
        # enable_low_battery: Force an adapter to enable support for
        #                     battery-monitor pin.
        #                     It should be only enabled if adapter is using
        #                     internal batteries. Optional, Off by default.

        settings_list = [
            Setting(
                name='sleep', type=Boolean, required=False,
                default_value=Boolean(False)),
            Setting(
                name='sample_rate_ms', type=int, required=False,
                default_value=0,
                verify_function=lambda x: x == 0 or \
                            CYCLIC_SLEEP_MIN_MS <= x <= 60000),
           Setting(
                name='sleep_time_ms', type=int, required=False,
                default_value=60000,
                verify_function=lambda x: x >= 0 and \
                                x <= CYCLIC_SLEEP_EXT_MAX_MS),
            Setting(
                name='power', type=Boolean, required=False,
                default_value=Boolean("On", STYLE_ONOFF)),
            Setting(
                name='channel1_dir', type=str, required=False,
                default_value='In'),
            Setting(
                name='channel1_default', type=Boolean, required=False),
            Setting(
                name='channel1_source', type=str, required=False,
                default_value=''),
            Setting(
                name='channel2_dir', type=str, required=False,
                default_value='In'),
            Setting(
                name='channel2_default', type=Boolean, required=False),
            Setting(
                name='channel2_source', type=str, required=False,
                default_value=''),
            Setting(
                name='channel3_dir', type=str, required=False,
                default_value='In'),
            Setting(
                name='channel3_default', type=Boolean, required=False),
            Setting(
                name='channel3_source', type=str, required=False,
                default_value=''),
            Setting(
                name='channel4_dir', type=str, required=False,
                default_value='In'),
            Setting(
                name='channel4_default', type=Boolean, required=False),
            Setting(
                name='channel4_source', type=str, required=False,
                default_value=''),

            # This setting is provided for advanced users, it is not required:
            Setting(
                name='awake_time_ms', type=int, required=False,
                default_value=5000,
                verify_function=lambda x: x >= 0 and x <= 0xffff),
            Setting(
                name='sample_predelay', type=int, required=False,
                default_value=1000,
                verify_function=lambda x: x >= 0 and x <= 0xffff),
            Setting(
                name='enable_low_battery', type=Boolean, required=False,
                default_value=Boolean("Off", STYLE_ONOFF)),
        ]
        # Add our settings_list entries into the settings passed to us.
        set_in = self.merge_settings(set_in, settings_list)

        ## Channel Properties Definition:
        # This device hardware can monitor the state of its output
        # pins.  Therefore, there are always four input channels.
        # The other properties and channels will be populated when we
        # know the directions of our IO ports.
        property_list = [
            ChannelSourceDeviceProperty(
                name=self.CHN_INPUT_NAME[0], type=bool,
                initial=Sample(timestamp=0, value=False, unit='bool'),
                perms_mask=DPROP_PERM_GET,
                options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(
                name=self.CHN_INPUT_NAME[1], type=bool,
                initial=Sample(timestamp=0, value=False, unit='bool'),
                perms_mask=DPROP_PERM_GET,
                options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(
                name=self.CHN_INPUT_NAME[2], type=bool,
                initial=Sample(timestamp=0, value=False, unit='bool'),
                perms_mask=DPROP_PERM_GET,
                options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(
                name=self.CHN_INPUT_NAME[3], type=bool,
                initial=Sample(timestamp=0, value=False, unit='bool'),
                perms_mask=DPROP_PERM_GET,
                options=DPROP_OPT_AUTOTIMESTAMP),
        ]
        # Add our property_list entries into the properties passed to us.
        prop_in = self.merge_properties(prop_in, property_list)

        ## Initialize the XBeeBase interface:
        XBeeBase.__init__(self, name, core_services, set_in, prop_in)

        self._tracer.calls("XBeeDIO.__init__()")
コード例 #25
0
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services

        from core.tracing import get_tracer
        self.__tracer = get_tracer(name)

        ## Settings Table Definition:
        settings_list = [
            Setting(name='volume',
                    type=int,
                    required=True,
                    default_value=5000,
                    verify_function=lambda x: x >= 1),
            Setting(name='initial_level',
                    type=int,
                    required=False,
                    default_value=50,
                    verify_function=lambda x: x >= 0 and x <= 100),
            Setting(name='initial_temperature',
                    type=int,
                    required=False,
                    default_value=12,
                    verify_function=lambda x: x >= TEMPERATURE_MIN_LIMIT and x
                    <= TEMPERATURE_MAX_LIMIT),
            Setting(name='inflow_rate',
                    type=float,
                    required=False,
                    default_value=10,
                    verify_function=lambda x: x >= 0),
            Setting(name='outflow_rate',
                    type=float,
                    required=False,
                    default_value=20,
                    verify_function=lambda x: x >= 0),
            Setting(name='min_level_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x >= 0 and x <= 100),
            Setting(name='max_level_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x > 0 and x <= 100),
            Setting(name='min_temperature_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x >= 0),
            Setting(name='max_temperature_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x >= 0),
        ]

        ## Channel Properties Definition:
        property_list = [
            ChannelSourceDeviceProperty(name="level",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       value=0,
                                                       unit="%"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="temperature",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       value=0.0,
                                                       unit="C"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(
                name="valve_in",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.set_valve(VALVE_IN, sample)),
            ChannelSourceDeviceProperty(
                name="valve_out",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.set_valve(VALVE_OUT, sample)),
            ChannelSourceDeviceProperty(name="level_alarm",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="temperature_alarm",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="virtual",
                                        type=bool,
                                        initial=Sample(timestamp=0,
                                                       value=True),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        ## Initialize the DeviceBase interface:
        DeviceBase.__init__(self, self.__name, self.__core, settings_list,
                            property_list)

        ## Thread initialization:
        self.__stopevent = threading.Event()
        threading.Thread.__init__(self, name=name)
        threading.Thread.setDaemon(self, True)
コード例 #26
0
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services

        from core.tracing import get_tracer
        self.__tracer = get_tracer(name)

        ## Settings Table Definition:
        settings_list = [
            Setting(name='serial_device',
                    type=str,
                    required=False,
                    default_value="/gps/0"),
            Setting(name='serial_baud',
                    type=int,
                    required=False,
                    default_value=4800,
                    verify_function=lambda x: x > 0.0),
            Setting(name='sample_rate_sec',
                    type=int,
                    required=False,
                    default_value=60,
                    verify_function=lambda x: x > 0.0),
        ]

        ## Channel Properties Definition:

        # Feel free to create a channel here for any item that the
        # nmea module can extract from a valid sentence.  The
        # property_setter routine will populate correctly.  You may
        # need to extend the sentence templates in nmea.py to teach
        # the library about non position based sentences and types.
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(name="fix_time",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="fix_good",
                                        type=Boolean,
                                        initial=Sample(timestamp=0,
                                                       value=Boolean(False)),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="latitude_degrees",
                                        type=float,
                                        initial=Sample(timestamp=0, value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="latitude_hemisphere",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="longitude_degrees",
                                        type=float,
                                        initial=Sample(timestamp=0, value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="longitude_hemisphere",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="speed_over_ground",
                                        type=float,
                                        initial=Sample(timestamp=0, value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="course_over_ground",
                                        type=float,
                                        initial=Sample(timestamp=0, value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="fix_date",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="num_satellites",
                                        type=int,
                                        initial=Sample(timestamp=0, value=0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="altitude",
                                        type=float,
                                        initial=Sample(timestamp=0, value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="hdop",
                                        type=float,
                                        initial=Sample(timestamp=0, value=0.0),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        ## Initialize the Devicebase interface:
        DeviceBase.__init__(self, self.__name, self.__core, settings_list,
                            property_list)

        ## Thread initialization:
        self.__stopevent = threading.Event()
        threading.Thread.__init__(self, name=name)
        threading.Thread.setDaemon(self, True)
コード例 #27
0
ファイル: xbee_RCS.py プロジェクト: bernhara/DigiGateway4Raph
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services
        self.__event_timer = None
        self.__serial_lock = Lock()

        from core.tracing import get_tracer
        self.__tracer = get_tracer(name)

        ## Local State Variables:
        self.__xbee_manager = None
        self.update_timer = None
        self.modes = {"Off": 0, "Heat": 1, "Cool": 2, "Auto": 3}

        ## Settings Table Definition:
        settings_list = [
            Setting(name='xbee_device_manager', type=str, required=True),
            Setting(name='extended_address', type=str, required=True),
            Setting(name='sample_rate_sec',
                    type=int,
                    required=False,
                    default_value=300,
                    verify_function=lambda x: x >= 10 and x < 0xffff),
        ]

        ## Channel Properties Definition:
        property_list = [
            # gettable properties
            ChannelSourceDeviceProperty(name="serialReceive",
                                        type=str,
                                        initial=Sample(timestamp=0,
                                                       unit="",
                                                       value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="serialSend",
                                        type=str,
                                        initial=Sample(timestamp=0,
                                                       unit="",
                                                       value=""),
                                        perms_mask=(DPROP_PERM_GET
                                                    | DPROP_PERM_SET),
                                        options=DPROP_OPT_AUTOTIMESTAMP,
                                        set_cb=self.serial_send),
            ChannelSourceDeviceProperty(name="current_temp",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       unit="F",
                                                       value=0),
                                        perms_mask=(DPROP_PERM_GET),
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="set_point_temp",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       unit="F",
                                                       value=75),
                                        perms_mask=(DPROP_PERM_GET
                                                    | DPROP_PERM_SET),
                                        options=DPROP_OPT_AUTOTIMESTAMP,
                                        set_cb=self.set_sp),
            ChannelSourceDeviceProperty(name="set_point_high_temp",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       unit="F",
                                                       value=80),
                                        perms_mask=(DPROP_PERM_GET
                                                    | DPROP_PERM_SET),
                                        options=DPROP_OPT_AUTOTIMESTAMP,
                                        set_cb=self.set_sph),
            ChannelSourceDeviceProperty(name="set_point_low_temp",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       unit="F",
                                                       value=65),
                                        perms_mask=(DPROP_PERM_GET
                                                    | DPROP_PERM_SET),
                                        options=DPROP_OPT_AUTOTIMESTAMP,
                                        set_cb=self.set_spc),
            ChannelSourceDeviceProperty(name="mode",
                                        type=str,
                                        initial=Sample(timestamp=0,
                                                       unit="o/h/c/a",
                                                       value="Off"),
                                        perms_mask=(DPROP_PERM_GET
                                                    | DPROP_PERM_SET),
                                        options=DPROP_OPT_AUTOTIMESTAMP,
                                        set_cb=self.set_mode),
            ChannelSourceDeviceProperty(
                name="fan",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(True, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=self.set_fan),
            ChannelSourceDeviceProperty(name="state",
                                        type=str,
                                        initial=Sample(timestamp=0,
                                                       unit="o/h/c/a",
                                                       value="Off"),
                                        perms_mask=(DPROP_PERM_GET),
                                        options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        ## Initialize the DeviceBase interface:
        DeviceBase.__init__(self, self.__name, self.__core, settings_list,
                            property_list)
コード例 #28
0
ファイル: xbee_dio.py プロジェクト: bernhara/DigiGateway4Raph
    def start(self):

        self._tracer.calls("XBeeDIO.start()")

        # init self._xbee_manager and self._extended_address
        # then register ourself with our Xbee manager
        XBeeBase.pre_start(self)

        cm = self._core.get_service("channel_manager")
        cp = cm.channel_publisher_get()
        
        self._xbee_manager.register_sample_listener(self, self._extended_address,
                                                     self.sample_indication)

        # XbeeBase enables self.running_indication

        # Create a DDO configuration block for this device:
        xbee_ddo_cfg = XBeeConfigBlockDDO(self._extended_address)

        # Configure pins DIO0 .. DIO3 for digital input:
        pr = 0xe1 # DIO0-3 pullups off, all else on
        ic = 0

        for io_pin in range(4):
            dir = SettingsBase.get_setting(self, 'channel%d_dir' % \
                                           (io_pin + 1))
            dir = dir.lower()

            # Enable input on all pins:
            xbee_ddo_cfg.add_parameter(CONTROL_LINES[io_pin][IN], 3)

            # Build our change detection mask for all io pins:
            ic |= 1 << INPUT_CHANNEL_TO_PIN[io_pin]

            if dir == 'in':
                # Disable sinking driver output:
                xbee_ddo_cfg.add_parameter(CONTROL_LINES[io_pin][OUT], 4)

            elif dir == 'out':
                # Create the output channel for this IO pin:
                self.add_property(
                    ChannelSourceDeviceProperty(
                        name=self.CHN_OUTPUT_NAME[io_pin], type=Boolean,
                        initial=Sample(timestamp=0, value=Boolean(False),
                                       unit='bool'),
                        perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                        options=DPROP_OPT_AUTOTIMESTAMP,
                        set_cb=lambda sample, io=io_pin: \
                                self.set_output(sample, io)))

                # If set, subscribe to the channel that drives our
                # output logic:
                source = SettingsBase.get_setting(self, 'channel%d_source'
                                                  % (io_pin + 1))
                if len(source):
                    cp.subscribe(source,
                                 lambda chan, io=io_pin: \
                                       self.update(chan, io))

                    self._tracer.debug("Linking DOUT %d to channel %s", io_pin+1, source)
                    
                # If not set, attempt to grab the default output setting,
                # and use that instead.
                else:
                    out = SettingsBase.get_setting(self, 'channel%d_default'
                                                   % (io_pin + 1))
                    if out == True:
                        self._tracer.debug("Setting default output to High")
                        xbee_ddo_cfg.add_parameter(CONTROL_LINES[io_pin][OUT],
                                                   5)
                    elif out == False:
                        self._tracer.debug("Setting default output to Low")
                        xbee_ddo_cfg.add_parameter(CONTROL_LINES[io_pin][OUT],
                                                   4)
                    else:
                        self._tracer.debug("Not setting default output value")

        # if adapter is using internal batteries, then configure
        # battery-monitor pin and add low_battery channel
        if SettingsBase.get_setting(self, "enable_low_battery"):
            # configure battery-monitor pin DIO11/P1 for digital input
            xbee_ddo_cfg.add_parameter('P1', 3)
            # add low_battery channel
            self._tracer.debug("Adapter is using internal batteries... " +
                               "adding low_battery channel")
            self.add_property(
                ChannelSourceDeviceProperty(name="low_battery", type=bool,
                    initial=Sample(timestamp=0, value=False),
                    perms_mask=DPROP_PERM_GET,
                    options=DPROP_OPT_AUTOTIMESTAMP))
        else:
            self._tracer.debug("Adapter is not using internal batteries.")

        # Enable I/O line monitoring on pins DIO0 .. DIO3 &
        # enable change detection on DIO11:
        #
        # 0x   8    0    0
        #   1000 0000 0000 (b)
        #   DDDD DDDD DDDD
        #   IIII IIII IIII
        #   OOOO OOOO OOOO
        #   1198 7654 3210
        #   10
        #
        xbee_ddo_cfg.add_parameter('IC', ic)

        # Assert input pull-ups
        xbee_ddo_cfg.add_parameter('PR', 0x1fff)

        # self._xbee_manager.get_sleep_block() manages 'IR'

        # Enable/disable power output on terminal 6:
        power = SettingsBase.get_setting(self, "power")
        if power:
            xbee_ddo_cfg.add_parameter('p3', 5)
        else:
            xbee_ddo_cfg.add_parameter('p3', 4)

        # Register this configuration block with the XBee Device Manager:
        self._xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg)

        # Setup the sleep parameters on this device:
        will_sleep = SettingsBase.get_setting(self, "sleep")
        sample_predelay = SettingsBase.get_setting(self, "sample_predelay")
        awake_time_ms = (SettingsBase.get_setting(self, "awake_time_ms") +
                         sample_predelay)
        # The original sample rate is used as the sleep rate:
        sleep_rate_ms = SettingsBase.get_setting(self, "sample_rate_ms")

        if sleep_rate_ms == 0 and will_sleep:
            # bounding sleep rate in when sampling is disabled and
            # sleeping is enabled
            sleep_rate_ms = CYCLIC_SLEEP_MIN_MS

        xbee_sleep_cfg = self._xbee_manager.get_sleep_block(\
            self._extended_address,
            sleep=will_sleep,
            sample_predelay=sample_predelay,
            awake_time_ms=awake_time_ms,
            sleep_rate_ms=sleep_rate_ms)

        self._xbee_manager.xbee_device_config_block_add(self, xbee_sleep_cfg)
        self._xbee_manager.xbee_device_configure(self)
        return True
コード例 #29
0
    def __init__(self, name, core_services):
        self.__name = name
        self.__core = core_services

        from core.tracing import get_tracer
        self.__tracer = get_tracer(name)

        # Settings Table Definition:
        settings_list = [
            Setting(name='tank_sensor_device',
                    type=str,
                    required=True,
                    default_value=""),
            Setting(name='input_valve_channel',
                    type=str,
                    required=True,
                    default_value=""),
            Setting(name='output_valve_channel',
                    type=str,
                    required=True,
                    default_value=""),
            Setting(name='tank_height',
                    type=float,
                    required=True,
                    default_value=2.0,
                    verify_function=lambda x: x > 0.0),
            Setting(name='min_level_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x >= 0 and x <= 100),
            Setting(name='max_level_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x > 0 and x <= 100),
            Setting(name='min_temperature_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x >= 0),
            Setting(name='max_temperature_alarm',
                    type=int,
                    required=False,
                    default_value=None,
                    verify_function=lambda x: x >= 0),
        ]

        # Channel Properties Definition:
        property_list = [
            ChannelSourceDeviceProperty(name="level",
                                        type=int,
                                        initial=Sample(timestamp=0,
                                                       value=0,
                                                       unit="%"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="temperature",
                                        type=float,
                                        initial=Sample(timestamp=0,
                                                       value=0.0,
                                                       unit="C"),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(
                name="valve_in",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.set_valve(VALVE_IN, sample)),
            ChannelSourceDeviceProperty(
                name="valve_out",
                type=Boolean,
                initial=Sample(timestamp=0,
                               value=Boolean(False, style=STYLE_ONOFF)),
                perms_mask=(DPROP_PERM_GET | DPROP_PERM_SET),
                options=DPROP_OPT_AUTOTIMESTAMP,
                set_cb=lambda sample: self.set_valve(VALVE_OUT, sample)),

            ##TODO: Max CR: level_alarm and temperature alarm should be replaced
            ## with LEVEL_ALARM and TEMPERATURE ALARM constants that are defined
            ## This will ensure that they are kept in synch at all parts of the
            ## code.
            ChannelSourceDeviceProperty(name="level_alarm",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="temperature_alarm",
                                        type=str,
                                        initial=Sample(timestamp=0, value=""),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
            ChannelSourceDeviceProperty(name="virtual",
                                        type=bool,
                                        initial=Sample(timestamp=0,
                                                       value=False),
                                        perms_mask=DPROP_PERM_GET,
                                        options=DPROP_OPT_AUTOTIMESTAMP),
        ]

        ## Initialize the DeviceBase interface:
        DeviceBase.__init__(self, self.__name, self.__core, settings_list,
                            property_list)