コード例 #1
0
ファイル: ssl_socket.py プロジェクト: dkfurrow/alarmdecoder
def main():
    """
    Example application that opens a device that has been exposed to the network
    with ser2sock and SSL encryption and authentication.
    """
    try:
        # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000.
        ssl_device = SocketDevice(interface=('localhost', 10000))

        # Enable SSL and set the certificates to be used.
        #
        # The key/cert attributes can either be a filesystem path or an X509/PKey
        # object from pyopenssl.
        ssl_device.ssl = True
        ssl_device.ssl_ca = SSL_CA              # CA certificate
        ssl_device.ssl_key = SSL_KEY            # Client private key
        ssl_device.ssl_certificate = SSL_CERT   # Client certificate

        device = AlarmDecoder(ssl_device)

        # Set up an event handler and open the device
        device.on_message += handle_message
        with device.open():
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #2
0
def create_device(device_args):
    """
    Creates an AlarmDecoder from the specified USB device arguments.

    :param device_args: Tuple containing information on the USB device to open.
    :type device_args: Tuple (vid, pid, serialnumber, interface_count, description)
    """
    device = AlarmDecoder(USBDevice.find(device_args))
    device.on_message += handle_message
    device.open()

    return device
コード例 #3
0
ファイル: lrr_example.py プロジェクト: rspier/alarmdecoder
def main():
    """
    Example application that prints messages from the panel to the terminal.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(USBDevice.find())

        # Set up an event handler and open the device
        device.on_lrr_message += handle_lrr_message
        with device.open():
            while True:
                time.sleep(1)

    except Exception, ex:
        print "Exception:", ex
コード例 #4
0
ファイル: lrr_example.py プロジェクト: dkfurrow/alarmdecoder
def main():
    """
    Example application that prints messages from the panel to the terminal.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_lrr_message += handle_lrr_message
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #5
0
def main():
    """
    Example application that opens a device that has been exposed to the network
    with ser2sock or similar serial-to-IP software.
    """
    try:
        # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000.
        device = AlarmDecoder(SocketDevice(interface=(HOSTNAME, PORT)))

        # Set up an event handler and open the device
        device.on_message += handle_message
        with device.open():
            while True:
                time.sleep(1)

    except Exception as ex:
        print('Exception:', ex)
コード例 #6
0
def main():
    """
    Example application that sends an email when an alarm event is
    detected.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(USBDevice.find())

        # Set up an event handler and open the device
        device.on_alarm += handle_alarm
        with device.open():
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #7
0
def main():
    """
    Example application that opens a device that has been exposed to the network
    with ser2sock or similar serial-to-IP software.
    """
    try:
        # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000.
        device = AlarmDecoder(SocketDevice(interface=(HOSTNAME, PORT)))

        # Set up an event handler and open the device
        device.on_message += handle_message
        with device.open():
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #8
0
ファイル: alarm_email.py プロジェクト: timlegge/alarmdecoder
def main():
    """
    Example application that sends an email when an alarm event is
    detected.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_alarm += handle_alarm
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #9
0
ファイル: alarm_email.py プロジェクト: dkfurrow/alarmdecoder
def main():
    """
    Example application that sends an email when an alarm event is
    detected.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_alarm += handle_alarm
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #10
0
ファイル: serialport.py プロジェクト: timlegge/alarmdecoder
def main():
    """
    Example application that opens a serial device and prints messages to the terminal.
    """
    try:
        # Retrieve the specified serial device.
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_message += handle_message

        # Override the default SerialDevice baudrate since we're using a USB device
        # over serial in this example.
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #11
0
    def open(self, no_reader_thread=False):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name('device_type').value
            self._device_location = Setting.get_by_name('device_location').value
            self._internal_address_mask = int(Setting.get_by_name('internal_address_mask', 'FFFFFFF').value, 16)

            if self._device_type:
                interface = ('localhost', 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == 'local':
                    devicetype = SerialDevice
                    interface = Setting.get_by_name('device_path').value
                    self._device_baudrate = Setting.get_by_name('device_baudrate').value

                elif self._device_location == 'network':
                    interface = (Setting.get_by_name('device_address').value, Setting.get_by_name('device_port').value)
                    use_ssl = Setting.get_by_name('use_ssl', False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        try:
                            ca_cert = Certificate.query.filter_by(name='AlarmDecoder CA').one()
                            internal_cert = Certificate.query.filter_by(name='AlarmDecoder Internal').one()

                            device.ssl = True
                            device.ssl_ca = ca_cert.certificate_obj
                            device.ssl_certificate = internal_cert.certificate_obj
                            device.ssl_key = internal_cert.key_obj
                        except NoResultFound, err:
                            self.app.logger.warning('No certificates found: %s', err[0], exc_info=True)
                            raise

                    self.device = AlarmDecoder(device)
                    self.device.internal_address_mask = self._internal_address_mask

                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate, no_reader_thread=no_reader_thread)

                except NoDeviceError, err:
                    self.app.logger.warning('Open failed: %s', err[0], exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning('SSL connection failed: %s - %s', fn, message, exc_info=True)
                    raise
コード例 #12
0
def main():
    """
    Example application that periodically faults a virtual zone and then
    restores it.

    This is an advanced feature that allows you to emulate a virtual zone.  When
    the AlarmDecoder is configured to emulate a zone expander we can fault and
    restore those zones programmatically at will. These events can also be seen by
    others, such as home automation platforms which allows you to connect other
    devices or services and monitor them as you would any physical zone.

    For example, you could connect a ZigBee device and receiver and fault or
    restore it's zone(s) based on the data received.

    In order for this to happen you need to perform a couple configuration steps:

    1. Enable zone expander emulation on your AlarmDecoder device by hitting '!'
       in a terminal and going through the prompts.
    2. Enable the zone expander in your panel programming.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handlers and open the device
        device.on_zone_fault += handle_zone_fault
        device.on_zone_restore += handle_zone_restore

        with device.open(baudrate=BAUDRATE):
            last_update = time.time()
            while True:
                if time.time() - last_update > WAIT_TIME:
                    last_update = time.time()

                    device.fault_zone(TARGET_ZONE)

                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #13
0
def main():
    """
    Example application that periodically faults a virtual zone and then
    restores it.

    This is an advanced feature that allows you to emulate a virtual zone.  When
    the AlarmDecoder is configured to emulate a zone expander we can fault and
    restore those zones programmatically at will. These events can also be seen by
    others, such as home automation platforms which allows you to connect other
    devices or services and monitor them as you would any pyhysical zone.

    For example, you could connect a ZigBee device and receiver and fault or
    restore it's zone(s) based on the data received.

    In order for this to happen you need to perform a couple configuration steps:

    1. Enable zone expander emulation on your AlarmDecoder device by hitting '!'
       in a terminal and going through the prompts.
    2. Enable the zone expander in your panel programming.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(USBDevice.find())

        # Set up an event handlers and open the device
        device.on_zone_fault += handle_zone_fault
        device.on_zone_restore += handle_zone_restore

        with device.open():
            last_update = time.time()
            while True:
                if time.time() - last_update > WAIT_TIME:
                    last_update = time.time()

                    device.fault_zone(TARGET_ZONE)

                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #14
0
    def open(self):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name("device_type").value
            self._device_location = Setting.get_by_name("device_location").value
            self._internal_address_mask = int(Setting.get_by_name("internal_address_mask", "FFFFFFF").value, 16)

            if self._device_type:
                interface = ("localhost", 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == "local":
                    devicetype = SerialDevice
                    interface = Setting.get_by_name("device_path").value
                    self._device_baudrate = Setting.get_by_name("device_baudrate").value

                elif self._device_location == "network":
                    interface = (Setting.get_by_name("device_address").value, Setting.get_by_name("device_port").value)
                    use_ssl = Setting.get_by_name("use_ssl", False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        ca_cert = Certificate.query.filter_by(name="AlarmDecoder CA").one()
                        internal_cert = Certificate.query.filter_by(name="AlarmDecoder Internal").one()

                        device.ssl = True
                        device.ssl_ca = ca_cert.certificate_obj
                        device.ssl_certificate = internal_cert.certificate_obj
                        device.ssl_key = internal_cert.key_obj

                    self.device = AlarmDecoder(device)
                    self.device.internal_address_mask = self._internal_address_mask

                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate)

                except NoDeviceError, err:
                    self.app.logger.warning("Open failed: %s", err[0], exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning("SSL connection failed: %s - %s", fn, message, exc_info=True)
                    raise
コード例 #15
0
ファイル: rf_device.py プロジェクト: henryse/alarmdecoder
def main():
    """
    Example application that watches for an event from a specific RF device.

    This feature allows you to watch for events from RF devices if you have
    an RF receiver.  This is useful in the case of internal sensors, which
    don't emit a FAULT if the sensor is tripped and the panel is armed STAY.
    It also will monitor sensors that aren't configured.

    NOTE: You must have an RF receiver installed and enabled in your panel
          for RFX messages to be seen.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_rfx_message += handle_rfx
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception as ex:
        print('Exception:', ex)
コード例 #16
0
ファイル: rf_device.py プロジェクト: dkfurrow/alarmdecoder
def main():
    """
    Example application that watches for an event from a specific RF device.

    This feature allows you to watch for events from RF devices if you have
    an RF receiver.  This is useful in the case of internal sensors, which
    don't emit a FAULT if the sensor is tripped and the panel is armed STAY.
    It also will monitor sensors that aren't configured.

    NOTE: You must have an RF receiver installed and enabled in your panel
          for RFX messages to be seen.
    """
    try:
        # Retrieve the first USB device
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_rfx_message += handle_rfx
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception, ex:
        print 'Exception:', ex
コード例 #17
0
ファイル: decoder.py プロジェクト: rayhe/alarmdecoder-webapp
class Decoder(object):
    """
    Primary application state
    """

    def __init__(self, app, websocket):
        """
        Constructor

        :param app: The flask application object
        :type app: Flask
        :param websocket: The websocket object
        :type websocket: SocketIOServer
        """
        with app.app_context():
            self.app = app
            self.websocket = websocket
            self.device = None
            self.updater = Updater()
            self.updates = {}

            self.trigger_reopen_device = False
            self.trigger_restart = False

            self._last_message = None
            self._device_baudrate = 115200
            self._device_type = None
            self._device_location = None
            self._event_thread = DecoderThread(self)
            self._version_thread = VersionChecker(self)
            self._notifier_system = None

    def start(self):
        """
        Starts the internal threads.
        """
        self._event_thread.start()
        self._version_thread.start()

    def stop(self, restart=False):
        """
        Closes the device, stops the internal threads, and shuts down.  Optionally
        triggers a restart of the application.

        :param restart: Indicates whether or not the application should be restarted.
        :type restart: bool
        """
        self.app.logger.info('Stopping service..')

        self.close()

        self._event_thread.stop()
        self._version_thread.stop()

        if restart:
            try:
                self._event_thread.join(5)
                self._version_thread.join(5)
            except RuntimeError:
                pass

        self.websocket.stop()

        if restart:
            self.app.logger.info('Restarting service..')
            os.execv(sys.executable, [sys.executable] + sys.argv)

    def init(self):
        """
        Initializes the application by triggering a device open if it's been
        previously configured.
        """
        with self.app.app_context():
            device_type = Setting.get_by_name('device_type').value

            if device_type:
                self.trigger_reopen_device = True

            self._notifier_system = NotificationSystem()

    def open(self):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name('device_type').value
            self._device_location = Setting.get_by_name('device_location').value

            if self._device_type:
                interface = ('localhost', 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == 'local':
                    devicetype = SerialDevice
                    interface = Setting.get_by_name('device_path').value
                    self._device_baudrate = Setting.get_by_name('device_baudrate').value

                elif self._device_location == 'network':
                    interface = (Setting.get_by_name('device_address').value, Setting.get_by_name('device_port').value)
                    use_ssl = Setting.get_by_name('use_ssl', False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        ca_cert = Certificate.query.filter_by(name='AlarmDecoder CA').one()
                        internal_cert = Certificate.query.filter_by(name='AlarmDecoder Internal').one()

                        device.ssl = True
                        device.ssl_ca = ca_cert.certificate_obj
                        device.ssl_certificate = internal_cert.certificate_obj
                        device.ssl_key = internal_cert.key_obj

                    self.device = AlarmDecoder(device)
                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate)

                except NoDeviceError, err:
                    self.app.logger.warning('Open failed: %s', err[0], exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning('SSL connection failed: %s - %s', fn, message, exc_info=True)
                    raise
コード例 #18
0
def setup(hass, config):
    """Set up for the AlarmDecoder devices."""
    from alarmdecoder import AlarmDecoder
    from alarmdecoder.devices import (SocketDevice, SerialDevice, USBDevice)

    conf = config.get(DOMAIN)

    device = conf.get(CONF_DEVICE)
    display = conf.get(CONF_PANEL_DISPLAY)
    zones = conf.get(CONF_ZONES)

    device_type = device.get(CONF_DEVICE_TYPE)
    host = DEFAULT_DEVICE_HOST
    port = DEFAULT_DEVICE_PORT
    path = DEFAULT_DEVICE_PATH
    baud = DEFAULT_DEVICE_BAUD

    def stop_alarmdecoder(event):
        """Handle the shutdown of AlarmDecoder."""
        _LOGGER.debug("Shutting down alarmdecoder")
        controller.close()

    def handle_message(sender, message):
        """Handle message from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(
            SIGNAL_PANEL_MESSAGE, message)

    def zone_fault_callback(sender, zone):
        """Handle zone fault from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(
            SIGNAL_ZONE_FAULT, zone)

    def zone_restore_callback(sender, zone):
        """Handle zone restore from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(
            SIGNAL_ZONE_RESTORE, zone)

    controller = False
    if device_type == 'socket':
        host = device.get(CONF_DEVICE_HOST)
        port = device.get(CONF_DEVICE_PORT)
        controller = AlarmDecoder(SocketDevice(interface=(host, port)))
    elif device_type == 'serial':
        path = device.get(CONF_DEVICE_PATH)
        baud = device.get(CONF_DEVICE_BAUD)
        controller = AlarmDecoder(SerialDevice(interface=path))
    elif device_type == 'usb':
        AlarmDecoder(USBDevice.find())
        return False

    controller.on_message += handle_message
    controller.on_zone_fault += zone_fault_callback
    controller.on_zone_restore += zone_restore_callback

    hass.data[DATA_AD] = controller

    controller.open(baud)

    _LOGGER.debug("Established a connection with the alarmdecoder")
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder)

    load_platform(hass, 'alarm_control_panel', DOMAIN, conf, config)

    if zones:
        load_platform(
            hass, 'binary_sensor', DOMAIN, {CONF_ZONES: zones}, config)

    if display:
        load_platform(hass, 'sensor', DOMAIN, conf, config)

    return True
コード例 #19
0
class Decoder(object):
    """
    Primary application state
    """

    def __init__(self, app, websocket):
        """
        Constructor

        :param app: The flask application object
        :type app: Flask
        :param websocket: The websocket object
        :type websocket: SocketIOServer
        """
        with app.app_context():
            self.app = app
            self.websocket = websocket
            self.device = None
            self.updater = Updater()
            self.updates = {}
            self.version = ""

            self.trigger_reopen_device = False
            self.trigger_restart = False

            self._last_message = None
            self._device_baudrate = 115200
            self._device_type = None
            self._device_location = None
            self._event_thread = DecoderThread(self)
            self._version_thread = VersionChecker(self)
            self._notifier_system = None
            self._internal_address_mask = 0xFFFFFFFF

    @property
    def internal_address_mask(self):
        return self._internal_address_mask

    @internal_address_mask.setter
    def internal_address_mask(self, mask):
        self._internal_address_mask = int(mask, 16)
        if self.device is not None:
            self.device.internal_address_mask = int(mask, 16)

    def start(self):
        """
        Starts the internal threads.
        """
        self._event_thread.start()
        self._version_thread.start()
        self._camera_thread.start()

    def stop(self, restart=False):
        """
        Closes the device, stops the internal threads, and shuts down.  Optionally
        triggers a restart of the application.

        :param restart: Indicates whether or not the application should be restarted.
        :type restart: bool
        """
        self.app.logger.info("Stopping service..")

        self.close()

        self._event_thread.stop()
        self._version_thread.stop()
        self._camera_thread.stop()

        if restart:
            try:
                self._event_thread.join(5)
                self._version_thread.join(5)
                self._camera_thread.join(5)
            except RuntimeError:
                pass

        self.websocket.stop()

        if restart:
            self.app.logger.info("Restarting service..")
            os.execv(sys.executable, [sys.executable] + sys.argv)

    def init(self):
        """
        Initializes the application by triggering a device open if it's been
        previously configured.
        """
        with self.app.app_context():
            device_type = Setting.get_by_name("device_type").value

            # Add any default event messages that may be missing due to additions.
            for event, message in DEFAULT_EVENT_MESSAGES.iteritems():
                if not NotificationMessage.query.filter_by(id=event).first():
                    db.session.add(NotificationMessage(id=event, text=message))
            db.session.commit()

            self.version = self.updater._components["webapp"].version
            current_app.jinja_env.globals["version"] = self.version

            current_app.logger.info("AlarmDecoder Webapp booting up - v{0}".format(self.version))

            # HACK: giant hack.. fix when we know this works.
            self.updater._components["webapp"]._db_updater.refresh()

            if self.updater._components["webapp"]._db_updater.needs_update:
                current_app.logger.debug("Database needs updating!")

                self.updater._components["webapp"]._db_updater.update()
            else:
                current_app.logger.debug("Database is good!")

            if device_type:
                self.trigger_reopen_device = True

            self._notifier_system = NotificationSystem()
            self._camera_thread = CameraChecker(self)

    def open(self):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name("device_type").value
            self._device_location = Setting.get_by_name("device_location").value
            self._internal_address_mask = int(Setting.get_by_name("internal_address_mask", "FFFFFFF").value, 16)

            if self._device_type:
                interface = ("localhost", 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == "local":
                    devicetype = SerialDevice
                    interface = Setting.get_by_name("device_path").value
                    self._device_baudrate = Setting.get_by_name("device_baudrate").value

                elif self._device_location == "network":
                    interface = (Setting.get_by_name("device_address").value, Setting.get_by_name("device_port").value)
                    use_ssl = Setting.get_by_name("use_ssl", False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        ca_cert = Certificate.query.filter_by(name="AlarmDecoder CA").one()
                        internal_cert = Certificate.query.filter_by(name="AlarmDecoder Internal").one()

                        device.ssl = True
                        device.ssl_ca = ca_cert.certificate_obj
                        device.ssl_certificate = internal_cert.certificate_obj
                        device.ssl_key = internal_cert.key_obj

                    self.device = AlarmDecoder(device)
                    self.device.internal_address_mask = self._internal_address_mask

                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate)

                except NoDeviceError, err:
                    self.app.logger.warning("Open failed: %s", err[0], exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning("SSL connection failed: %s - %s", fn, message, exc_info=True)
                    raise
コード例 #20
0
ファイル: alarmdecoder.py プロジェクト: azogue/home-assistant
def async_setup(hass, config):
    """Common setup for AlarmDecoder devices."""
    from alarmdecoder import AlarmDecoder
    from alarmdecoder.devices import (SocketDevice, SerialDevice, USBDevice)

    conf = config.get(DOMAIN)

    device = conf.get(CONF_DEVICE)
    display = conf.get(CONF_PANEL_DISPLAY)
    zones = conf.get(CONF_ZONES)

    device_type = device.get(CONF_DEVICE_TYPE)
    host = DEFAULT_DEVICE_HOST
    port = DEFAULT_DEVICE_PORT
    path = DEFAULT_DEVICE_PATH
    baud = DEFAULT_DEVICE_BAUD

    sync_connect = asyncio.Future(loop=hass.loop)

    def handle_open(device):
        """Callback for a successful connection."""
        _LOGGER.info("Established a connection with the alarmdecoder.")
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder)
        sync_connect.set_result(True)

    @callback
    def stop_alarmdecoder(event):
        """Callback to handle shutdown alarmdecoder."""
        _LOGGER.debug("Shutting down alarmdecoder.")
        controller.close()

    @callback
    def handle_message(sender, message):
        """Callback to handle message from alarmdecoder."""
        async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE, message)

    def zone_fault_callback(sender, zone):
        """Callback to handle zone fault from alarmdecoder."""
        async_dispatcher_send(hass, SIGNAL_ZONE_FAULT, zone)

    def zone_restore_callback(sender, zone):
        """Callback to handle zone restore from alarmdecoder."""
        async_dispatcher_send(hass, SIGNAL_ZONE_RESTORE, zone)

    controller = False
    if device_type == 'socket':
        host = device.get(CONF_DEVICE_HOST)
        port = device.get(CONF_DEVICE_PORT)
        controller = AlarmDecoder(SocketDevice(interface=(host, port)))
    elif device_type == 'serial':
        path = device.get(CONF_DEVICE_PATH)
        baud = device.get(CONF_DEVICE_BAUD)
        controller = AlarmDecoder(SerialDevice(interface=path))
    elif device_type == 'usb':
        AlarmDecoder(USBDevice.find())
        return False

    controller.on_open += handle_open
    controller.on_message += handle_message
    controller.on_zone_fault += zone_fault_callback
    controller.on_zone_restore += zone_restore_callback

    hass.data[DATA_AD] = controller

    controller.open(baud)

    result = yield from sync_connect

    if not result:
        return False

    hass.async_add_job(async_load_platform(hass, 'alarm_control_panel', DOMAIN,
                                           conf, config))

    if zones:
        hass.async_add_job(async_load_platform(
            hass, 'binary_sensor', DOMAIN, {CONF_ZONES: zones}, config))

    if display:
        hass.async_add_job(async_load_platform(hass, 'sensor', DOMAIN,
                                               conf, config))

    return True
コード例 #21
0
    def open(self, no_reader_thread=False):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name('device_type').value
            self._device_location = Setting.get_by_name(
                'device_location').value
            self._internal_address_mask = int(
                Setting.get_by_name('internal_address_mask', 'FFFFFFFF').value,
                16)

            if self._device_type:
                interface = ('localhost', 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == 'local':
                    devicetype = SerialDevice
                    interface = Setting.get_by_name('device_path').value
                    self._device_baudrate = Setting.get_by_name(
                        'device_baudrate').value

                elif self._device_location == 'network':
                    interface = (Setting.get_by_name('device_address').value,
                                 Setting.get_by_name('device_port').value)
                    use_ssl = Setting.get_by_name('use_ssl', False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        try:
                            ca_cert = Certificate.query.filter_by(
                                name='AlarmDecoder CA').one()
                            internal_cert = Certificate.query.filter_by(
                                name='AlarmDecoder Internal').one()

                            device.ssl = True
                            device.ssl_ca = ca_cert.certificate_obj
                            device.ssl_certificate = internal_cert.certificate_obj
                            device.ssl_key = internal_cert.key_obj
                        except NoResultFound, err:
                            self.app.logger.warning(
                                'No certificates found: %s',
                                err[0],
                                exc_info=True)
                            raise

                    self.device = AlarmDecoder(device)
                    self.device.internal_address_mask = self._internal_address_mask

                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate,
                                     no_reader_thread=no_reader_thread)

                except NoDeviceError, err:
                    self.app.logger.warning('Open failed: %s',
                                            err[0],
                                            exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning('SSL connection failed: %s - %s',
                                            fn,
                                            message,
                                            exc_info=True)
                    raise
コード例 #22
0
class Decoder(object):
    """
    Primary application state
    """
    def __init__(self, app, websocket):
        """
        Constructor

        :param app: The flask application object
        :type app: Flask
        :param websocket: The websocket object
        :type websocket: SocketIOServer
        """
        with app.app_context():
            self.app = app
            self.websocket = websocket
            self.device = None
            self.updater = Updater()
            self.updates = {}
            self.version = ''

            self.trigger_reopen_device = False
            self.trigger_restart = False

            self._last_message = None
            self._device_baudrate = 115200
            self._device_type = None
            self._device_location = None
            self._event_thread = DecoderThread(self)
            self._version_thread = VersionChecker(self)
            self._notifier_system = None

    def start(self):
        """
        Starts the internal threads.
        """
        self._event_thread.start()
        self._version_thread.start()

    def stop(self, restart=False):
        """
        Closes the device, stops the internal threads, and shuts down.  Optionally
        triggers a restart of the application.

        :param restart: Indicates whether or not the application should be restarted.
        :type restart: bool
        """
        self.app.logger.info('Stopping service..')

        self.close()

        self._event_thread.stop()
        self._version_thread.stop()

        if restart:
            try:
                self._event_thread.join(5)
                self._version_thread.join(5)
            except RuntimeError:
                pass

        self.websocket.stop()

        if restart:
            self.app.logger.info('Restarting service..')
            os.execv(sys.executable, [sys.executable] + sys.argv)

    def init(self):
        """
        Initializes the application by triggering a device open if it's been
        previously configured.
        """
        with self.app.app_context():
            device_type = Setting.get_by_name('device_type').value

            # Add any default event messages that may be missing due to additions.
            for event, message in DEFAULT_EVENT_MESSAGES.iteritems():
                if not NotificationMessage.query.filter_by(id=event).first():
                    db.session.add(NotificationMessage(id=event, text=message))
            db.session.commit()

            self.version = self.updater._components['webapp'].version
            current_app.jinja_env.globals['version'] = self.version

            current_app.logger.info(
                'AlarmDecoder Webapp booting up - v{0}'.format(self.version))

            # HACK: giant hack.. fix when we know this works.
            self.updater._components['webapp']._db_updater.refresh()

            if self.updater._components['webapp']._db_updater.needs_update:
                current_app.logger.debug('Database needs updating!!!!')

                self.updater._components['webapp']._db_updater.update()
            else:
                current_app.logger.debug('Database is good!!!!!!')

            if device_type:
                self.trigger_reopen_device = True

            self._notifier_system = NotificationSystem()

    def open(self):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name('device_type').value
            self._device_location = Setting.get_by_name(
                'device_location').value

            if self._device_type:
                interface = ('localhost', 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == 'local':
                    devicetype = SerialDevice
                    interface = Setting.get_by_name('device_path').value
                    self._device_baudrate = Setting.get_by_name(
                        'device_baudrate').value

                elif self._device_location == 'network':
                    interface = (Setting.get_by_name('device_address').value,
                                 Setting.get_by_name('device_port').value)
                    use_ssl = Setting.get_by_name('use_ssl', False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        ca_cert = Certificate.query.filter_by(
                            name='AlarmDecoder CA').one()
                        internal_cert = Certificate.query.filter_by(
                            name='AlarmDecoder Internal').one()

                        device.ssl = True
                        device.ssl_ca = ca_cert.certificate_obj
                        device.ssl_certificate = internal_cert.certificate_obj
                        device.ssl_key = internal_cert.key_obj

                    self.device = AlarmDecoder(device)
                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate)

                except NoDeviceError, err:
                    self.app.logger.warning('Open failed: %s',
                                            err[0],
                                            exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning('SSL connection failed: %s - %s',
                                            fn,
                                            message,
                                            exc_info=True)
                    raise
コード例 #23
0
class Decoder(object):
    """
    Primary application state
    """
    def __init__(self, app, websocket):
        """
        Constructor

        :param app: The flask application object
        :type app: Flask
        :param websocket: The websocket object
        :type websocket: SocketIOServer
        """
        with app.app_context():
            self.app = app
            self.websocket = websocket
            self.device = None
            self.updater = Updater()
            self.updates = {}
            self.version = ''
            self.firmware_file = None
            self.firmware_length = -1

            self.trigger_reopen_device = False
            self.trigger_restart = False

            self._last_message = None
            self._device_baudrate = 115200
            self._device_type = None
            self._device_location = None
            self._event_thread = DecoderThread(self)
            self._discovery_thread = None
            self._notification_thread = None
            self._notifier_system = None
            self._upnp_thread = None
            self._internal_address_mask = 0xFFFFFFFF
            self.last_message_received = None

    @property
    def internal_address_mask(self):
        return self._internal_address_mask

    @internal_address_mask.setter
    def internal_address_mask(self, mask):
        self._internal_address_mask = int(mask, 16)
        if self.device is not None:
            self.device.internal_address_mask = int(mask, 16)

    def start(self):
        """
        Starts the internal threads.
        """
        self._event_thread.start()
        self._version_thread.start()
        self._camera_thread.start()
        self._discovery_thread.start()
        self._notification_thread.start()
        self._exporter_thread.start()
        if has_upnp:
            self._upnp_thread.start()

    def stop(self, restart=False):
        """
        Closes the device, stops the internal threads, and shuts down.  Optionally
        triggers a restart of the application.

        :param restart: Indicates whether or not the application should be restarted.
        :type restart: bool
        """
        self.app.logger.info('Stopping service..')

        self.close()

        self._event_thread.stop()
        self._version_thread.stop()
        self._camera_thread.stop()
        self._discovery_thread.stop()
        self._notification_thread.stop()
        self._exporter_thread.stop()
        if has_upnp:
            self._upnp_thread.stop()

        if restart:
            try:
                self._event_thread.join(5)
                self._version_thread.join(5)
                self._camera_thread.join(5)
                self._discovery_thread.join(5)
                self._notification_thread.join(5)
                self._exporter_thread.join(5)
                if has_upnp:
                    self._upnp_thread.join(5)

            except RuntimeError:
                pass

        self.websocket.stop()

        if restart:
            self.app.logger.info('Restarting service..')
            os.execv(sys.executable, [sys.executable] + sys.argv)

    def init(self):
        """
        Initializes the application by triggering a device open if it's been
        previously configured.
        """
        with self.app.app_context():
            device_type = Setting.get_by_name('device_type').value

            # Add any default event messages that may be missing due to additions.
            for event, message in DEFAULT_EVENT_MESSAGES.iteritems():
                if not NotificationMessage.query.filter_by(id=event).first():
                    db.session.add(NotificationMessage(id=event, text=message))
            db.session.commit()

            current_app.config['MAIL_SERVER'] = Setting.get_by_name(
                'system_email_server', default='localhost').value
            current_app.config['MAIL_PORT'] = Setting.get_by_name(
                'system_email_port', default=25).value
            current_app.config['MAIL_USE_TLS'] = Setting.get_by_name(
                'system_email_tls', default=False).value
            current_app.config['MAIL_USERNAME'] = Setting.get_by_name(
                'system_email_username', default='').value
            current_app.config['MAIL_PASSWORD'] = Setting.get_by_name(
                'system_email_password', default='').value
            current_app.config['MAIL_DEFAULT_SENDER'] = Setting.get_by_name(
                'system_email_from', default='*****@*****.**').value

            mail.init_app(current_app)

            # Generate a new session key if it doesn't exist.
            secret_key = Setting.get_by_name('secret_key')
            if secret_key.value is None:
                secret_key.value = binascii.hexlify(os.urandom(24))
                db.session.add(secret_key)
                db.session.commit()

            current_app.secret_key = secret_key.value

            self.version = self.updater._components[
                'AlarmDecoderWebapp'].version
            current_app.jinja_env.globals['version'] = self.version
            current_app.logger.info(
                'AlarmDecoder Webapp booting up - v{0}'.format(self.version))

            # Expose wrapped is_authenticated to jinja.
            current_app.jinja_env.globals[
                'user_is_authenticated'] = user_is_authenticated

            # HACK: giant hack.. fix when we know this works.
            self.updater._components['AlarmDecoderWebapp']._db_updater.refresh(
            )

            if self.updater._components[
                    'AlarmDecoderWebapp']._db_updater.needs_update:
                current_app.logger.debug('Database needs updating!')

                self.updater._components[
                    'AlarmDecoderWebapp']._db_updater.update()
            else:
                current_app.logger.debug('Database is good!')

            if device_type:
                self.trigger_reopen_device = True

            self._notifier_system = NotificationSystem()
            self._camera_thread = CameraChecker(self)
            self._discovery_thread = DiscoveryServer(self)
            self._notification_thread = NotificationThread(self)
            self._exporter_thread = ExportChecker(self)
            self._version_thread = VersionChecker(self)

            if has_upnp:
                self._upnp_thread = UPNPThread(self)

    def open(self, no_reader_thread=False):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name('device_type').value
            self._device_location = Setting.get_by_name(
                'device_location').value
            self._internal_address_mask = int(
                Setting.get_by_name('internal_address_mask', 'FFFFFFFF').value,
                16)

            if self._device_type:
                interface = ('localhost', 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == 'local':
                    devicetype = SerialDevice
                    interface = Setting.get_by_name('device_path').value
                    self._device_baudrate = Setting.get_by_name(
                        'device_baudrate').value

                elif self._device_location == 'network':
                    interface = (Setting.get_by_name('device_address').value,
                                 Setting.get_by_name('device_port').value)
                    use_ssl = Setting.get_by_name('use_ssl', False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        try:
                            ca_cert = Certificate.query.filter_by(
                                name='AlarmDecoder CA').one()
                            internal_cert = Certificate.query.filter_by(
                                name='AlarmDecoder Internal').one()

                            device.ssl = True
                            device.ssl_ca = ca_cert.certificate_obj
                            device.ssl_certificate = internal_cert.certificate_obj
                            device.ssl_key = internal_cert.key_obj
                        except NoResultFound, err:
                            self.app.logger.warning(
                                'No certificates found: %s',
                                err[0],
                                exc_info=True)
                            raise

                    self.device = AlarmDecoder(device)
                    self.device.internal_address_mask = self._internal_address_mask

                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate,
                                     no_reader_thread=no_reader_thread)

                except NoDeviceError, err:
                    self.app.logger.warning('Open failed: %s',
                                            err[0],
                                            exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning('SSL connection failed: %s - %s',
                                            fn,
                                            message,
                                            exc_info=True)
                    raise
コード例 #24
0
ファイル: __init__.py プロジェクト: pp81381/home-assistant
def setup(hass, config):
    """Set up for the AlarmDecoder devices."""
    from alarmdecoder import AlarmDecoder
    from alarmdecoder.devices import (SocketDevice, SerialDevice, USBDevice)

    conf = config.get(DOMAIN)

    restart = False
    device = conf.get(CONF_DEVICE)
    display = conf.get(CONF_PANEL_DISPLAY)
    zones = conf.get(CONF_ZONES)

    device_type = device.get(CONF_DEVICE_TYPE)
    host = DEFAULT_DEVICE_HOST
    port = DEFAULT_DEVICE_PORT
    path = DEFAULT_DEVICE_PATH
    baud = DEFAULT_DEVICE_BAUD

    def stop_alarmdecoder(event):
        """Handle the shutdown of AlarmDecoder."""
        _LOGGER.debug("Shutting down alarmdecoder")
        nonlocal restart
        restart = False
        controller.close()

    def open_connection(now=None):
        """Open a connection to AlarmDecoder."""
        from alarmdecoder.util import NoDeviceError
        nonlocal restart
        try:
            controller.open(baud)
        except NoDeviceError:
            _LOGGER.debug("Failed to connect.  Retrying in 5 seconds")
            hass.helpers.event.track_point_in_time(
                open_connection,
                dt_util.utcnow() + timedelta(seconds=5))
            return
        _LOGGER.debug("Established a connection with the alarmdecoder")
        restart = True

    def handle_closed_connection(event):
        """Restart after unexpected loss of connection."""
        nonlocal restart
        if not restart:
            return
        restart = False
        _LOGGER.warning("AlarmDecoder unexpectedly lost connection.")
        hass.add_job(open_connection)

    def handle_message(sender, message):
        """Handle message from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(SIGNAL_PANEL_MESSAGE, message)

    def handle_rfx_message(sender, message):
        """Handle RFX message from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(SIGNAL_RFX_MESSAGE, message)

    def zone_fault_callback(sender, zone):
        """Handle zone fault from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_FAULT, zone)

    def zone_restore_callback(sender, zone):
        """Handle zone restore from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_RESTORE, zone)

    def handle_rel_message(sender, message):
        """Handle relay message from AlarmDecoder."""
        hass.helpers.dispatcher.dispatcher_send(SIGNAL_REL_MESSAGE, message)

    controller = False
    if device_type == 'socket':
        host = device.get(CONF_DEVICE_HOST)
        port = device.get(CONF_DEVICE_PORT)
        controller = AlarmDecoder(SocketDevice(interface=(host, port)))
    elif device_type == 'serial':
        path = device.get(CONF_DEVICE_PATH)
        baud = device.get(CONF_DEVICE_BAUD)
        controller = AlarmDecoder(SerialDevice(interface=path))
    elif device_type == 'usb':
        AlarmDecoder(USBDevice.find())
        return False

    controller.on_message += handle_message
    controller.on_rfx_message += handle_rfx_message
    controller.on_zone_fault += zone_fault_callback
    controller.on_zone_restore += zone_restore_callback
    controller.on_close += handle_closed_connection
    controller.on_relay_changed += handle_rel_message

    hass.data[DATA_AD] = controller

    open_connection()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder)

    load_platform(hass, 'alarm_control_panel', DOMAIN, conf, config)

    if zones:
        load_platform(hass, 'binary_sensor', DOMAIN, {CONF_ZONES: zones},
                      config)

    if display:
        load_platform(hass, 'sensor', DOMAIN, conf, config)

    return True
コード例 #25
0
class Decoder(object):
    """
    Primary application state
    """

    def __init__(self, app, websocket):
        """
        Constructor

        :param app: The flask application object
        :type app: Flask
        :param websocket: The websocket object
        :type websocket: SocketIOServer
        """
        with app.app_context():
            self.app = app
            self.websocket = websocket
            self.device = None
            self.updater = Updater()
            self.updates = {}
            self.version = ''
            self.firmware_file = None
            self.firmware_length = -1

            self.trigger_reopen_device = False
            self.trigger_restart = False

            self._last_message = None
            self._device_baudrate = 115200
            self._device_type = None
            self._device_location = None
            self._event_thread = DecoderThread(self)
            self._version_thread = VersionChecker(self)
            self._discovery_thread = None
            self._notification_thread = None
            self._notifier_system = None
            self._upnp_thread = None
            self._internal_address_mask = 0xFFFFFFFF
            self.last_message_received = None

    @property
    def internal_address_mask(self):
        return self._internal_address_mask

    @internal_address_mask.setter
    def internal_address_mask(self, mask):
        self._internal_address_mask = int(mask, 16)
        if self.device is not None:
            self.device.internal_address_mask = int(mask, 16)

    def start(self):
        """
        Starts the internal threads.
        """
        self._event_thread.start()
        self._version_thread.start()
        self._camera_thread.start()
        self._discovery_thread.start()
        self._notification_thread.start()
        if has_upnp:
            self._upnp_thread.start()

    def stop(self, restart=False):
        """
        Closes the device, stops the internal threads, and shuts down.  Optionally
        triggers a restart of the application.

        :param restart: Indicates whether or not the application should be restarted.
        :type restart: bool
        """
        self.app.logger.info('Stopping service..')

        self.close()

        self._event_thread.stop()
        self._version_thread.stop()
        self._camera_thread.stop()
        self._discovery_thread.stop()
        self._notification_thread.stop()
        if has_upnp:
            self._upnp_thread.stop()

        if restart:
            try:
                self._event_thread.join(5)
                self._version_thread.join(5)
                self._camera_thread.join(5)
                self._discovery_thread.join(5)
                self._notification_thread.join(5)
                if has_upnp:
                    self._upnp_thread.join(5)

            except RuntimeError:
                pass

        self.websocket.stop()

        if restart:
            self.app.logger.info('Restarting service..')
            os.execv(sys.executable, [sys.executable] + sys.argv)

    def init(self):
        """
        Initializes the application by triggering a device open if it's been
        previously configured.
        """
        with self.app.app_context():
            device_type = Setting.get_by_name('device_type').value

            # Add any default event messages that may be missing due to additions.
            for event, message in DEFAULT_EVENT_MESSAGES.iteritems():
                if not NotificationMessage.query.filter_by(id=event).first():
                    db.session.add(NotificationMessage(id=event, text=message))
            db.session.commit()

            current_app.config['MAIL_SERVER'] = Setting.get_by_name('system_email_server',default='localhost').value
            current_app.config['MAIL_PORT'] = Setting.get_by_name('system_email_port',default=25).value
            current_app.config['MAIL_USE_TLS'] = Setting.get_by_name('system_email_tls',default=False).value
            current_app.config['MAIL_USERNAME'] = Setting.get_by_name('system_email_username',default='').value
            current_app.config['MAIL_PASSWORD'] = Setting.get_by_name('system_email_password',default='').value
            current_app.config['MAIL_DEFAULT_SENDER'] = Setting.get_by_name('system_email_from',default='root@localhost').value

            mail.init_app(current_app)

            # Generate a new session key if it doesn't exist.
            secret_key = Setting.get_by_name('secret_key')
            if secret_key.value is None:
                secret_key.value = binascii.hexlify(os.urandom(24))
                db.session.add(secret_key)
                db.session.commit()

            current_app.secret_key = secret_key.value

            self.version = self.updater._components['AlarmDecoderWebapp'].version
            current_app.jinja_env.globals['version'] = self.version
            current_app.logger.info('AlarmDecoder Webapp booting up - v{0}'.format(self.version))

            # Expose wrapped is_authenticated to jinja.
            current_app.jinja_env.globals['user_is_authenticated'] = user_is_authenticated

            # HACK: giant hack.. fix when we know this works.
            self.updater._components['AlarmDecoderWebapp']._db_updater.refresh()

            if self.updater._components['AlarmDecoderWebapp']._db_updater.needs_update:
                current_app.logger.debug('Database needs updating!')

                self.updater._components['AlarmDecoderWebapp']._db_updater.update()
            else:
                current_app.logger.debug('Database is good!')

            if device_type:
                self.trigger_reopen_device = True

            self._notifier_system = NotificationSystem()
            self._camera_thread = CameraChecker(self)
            self._discovery_thread = DiscoveryServer(self)
            self._notification_thread = NotificationThread(self)
            if has_upnp:
                self._upnp_thread = UPNPThread(self)

    def open(self, no_reader_thread=False):
        """
        Opens the AlarmDecoder device.
        """
        with self.app.app_context():
            self._device_type = Setting.get_by_name('device_type').value
            self._device_location = Setting.get_by_name('device_location').value
            self._internal_address_mask = int(Setting.get_by_name('internal_address_mask', 'FFFFFFF').value, 16)

            if self._device_type:
                interface = ('localhost', 10000)
                use_ssl = False
                devicetype = SocketDevice

                # Set up device interfaces based on our location.
                if self._device_location == 'local':
                    devicetype = SerialDevice
                    interface = Setting.get_by_name('device_path').value
                    self._device_baudrate = Setting.get_by_name('device_baudrate').value

                elif self._device_location == 'network':
                    interface = (Setting.get_by_name('device_address').value, Setting.get_by_name('device_port').value)
                    use_ssl = Setting.get_by_name('use_ssl', False).value

                # Create and open the device.
                try:
                    device = devicetype(interface=interface)
                    if use_ssl:
                        try:
                            ca_cert = Certificate.query.filter_by(name='AlarmDecoder CA').one()
                            internal_cert = Certificate.query.filter_by(name='AlarmDecoder Internal').one()

                            device.ssl = True
                            device.ssl_ca = ca_cert.certificate_obj
                            device.ssl_certificate = internal_cert.certificate_obj
                            device.ssl_key = internal_cert.key_obj
                        except NoResultFound, err:
                            self.app.logger.warning('No certificates found: %s', err[0], exc_info=True)
                            raise

                    self.device = AlarmDecoder(device)
                    self.device.internal_address_mask = self._internal_address_mask

                    self.bind_events()
                    self.device.open(baudrate=self._device_baudrate, no_reader_thread=no_reader_thread)

                except NoDeviceError, err:
                    self.app.logger.warning('Open failed: %s', err[0], exc_info=True)
                    raise

                except SSL.Error, err:
                    source, fn, message = err[0][0]
                    self.app.logger.warning('SSL connection failed: %s - %s', fn, message, exc_info=True)
                    raise
コード例 #26
0
def async_setup(hass, config):
    """Set up for the AlarmDecoder devices."""
    from alarmdecoder import AlarmDecoder
    from alarmdecoder.devices import (SocketDevice, SerialDevice, USBDevice)

    conf = config.get(DOMAIN)

    device = conf.get(CONF_DEVICE)
    display = conf.get(CONF_PANEL_DISPLAY)
    zones = conf.get(CONF_ZONES)

    device_type = device.get(CONF_DEVICE_TYPE)
    host = DEFAULT_DEVICE_HOST
    port = DEFAULT_DEVICE_PORT
    path = DEFAULT_DEVICE_PATH
    baud = DEFAULT_DEVICE_BAUD

    sync_connect = asyncio.Future(loop=hass.loop)

    def handle_open(device):
        """Handle the successful connection."""
        _LOGGER.info("Established a connection with the alarmdecoder")
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder)
        sync_connect.set_result(True)

    @callback
    def stop_alarmdecoder(event):
        """Handle the shutdown of AlarmDecoder."""
        _LOGGER.debug("Shutting down alarmdecoder")
        controller.close()

    @callback
    def handle_message(sender, message):
        """Handle message from AlarmDecoder."""
        async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE, message)

    def zone_fault_callback(sender, zone):
        """Handle zone fault from AlarmDecoder."""
        async_dispatcher_send(hass, SIGNAL_ZONE_FAULT, zone)

    def zone_restore_callback(sender, zone):
        """Handle zone restore from AlarmDecoder."""
        async_dispatcher_send(hass, SIGNAL_ZONE_RESTORE, zone)

    controller = False
    if device_type == 'socket':
        host = device.get(CONF_DEVICE_HOST)
        port = device.get(CONF_DEVICE_PORT)
        controller = AlarmDecoder(SocketDevice(interface=(host, port)))
    elif device_type == 'serial':
        path = device.get(CONF_DEVICE_PATH)
        baud = device.get(CONF_DEVICE_BAUD)
        controller = AlarmDecoder(SerialDevice(interface=path))
    elif device_type == 'usb':
        AlarmDecoder(USBDevice.find())
        return False

    controller.on_open += handle_open
    controller.on_message += handle_message
    controller.on_zone_fault += zone_fault_callback
    controller.on_zone_restore += zone_restore_callback

    hass.data[DATA_AD] = controller

    controller.open(baud)

    result = yield from sync_connect

    if not result:
        return False

    hass.async_add_job(
        async_load_platform(hass, 'alarm_control_panel', DOMAIN, conf, config))

    if zones:
        hass.async_add_job(
            async_load_platform(hass, 'binary_sensor', DOMAIN,
                                {CONF_ZONES: zones}, config))

    if display:
        hass.async_add_job(
            async_load_platform(hass, 'sensor', DOMAIN, conf, config))

    return True
コード例 #27
0
def main():
    global deactivate

    # Number map of different Zones
    zm = ZoneMapper('./zone-map.yml')

    # used to toggle disarm message send
    deactivate = False

    # Load Account settings
    with open("./settings.yml") as filestream:
        try:
            settings = yaml.load(filestream)
        except yaml.YAMLError as exc:
            print(exc)



    class DisarmEventHandler(FileSystemEventHandler):
        def on_modified(self, event):
            global deactivate
            # Only deactivate when file matches
            if self.find_file(event.src_path) == settings["dir_watch_file"]:
                #Find last line in file
                line = subprocess.check_output(['tail', '-1', event.src_path])
                # if you find the passcode in the line
                if "Body="+settings["alarm_pass"] in line:
                    print("Disarming")
                    deactivate = True

        def find_file(self, file_path):
            pathArr = file_path.split("/")
            return pathArr[len(pathArr)-1]

            



    def handle_on_arm(device):
        send_sms_message("Alarm Armed")


    def handle_on_disarm(device):
        send_sms_message("Alarm Disarmed")



    def handle_on_fire(device, status):
        send_sms_message("Alarm is going off! FIRE - " + str(status))


    def handle_on_panic(device, status):
        send_sms_message("Alarm is going off! PANIC - " + str(status))



    def handle_on_alarm(device, zone):
        zone_name = zm.get_zone_name(int(zone))
        send_sms_message("Alarm is going off for the " + zone_name + "!")


    def handle_on_alarm_restored(device, zone):
        zone_name = zm.get_zone_name(int(zone))
        send_sms_message("Alarm is restored for the " + zone_name)



    def handle_on_zone_fault(device, zone):
        zone_name = zm.get_zone_name(zone)
        if not zm.is_zone_whitelist(zone):
            send_sms_message("Zone Fault - " + zone_name)


    def handle_zone_restore(device, zone):
        zone_name = zm.get_zone_name(zone)
        if not zm.is_zone_whitelist(zone):
            send_sms_message("Zone Restored - " + zone_name)



    def send_sms_message(msg):
        client = TwilioRestClient(settings["twilio_account_sid"], settings["twilio_auth_token"])
        for numb in settings["twilio_numbers_to_text"]:
            client.messages.create(to=numb, from_=settings["twilio_number_from"], body=msg)



    event_handler = DisarmEventHandler()
    observer = Observer()
    observer.schedule(event_handler, settings["dir_watch_path"], recursive=False)
    observer.start()



    try:
        # Retrieve the first USB device /dev/tty.usbserial-DJ009GBR
        serialDevice = SerialDevice(interface=settings["device"])
        device = AlarmDecoder(serialDevice)

        device.on_zone_fault += handle_on_zone_fault
        device.on_zone_restore += handle_zone_restore
        device.on_arm += handle_on_arm
        device.on_disarm += handle_on_disarm
        device.on_alarm += handle_on_alarm
        device.on_alarm_restored += handle_on_alarm_restored
        device.on_fire += handle_on_fire
        device.on_panic += handle_on_panic

        with device.open(baudrate=115200):
            while True:
                if deactivate:
                    deactivate = False
                    print "Deactivated!"
                    device.send(settings["alarm_pass"] + "1")

                time.sleep(1)


    except Exception, ex:
        print 'Exception:', ex