Esempio n. 1
0
 def __init__(self,name,registrations):
     
     assert type(name)==str
     assert type(registrations)==list
     for r in registrations:
         assert type(r)==dict
         for k in r.keys():
             assert k in ['signal','sender','callback']
     
     # log
     log.info("create instance")
     
     # store params
     self.dataLock        = threading.RLock()
     self.registrations   = []
     
     # give this thread a name
     self.name            = name
     
     # local variables
     self.goOn            = True
     
     # register registrations
     for r in registrations:
         self.register(
             sender       = r['sender'],
             signal       = r['signal'],
             callback     = r['callback'],
         )
     
     # connect to dispatcher
     dispatcher.connect(
         receiver = self._eventBusNotification,
     )
Esempio n. 2
0
 def __init__(self):
     dispatcher.connect(self.handle_image_load_event, signal='load_image', sender=dispatcher.Any)
     dispatcher.connect(self.handle_filter_event, signal='apply_filter', sender=dispatcher.Any)
     self.image = None
     self.im_processor = ImageProcessor()
     self.user_interface = GUI()
     self.user_interface.run()
Esempio n. 3
0
 def __init__(self, node, network, new_entity_ids):
     """Initialize node."""
     # pylint: disable=import-error
     super().__init__()
     from openzwave.network import ZWaveNetwork
     from pydispatch import dispatcher
     self._network = network
     self.node = node
     self.node_id = self.node.node_id
     self._name = node_name(self.node)
     self._product_name = node.product_name
     self._manufacturer_name = node.manufacturer_name
     self.old_entity_id = "{}.{}_{}".format(
         DOMAIN, slugify(self._name), self.node_id)
     self.new_entity_id = "{}.{}".format(DOMAIN, slugify(self._name))
     if not new_entity_ids:
         self.entity_id = self.old_entity_id
     self._attributes = {}
     self.wakeup_interval = None
     self.location = None
     self.battery_level = None
     dispatcher.connect(
         self.network_node_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
     dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE)
     dispatcher.connect(
         self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION)
     dispatcher.connect(
         self.network_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT)
     dispatcher.connect(
         self.network_scene_activated, ZWaveNetwork.SIGNAL_SCENE_EVENT)
Esempio n. 4
0
 def __init__(self,refresh_period=REFRESH_PERIOD):
     
     # log
     log.info('creating instance')
     
     # store params
     self.refresh_period       = refresh_period
     
     # initialize parent class
     threading.Thread.__init__(self)
     
     # give this thread a name
     self.name                 = 'DustLink'
     
     # local variables
     self.goOn                 = True
     self.dataLock             = threading.Lock()
     self.gateway              = None
     self.lbr                  = None
     self.dataConnector        = None
     
     # connect to dispatcher
     dispatcher.connect(
         self.tearDown,
         signal = 'tearDown',
         weak   = False,
     )
     
     # start itself
     self.start()
Esempio n. 5
0
    def __init__(self, value, refresh, delay):
        """Initialize the light."""
        from openzwave.network import ZWaveNetwork
        from pydispatch import dispatcher

        zwave.ZWaveDeviceEntity.__init__(self, value, DOMAIN)
        self._brightness = None
        self._state = None
        self._delay = delay
        self._refresh_value = refresh
        self._zw098 = None

        # Enable appropriate workaround flags for our device
        # Make sure that we have values for the key before converting to int
        if (value.node.manufacturer_id.strip() and
                value.node.product_id.strip()):
            specific_sensor_key = (int(value.node.manufacturer_id, 16),
                                   int(value.node.product_id, 16))
            if specific_sensor_key in DEVICE_MAPPINGS:
                if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_ZW098:
                    _LOGGER.debug("AEOTEC ZW098 workaround enabled")
                    self._zw098 = 1

        self.update_properties()

        # Used for value change event handling
        self._refreshing = False
        self._timer = None
        _LOGGER.debug('self._refreshing=%s self.delay=%s',
                      self._refresh_value, self._delay)
        dispatcher.connect(
            self._value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
Esempio n. 6
0
def configure():
    level = cbpos.config['app', 'log']
    level = getattr(logging, level if level in LEVELS else LEVELS[0])
    
    filename = cbpos.config['app', 'log_file']
    filepath = os.path.realpath(filename) if filename != '' else None
    
    use_colors = bool(cbpos.config['app', 'log_use_colors'])
    
    root = logging.getLogger() 
    root.setLevel(level)
    
    # The standard format used for file logging and console logging
    log_format = '%(name)s: %(message)s (%(filename)s:%(lineno)s)'
    long_log_format = '[%(levelname)8s]\t'+log_format
    
    console = logging.StreamHandler()
    
    # Format with colors
    if use_colors and ColoredFormatter is not None:
        console.setFormatter(ColoredFormatter(log_format))
    else:
        console.setFormatter(logging.Formatter(long_log_format))
    
    if filepath:
        # Set up logging to a file
        fh = logging.FileHandler(filepath, 'w')
        fh.setFormatter(logging.Formatter(long_log_format))
        root.addHandler(fh)
    else:
        root.addHandler(console)
    
    # Log any signal from any sender
    dispatcher.connect(log_signals, signal=dispatcher.Any, sender=dispatcher.Any)
Esempio n. 7
0
def run(config_path=None):
        
    if config_path != None and not os.path.isfile(config_path):
        raise Exception('config_path does not exist! %s' % config_path)
    elif config_path is None:
        config_path = resource_filename("illiquids", "tornado.conf")
        if not os.path.isfile(config_path):
            raise Exception('no config_path!')
        
    tornado.options.parse_config_file(config_path)
    tornado.options.parse_command_line()
    logging.info("Loaded tornado config %s " % config_path)
    
    application = Application()

    logging.info('listening on port:%s' % options.port)
    
    #Native Tornado stuff
    application.listen(options.port)
    io_loop = tornado.ioloop.IOLoop.instance()
    
    def shutdown():
        logging.warning('Service request message to shut down')
        io_loop.stop()
    
    dispatcher.connect(shutdown, SHUTTING_DOWN)
    io_loop.start()
    
    return application
 def __init__(self,signal,sender,notifCallback):
     
     # log
     log.debug("create instance")
     
     # store params
     self.notifCallback = notifCallback
     self.sender        = sender
     
     # initialize parent class
     threading.Thread.__init__(self)
     
     # give this thread a name
     self.name          = 'MoteConnectorConsumer'
     
     # local variables
     self.goOn          = True
     self.dataQueue     = Queue.Queue(self.QUEUESIZE)
     
     # connect to dispatcher
     dispatcher.connect(
         #notifCallback,
         self._eventBusNotification,
         signal = signal,
     )
Esempio n. 9
0
 def __init__(self):
     self.wm = pyinotify.WatchManager()
     # These two instance variables are assumed to be constant
     self.watch_channel    = getsig('watch')
     self.organize_channel = getsig('organize')
     self.watch_listener   = StoreWatchListener(signal = self.watch_channel)
     self.__timeout_thread = ManagerTimeout(self)
     self.__timeout_thread.daemon = True
     self.__timeout_thread.start()
     self.organize = {
         'organize_path'      : None,
         'imported_path'      : None,
         'recorded_path'      : None,
         'problem_files_path' : None,
         'organizer'          : None,
         'problem_handler'    : None,
         'organize_listener'  : OrganizeListener(signal=
             self.organize_channel),
     }
     def dummy(sender, event): self.watch_move( event.path, sender=sender )
     dispatcher.connect(dummy, signal=getsig('watch_move'), 
             sender=dispatcher.Any, weak=False)
     def subwatch_add(sender, directory):
         self.__add_watch(directory, self.watch_listener)
     dispatcher.connect(subwatch_add, signal=getsig('add_subwatch'),
             sender=dispatcher.Any, weak=False)
     # A private mapping path => watch_descriptor
     # we use the same dictionary for organize, watch, store wd events.
     # this is a little hacky because we are unable to have multiple wd's
     # on the same path.
     self.__wd_path = {}
     # The following set isn't really necessary anymore. Should be
     # removed...
     self.watched_directories = set([])
Esempio n. 10
0
 def _fromXMLElement(cls, xmlElement, network = None):
     frame = NeuroptikonFrame()
     
     # Restore any console history.
     commandHistoryElement = xmlElement.find('CommandHistory')
     if commandHistoryElement is not None:
         history = []
         for commandElement in commandHistoryElement.findall('Command'):
             history += [commandElement.text]
         frame._console.history = history
     
     # TODO: set frame position and size
     
     # Populate the display (can't use the _fromXMLElement pattern here because it doesn't seem possible to re-parent a wx.GLCanvas.
     displayElement = xmlElement.find('Display')
     if displayElement is None:
         raise ValueError, gettext('Display windows must contain a display')
     frame.display.autoVisualize = False
     frame.display.setNetwork(network)
     if network:
         dispatcher.connect(frame.networkDidChangeSavePath, ('set', 'savePath'), network)
     frame.display._fromXMLElement(displayElement)
     frame.networkDidChangeSavePath()
     frame.setModified(False)
     wx.GetApp().inspector.inspectDisplay(frame.display)
     
     return frame
    def __init__(self, serialport):

        # log
        log.info("creating instance")

        # store params
        self.serialport = serialport

        # local variables
        self.parser = OpenParser.OpenParser()
        self.stateLock = threading.Lock()
        self.networkPrefix = None
        self._subcribedDataForDagRoot = False

        # give this thread a name
        self.name = "moteConnector@{0}".format(self.serialport)

        eventBusClient.eventBusClient.__init__(
            self,
            name=self.name,
            registrations=[
                {"sender": self.WILDCARD, "signal": "infoDagRoot", "callback": self._infoDagRoot_handler},
                {"sender": self.WILDCARD, "signal": "cmdToMote", "callback": self._cmdToMote_handler},
            ],
        )

        # subscribe to dispatcher
        dispatcher.connect(self._sendToParser, signal="fromMoteProbe@" + self.serialport)
Esempio n. 12
0
 def depend_signal( self, signal, sender=dispatcher.Any ):
     """Depend on signal from sender"""
     dispatcher.connect(
         self.clear,#receiver
         signal,
         sender,
     )
Esempio n. 13
0
 def __init__(self, node, network):
     """Initialize node."""
     # pylint: disable=import-error
     super().__init__()
     from openzwave.network import ZWaveNetwork
     from pydispatch import dispatcher
     self._network = network
     self.node = node
     self.node_id = self.node.node_id
     self._name = node_name(self.node)
     self._product_name = node.product_name
     self._manufacturer_name = node.manufacturer_name
     self._unique_id = self._compute_unique_id()
     self._attributes = {}
     self.wakeup_interval = None
     self.location = None
     self.battery_level = None
     dispatcher.connect(
         self.network_node_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
     dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE)
     dispatcher.connect(
         self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION)
     dispatcher.connect(
         self.network_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT)
     dispatcher.connect(
         self.network_scene_activated, ZWaveNetwork.SIGNAL_SCENE_EVENT)
Esempio n. 14
0
 def inner(receiver):
     if isinstance(signal, Signal):
         # preferable: involves proper logging
         signal.connect(receiver=receiver, sender=sender, weak=weak)
     else:
         connect(receiver, signal=signal, sender=sender, weak=weak)
     return receiver
    def __init__(self, parent):
        mdc_gui.MultiPing.__init__(self, parent)

        self.ping_list = ObjectListView(self.olv_panel, wx.ID_ANY,
                                        style=wx.LC_REPORT |
                                        wx.SUNKEN_BORDER)
        self.ping_list.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,
                            self.MultiPingOnContextMenu)
        self.ping_list.SetColumns(
            [ColumnDefn("IP", "center", 100, "ip_address"),
             ColumnDefn("MAC", "center", 130, "mac_address"),
             ColumnDefn("Hostname", "center", 130, "hostname"),
             ColumnDefn("Serial", "center", 150, "serial"),
             ColumnDefn("Successful Pings", "center", 110, "success"),
             ColumnDefn("Failed Pings", "center", 80, "failed")])

        self.olv_sizer.Add(self.ping_list, 1, wx.ALL | wx.EXPAND, 0)
        self.olv_sizer.Layout()

        self.parent = parent
        self.log_link_txt.SetURL(os.path.join(self.parent.path, 'ping_logs'))

        self.SetTitle("Multiple Ping Monitor")
        self.Bind(wx.EVT_CLOSE, self.on_close)

        self.redraw_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_refresh, self.redraw_timer)
        self.redraw_timer.Start(1000)

        dispatcher.connect(self.list_update,
                           signal='Ping Model Update',
                           sender=dispatcher.Any)
    def __init__(self, *args, **kwargs):
        self._set_ref_object(Scraper, **kwargs)
        self.scraper = self.ref_object
        self._set_config(**kwargs)
        
        if self.scraper.checker_set.count() == 0:
            msg = "No checkers defined for scraper!"
            logging.error(msg)
            raise CloseSpider(msg)
        
        for checker in self.scraper.checker_set.all():
            if checker.checker_type == '4':
                if not checker.checker_ref_url:
                    msg = "Please provide a reference url for your checker ({c}) (Command: {cr}).".format(c=str(checker), cr=self.command)
                    logging.error(msg)
                    raise CloseSpider(msg)
            
            if checker.checker_type == 'X':
                if not checker.checker_x_path or not checker.checker_ref_url:
                    msg = "Please provide the necessary x_path fields for your checker ({c}) (Command: {cr}).".format(c=str(checker), cr=self.command)
                    logging.error(msg)
                    raise CloseSpider(msg)

        self._set_request_kwargs()
        self._set_meta_splash_args()
        
        dispatcher.connect(self.response_received, signal=signals.response_received)
Esempio n. 17
0
    def __init__(self, value):
        """Initialize the zwave hvac."""
        from openzwave.network import ZWaveNetwork
        from pydispatch import dispatcher
        ZWaveDeviceEntity.__init__(self, value, DOMAIN)
        self._node = value.node
        self._target_temperature = None
        self._current_temperature = None
        self._current_operation = None
        self._operation_list = None
        self._current_operation_state = None
        self._current_fan_mode = None
        self._fan_list = None
        self._current_swing_mode = None
        self._swing_list = None
        self._unit = None
        self._zxt_120 = None
        self.update_properties()
        # register listener
        dispatcher.connect(
            self.value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
        # Make sure that we have values for the key before converting to int
        if (value.node.manufacturer_id.strip() and
                value.node.product_id.strip()):
            specific_sensor_key = (int(value.node.manufacturer_id, 16),
                                   int(value.node.product_id, 16),
                                   value.index)

            if specific_sensor_key in DEVICE_MAPPINGS:
                if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_ZXT_120:
                    _LOGGER.debug("Remotec ZXT-120 Zwave Thermostat as HVAC")
                    self._zxt_120 = 1
Esempio n. 18
0
 def __init__(self,refresh_period=REFRESH_PERIOD):
     
     # log
     log.info('creating instance')
     
     # store params
     self.refresh_period  = refresh_period
     
     # initialize parent class
     threading.Thread.__init__(self)
     
     # give this thread a name
     self.name                 = 'DataConnector'
     
     # local variables
     self.goOn                 = True
     self.dataLock             = threading.Lock()
     self.udpListeners         = {}
     self.appIdentifier        = AppIdentifier.AppIdentifier()
     self.appPayloadParsers    = {}
     self.appDataPublishers    = {}
     self.appInjectors         = {}
     self.mirrorEngine         = MirrorEngine.MirrorEngine()
     self.googleSyncEngine     = GoogleSyncEngine.GoogleSyncEngine()
     self.xivelySyncEngine     = XivelySyncEngine.XivelySyncEngine()
     
     # connect to dispatcher
     dispatcher.connect(
         self.tearDown,
         signal = 'tearDown',
         weak   = False,
     )
     
     # start itself
     self.start()
Esempio n. 19
0
    def __init__(self, playerOne=None, playerTwo=None):
        """Inits an instance of the Game class.

        PlayerOne is always the human side of the game.

        Args:
            playerOne (Optional[model.player.Player]):
                The human player (default is None).
            playerTwo (Optional[model.player.Player]):
                The AI player (default is None).

        """

        self.playerOne = playerOne
        self.playerTwo = playerTwo
        self.listeners = list()

        self.aiPlayer = self.playerOne if self.playerOne.isAi \
            else self.playerTwo

        self._board = Board()
        self._uuid = None
        self._moves = list()
        self.status = Status.InProgress
        self.nextPlayer = self.playerOne

        dispatcher.connect(self._onAiMoveResponse, signal=Events.aiResponse)
 def inspectDisplay(self, display):
     # Object inspectors are supposed to work purely at the network/biological layer so they don't need to know what the display is.
     self.display = display
     
     self.objects = ObjectList()
     self.updatingObjects = False
     for visible in display.selection():
         if visible.client.__class__ == self.__class__.objectClass():
             self.objects.append(visible.client)
             dispatcher.connect(self.nameChanged, ('set', 'name'), visible.client)
             for attributePath in self.inspectedAttributes():
                 if '.' in attributePath:
                     (subObject, attribute) = attributePath.split('.')
                     object = getattr(visible.client, subObject)
                 else:
                     object = visible.client
                     attribute = attributePath
                 dispatcher.connect(self.inspectedAttributeChanged, ('set', attribute), object)
     
     # Set the icon
     image = self.objects[0].__class__.image()
     if image == None:
         pass
     else:
         scaledImage = image.Rescale(32, 32, wx.IMAGE_QUALITY_HIGH)
         self.iconField.SetBitmap(wx.BitmapFromImage(scaledImage))
     
     self.populateNameField()
     self.populateObjectSizer()
     self._window.Layout()
Esempio n. 21
0
 def __init__ (self, type=None, *args, **kwargs):
  self.type = type
  self.kind = self.type.lower()
  super(Session, self).__init__(*args, **kwargs)
  dispatcher.connect(self.initialize, signals.session_created, sender=self)
  self.active = 0
  logging.debug("Created new session: %s" % self.name)
Esempio n. 22
0
 def register(self, callback, event, sender=dispatcher.Any, weak=True, expiry=-1, priority=dispatcher.LOWEST_PRIORITY):
     # register to receive events
     # if expiry == -1, then it is continuous, otherwise number is the number of times
     # that the callback is processed
     # XXX Major python problem - each callback must be a separate function (or wrapped in a lambda)
     # which makes it hard to disconnect it
     dispatcher.connect(callback, signal=event, sender=sender,weak=weak,expiry=expiry,priority=priority)
Esempio n. 23
0
 def __init__(self, jobs_root_path, jobs_loader):
     self.control_threads = {}
     self.jobs_loader = jobs_loader
     self.job_configs = jobs_loader.get_jobs()
     self.jobs_root_path = jobs_root_path
     dispatcher.connect(self.handle_job_signal, signal=JOB_COMMAND_SIGNAL, sender=dispatcher.Any)
     dispatcher.connect(self.handle_generic_signal, signal=COMMAND_SIGNAL, sender=dispatcher.Any)
    def test_signal(self):
        '''
        Test if setting a value the widget value is changed
        :return:
        '''
        # QT Stuff
        app = QApplication([])
        view1 = guidatawrapper.GuidataView(viewname='test_signal: Change one value and apply',  qtapp=app)
        (data1, widgettype1, widget1) = guidatawrapper.unittest.TestGuidataUtility.create_widget1(value=-2)
        view1.addWidgets(widget1)

        # prepare signal calls
        _viewChanged = [0]
        def on_viewUpdated():
            _viewChanged[0] = 1
        # Connect the signal
        dispatcher.connect(on_viewUpdated, signal=view.GenericView.SIGNAL_VIEWUPDATE, sender=view1)

        # test by setting directly the value in the dataclass associated to widget
        data1[0].value = 2.1
        self.assertEqual(_viewChanged[0], 1)

        # test the set widget
        _viewChanged[0] = 0
        widget1[0].setWidgetValue(3)
        self.assertEqual(_viewChanged[0], 1)
Esempio n. 25
0
    def registerCallback(
        cls,
        key,
        function = None,
        node = None,
        capture = 0,
    ):
        """Register callback function for the given key (possibly node-specific)

        key -- as returned by event.getKey()
        function -- callable function taking at least an
            event object as it's first parameter, or None
        node -- the node to be watched, None to register a
            context-level callback ( default )
        capture -- if true, capture events before passing to
            children, rather than processing during the
            bubbling phase.  (default false)

        Note: this method would normally be called by a sub-
            class with the calculated key for the sub-class.

        return previous callback function or None
        """
        previous = cls._removeCurrentCallbacks( key, node=node, capture=capture )
        if function is not None:
            metaKey = (cls.type,capture,key)
            if __debug__:
                log.info( """Register(%(capture)s): %(metaKey)r for node %(node)r -> %(function)r"""%locals())
            dispatcher.connect( function, sender=node, signal=metaKey )
            assert len(dispatcher.getReceivers(
                sender=node,
                signal=metaKey,
            )) == 1, """Have != 1 registered handlers for %(metaKey)r for node %(node)r"""%locals()
        return previous
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = cls(*args, **kwargs)
        spider._set_crawler(crawler)
        
        spider._set_ref_object(Scraper, **kwargs)
        spider.scraper = spider.ref_object
        spider._set_config(**kwargs)
        
        if spider.scraper.checker_set.count() == 0:
            msg = "No checkers defined for scraper!"
            spider.dds_logger.error(msg)
            raise CloseSpider(msg)
        
        for checker in spider.scraper.checker_set.all():
            if checker.checker_type == '4':
                if not checker.checker_ref_url:
                    msg = "Please provide a reference url for your checker ({c}).".format(c=str(checker))
                    spider.dds_logger.error(msg)
                    raise CloseSpider(msg)
            
            if checker.checker_type == 'X':
                if not checker.checker_x_path or not checker.checker_ref_url:
                    msg = "Please provide the necessary x_path fields for your checker ({c}).".format(c=str(checker))
                    spider.dds_logger.error(msg)
                    raise CloseSpider(msg)

        spider._set_request_kwargs()
        spider._set_meta_splash_args()
        
        dispatcher.connect(spider.response_received, signal=signals.response_received)
        
        return spider
 def __init__(self,serialportName,serialportBaudrate):
     
     # log
     log.debug("create instance")
     
     # store params
     self.serialportName       = serialportName
     self.serialportBaudrate   = serialportBaudrate
     
     # local variables
     self.hdlc                 = OpenHdlc.OpenHdlc()
     self.lastRxByte           = self.hdlc.HDLC_FLAG
     self.busyReceiving        = False
     self.inputBuf             = ''
     self.outputBuf            = []
     self.outputBufLock        = threading.RLock()
     
     # initialize the parent class
     threading.Thread.__init__(self)
     
     # give this thread a name
     self.name                 = 'moteProbeSerialThread@'+self.serialportName
     
     # connect to dispatcher
     dispatcher.connect(
         self.send,
         signal = 'bytesFromTcpPort'+self.serialportName,
     )
 def test_000_network_start_stop(self):
     self.driver_ready = False
     self.driver_removed = False
     self.options = ZWaveOption(device=self.device, user_path=self.userpath)
     self.options.set_log_file("OZW_Log.log")
     self.options.set_append_log_file(False)
     self.options.set_console_output(False)
     self.options.set_save_log_level("Debug")
     self.options.set_logging(True)
     self.options.lock()
     dispatcher.connect(self.driver_ready_message, ZWaveNetwork.SIGNAL_DRIVER_READY)
     dispatcher.connect(self.driver_removed_message, ZWaveNetwork.SIGNAL_DRIVER_REMOVED)
     self.network = ZWaveNetwork(self.options)
     for i in range(0, SLEEP):
         if self.network.state>=self.network.STATE_AWAKED:
             break
         else:
             time.sleep(1.0)
     self.assertTrue(self.driver_ready)
     self.network.stop()
     for i in range(0, SLEEP):
         if self.network.state==self.network.STATE_STOPPED:
             break
         else:
             time.sleep(1.0)
     self.assertEqual(self.network.state, self.network.STATE_STOPPED)
Esempio n. 29
0
    def connect(self, receiver, sender=Any, weak=True):
        """
        Connect receiver to sender for this signal. Wrapper for
        :func:`connect`. Usage::

            from xyz import post_save

            def log_saving_event(**kwargs):
                ...
            # call log_saving_event each time a Note is saved
            post_save.connect(log_saving_event, Note)

        Publishes a debug log message via Python's `logging` module.
        """
        connect(receiver, signal=self, sender=sender, weak=weak)

        # Log readable representation of both signal and receiver.
        # This is cheap because signals are mostly connected on start.
        if hasattr(receiver, '__module__') and hasattr(receiver, '__name__'):
            rcvr_repr = u'{0}.{1}'.format(receiver.__module__,
                                          receiver.__name__)
        else:
            rcvr_repr = unicode(repr(receiver))

        logger.debug('Subscribed {rcvr_repr} to "{self}"'.format(**locals()))
 def test_910_controller_stats_poll(self):
     self.stats_received = None
     dispatcher.connect(self.louie_controller_stats, ZWaveController.SIGNAL_CONTROLLER_STATS)
     self.network.controller.poll_stats = 8
     for i in range(0,10):
         #print("self.ctrl_command_result = %s" % self.ctrl_command_result)
         if self.stats_received is not None:
             break
         else:
             time.sleep(1.0)
     self.assertEqual(type(self.stats_received), type({}))
     self.assertTrue('SOFCnt' in self.stats_received)
     self.stats_received = None
     for i in range(0,10):
         #print("self.ctrl_command_result = %s" % self.ctrl_command_result)
         if self.stats_received is not None:
             break
         else:
             time.sleep(1.0)
     self.assertEqual(type(self.stats_received), type({}))
     self.network.controller.poll_stats = 0
     self.stats_received = None
     for i in range(0,12):
         #print("self.ctrl_command_result = %s" % self.ctrl_command_result)
         if self.stats_received is not None:
             break
         else:
             time.sleep(1.0)
     self.assertEqual(self.stats_received, None)
Esempio n. 31
0
    def set(self, **kwargs):
        """Set configuration parameters.

        **kwargs (dict): settings to be sent. Example:
        {'setting_1': 'value_1', 'setting_2': 'value_2'}

        pause (string): pause status
            'pause' = all  pause Interfacer fully, nothing read, processed or posted.
            'pause' = in   pauses the input only, no input read performed
            'pause' = out  pauses output only, input is read, processed but not posted to buffer
            'pause' = off  pause is off and Interfacer is fully operational (default)

        """
        #def setall(self, **kwargs):

        for key, setting in self._defaults.iteritems():
            if key in kwargs.keys():
                setting = kwargs[key]
            else:
                setting = self._defaults[key]
            if key in self._settings and self._settings[key] == setting:
                continue
            #self.set(key, setting)

    #def set(self, key, setting):

    #if key == 'pause' and str(setting).lower() in ['all', 'in', 'out', 'off']:
            elif key == 'pause' and str(setting).lower() in [
                    'all', 'in', 'out', 'off'
            ]:
                pass
            elif key == 'interval' and str(setting).isdigit():
                pass
            elif key == 'nodeoffset' and str(setting).isdigit():
                pass
            elif key == 'datacode' and str(setting) in [
                    '0', 'b', 'B', 'h', 'H', 'L', 'l', 'f'
            ]:
                pass
            elif key == 'scale' and (int(setting == 1)
                                     or not (int(setting % 10))):
                pass
            elif key == 'timestamped' and str(setting).lower() in [
                    'true', 'false'
            ]:
                pass
            elif key == 'targeted' and str(setting).lower() in [
                    'true', 'false'
            ]:
                pass
            elif key == 'pubchannels':
                pass
            elif key == 'subchannels':
                pass
            # elif key == 'rxchannels' and int(setting) >= 0 and int(setting) < 256:
            #     pass
            # elif key == 'txchannels' and int(setting) >= 0 and int(setting) < 256:
            #     pass
            else:
                self._log.warning(
                    "In interfacer set '%s' is not a valid setting for %s: %s"
                    % (str(setting), self.name, key))
                continue
            self._settings[key] = setting
            self._log.debug("Setting " + self.name + " " + key + ": " +
                            str(setting))

            # Is there a better place to put this?
            for channel in self._settings["subchannels"]:
                dispatcher.connect(self.receiver, channel)
                self._log.debug("Interfacer: Subscribed to channel' : " +
                                str(channel))
Esempio n. 32
0
async def async_setup_entry(hass, config_entry):
    """Set up Z-Wave from a config entry.

    Will automatically load components to support devices found on the network.
    """
    from pydispatch import dispatcher

    # pylint: disable=import-error
    from openzwave.option import ZWaveOption
    from openzwave.network import ZWaveNetwork
    from openzwave.group import ZWaveGroup

    # Merge config entry and yaml config
    config = config_entry.data
    if DATA_ZWAVE_CONFIG in hass.data:
        config = {**config, **hass.data[DATA_ZWAVE_CONFIG]}

    # Update hass.data with merged config so we can access it elsewhere
    hass.data[DATA_ZWAVE_CONFIG] = config

    # Load configuration
    use_debug = config.get(CONF_DEBUG, DEFAULT_DEBUG)
    autoheal = config.get(CONF_AUTOHEAL, DEFAULT_CONF_AUTOHEAL)
    device_config = EntityValues(
        config.get(CONF_DEVICE_CONFIG),
        config.get(CONF_DEVICE_CONFIG_DOMAIN),
        config.get(CONF_DEVICE_CONFIG_GLOB),
    )

    usb_path = config[CONF_USB_STICK_PATH]

    _LOGGER.info("Z-Wave USB path is %s", usb_path)

    # Setup options
    options = ZWaveOption(
        usb_path,
        user_path=hass.config.config_dir,
        config_path=config.get(CONF_CONFIG_PATH),
    )

    options.set_console_output(use_debug)

    if config.get(CONF_NETWORK_KEY):
        options.addOption("NetworkKey", config[CONF_NETWORK_KEY])

    await hass.async_add_executor_job(options.lock)
    network = hass.data[DATA_NETWORK] = ZWaveNetwork(options, autostart=False)
    hass.data[DATA_DEVICES] = {}
    hass.data[DATA_ENTITY_VALUES] = []

    registry = await async_get_registry(hass)

    wsapi.async_load_websocket_api(hass)

    if use_debug:  # pragma: no cover

        def log_all(signal, value=None):
            """Log all the signals."""
            print("")
            print("SIGNAL *****", signal)
            if value and signal in (
                    ZWaveNetwork.SIGNAL_VALUE_CHANGED,
                    ZWaveNetwork.SIGNAL_VALUE_ADDED,
                    ZWaveNetwork.SIGNAL_SCENE_EVENT,
                    ZWaveNetwork.SIGNAL_NODE_EVENT,
                    ZWaveNetwork.SIGNAL_AWAKE_NODES_QUERIED,
                    ZWaveNetwork.SIGNAL_ALL_NODES_QUERIED,
                    ZWaveNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD,
            ):
                pprint(_obj_to_dict(value))

            print("")

        dispatcher.connect(log_all, weak=False)

    def value_added(node, value):
        """Handle new added value to a node on the network."""
        # Check if this value should be tracked by an existing entity
        for values in hass.data[DATA_ENTITY_VALUES]:
            values.check_value(value)

        for schema in DISCOVERY_SCHEMAS:
            if not check_node_schema(node, schema):
                continue
            if not check_value_schema(
                    value, schema[const.DISC_VALUES][const.DISC_PRIMARY]):
                continue

            values = ZWaveDeviceEntityValues(hass, schema, value, config,
                                             device_config, registry)

            # We create a new list and update the reference here so that
            # the list can be safely iterated over in the main thread
            new_values = hass.data[DATA_ENTITY_VALUES] + [values]
            hass.data[DATA_ENTITY_VALUES] = new_values

    platform = EntityPlatform(
        hass=hass,
        logger=_LOGGER,
        domain=DOMAIN,
        platform_name=DOMAIN,
        platform=None,
        scan_interval=DEFAULT_SCAN_INTERVAL,
        entity_namespace=None,
        async_entities_added_callback=lambda: None,
    )
    platform.config_entry = config_entry

    def node_added(node):
        """Handle a new node on the network."""
        entity = ZWaveNodeEntity(node, network)

        async def _add_node_to_component():
            if hass.data[DATA_DEVICES].get(entity.unique_id):
                return

            name = node_name(node)
            generated_id = generate_entity_id(DOMAIN + ".{}", name, [])
            node_config = device_config.get(generated_id)
            if node_config.get(CONF_IGNORED):
                _LOGGER.info("Ignoring node entity %s due to device settings",
                             generated_id)
                return

            hass.data[DATA_DEVICES][entity.unique_id] = entity
            await platform.async_add_entities([entity])

        if entity.unique_id:
            hass.async_add_job(_add_node_to_component())
            return

        @callback
        def _on_ready(sec):
            _LOGGER.info("Z-Wave node %d ready after %d seconds",
                         entity.node_id, sec)
            hass.async_add_job(_add_node_to_component)

        @callback
        def _on_timeout(sec):
            _LOGGER.warning(
                "Z-Wave node %d not ready after %d seconds, "
                "continuing anyway",
                entity.node_id,
                sec,
            )
            hass.async_add_job(_add_node_to_component)

        hass.add_job(check_has_unique_id, entity, _on_ready, _on_timeout)

    def node_removed(node):
        node_id = node.node_id
        node_key = f"node-{node_id}"
        _LOGGER.info("Node Removed: %s", hass.data[DATA_DEVICES][node_key])
        for key in list(hass.data[DATA_DEVICES]):
            if not key.startswith(f"{node_id}-"):
                continue

            entity = hass.data[DATA_DEVICES][key]
            _LOGGER.info("Removing Entity - value: %s - entity_id: %s", key,
                         entity.entity_id)
            hass.add_job(entity.node_removed())
            del hass.data[DATA_DEVICES][key]

        entity = hass.data[DATA_DEVICES][node_key]
        hass.add_job(entity.node_removed())
        del hass.data[DATA_DEVICES][node_key]

    def network_ready():
        """Handle the query of all awake nodes."""
        _LOGGER.info("Z-Wave network is ready for use. All awake nodes "
                     "have been queried. Sleeping nodes will be "
                     "queried when they awake.")
        hass.bus.fire(const.EVENT_NETWORK_READY)

    def network_complete():
        """Handle the querying of all nodes on network."""
        _LOGGER.info("Z-Wave network is complete. All nodes on the network "
                     "have been queried")
        hass.bus.fire(const.EVENT_NETWORK_COMPLETE)

    def network_complete_some_dead():
        """Handle the querying of all nodes on network."""
        _LOGGER.info("Z-Wave network is complete. All nodes on the network "
                     "have been queried, but some nodes are marked dead")
        hass.bus.fire(const.EVENT_NETWORK_COMPLETE_SOME_DEAD)

    dispatcher.connect(value_added,
                       ZWaveNetwork.SIGNAL_VALUE_ADDED,
                       weak=False)
    dispatcher.connect(node_added, ZWaveNetwork.SIGNAL_NODE_ADDED, weak=False)
    dispatcher.connect(node_removed,
                       ZWaveNetwork.SIGNAL_NODE_REMOVED,
                       weak=False)
    dispatcher.connect(network_ready,
                       ZWaveNetwork.SIGNAL_AWAKE_NODES_QUERIED,
                       weak=False)
    dispatcher.connect(network_complete,
                       ZWaveNetwork.SIGNAL_ALL_NODES_QUERIED,
                       weak=False)
    dispatcher.connect(
        network_complete_some_dead,
        ZWaveNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD,
        weak=False,
    )

    def add_node(service):
        """Switch into inclusion mode."""
        _LOGGER.info("Z-Wave add_node have been initialized")
        network.controller.add_node()

    def add_node_secure(service):
        """Switch into secure inclusion mode."""
        _LOGGER.info("Z-Wave add_node_secure have been initialized")
        network.controller.add_node(True)

    def remove_node(service):
        """Switch into exclusion mode."""
        _LOGGER.info("Z-Wave remove_node have been initialized")
        network.controller.remove_node()

    def cancel_command(service):
        """Cancel a running controller command."""
        _LOGGER.info("Cancel running Z-Wave command")
        network.controller.cancel_command()

    def heal_network(service):
        """Heal the network."""
        _LOGGER.info("Z-Wave heal running")
        network.heal()

    def soft_reset(service):
        """Soft reset the controller."""
        _LOGGER.info("Z-Wave soft_reset have been initialized")
        network.controller.soft_reset()

    def test_network(service):
        """Test the network by sending commands to all the nodes."""
        _LOGGER.info("Z-Wave test_network have been initialized")
        network.test()

    def stop_network(_service_or_event):
        """Stop Z-Wave network."""
        _LOGGER.info("Stopping Z-Wave network")
        network.stop()
        if hass.state == CoreState.running:
            hass.bus.fire(const.EVENT_NETWORK_STOP)

    async def rename_node(service):
        """Rename a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        name = service.data.get(const.ATTR_NAME)
        node.name = name
        _LOGGER.info("Renamed Z-Wave node %d to %s", node_id, name)
        update_ids = service.data.get(const.ATTR_UPDATE_IDS)
        # We want to rename the device, the node entity,
        # and all the contained entities
        node_key = f"node-{node_id}"
        entity = hass.data[DATA_DEVICES][node_key]
        await entity.node_renamed(update_ids)
        for key in list(hass.data[DATA_DEVICES]):
            if not key.startswith(f"{node_id}-"):
                continue
            entity = hass.data[DATA_DEVICES][key]
            await entity.value_renamed(update_ids)

    async def rename_value(service):
        """Rename a node value."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        value_id = service.data.get(const.ATTR_VALUE_ID)
        node = network.nodes[node_id]
        value = node.values[value_id]
        name = service.data.get(const.ATTR_NAME)
        value.label = name
        _LOGGER.info("Renamed Z-Wave value (Node %d Value %d) to %s", node_id,
                     value_id, name)
        update_ids = service.data.get(const.ATTR_UPDATE_IDS)
        value_key = f"{node_id}-{value_id}"
        entity = hass.data[DATA_DEVICES][value_key]
        await entity.value_renamed(update_ids)

    def set_poll_intensity(service):
        """Set the polling intensity of a node value."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        value_id = service.data.get(const.ATTR_VALUE_ID)
        node = network.nodes[node_id]
        value = node.values[value_id]
        intensity = service.data.get(const.ATTR_POLL_INTENSITY)
        if intensity == 0:
            if value.disable_poll():
                _LOGGER.info("Polling disabled (Node %d Value %d)", node_id,
                             value_id)
                return
            _LOGGER.info("Polling disabled failed (Node %d Value %d)", node_id,
                         value_id)
        else:
            if value.enable_poll(intensity):
                _LOGGER.info(
                    "Set polling intensity (Node %d Value %d) to %s",
                    node_id,
                    value_id,
                    intensity,
                )
                return
            _LOGGER.info("Set polling intensity failed (Node %d Value %d)",
                         node_id, value_id)

    def remove_failed_node(service):
        """Remove failed node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        _LOGGER.info("Trying to remove zwave node %d", node_id)
        network.controller.remove_failed_node(node_id)

    def replace_failed_node(service):
        """Replace failed node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        _LOGGER.info("Trying to replace zwave node %d", node_id)
        network.controller.replace_failed_node(node_id)

    def set_config_parameter(service):
        """Set a config parameter to a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        param = service.data.get(const.ATTR_CONFIG_PARAMETER)
        selection = service.data.get(const.ATTR_CONFIG_VALUE)
        size = service.data.get(const.ATTR_CONFIG_SIZE)
        for value in node.get_values(
                class_id=const.COMMAND_CLASS_CONFIGURATION).values():
            if value.index != param:
                continue
            if value.type == const.TYPE_BOOL:
                value.data = int(selection == "True")
                _LOGGER.info(
                    "Setting config parameter %s on Node %s "
                    "with bool selection %s",
                    param,
                    node_id,
                    str(selection),
                )
                return
            if value.type == const.TYPE_LIST:
                value.data = str(selection)
                _LOGGER.info(
                    "Setting config parameter %s on Node %s "
                    "with list selection %s",
                    param,
                    node_id,
                    str(selection),
                )
                return
            if value.type == const.TYPE_BUTTON:
                network.manager.pressButton(value.value_id)
                network.manager.releaseButton(value.value_id)
                _LOGGER.info(
                    "Setting config parameter %s on Node %s "
                    "with button selection %s",
                    param,
                    node_id,
                    selection,
                )
                return
            value.data = int(selection)
            _LOGGER.info(
                "Setting config parameter %s on Node %s "
                "with selection %s",
                param,
                node_id,
                selection,
            )
            return
        node.set_config_param(param, selection, size)
        _LOGGER.info(
            "Setting unknown config parameter %s on Node %s "
            "with selection %s",
            param,
            node_id,
            selection,
        )

    def refresh_node_value(service):
        """Refresh the specified value from a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        value_id = service.data.get(const.ATTR_VALUE_ID)
        node = network.nodes[node_id]
        node.values[value_id].refresh()
        _LOGGER.info("Node %s value %s refreshed", node_id, value_id)

    def set_node_value(service):
        """Set the specified value on a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        value_id = service.data.get(const.ATTR_VALUE_ID)
        value = service.data.get(const.ATTR_CONFIG_VALUE)
        node = network.nodes[node_id]
        node.values[value_id].data = value
        _LOGGER.info("Node %s value %s set to %s", node_id, value_id, value)

    def print_config_parameter(service):
        """Print a config parameter from a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        param = service.data.get(const.ATTR_CONFIG_PARAMETER)
        _LOGGER.info(
            "Config parameter %s on Node %s: %s",
            param,
            node_id,
            get_config_value(node, param),
        )

    def print_node(service):
        """Print all information about z-wave node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        nice_print_node(node)

    def set_wakeup(service):
        """Set wake-up interval of a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        value = service.data.get(const.ATTR_CONFIG_VALUE)
        if node.can_wake_up():
            for value_id in node.get_values(
                    class_id=const.COMMAND_CLASS_WAKE_UP):
                node.values[value_id].data = value
                _LOGGER.info("Node %s wake-up set to %d", node_id, value)
        else:
            _LOGGER.info("Node %s is not wakeable", node_id)

    def change_association(service):
        """Change an association in the zwave network."""
        association_type = service.data.get(const.ATTR_ASSOCIATION)
        node_id = service.data.get(const.ATTR_NODE_ID)
        target_node_id = service.data.get(const.ATTR_TARGET_NODE_ID)
        group = service.data.get(const.ATTR_GROUP)
        instance = service.data.get(const.ATTR_INSTANCE)

        node = ZWaveGroup(group, network, node_id)
        if association_type == "add":
            node.add_association(target_node_id, instance)
            _LOGGER.info(
                "Adding association for node:%s in group:%s "
                "target node:%s, instance=%s",
                node_id,
                group,
                target_node_id,
                instance,
            )
        if association_type == "remove":
            node.remove_association(target_node_id, instance)
            _LOGGER.info(
                "Removing association for node:%s in group:%s "
                "target node:%s, instance=%s",
                node_id,
                group,
                target_node_id,
                instance,
            )

    async def async_refresh_entity(service):
        """Refresh values that specific entity depends on."""
        entity_id = service.data.get(ATTR_ENTITY_ID)
        async_dispatcher_send(hass,
                              SIGNAL_REFRESH_ENTITY_FORMAT.format(entity_id))

    def refresh_node(service):
        """Refresh all node info."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        node.refresh_info()

    def reset_node_meters(service):
        """Reset meter counters of a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        instance = service.data.get(const.ATTR_INSTANCE)
        node = network.nodes[node_id]
        for value in node.get_values(
                class_id=const.COMMAND_CLASS_METER).values():
            if value.index != const.INDEX_METER_RESET:
                continue
            if value.instance != instance:
                continue
            network.manager.pressButton(value.value_id)
            network.manager.releaseButton(value.value_id)
            _LOGGER.info("Resetting meters on node %s instance %s....",
                         node_id, instance)
            return
        _LOGGER.info(
            "Node %s on instance %s does not have resettable "
            "meters.",
            node_id,
            instance,
        )

    def heal_node(service):
        """Heal a node on the network."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        update_return_routes = service.data.get(const.ATTR_RETURN_ROUTES)
        node = network.nodes[node_id]
        _LOGGER.info("Z-Wave node heal running for node %s", node_id)
        node.heal(update_return_routes)

    def test_node(service):
        """Send test messages to a node on the network."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        messages = service.data.get(const.ATTR_MESSAGES)
        node = network.nodes[node_id]
        _LOGGER.info("Sending %s test-messages to node %s.", messages, node_id)
        node.test(messages)

    def start_zwave(_service_or_event):
        """Startup Z-Wave network."""
        _LOGGER.info("Starting Z-Wave network...")
        network.start()
        hass.bus.fire(const.EVENT_NETWORK_START)

        async def _check_awaked():
            """Wait for Z-wave awaked state (or timeout) and finalize start."""
            _LOGGER.debug("network state: %d %s", network.state,
                          network.state_str)

            start_time = dt_util.utcnow()
            while True:
                waited = int((dt_util.utcnow() - start_time).total_seconds())

                if network.state >= network.STATE_AWAKED:
                    # Need to be in STATE_AWAKED before talking to nodes.
                    _LOGGER.info("Z-Wave ready after %d seconds", waited)
                    break
                elif waited >= const.NETWORK_READY_WAIT_SECS:
                    # Wait up to NETWORK_READY_WAIT_SECS seconds for the Z-Wave
                    # network to be ready.
                    _LOGGER.warning(
                        "Z-Wave not ready after %d seconds, continuing anyway",
                        waited)
                    _LOGGER.info("final network state: %d %s", network.state,
                                 network.state_str)
                    break
                else:
                    await asyncio.sleep(1)

            hass.async_add_job(_finalize_start)

        hass.add_job(_check_awaked)

    def _finalize_start():
        """Perform final initializations after Z-Wave network is awaked."""
        polling_interval = convert(config.get(CONF_POLLING_INTERVAL), int)
        if polling_interval is not None:
            network.set_poll_interval(polling_interval, False)

        poll_interval = network.get_poll_interval()
        _LOGGER.info("Z-Wave polling interval set to %d ms", poll_interval)

        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_network)

        # Register node services for Z-Wave network
        hass.services.register(DOMAIN, const.SERVICE_ADD_NODE, add_node)
        hass.services.register(DOMAIN, const.SERVICE_ADD_NODE_SECURE,
                               add_node_secure)
        hass.services.register(DOMAIN, const.SERVICE_REMOVE_NODE, remove_node)
        hass.services.register(DOMAIN, const.SERVICE_CANCEL_COMMAND,
                               cancel_command)
        hass.services.register(DOMAIN, const.SERVICE_HEAL_NETWORK,
                               heal_network)
        hass.services.register(DOMAIN, const.SERVICE_SOFT_RESET, soft_reset)
        hass.services.register(DOMAIN, const.SERVICE_TEST_NETWORK,
                               test_network)
        hass.services.register(DOMAIN, const.SERVICE_STOP_NETWORK,
                               stop_network)
        hass.services.register(DOMAIN,
                               const.SERVICE_RENAME_NODE,
                               rename_node,
                               schema=RENAME_NODE_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_RENAME_VALUE,
                               rename_value,
                               schema=RENAME_VALUE_SCHEMA)
        hass.services.register(
            DOMAIN,
            const.SERVICE_SET_CONFIG_PARAMETER,
            set_config_parameter,
            schema=SET_CONFIG_PARAMETER_SCHEMA,
        )
        hass.services.register(
            DOMAIN,
            const.SERVICE_SET_NODE_VALUE,
            set_node_value,
            schema=SET_NODE_VALUE_SCHEMA,
        )
        hass.services.register(
            DOMAIN,
            const.SERVICE_REFRESH_NODE_VALUE,
            refresh_node_value,
            schema=REFRESH_NODE_VALUE_SCHEMA,
        )
        hass.services.register(
            DOMAIN,
            const.SERVICE_PRINT_CONFIG_PARAMETER,
            print_config_parameter,
            schema=PRINT_CONFIG_PARAMETER_SCHEMA,
        )
        hass.services.register(
            DOMAIN,
            const.SERVICE_REMOVE_FAILED_NODE,
            remove_failed_node,
            schema=NODE_SERVICE_SCHEMA,
        )
        hass.services.register(
            DOMAIN,
            const.SERVICE_REPLACE_FAILED_NODE,
            replace_failed_node,
            schema=NODE_SERVICE_SCHEMA,
        )

        hass.services.register(
            DOMAIN,
            const.SERVICE_CHANGE_ASSOCIATION,
            change_association,
            schema=CHANGE_ASSOCIATION_SCHEMA,
        )
        hass.services.register(DOMAIN,
                               const.SERVICE_SET_WAKEUP,
                               set_wakeup,
                               schema=SET_WAKEUP_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_PRINT_NODE,
                               print_node,
                               schema=NODE_SERVICE_SCHEMA)
        hass.services.register(
            DOMAIN,
            const.SERVICE_REFRESH_ENTITY,
            async_refresh_entity,
            schema=REFRESH_ENTITY_SCHEMA,
        )
        hass.services.register(DOMAIN,
                               const.SERVICE_REFRESH_NODE,
                               refresh_node,
                               schema=NODE_SERVICE_SCHEMA)
        hass.services.register(
            DOMAIN,
            const.SERVICE_RESET_NODE_METERS,
            reset_node_meters,
            schema=RESET_NODE_METERS_SCHEMA,
        )
        hass.services.register(
            DOMAIN,
            const.SERVICE_SET_POLL_INTENSITY,
            set_poll_intensity,
            schema=SET_POLL_INTENSITY_SCHEMA,
        )
        hass.services.register(DOMAIN,
                               const.SERVICE_HEAL_NODE,
                               heal_node,
                               schema=HEAL_NODE_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_TEST_NODE,
                               test_node,
                               schema=TEST_NODE_SCHEMA)

    # Setup autoheal
    if autoheal:
        _LOGGER.info("Z-Wave network autoheal is enabled")
        async_track_time_change(hass, heal_network, hour=0, minute=0, second=0)

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_zwave)

    hass.services.async_register(DOMAIN, const.SERVICE_START_NETWORK,
                                 start_zwave)

    for entry_component in SUPPORTED_PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(
                config_entry, entry_component))

    return True
Esempio n. 33
0
def louie_network_ready(network):
    L.l.info(
        'Louie signal: ZWave network is ready : {} nodes were found.'.format(
            network.nodes_count))
    L.l.info('Louie signal: Controller : {}'.format(network.controller))
    dispatcher.connect(louie_node_update, ZWaveNetwork.SIGNAL_NODE)
    # dispatcher.connect(louie_value, ZWaveNetwork.SIGNAL_VALUE)
    dispatcher.connect(louie_value_refreshed,
                       ZWaveNetwork.SIGNAL_VALUE_REFRESHED)
    dispatcher.connect(louie_value_added, ZWaveNetwork.SIGNAL_VALUE_ADDED)
    dispatcher.connect(louie_value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
    dispatcher.connect(louie_value_removed, ZWaveNetwork.SIGNAL_VALUE_REMOVED)
    dispatcher.connect(louie_ctrl_message, ZWaveController.SIGNAL_CONTROLLER)
    dispatcher.connect(louie_button_on, ZWaveNetwork.SIGNAL_BUTTON_ON)
    dispatcher.connect(louie_button_off, ZWaveNetwork.SIGNAL_BUTTON_OFF)
    dispatcher.connect(louie_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT)
    dispatcher.connect(louie_node_event, ZWaveNetwork.SIGNAL_NODE_ADDED)
    dispatcher.connect(louie_node_event, ZWaveNetwork.SIGNAL_NODE_NEW)
    dispatcher.connect(louie_scene_event, ZWaveNetwork.SIGNAL_SCENE_EVENT)
    def __init__(self, **kwargs):
        """Attrs initialized here have names as in :dict:`_initials`

        Doctests
        ++++++++

        >>> t.start()
        (True, 'OK')

        # >>> t.hard_reset(force=True)
        # (True, 'OK')
        # >>> print("*** Action needed for node to be _added_ ***") # doctest:+ELLIPSIS
        # *** ...
        # >>> t.add_node() # doctest:+ELLIPSIS
        # {...}
        """
        if self._initialized:
            raise RuntimeErr("[Bug] backend already initialized!?")

        self._initialized = True

        # set defaults
        for attr in self._initials.keys():
            setattr(self, attr, self._initials[attr])

        # ...remainder.
        for k in kwargs.keys():
            if not hasattr(self, k):
                raise AttributeError(
                    "{}: no such attribute in definition of class {}.".format(
                        k, self.__class__.__name__))
            else:
                setattr(self, k, kwargs[k])

        # we put all artifacts here
        user_path = os.path.expanduser(os.path.expandvars(self.ozw_user_path))
        try:
            os.makedirs(self.ozw_user_path, exist_ok=True)
        except Exception as e:
            raise RuntimeError("Can't create user_path: {}".format(e))

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(self.log_level)

        fh = logging.FileHandler("{}/{}.log".format(self.ozw_user_path,
                                                    __name__),
                                 mode='w')
        fh.setLevel(self.log_level)
        fh.setFormatter(
            logging.Formatter(self.log_format_dbg if self.log_level <= logging.
                              DEBUG else self.log_format))
        self.logger.addHandler(fh)

        self.logger.debug('initializing OZW backend...')

        options = ZWaveOption(self.device,
                              config_path=self.ozw_config_path,
                              user_path=self.ozw_user_path)

        options.set_log_file('OZW.log')
        options.set_append_log_file(False)
        options.set_console_output(False)
        options.set_save_log_level(
            'Debug' if self.log_level <= logging.DEBUG else 'Warning')
        options.set_logging(True)
        options.lock()

        self.network = ZWaveNetwork(options, autostart=False)

        # A dispatcher associates a callback method to a signal. Signals
        # are generated by the library python-openzwave. Once a signal is
        # received, its associated callback is executed (see "_node_added"
        # example below in "_network_started" method)
        dispatcher.connect(self._network_started,
                           ZWaveNetwork.SIGNAL_NETWORK_STARTED)
        dispatcher.connect(self._network_ready,
                           ZWaveNetwork.SIGNAL_NETWORK_READY)
        # Yep! It's really 'RESETTED', wanna file a bug for bad english usage? ;-)
        dispatcher.connect(self._network_reset,
                           ZWaveNetwork.SIGNAL_NETWORK_RESETTED)

        # dynamically set on add/remove events. See notification handlers below.
        self.node_added = None
        self.node_removed = None
        self.timestamps = {
        }  # times of the last values' update for each sensor

        # The different stages that a node object gets through before being
        # ready. [BUG] Why do we need to explicitly list them? Anyway to get
        # them from the lib?
        self.queryStages = {
            "None": 1,  # Query process hasn't started for this node
            "ProtocolInfo": 2,  # Retrieve protocol information
            "Probe": 3,  # Ping node to see if alive
            "WakeUp": 4,  # Start wake up process if a sleeping node
            "ManufacturerSpecific1":
            5,  # Retrieve manufacturer name and product ids if ProtocolInfo lets us
            "NodeInfo":
            6,  # Retrieve info about supported, controlled command classes
            "NodePlusInfo":
            7,  # Retrieve Z-Wave+ info and update device classes (Added by Edin et Daniel)
            "SecurityReport":
            8,  # Retrieve a list of Command Classes that require Security
            "ManufacturerSpecific2":
            9,  # Retrieve manufacturer name and product ids
            "Versions": 10,  # Retrieve version information
            "Instances":
            11,  # Retrieve information about multiple command class instances
            "Static": 12,  # Retrieve static information (doesn't change)
            "Probe1": 13,  # Ping a node upon starting with configuration
            "Associations": 14,  # Retrieve information about associations
            "Neighbors": 15,  # Retrieve node neighbor list
            "Session":
            16,  # Retrieve session information (changes infrequently)
            "Dynamic": 17,  # Retrieve dynamic information (changes frequently)
            "Configuration":
            18,  # Retrieve configurable parameter information (only done on request)
            "Complete": 19  # Query process is completed for this node
        }
Esempio n. 35
0
def setup(hass, config):
    """
    Setup Z-wave.
    Will automatically load components to support devices found on the network.
    """
    # pylint: disable=global-statement, import-error
    global NETWORK

    from pydispatch import dispatcher
    from openzwave.option import ZWaveOption
    from openzwave.network import ZWaveNetwork

    # Load configuration
    use_debug = str(config[DOMAIN].get(CONF_DEBUG)) == '1'
    customize = config[DOMAIN].get(CONF_CUSTOMIZE, {})

    # Setup options
    options = ZWaveOption(
        config[DOMAIN].get(CONF_USB_STICK_PATH, DEFAULT_CONF_USB_STICK_PATH),
        user_path=hass.config.config_dir,
        config_path=config[DOMAIN].get('config_path',
                                       DEFAULT_ZWAVE_CONFIG_PATH),
    )

    options.set_console_output(use_debug)
    options.lock()

    NETWORK = ZWaveNetwork(options, autostart=False)

    if use_debug:

        def log_all(signal, value=None):
            """ Log all the signals. """
            print("")
            print("SIGNAL *****", signal)
            if value and signal in (ZWaveNetwork.SIGNAL_VALUE_CHANGED,
                                    ZWaveNetwork.SIGNAL_VALUE_ADDED):
                pprint(_obj_to_dict(value))

            print("")

        dispatcher.connect(log_all, weak=False)

    def value_added(node, value):
        """ Called when a value is added to a node on the network. """

        for (component, discovery_service, command_ids, value_type,
             value_genre) in DISCOVERY_COMPONENTS:

            if value.command_class not in command_ids:
                continue
            if value_type is not None and value_type != value.type:
                continue
            if value_genre is not None and value_genre != value.genre:
                continue

            # Ensure component is loaded
            bootstrap.setup_component(hass, component, config)

            # Configure node
            name = "{}.{}".format(component, _object_id(value))

            node_config = customize.get(name, {})
            polling_intensity = convert(
                node_config.get(CONF_POLLING_INTENSITY), int)
            if polling_intensity is not None:
                value.enable_poll(polling_intensity)

            # Fire discovery event
            hass.bus.fire(
                EVENT_PLATFORM_DISCOVERED, {
                    ATTR_SERVICE: discovery_service,
                    ATTR_DISCOVERED: {
                        ATTR_NODE_ID: node.node_id,
                        ATTR_VALUE_ID: value.value_id,
                    }
                })

    def scene_activated(node, scene_id):
        """ Called when a scene is activated on any node in the network. """
        name = _node_name(node)
        object_id = "{}_{}".format(slugify(name), node.node_id)

        hass.bus.fire(EVENT_SCENE_ACTIVATED, {
            ATTR_ENTITY_ID: object_id,
            ATTR_SCENE_ID: scene_id
        })

    dispatcher.connect(value_added,
                       ZWaveNetwork.SIGNAL_VALUE_ADDED,
                       weak=False)
    dispatcher.connect(scene_activated,
                       ZWaveNetwork.SIGNAL_SCENE_EVENT,
                       weak=False)

    def add_node(event):
        """ Switch into inclusion mode """
        NETWORK.controller.begin_command_add_device()

    def remove_node(event):
        """ Switch into exclusion mode"""
        NETWORK.controller.begin_command_remove_device()

    def stop_zwave(event):
        """ Stop Z-wave. """
        NETWORK.stop()

    def start_zwave(event):
        """ Called when Home Assistant starts up. """
        NETWORK.start()

        polling_interval = convert(config[DOMAIN].get(CONF_POLLING_INTERVAL),
                                   int)
        if polling_interval is not None:
            NETWORK.set_poll_interval(polling_interval, False)

        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zwave)

        # register add / remove node services for zwave sticks without
        # hardware inclusion button
        hass.services.register(DOMAIN, SERVICE_ADD_NODE, add_node)
        hass.services.register(DOMAIN, SERVICE_REMOVE_NODE, remove_node)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_zwave)

    return True
 def __init__(self, parent):
     StatusBar.__init__(self, parent)
     connect(self.update, signal='status_update', sender=Any)
     connect(self.clear, signal='status_clear', sender=Any)
 def __init__(self, redis_host, redis_port, *args, **kwargs):
     super(HistoricSoldURLCollector, self).__init__()
     self.sold_age = kwargs.get('SOLD_AGE', '12m')
     self.max_locations_per_run = int(kwargs.get('MAX_LOC_PER_RUN', 5))
     self.redis = self._connect_to_redis(redis_host, redis_port)
     dispatcher.connect(self.spider_closed, signals.spider_closed)
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.items = []
     dispatcher.connect(self.load_asin, signals.engine_started)
Esempio n. 39
0
    def __init__(self, flask_app, socket_io):
        dispatcher.connect(self.taking_image,
                           signal=CarStatus.TAKING_IMAGE,
                           sender=dispatcher.Any)
        dispatcher.connect(self.image_taken,
                           signal=CarStatus.IMAGE_TAKEN,
                           sender=dispatcher.Any)
        dispatcher.connect(self.uploading_image,
                           signal=CarStatus.UPLOADING_IMAGE,
                           sender=dispatcher.Any)
        dispatcher.connect(self.image_uploaded,
                           signal=CarStatus.IMAGE_UPLOADED,
                           sender=dispatcher.Any)
        dispatcher.connect(self.analysing_image,
                           signal=CarStatus.ANALYSING_IMAGE,
                           sender=dispatcher.Any)
        dispatcher.connect(self.traffic_light_detected,
                           signal=CarStatus.TRAFFIC_LIGHT_DETECTED,
                           sender=dispatcher.Any)
        dispatcher.connect(self.traffic_light_not_present,
                           signal=CarStatus.TRAFFIC_LIGHT_NOT_PRESENT,
                           sender=dispatcher.Any)
        dispatcher.connect(self.move_forward,
                           signal=CarStatus.MOVING_FORWARD,
                           sender=dispatcher.Any)
        dispatcher.connect(self.stopped,
                           signal=CarStatus.STOPPED,
                           sender=dispatcher.Any)

        self._flaskApp = flask_app
        self._socketIo = socket_io
Esempio n. 40
0
 def __init__(self):
     dispatcher.connect(self.spider_closed, signals.spider_closed)
Esempio n. 41
0
 def __init__(self):
     dispatcher.connect(self._exit, signal=Signals.EXIT, sender=dispatcher.Any)
     self._run()
Esempio n. 42
0
    def __init__(self, node, network):
        """Initialize node."""
        super().__init__()
        from openzwave.network import ZWaveNetwork
        from pydispatch import dispatcher

        self._network = network
        self.node = node
        self.node_id = self.node.node_id
        self._name = node_name(self.node)
        self._product_name = node.product_name
        self._manufacturer_name = node.manufacturer_name
        self._unique_id = self._compute_unique_id()
        self._application_version = None
        self._attributes = {}
        self.wakeup_interval = None
        self.location = None
        self.battery_level = None
        dispatcher.connect(self.network_node_value_added,
                           ZWaveNetwork.SIGNAL_VALUE_ADDED)
        dispatcher.connect(self.network_node_changed,
                           ZWaveNetwork.SIGNAL_VALUE_CHANGED)
        dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(self.network_node_changed,
                           ZWaveNetwork.SIGNAL_NOTIFICATION)
        dispatcher.connect(self.network_node_event,
                           ZWaveNetwork.SIGNAL_NODE_EVENT)
        dispatcher.connect(self.network_scene_activated,
                           ZWaveNetwork.SIGNAL_SCENE_EVENT)
Esempio n. 43
0
 def messageHandler(self, randWakeup):
     print("randWakeup = %d at %d\n" % (randWakeup, self.env.now))
     dispatcher.connect(self.handler,
                        signal=TRANSFER_SIGNAL,
                        sender=TRANSFER_SENDER)
Esempio n. 44
0
def setup(hass, config):
    """Set up Z-Wave.

    Will automatically load components to support devices found on the network.
    """
    descriptions = conf_util.load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    from pydispatch import dispatcher
    # pylint: disable=import-error
    from openzwave.option import ZWaveOption
    from openzwave.network import ZWaveNetwork
    from openzwave.group import ZWaveGroup

    # Load configuration
    use_debug = config[DOMAIN].get(CONF_DEBUG)
    autoheal = config[DOMAIN].get(CONF_AUTOHEAL)
    device_config = EntityValues(config[DOMAIN][CONF_DEVICE_CONFIG],
                                 config[DOMAIN][CONF_DEVICE_CONFIG_DOMAIN],
                                 config[DOMAIN][CONF_DEVICE_CONFIG_GLOB])
    new_entity_ids = config[DOMAIN][CONF_NEW_ENTITY_IDS]
    if not new_entity_ids:
        _LOGGER.warning(
            "ZWave entity_ids will soon be changing. To opt in to new "
            "entity_ids now, set `new_entity_ids: true` under zwave in your "
            "configuration.yaml. See the following blog post for details: "
            "https://home-assistant.io/blog/2017/06/15/zwave-entity-ids/")

    # Setup options
    options = ZWaveOption(config[DOMAIN].get(CONF_USB_STICK_PATH),
                          user_path=hass.config.config_dir,
                          config_path=config[DOMAIN].get(CONF_CONFIG_PATH))

    options.set_console_output(use_debug)

    if CONF_NETWORK_KEY in config[DOMAIN]:
        options.addOption("NetworkKey", config[DOMAIN][CONF_NETWORK_KEY])

    options.lock()

    network = hass.data[DATA_NETWORK] = ZWaveNetwork(options, autostart=False)
    hass.data[DATA_DEVICES] = {}
    hass.data[DATA_ENTITY_VALUES] = []

    if use_debug:  # pragma: no cover

        def log_all(signal, value=None):
            """Log all the signals."""
            print("")
            print("SIGNAL *****", signal)
            if value and signal in (ZWaveNetwork.SIGNAL_VALUE_CHANGED,
                                    ZWaveNetwork.SIGNAL_VALUE_ADDED,
                                    ZWaveNetwork.SIGNAL_SCENE_EVENT,
                                    ZWaveNetwork.SIGNAL_NODE_EVENT,
                                    ZWaveNetwork.SIGNAL_AWAKE_NODES_QUERIED,
                                    ZWaveNetwork.SIGNAL_ALL_NODES_QUERIED):
                pprint(_obj_to_dict(value))

            print("")

        dispatcher.connect(log_all, weak=False)

    def value_added(node, value):
        """Handle new added value to a node on the network."""
        # Check if this value should be tracked by an existing entity
        for values in hass.data[DATA_ENTITY_VALUES]:
            values.check_value(value)

        for schema in DISCOVERY_SCHEMAS:
            if not check_node_schema(node, schema):
                continue
            if not check_value_schema(
                    value, schema[const.DISC_VALUES][const.DISC_PRIMARY]):
                continue

            values = ZWaveDeviceEntityValues(hass, schema, value, config,
                                             device_config)

            # We create a new list and update the reference here so that
            # the list can be safely iterated over in the main thread
            new_values = hass.data[DATA_ENTITY_VALUES] + [values]
            hass.data[DATA_ENTITY_VALUES] = new_values

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    def node_added(node):
        """Handle a new node on the network."""
        entity = ZWaveNodeEntity(node, network, new_entity_ids)
        name = node_name(node)
        if new_entity_ids:
            generated_id = generate_entity_id(DOMAIN + '.{}', name, [])
        else:
            generated_id = entity.entity_id
        node_config = device_config.get(generated_id)
        if node_config.get(CONF_IGNORED):
            _LOGGER.info("Ignoring node entity %s due to device settings",
                         generated_id)
            return
        component.add_entities([entity])

    def network_ready():
        """Handle the query of all awake nodes."""
        _LOGGER.info("Zwave network is ready for use. All awake nodes "
                     "have been queried. Sleeping nodes will be "
                     "queried when they awake.")
        hass.bus.fire(const.EVENT_NETWORK_READY)

    def network_complete():
        """Handle the querying of all nodes on network."""
        _LOGGER.info("Z-Wave network is complete. All nodes on the network "
                     "have been queried")
        hass.bus.fire(const.EVENT_NETWORK_COMPLETE)

    dispatcher.connect(value_added,
                       ZWaveNetwork.SIGNAL_VALUE_ADDED,
                       weak=False)
    dispatcher.connect(node_added, ZWaveNetwork.SIGNAL_NODE_ADDED, weak=False)
    dispatcher.connect(network_ready,
                       ZWaveNetwork.SIGNAL_AWAKE_NODES_QUERIED,
                       weak=False)
    dispatcher.connect(network_complete,
                       ZWaveNetwork.SIGNAL_ALL_NODES_QUERIED,
                       weak=False)

    def add_node(service):
        """Switch into inclusion mode."""
        _LOGGER.info("Z-Wave add_node have been initialized")
        network.controller.add_node()

    def add_node_secure(service):
        """Switch into secure inclusion mode."""
        _LOGGER.info("Z-Wave add_node_secure have been initialized")
        network.controller.add_node(True)

    def remove_node(service):
        """Switch into exclusion mode."""
        _LOGGER.info("Z-Wwave remove_node have been initialized")
        network.controller.remove_node()

    def cancel_command(service):
        """Cancel a running controller command."""
        _LOGGER.info("Cancel running Z-Wave command")
        network.controller.cancel_command()

    def heal_network(service):
        """Heal the network."""
        _LOGGER.info("Z-Wave heal running")
        network.heal()

    def soft_reset(service):
        """Soft reset the controller."""
        _LOGGER.info("Z-Wave soft_reset have been initialized")
        network.controller.soft_reset()

    def test_network(service):
        """Test the network by sending commands to all the nodes."""
        _LOGGER.info("Z-Wave test_network have been initialized")
        network.test()

    def stop_network(_service_or_event):
        """Stop Z-Wave network."""
        _LOGGER.info("Stopping Z-Wave network")
        network.stop()
        if hass.state == CoreState.running:
            hass.bus.fire(const.EVENT_NETWORK_STOP)

    def rename_node(service):
        """Rename a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        name = service.data.get(const.ATTR_NAME)
        node.name = name
        _LOGGER.info("Renamed Z-Wave node %d to %s", node_id, name)

    def rename_value(service):
        """Rename a node value."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        value_id = service.data.get(const.ATTR_VALUE_ID)
        node = network.nodes[node_id]
        value = node.values[value_id]
        name = service.data.get(const.ATTR_NAME)
        value.label = name
        _LOGGER.info("Renamed Z-Wave value (Node %d Value %d) to %s", node_id,
                     value_id, name)

    def set_poll_intensity(service):
        """Set the polling intensity of a node value."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        value_id = service.data.get(const.ATTR_VALUE_ID)
        node = network.nodes[node_id]
        value = node.values[value_id]
        intensity = service.data.get(const.ATTR_POLL_INTENSITY)
        if intensity == 0:
            if value.disable_poll():
                _LOGGER.info("Polling disabled (Node %d Value %d)", node_id,
                             value_id)
                return
            _LOGGER.info("Polling disabled failed (Node %d Value %d)", node_id,
                         value_id)
        else:
            if value.enable_poll(intensity):
                _LOGGER.info("Set polling intensity (Node %d Value %d) to %s",
                             node_id, value_id, intensity)
                return
            _LOGGER.info("Set polling intensity failed (Node %d Value %d)",
                         node_id, value_id)

    def remove_failed_node(service):
        """Remove failed node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        _LOGGER.info("Trying to remove zwave node %d", node_id)
        network.controller.remove_failed_node(node_id)

    def replace_failed_node(service):
        """Replace failed node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        _LOGGER.info("Trying to replace zwave node %d", node_id)
        network.controller.replace_failed_node(node_id)

    def set_config_parameter(service):
        """Set a config parameter to a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        param = service.data.get(const.ATTR_CONFIG_PARAMETER)
        selection = service.data.get(const.ATTR_CONFIG_VALUE)
        size = service.data.get(const.ATTR_CONFIG_SIZE)
        for value in (node.get_values(
                class_id=const.COMMAND_CLASS_CONFIGURATION).values()):
            if value.index != param:
                continue
            if value.type in [const.TYPE_LIST, const.TYPE_BOOL]:
                value.data = selection
                _LOGGER.info(
                    "Setting config list parameter %s on Node %s "
                    "with selection %s", param, node_id, selection)
                return
            value.data = int(selection)
            _LOGGER.info(
                "Setting config parameter %s on Node %s "
                "with selection %s", param, node_id, selection)
            return
        node.set_config_param(param, selection, size)
        _LOGGER.info(
            "Setting unknown config parameter %s on Node %s "
            "with selection %s", param, node_id, selection)

    def print_config_parameter(service):
        """Print a config parameter from a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        param = service.data.get(const.ATTR_CONFIG_PARAMETER)
        _LOGGER.info("Config parameter %s on Node %s: %s", param, node_id,
                     get_config_value(node, param))

    def print_node(service):
        """Print all information about z-wave node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        nice_print_node(node)

    def set_wakeup(service):
        """Set wake-up interval of a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        value = service.data.get(const.ATTR_CONFIG_VALUE)
        if node.can_wake_up():
            for value_id in node.get_values(
                    class_id=const.COMMAND_CLASS_WAKE_UP):
                node.values[value_id].data = value
                _LOGGER.info("Node %s wake-up set to %d", node_id, value)
        else:
            _LOGGER.info("Node %s is not wakeable", node_id)

    def change_association(service):
        """Change an association in the zwave network."""
        association_type = service.data.get(const.ATTR_ASSOCIATION)
        node_id = service.data.get(const.ATTR_NODE_ID)
        target_node_id = service.data.get(const.ATTR_TARGET_NODE_ID)
        group = service.data.get(const.ATTR_GROUP)
        instance = service.data.get(const.ATTR_INSTANCE)

        node = ZWaveGroup(group, network, node_id)
        if association_type == 'add':
            node.add_association(target_node_id, instance)
            _LOGGER.info(
                "Adding association for node:%s in group:%s "
                "target node:%s, instance=%s", node_id, group, target_node_id,
                instance)
        if association_type == 'remove':
            node.remove_association(target_node_id, instance)
            _LOGGER.info(
                "Removing association for node:%s in group:%s "
                "target node:%s, instance=%s", node_id, group, target_node_id,
                instance)

    @asyncio.coroutine
    def async_refresh_entity(service):
        """Refresh values that specific entity depends on."""
        entity_id = service.data.get(ATTR_ENTITY_ID)
        async_dispatcher_send(hass,
                              SIGNAL_REFRESH_ENTITY_FORMAT.format(entity_id))

    def refresh_node(service):
        """Refresh all node info."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        node = network.nodes[node_id]
        node.refresh_info()

    def reset_node_meters(service):
        """Reset meter counters of a node."""
        node_id = service.data.get(const.ATTR_NODE_ID)
        instance = service.data.get(const.ATTR_INSTANCE)
        node = network.nodes[node_id]
        for value in (node.get_values(
                class_id=const.COMMAND_CLASS_METER).values()):
            if value.index != const.INDEX_METER_RESET:
                continue
            if value.instance != instance:
                continue
            network.manager.pressButton(value.value_id)
            network.manager.releaseButton(value.value_id)
            _LOGGER.info("Resetting meters on node %s instance %s....",
                         node_id, instance)
            return
        _LOGGER.info(
            "Node %s on instance %s does not have resettable "
            "meters.", node_id, instance)

    def start_zwave(_service_or_event):
        """Startup Z-Wave network."""
        _LOGGER.info("Starting Z-Wave network...")
        network.start()
        hass.bus.fire(const.EVENT_NETWORK_START)

        # Need to be in STATE_AWAKED before talking to nodes.
        # Wait up to NETWORK_READY_WAIT_SECS seconds for the zwave network
        # to be ready.
        for i in range(const.NETWORK_READY_WAIT_SECS):
            _LOGGER.debug("network state: %d %s", network.state,
                          network.state_str)
            if network.state >= network.STATE_AWAKED:
                _LOGGER.info("Z-Wave ready after %d seconds", i)
                break
            time.sleep(1)
        else:
            _LOGGER.warning(
                "zwave not ready after %d seconds, continuing anyway",
                const.NETWORK_READY_WAIT_SECS)
            _LOGGER.info("final network state: %d %s", network.state,
                         network.state_str)

        polling_interval = convert(config[DOMAIN].get(CONF_POLLING_INTERVAL),
                                   int)
        if polling_interval is not None:
            network.set_poll_interval(polling_interval, False)

        poll_interval = network.get_poll_interval()
        _LOGGER.info("Z-Wave polling interval set to %d ms", poll_interval)

        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_network)

        # Register node services for Z-Wave network
        hass.services.register(DOMAIN, const.SERVICE_ADD_NODE, add_node,
                               descriptions[const.SERVICE_ADD_NODE])
        hass.services.register(DOMAIN, const.SERVICE_ADD_NODE_SECURE,
                               add_node_secure,
                               descriptions[const.SERVICE_ADD_NODE_SECURE])
        hass.services.register(DOMAIN, const.SERVICE_REMOVE_NODE, remove_node,
                               descriptions[const.SERVICE_REMOVE_NODE])
        hass.services.register(DOMAIN, const.SERVICE_CANCEL_COMMAND,
                               cancel_command,
                               descriptions[const.SERVICE_CANCEL_COMMAND])
        hass.services.register(DOMAIN, const.SERVICE_HEAL_NETWORK,
                               heal_network,
                               descriptions[const.SERVICE_HEAL_NETWORK])
        hass.services.register(DOMAIN, const.SERVICE_SOFT_RESET, soft_reset,
                               descriptions[const.SERVICE_SOFT_RESET])
        hass.services.register(DOMAIN, const.SERVICE_TEST_NETWORK,
                               test_network,
                               descriptions[const.SERVICE_TEST_NETWORK])
        hass.services.register(DOMAIN, const.SERVICE_STOP_NETWORK,
                               stop_network,
                               descriptions[const.SERVICE_STOP_NETWORK])
        hass.services.register(DOMAIN, const.SERVICE_START_NETWORK,
                               start_zwave,
                               descriptions[const.SERVICE_START_NETWORK])
        hass.services.register(DOMAIN,
                               const.SERVICE_RENAME_NODE,
                               rename_node,
                               descriptions[const.SERVICE_RENAME_NODE],
                               schema=RENAME_NODE_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_RENAME_VALUE,
                               rename_value,
                               descriptions[const.SERVICE_RENAME_VALUE],
                               schema=RENAME_VALUE_SCHEMA)
        hass.services.register(
            DOMAIN,
            const.SERVICE_SET_CONFIG_PARAMETER,
            set_config_parameter,
            descriptions[const.SERVICE_SET_CONFIG_PARAMETER],
            schema=SET_CONFIG_PARAMETER_SCHEMA)
        hass.services.register(
            DOMAIN,
            const.SERVICE_PRINT_CONFIG_PARAMETER,
            print_config_parameter,
            descriptions[const.SERVICE_PRINT_CONFIG_PARAMETER],
            schema=PRINT_CONFIG_PARAMETER_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_REMOVE_FAILED_NODE,
                               remove_failed_node,
                               descriptions[const.SERVICE_REMOVE_FAILED_NODE],
                               schema=NODE_SERVICE_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_REPLACE_FAILED_NODE,
                               replace_failed_node,
                               descriptions[const.SERVICE_REPLACE_FAILED_NODE],
                               schema=NODE_SERVICE_SCHEMA)

        hass.services.register(DOMAIN,
                               const.SERVICE_CHANGE_ASSOCIATION,
                               change_association,
                               descriptions[const.SERVICE_CHANGE_ASSOCIATION],
                               schema=CHANGE_ASSOCIATION_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_SET_WAKEUP,
                               set_wakeup,
                               descriptions[const.SERVICE_SET_WAKEUP],
                               schema=SET_WAKEUP_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_PRINT_NODE,
                               print_node,
                               descriptions[const.SERVICE_PRINT_NODE],
                               schema=NODE_SERVICE_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_REFRESH_ENTITY,
                               async_refresh_entity,
                               descriptions[const.SERVICE_REFRESH_ENTITY],
                               schema=REFRESH_ENTITY_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_REFRESH_NODE,
                               refresh_node,
                               descriptions[const.SERVICE_REFRESH_NODE],
                               schema=NODE_SERVICE_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_RESET_NODE_METERS,
                               reset_node_meters,
                               descriptions[const.SERVICE_RESET_NODE_METERS],
                               schema=RESET_NODE_METERS_SCHEMA)
        hass.services.register(DOMAIN,
                               const.SERVICE_SET_POLL_INTENSITY,
                               set_poll_intensity,
                               descriptions[const.SERVICE_SET_POLL_INTENSITY],
                               schema=SET_POLL_INTENSITY_SCHEMA)

    # Setup autoheal
    if autoheal:
        _LOGGER.info("Z-Wave network autoheal is enabled")
        track_time_change(hass, heal_network, hour=0, minute=0, second=0)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_zwave)

    return True
Esempio n. 45
0
    def __init__(
        self,
        workflow_id,
        phase,
        artifacts_dir,
        comparison_pairs=None,
        show_all_axes=False,
    ):
        """
        This method instantiates an object of type TensorboardSummaryHook. The signature of this method is similar to
        that of every other hook. There is one additional parameter called `comparison_pairs` which is meant to
        hold a list of lists each containing a pair of input/output names that share the same dimensionality and can be
        compared to each other.

        A typical use of `comparison_pairs` is when users want to plot a pr_curve or a confusion matrix by comparing
        some input with some output. Eg. by comparing the labels with the predictions.

        .. code-block:: python

            from eisen.utils.logging import TensorboardSummaryHook

            workflow = # Eg. An instance of Training workflow

            logger = TensorboardSummaryHook(
                workflow_id=workflow.id,
                phase='Training',
                artifacts_dir='/artifacts/dir'
                comparison_pairs=[['labels', 'predictions']]
            )

        :param workflow_id: string containing the workflow id of the workflow being monitored (workflow_instance.id)
        :type workflow_id: UUID
        :param phase: string containing the name of the phase (training, testing, ...) of the workflow monitored
        :type phase: str
        :param artifacts_dir: whether the history of all models that were at a certain point the best should be saved
        :type artifacts_dir: bool
        :param comparison_pairs: list of lists of pairs, which are names of inputs and outputs to be compared directly
        :type comparison_pairs: list of lists of strings
        :param show_all_axes: whether any volumetric data should be shown as axial + sagittal + coronal
        :type show_all_axes: bool

        <json>
        [
            {"name": "comparison_pairs", "type": "list:list:string", "value": ""},
            {"name": "show_all_axes", "type": "bool", "value": "false"}
        ]
        </json>
        """
        self.workflow_id = workflow_id
        self.phase = phase

        self.comparison_pairs = comparison_pairs
        self.show_all_axes = show_all_axes

        if not os.path.exists(artifacts_dir):
            raise ValueError("The directory specified to save artifacts does not exist!")

        dispatcher.connect(self.end_epoch, signal=EISEN_END_EPOCH_EVENT, sender=workflow_id)

        self.artifacts_dir = os.path.join(artifacts_dir, "summaries", phase)

        if not os.path.exists(self.artifacts_dir):
            os.makedirs(self.artifacts_dir)

        self.writer = SummaryWriter(log_dir=self.artifacts_dir)
Esempio n. 46
0
 def subscribe(self, handle_new_gateway):
     """Subscribe to gateway events."""
     dispatcher.connect(handle_new_gateway,
                        signal=AQARA_EVENT_NEW_GATEWAY,
                        sender=self)
Esempio n. 47
0
 def __init__(self, *a, **kw):
     print("derp")
     super(infochoice, self).__init__(*a, **kw)
     self._data = []
     self._headers = set()
     dispatcher.connect(self.spider_closed, signals.spider_closed)
Esempio n. 48
0
 def __init__(self, **kwargs):
     super(JobsScreen, self).__init__(**kwargs)
     dispatcher.connect(self._on_status_update,
                        "CI_UPDATE",
                        sender=dispatcher.Any)
Esempio n. 49
0
def init():
    thread_pool.add_interval_callable(thread_run,
                                      run_interval_second=P.interval)
    dispatcher.connect(_init_recovery,
                       signal=Constant.SIGNAL_USB_DEVICE_CHANGE,
                       sender=dispatcher.Any)
Esempio n. 50
0
    def __init__(self,
                 version_full,
                 nobins=False,
                 restrictions=None,
                 force_restrictions=False):
        self.prefsdir = user_data_dir("HondaECU", "MCUInnovationsInc")
        if not os.path.exists(self.prefsdir):
            os.makedirs(self.prefsdir)
        self.configfile = os.path.join(self.prefsdir, 'hondaecu.ini')
        self.config = configparser.ConfigParser()
        if os.path.isfile(self.configfile):
            self.config.read(self.configfile)
        if not "retries" in self.config['DEFAULT']:
            self.config['DEFAULT'] = {'retries': '1'}
        self.nobins = nobins
        self.restrictions = restrictions
        self.force_restrictions = force_restrictions
        self.run = True
        self.active_ftdi_device = None
        self.ftdi_devices = {}
        self.__clear_data()

        if getattr(sys, 'frozen', False):
            self.basepath = sys._MEIPASS
        else:
            self.basepath = os.path.dirname(os.path.realpath(__file__))

        self.version_full = version_full
        self.version_short = self.version_full.split("-")[0]

        self.apps = {
            "flash": {
                "label": "Flash",
                "panel": HondaECU_FlashPanel,
            },
            # "hrc": {
            # 	"label":"HRC Data Settings",
            # 	"panel":HondaECU_HRCDataSettingsPanel,
            # },
            "data": {
                "label": "Data Logging",
                "panel": HondaECU_DatalogPanel,
            },
            "dtc": {
                "label": "Trouble Codes",
                "panel": HondaECU_ErrorPanel,
            },
        }
        self.appanels = {}

        wx.Frame.__init__(self,
                          None,
                          title="HondaECU %s" % (self.version_short),
                          style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER,
                          size=(500, 300))

        ib = wx.IconBundle()
        ib.AddIcon(os.path.join(self.basepath, "images", "honda.ico"))
        self.SetIcons(ib)

        self.menubar = wx.MenuBar()
        self.SetMenuBar(self.menubar)
        fileMenu = wx.Menu()
        self.menubar.Append(fileMenu, '&File')
        quitItem = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\tCtrl+Q')
        self.Bind(wx.EVT_MENU, self.OnClose, quitItem)
        fileMenu.Append(quitItem)
        helpMenu = wx.Menu()
        self.menubar.Append(helpMenu, '&Help')
        debugItem = wx.MenuItem(helpMenu, wx.ID_ANY, 'Show debug log')
        self.Bind(wx.EVT_MENU, self.OnDebug, debugItem)
        helpMenu.Append(debugItem)
        helpMenu.AppendSeparator()
        detectmapItem = wx.MenuItem(helpMenu, wx.ID_ANY, 'Detect map id')
        self.Bind(wx.EVT_MENU, self.OnDetectMap, detectmapItem)
        helpMenu.Append(detectmapItem)
        checksumItem = wx.MenuItem(helpMenu, wx.ID_ANY,
                                   'Validate bin checksum')
        self.Bind(wx.EVT_MENU, self.OnBinChecksum, checksumItem)
        helpMenu.Append(checksumItem)

        self.statusicons = [
            wx.Image(os.path.join(self.basepath, "images/bullet_black.png"),
                     wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
            wx.Image(os.path.join(self.basepath, "images/bullet_yellow.png"),
                     wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
            wx.Image(os.path.join(self.basepath, "images/bullet_green.png"),
                     wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
            wx.Image(os.path.join(self.basepath, "images/bullet_blue.png"),
                     wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
            wx.Image(os.path.join(self.basepath, "images/bullet_purple.png"),
                     wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
            wx.Image(os.path.join(self.basepath, "images/bullet_red.png"),
                     wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        ]
        self.statusbar = ESB.EnhancedStatusBar(self, -1)
        self.SetStatusBar(self.statusbar)
        self.statusbar.SetSize((-1, 28))
        self.statusicon = wx.StaticBitmap(self.statusbar)
        self.statusicon.SetBitmap(self.statusicons[0])
        self.ecmidl = wx.StaticText(self.statusbar)
        self.flashcountl = wx.StaticText(self.statusbar)
        self.dtccountl = wx.StaticText(self.statusbar)
        self.statusbar.SetFieldsCount(4)
        self.statusbar.SetStatusWidths([32, 170, 130, 110])
        self.statusbar.AddWidget(self.statusicon, pos=0)
        self.statusbar.AddWidget(self.ecmidl,
                                 pos=1,
                                 horizontalalignment=ESB.ESB_ALIGN_LEFT)
        self.statusbar.AddWidget(self.flashcountl,
                                 pos=2,
                                 horizontalalignment=ESB.ESB_ALIGN_LEFT)
        self.statusbar.AddWidget(self.dtccountl,
                                 pos=3,
                                 horizontalalignment=ESB.ESB_ALIGN_LEFT)
        self.statusbar.SetStatusStyles(
            [wx.SB_SUNKEN, wx.SB_SUNKEN, wx.SB_SUNKEN, wx.SB_SUNKEN])

        self.outerp = wx.Panel(self)

        self.adapterboxp = wx.Panel(self.outerp)
        self.adapterboxsizer = wx.StaticBoxSizer(wx.VERTICAL, self.adapterboxp,
                                                 "FTDI Devices:")
        self.adapterboxp.SetSizer(self.adapterboxsizer)
        self.adapterlist = wx.Choice(self.adapterboxp,
                                     wx.ID_ANY,
                                     size=(-1, 32))
        self.adapterboxsizer.Add(self.adapterlist,
                                 1,
                                 wx.ALL | wx.EXPAND,
                                 border=10)

        self.labelbook = LB.LabelBook(self.outerp,
                                      agwStyle=LB.INB_FIT_LABELTEXT
                                      | LB.INB_LEFT | LB.INB_DRAW_SHADOW
                                      | LB.INB_GRADIENT_BACKGROUND)

        self.bookpages = {}
        maxdims = [0, 0]
        for a, d in self.apps.items():
            enablestates = None
            if "enable" in self.apps[a]:
                enablestates = self.apps[a]["enable"]
            self.bookpages[a] = d["panel"](self, a, self.apps[a], enablestates)
            x, y = self.bookpages[a].GetSize()
            if x > maxdims[0]:
                maxdims[0] = x
            if y > maxdims[1]:
                maxdims[1] = y
            self.labelbook.AddPage(self.bookpages[a], d["label"], False)
        for k in self.bookpages.keys():
            self.bookpages[k].SetMinSize(maxdims)

        self.modelp = wx.Panel(self.outerp, style=wx.BORDER_SUNKEN)
        self.modelbox = wx.BoxSizer(wx.VERTICAL)
        self.modell = wx.StaticText(self.modelp,
                                    label="",
                                    style=wx.ALIGN_CENTRE_HORIZONTAL
                                    | wx.ALIGN_CENTRE_VERTICAL)
        self.ecupnl = wx.StaticText(self.modelp,
                                    label="",
                                    style=wx.ALIGN_CENTRE_HORIZONTAL
                                    | wx.ALIGN_CENTRE_VERTICAL)
        font1 = self.GetFont().Bold()
        font2 = self.GetFont().Bold()
        font1.SetPointSize(font1.GetPointSize() * 1.25)
        font2.SetPointSize(font2.GetPointSize() * 2)
        self.modell.SetFont(font2)
        self.ecupnl.SetFont(font1)
        self.modelbox.AddSpacer(5)
        self.modelbox.Add(self.modell, 0, wx.CENTER)
        self.modelbox.Add(self.ecupnl, 0, wx.CENTER)
        self.modelbox.AddSpacer(5)
        self.modelp.SetSizer(self.modelbox)

        self.outersizer = wx.BoxSizer(wx.VERTICAL)
        self.outersizer.Add(self.adapterboxp, 0, wx.EXPAND | wx.ALL, 5)
        self.outersizer.Add(self.modelp, 0, wx.EXPAND | wx.ALL, 5)
        self.outersizer.Add(self.labelbook, 2, wx.EXPAND | wx.ALL, 5)
        self.outerp.SetSizer(self.outersizer)

        self.mainsizer = wx.BoxSizer(wx.VERTICAL)
        self.mainsizer.Add(self.outerp, 1, wx.EXPAND)
        self.mainsizer.SetSizeHints(self)
        self.SetSizer(self.mainsizer)

        self.adapterlist.Bind(wx.EVT_CHOICE, self.OnAdapterSelected)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.debuglog = HondaECU_LogPanel(self)

        dispatcher.connect(self.USBMonitorHandler,
                           signal="USBMonitor",
                           sender=dispatcher.Any)
        dispatcher.connect(self.AppPanelHandler,
                           signal="AppPanel",
                           sender=dispatcher.Any)
        dispatcher.connect(self.KlineWorkerHandler,
                           signal="KlineWorker",
                           sender=dispatcher.Any)

        self.usbmonitor = USBMonitor(self)
        self.klineworker = KlineWorker(self)

        self.Layout()
        self.Center()
        self.Show()

        self.usbmonitor.start()
        self.klineworker.start()

        self.powercycle = PowerCycleDialog(None)
Esempio n. 51
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.items = {}
     self.found = {}
     dispatcher.connect(self.init_scrapy, signals.engine_started)
     dispatcher.connect(self.close_scrapy, signals.engine_stopped)
Esempio n. 52
0
    def __init__(self,
                 version_full,
                 nobins=False,
                 restrictions=None,
                 force_restrictions=False):
        self.nobins = nobins
        self.restrictions = restrictions
        self.force_restrictions = force_restrictions
        self.run = True
        self.active_ftdi_device = None
        self.ftdi_devices = {}
        self.__clear_data()

        if getattr(sys, 'frozen', False):
            self.basepath = sys._MEIPASS
        else:
            self.basepath = os.path.dirname(os.path.realpath(__file__))

        self.version_full = version_full
        self.version_short = self.version_full.split("-")[0]

        self.apps = {
            "flash": {
                "label":
                "Flash",
                "icon":
                "images/chip2.png",
                "conflicts": ["data", "hrc"],
                "panel":
                HondaECU_FlashPanel,
                "disabled":
                True,
                "enable": [
                    ECUSTATE.OK, ECUSTATE.RECOVER_OLD, ECUSTATE.RECOVER_NEW,
                    ECUSTATE.WRITEx00, ECUSTATE.WRITEx30, ECUSTATE.READ
                ],
            },
            "tunehelper": {
                "label": "Tune",
                "icon": "images/bike.png",
                "panel": HondaECU_TunePanelHelper,
            },
            "info": {
                "label": "ECU Info",
                "icon": "images/info2.png",
                "conflicts": ["flash", "hrc"],
                "panel": HondaECU_InfoPanel,
            },
            "data": {
                "label": "Data Logging",
                "icon": "images/monitor.png",
                "conflicts": ["flash", "hrc"],
                "panel": HondaECU_DatalogPanel,
                "disabled": True,
                "enable": [ECUSTATE.OK],
            },
            "dtc": {
                "label": "Trouble Codes",
                "icon": "images/warning.png",
                "conflicts": ["flash", "hrc"],
                "panel": HondaECU_ErrorPanel,
                "disabled": True,
                "enable": [ECUSTATE.OK],
            },
            # "hrcsettings": {
            # 	"label":"HRC Settings",
            # 	"icon":"images/cog.png",
            # 	"conflicts":["flash","data","dtc","info"],
            # 	"panel":HondaECU_HRCDataSettingsPanel,
            # 	"disabled":True,
            # 	"enable": [ECUSTATE.OK],
            # },
        }
        self.appanels = {}

        wx.Frame.__init__(self,
                          None,
                          title="HondaECU %s :: Control Panel" %
                          (self.version_short),
                          style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER,
                          size=(500, 300))

        ib = wx.IconBundle()
        ib.AddIcon(os.path.join(self.basepath, "images", "honda.ico"))
        self.SetIcons(ib)

        self.menubar = wx.MenuBar()
        self.SetMenuBar(self.menubar)
        fileMenu = wx.Menu()
        self.menubar.Append(fileMenu, '&File')
        self.devicesMenu = wx.Menu()
        fileMenu.AppendSubMenu(self.devicesMenu, "Devices")
        fileMenu.AppendSeparator()
        quitItem = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\tCtrl+Q')
        self.Bind(wx.EVT_MENU, self.OnClose, quitItem)
        fileMenu.Append(quitItem)
        helpMenu = wx.Menu()
        self.menubar.Append(helpMenu, '&Help')
        debugItem = wx.MenuItem(helpMenu, wx.ID_ANY, 'Show debug log')
        self.Bind(wx.EVT_MENU, self.OnDebug, debugItem)
        helpMenu.Append(debugItem)
        helpMenu.AppendSeparator()
        detectmapItem = wx.MenuItem(helpMenu, wx.ID_ANY, 'Detect map id')
        self.Bind(wx.EVT_MENU, self.OnDetectMap, detectmapItem)
        helpMenu.Append(detectmapItem)
        checksumItem = wx.MenuItem(helpMenu, wx.ID_ANY,
                                   'Validate bin checksum')
        self.Bind(wx.EVT_MENU, self.OnBinChecksum, checksumItem)
        helpMenu.Append(checksumItem)

        self.statusbar = self.CreateStatusBar(1)
        self.statusbar.SetSize((-1, 28))
        self.statusbar.SetStatusStyles([wx.SB_SUNKEN])
        self.SetStatusBar(self.statusbar)

        self.outerp = wx.Panel(self)
        self.wrappanel = wx.Panel(self.outerp)
        wrapsizer = wx.WrapSizer(wx.HORIZONTAL)
        self.appbuttons = {}
        for a, d in self.apps.items():
            icon = wx.Image(os.path.join(self.basepath, d["icon"]),
                            wx.BITMAP_TYPE_ANY).ConvertToBitmap()
            enablestates = None
            if "enable" in d:
                enablestates = d["enable"]
            self.appbuttons[a] = HondaECU_AppButton(a,
                                                    enablestates,
                                                    self.wrappanel,
                                                    wx.ID_ANY,
                                                    icon,
                                                    label=d["label"])
            if "disabled" in d and d["disabled"]:
                self.appbuttons[a].Disable()
            wrapsizer.Add(self.appbuttons[a], 0)
            self.Bind(wx.EVT_BUTTON, self.OnAppButtonClicked,
                      self.appbuttons[a])
        self.wrappanel.SetSizer(wrapsizer)

        self.outersizer = wx.BoxSizer(wx.VERTICAL)
        self.outersizer.Add(self.wrappanel, 1, wx.EXPAND)
        self.outerp.SetSizer(self.outersizer)

        self.mainsizer = wx.BoxSizer(wx.VERTICAL)
        self.mainsizer.Add(self.outerp, 1, wx.EXPAND)
        self.SetSizer(self.mainsizer)

        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.debuglog = HondaECU_LogPanel(self)

        dispatcher.connect(self.USBMonitorHandler,
                           signal="USBMonitor",
                           sender=dispatcher.Any)
        dispatcher.connect(self.AppPanelHandler,
                           signal="AppPanel",
                           sender=dispatcher.Any)
        dispatcher.connect(self.KlineWorkerHandler,
                           signal="KlineWorker",
                           sender=dispatcher.Any)
        dispatcher.connect(self.TunePanelHelperHandler,
                           signal="TunePanelHelper",
                           sender=dispatcher.Any)

        self.usbmonitor = USBMonitor(self)
        self.klineworker = KlineWorker(self)

        self.Layout()
        self.mainsizer.Fit(self)
        self.Center()
        self.Show()

        self.usbmonitor.start()
        self.klineworker.start()
Esempio n. 53
0
def _init_controller():
    if P.module_imported:
        device = '{}{}'.format(P.device, P.device_index)
        L.l.info('Zwave initialising on {}'.format(device))
        _stop_net()
        # Define some manager options
        try:
            options = ZWaveOption(device,
                                  config_path="../openzwave/config",
                                  user_path=".",
                                  cmd_line="")
            options.set_log_file(P.log_file)
            options.set_append_log_file(True)
            options.set_console_output(False)
            # options.set_save_log_level('Debug')
            # options.set_save_log_level('Info')
            options.set_save_log_level('Warning')
            # options.set_save_log_level('Error')
            options.set_logging(False)
            #options.set_logging(True)
            # options.set_poll_interval(5)
            options.set_save_configuration(True)
            options.lock()

            # Create a network object
            P.network = ZWaveNetwork(options, log=None, autostart=False)
            dispatcher.connect(louie_network_started,
                               ZWaveNetwork.SIGNAL_NETWORK_STARTED)
            dispatcher.connect(louie_network_failed,
                               ZWaveNetwork.SIGNAL_NETWORK_FAILED)
            dispatcher.connect(louie_network_resetted,
                               ZWaveNetwork.SIGNAL_NETWORK_RESETTED)
            dispatcher.connect(louie_network_ready,
                               ZWaveNetwork.SIGNAL_NETWORK_READY)
            dispatcher.connect(louie_network_stopped,
                               ZWaveNetwork.SIGNAL_NETWORK_STOPPED)
            dispatcher.connect(louie_network_awaked,
                               ZWaveNetwork.SIGNAL_NETWORK_AWAKED)

            P.network.start()

            L.l.info("Waiting for zwave driver")
            for i in range(0, 120):
                if P.network.state >= P.network.STATE_STARTED:
                    L.l.info("Zwave driver started")
                    break
                else:
                    time.sleep(0.1)
            if P.network.state < P.network.STATE_STARTED:
                L.l.info(
                    "Can't initialise zwave driver. Look at the logs in {}".
                    format(P.log_file))
                return False
            L.l.info("Home id : {}, Nodes in network : {}".format(
                P.network.home_id_str, P.network.nodes_count))

            L.l.info("Waiting 120 sec for zwave network to become ready")
            for i in range(0, 240):
                if P.network.state >= P.network.STATE_READY:
                    break
                else:
                    time.sleep(0.5)
                    # L.l.info("state = {}".format(P.network.state))
            if not P.network.is_ready:
                L.l.info(
                    "Can't start network! Look at the logs in OZW_Log.log")
                P.network.stop()
                return False
            else:
                L.l.info("Zwave network is started!")
            # print nodes
            for node_id in P.network.nodes:
                node = P.network.nodes[node_id]
                try:
                    L.l.info("Node {}={}".format(node_id, node))
                    # L.l.info("Node {} attrib: model={} man={} prod_name={} prod_id={}".format(
                    #     node_id, node.manufacturer_name, node.product_name, node.product_id))
                except Exception as ex:
                    pass
            # not working
            # P.network.set_poll_interval(milliseconds=3000, bIntervalBetweenPolls=False)
            # P.network.test(1)
            variable.USB_PORTS_IN_USE.append(device)
            return True
        except ZWaveException as ze:
            L.l.error('Unable to init zwave, exception={}'.format(ze))
            P.device_index += 1
            if P.device_index > 3:
                P.device_index = 0
    return False
Esempio n. 54
0
 def componentComplete(self):
     super(Marquee, self).componentComplete()
     self.on_show_marquee.connect(self.on_show_marquee_on_ui_thread)
     dispatcher.connect(self.on_marquee,
                        signals.SHOW_MARQUEE,
                        sender=dispatcher.Any)
Esempio n. 55
0
    dispatcher.connect(louie_value_update, ZWaveNetwork.SIGNAL_VALUE)


def louie_node_update(network, node):
    print("Hello from node : {}.".format(node))


def louie_value_update(network, node, value):
    print("Hello from value : {}.".format(value))


#Create a network object
network = ZWaveNetwork(options, autostart=False)

# We connect to the louie dispatcher
dispatcher.connect(louie_network_started, ZWaveNetwork.SIGNAL_NETWORK_STARTED)
dispatcher.connect(louie_network_failed, ZWaveNetwork.SIGNAL_NETWORK_FAILED)
dispatcher.connect(louie_network_ready, ZWaveNetwork.SIGNAL_NETWORK_READY)

# Start the network
network.start()

# Wait for network
print("***** Waiting for network to become ready : ")
for i in range(0, 90):
    if network.state >= network.STATE_READY:
        print("***** Network is ready")
        break
    else:
        sys.stdout.write(".")
        sys.stdout.flush()
Esempio n. 56
0
 def subscribe(self, handle_new_device):
     """Subscribe to new device event."""
     dispatcher.connect(handle_new_device,
                        signal=AQARA_EVENT_NEW_DEVICE,
                        sender=self)
Esempio n. 57
0
 def connect(self, handler, signal, sender=dispatcher.Any, weak=False):
     if isinstance(signal, dict):
         signal = json.dumps(signal)
     logging.getLogger('system').debug(self.id+" connecting signal to handler "+str(signal))
     dispatcher.connect(receiver=handler, signal=signal, sender=sender, weak=weak)
def _do_onStartup_DispatchRegistration():
    dispatcher.connect(_log_modem_traffic, signal='MODEM_COMMAND')
    dispatcher.connect(_log_modem_traffic, signal='MODEM_RESPONSE')
Esempio n. 59
0
 def subscribe_update(self, handle_update):
     """subscribe to sensor update event"""
     dispatcher.connect(handle_update, signal=HASS_UPDATE_SIGNAL, sender=self)
Esempio n. 60
0
 def __init__(self):
     # 信号量
     self.chrome = Chrome_Tool()
     super().__init__()
     dispatcher.connect(self.spider_closed, signal=signals.spider_closed)
     self.number = 1