当前位置: 首页>>代码示例>>Python>>正文


Python ZWaveNetwork.start方法代码示例

本文整理汇总了Python中openzwave.network.ZWaveNetwork.start方法的典型用法代码示例。如果您正苦于以下问题:Python ZWaveNetwork.start方法的具体用法?Python ZWaveNetwork.start怎么用?Python ZWaveNetwork.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在openzwave.network.ZWaveNetwork的用法示例。


在下文中一共展示了ZWaveNetwork.start方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: startup_zwave

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
  def startup_zwave(self, args={}):
    ffEvent(self._id,{'zwave':'starting_up'})
    zwaveSetup = ZWaveOption(self._port, self._configFile)
    zwaveSetup.set_console_output(False)
    zwaveSetup.lock()
    network = ZWaveNetwork(zwaveSetup, autostart=False)
    network.start()

    stdout.write("Waking up Zwave (This can take up to 5 minutes)")
    for i in xrange(3):
      if network.state >= network.STATE_AWAKED:
        logging.info('Zwave Network Awake')
        break
      else:
        stdout.write(".")
        stdout.flush()
        sleep(1)

    for x in xrange(3):
      if network.state >= network.STATE_READY:
        ffEvent(self._id,{'zwave':'network_ready'})
      else:
        stdout.write(".")
        stdout.flush()
        sleep(.5)

    return network
开发者ID:zpriddy,项目名称:Firefly,代码行数:29,代码来源:ffZwave.py

示例2: main

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
def main():
  global LIGHT, PUSHOVER

  logging.basicConfig(level=logging.INFO,
    format="%(asctime)-15s %(levelno)d %(message)s")

  # TODO: Put in argparse
  device = None
  if device is None:
    device = discover_device()
  check_device(device)

  CONFIG = read_config("config.json")
  if CONFIG.pushover.apikey is not None:
    logging.info("Setting up Pushover")
    PUSHOVER = Pushover(CONFIG.pushover.apikey, CONFIG.pushover.userkeys)

  connect_signals()

  options = create_zwave_options(device=device)
  network = ZWaveNetwork(options, log=None, autostart=False)

  queue = threading.Thread(target=DataQueue.worker,
      kwargs={"location": "home.db"},
      name="db")
  queue.start()

  try:
    network.start()

    # Start REPL with a union where globals override locals
    local = locals().copy()
    local.update(globals())
    code.interact(local=local)
  except KeyboardInterrupt:
    pass
  finally:
    logging.info("\nStopping network ...")
    network.stop()

    logging.info("Stopping data queue ...")
    DataQueue.stop()
    queue.join()
开发者ID:cslarsen,项目名称:home-zwave,代码行数:45,代码来源:home.py

示例3: louie_node_update

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
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)

network.start()

#We wait for the 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()
        time.sleep(1.0)

time.sleep(5.0)

for node in network.nodes:
开发者ID:leemac,项目名称:home-automation,代码行数:32,代码来源:main.py

示例4: ZWDeviceController

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class ZWDeviceController(IOTDeviceController):
    def louie_network_started(network):
        print (
            "Hello from network : I'm started : homeid %0.8x - %d nodes were found."
            % (network.home_id, network.nodes_count)
        )

    def louie_network_failed(network):
        print ("Hello from network : can't load :(.")

    def louie_network_ready(network):
        print ("Hello from network : I'm ready : %d nodes were found." % network.nodes_count)
        print ("Hello from network : my controller is : %s" % network.controller)
        dispatcher.connect(louie_node_update, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(louie_value_update, ZWaveNetwork.SIGNAL_VALUE)

    def louie_node_update(network, node):
        print ("Hello from node : %s." % node)

    def louie_value_update(network, node, value):
        print ("Hello from value : %s." % value)

    def __init__(self, name, location, nodefilename="/opt/seciot/nodenames.json"):
        IOTDeviceController.__init__(self, name)

        # Restore node stuff
        nodefile = open(nodefilename, "r")
        nodejson = nodefile.read()
        self.node_dict = json.loads(nodejson)

        # Init options
        device = "/dev/ttyACM0"
        sniff = 300.0
        options = ZWaveOption(device, config_path="/opt/openzwave/config", user_path=".", cmd_line="")
        options.set_logging(False)
        options.set_console_output(False)
        options.lock()
        # Create a network object
        self.network = ZWaveNetwork(options, autostart=False)
        self.network.set_poll_interval(10, True)
        # We connect to the louie dispatcher
        dispatcher.connect(self.louie_network_started, ZWaveNetwork.SIGNAL_NETWORK_STARTED)
        dispatcher.connect(self.louie_network_failed, ZWaveNetwork.SIGNAL_NETWORK_FAILED)
        self.network.start()
        # We wait for the network.
        print "***** Waiting for network to become ready : "
        for i in range(0, 300):
            if self.network.state >= self.network.STATE_READY:
                print "***** Network is ready"
                break
            else:
                sys.stdout.write(".")
                sys.stdout.flush()
            time.sleep(1.0)
            # We update the name of the controller
        self.network.controller.node.name = name
        self.network.controller.node.location = location

    def export(self):
        # list of devices
        # each device has zwavename, friendly name, device type, statepool, currentstates (timestamped)
        # return self.network.nodes
        return self.node_dict.keys()

    def readState(self, node):
        print "read", self.node_dict
        print "read", node
        if type(node) in [str, unicode]:
            nodenum = self.node_dict[node]
        else:
            print type(node)
            nodenum = node
        mynode = self.network.nodes[nodenum]
        state = None
        for switch in mynode.get_switches():
            state = mynode.get_switch_state(switch)
            print node
            print state
        return state

    def setState(self, node, state):
        print "set", self.node_dict
        print "set", node
        if type(node) in [str, unicode]:
            nodenum = self.node_dict[node]
        else:
            nodenum = node
        if state in [1, "1", u"1", True]:
            boolstate = True
        elif state in [0, "0", u"0", False]:
            boolstate = False
        else:
            print state
            print type(state)
            raise error("bad")
        print state
        for switch in self.network.nodes[nodenum].get_switches():
            self.network.nodes[nodenum].set_switch(switch, boolstate)
开发者ID:aakatz3,项目名称:seciot,代码行数:100,代码来源:zwservice.py

示例5: Open_zwave

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class Open_zwave(HAInterface):
    VERSION = '0.0.4'

    def louie_network_ready(self, network):
        self._logger.info(">>>>>>> Hello from network : I'm ready : %d nodes were found.".format(self._network.nodes_count))
        self._logger.info(">>>>>>> Hello from network : my controller is : {}".format(self._network.controller))
        dispatcher.connect(self.louie_node_update, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(self.louie_value_update, ZWaveNetwork.SIGNAL_VALUE)

    def louie_node_update(self, network, node):
        self._logger.debug('>>>>>>> Hello from node : {}.'.format(node))

    def louie_value_update(self, network, node, value):
        self._logger.debug('>>>>>>> Hello from value : {}'.format(value))
        for lockvalue in self.get_door_locks(node.node_id).values():
            if lockvalue.value_id == value.value_id:
                if value.data:
                    self._onCommand(address=str(node.node_id), command=Command.LOCK)
                else:
                    self._onCommand(address=str(node.node_id), command=Command.UNLOCK)
        for val in self._network.nodes[node.node_id].get_switches():
            if val == value.value_id:
                if value.data:
                    self._onCommand(address=str(node.node_id), command=Command.ON)
                else:
                    self._onCommand(address=str(node.node_id), command=Command.OFF)
        for val in self._network.nodes[node.node_id].get_dimmers() :
            if val == value.value_id:
                #Poll dimmer to ensure ramp up/down completes
                level = value.data
                if self.dimmer_polled_value.has_key(val):
                    self._logger.debug('>>>>>>> Hello from level : {} {}'.format(level, self.dimmer_polled_value[val]))
                    if level == self.dimmer_polled_value[val]:
                        del self.dimmer_polled_value[val]
                        if level < 2:
                            self._onCommand(address=str(node.node_id), command=Command.OFF)
                        elif level > 98:
                            self._onCommand(address=str(node.node_id), command=Command.ON)
                        else:
                            self._onCommand(address=str(node.node_id), command=(Command.LEVEL,level))
                    else:
                        self.dimmer_polled_value[val] = level
                        time.sleep(1)
                        value.refresh()
                else:
                    time.sleep(1)
                    self.dimmer_polled_value[val] = level
                    value.refresh()

    def __init__(self, *args, **kwargs):
        self._serialDevicePath = kwargs.get('serialDevicePath', None)
        self._configpath = kwargs.get('config_path', "/etc/openzwave/")
        super(Open_zwave, self).__init__(self, *args, **kwargs)
        self.dimmer_polled_value = {}

    def _init(self, *args, **kwargs):
        self.awake = False
        self.ready = False
        self.nodesdisplayed = False
        self._options = ZWaveOption(self._serialDevicePath, \
          config_path=self._configpath, \
          user_path=".", cmd_line="")
        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(log)
        self._options.set_save_log_level('Info')
        self._options.set_logging(True)
        self._options.set_notify_transactions(True)
        self._options.lock()

        self._network = ZWaveNetwork(self._options, log=None,autostart=False)
        dispatcher.connect(self.louie_network_ready, ZWaveNetwork.SIGNAL_NETWORK_READY)
        self._network.start()
        super(Open_zwave, self)._init(self, *args, **kwargs)

    def _printNetwork(self, node):
        node = self._network.nodes[node]
        self._logger.info("------------------------------------------------------")
        self._logger.info("{} - Name : {}".format(node.node_id,
            node.name))
        self._logger.info("{} - Manufacturer name / id : {} / {}".format(
            node.node_id,
            node.manufacturer_name,
            node.manufacturer_id))
        self._logger.info("{} - Product name / id / type : {} / {} / {}".format(
            node.node_id,
            node.product_name,
            node.product_id,
            node.product_type))
        self._logger.info("{} - Version : {}".format(node.node_id,
            node.version))
        self._logger.info("{} - Command classes : {}".format(node.node_id,
            node.command_classes_as_string))
        self._logger.info("{} - Capabilities : {}".format(node.node_id,
            node.capabilities))
        self._logger.info("{} - Neighbors : {}".format(node.node_id,
            node.neighbors))
        self._logger.info("{} - Can sleep : {}".format(node.node_id,
            node.can_wake_up()))
#.........这里部分代码省略.........
开发者ID:ddyeakley,项目名称:pytomation,代码行数:103,代码来源:open_zwave.py

示例6: zwave

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class zwave(object):

    #Define some manager options
    options = ZWaveOption(device, \
      config_path=constants.zwpath, \
      user_path=".", cmd_line="")
    options.set_log_file("OZW_Log.log")
    options.set_append_log_file(False)
    options.set_console_output(False)
    options.set_save_log_level(log)
    options.set_logging(True)
    options.lock()
    
    def louie_network_started(self, network):
        dicti = {'Log':'Z-Wave Network started'}
#        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        mqtt_publish.mqtt_pub('Inputs/Satellite/' + constants.name + '/Log',dicti)
        print("Hello from network : I'm started : homeid {:08x} - {} nodes were found.".format(network.home_id, network.nodes_count))
    
    def louie_network_failed(self, network):
        pass
        print("Hello from network : can't load :(.")
    
    def louie_network_ready(self, network):
        dicti = {'Log':'Z-Wave Network up running'}
#        mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))
        mqtt_publish.mqtt_pub('Inputs/Satellite/' + constants.name + '/Log',dicti)
        dispatcher.connect(self.louie_node_update, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(self.louie_scene_message, ZWaveNetwork.SIGNAL_NODE_EVENT)
        dispatcher.connect(self.louie_value_update, ZWaveNetwork.SIGNAL_VALUE)
        
        print('Dispatcher connected')
    
    def louie_scene_message(self, *args, **kwargs):
        print('scene happening')
        for count, thing in enumerate(args):
            print( '{0}. {1}'.format(count, thing))  
        for name, value in kwargs.items():
            print( '{0} = {1}'.format(name, value))            
    
    def loui_ess_q_comp(self):
        pass
#        print('nodes ess queried')
    
    def loui_mess_comp(self):
        print('mess complete')
    

    def louie_node_update(self, network, node):
        pass
        print("Hello from node : {}.".format(node))
    
    def louie_value_update(self, network, node, value):
        print "value changed"
        try:
#            print zw_config.inputs[node.home_id][value.value_id], int(value.data)
            dicti = {'Value': str(int(value.data))}
            dicti['Name'] = 'ZWave.' + str(node.home_id) + '.' + str(value.value_id)
            #print dicti
#            mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))     
            mqtt_publish.mqtt_pub('Inputs/Satellite/' + constants.name + '/ZWave/' + str(int(node.home_id)) +'/'+ str(int(value.value_id)) ,dicti)
        except:
            print 'not understood', node, value.value_id, value.data
#        print("Hello from value : {}.".format( value ))
    #    home_id: [0xeefad666] id: [72057594093060096] parent_id: [3] label: [Switch] data: [False].
    #    home_id: [0xeefad666] id: [72057594093273218] parent_id: [3] label: [Power] data: [0.0].
    #    home_id: [0xeefad666] id: [144115188131201026] parent_id: [3] label: [Energy] data: [0.00999999977648]
    #   value.label = switch

    def __init__(self):
        pass
    
    def start(self):
        #Create a network object
        self.network = ZWaveNetwork(self.options, autostart=False)
        
        
        #We connect to the louie dispatcher
        dispatcher.connect(self.louie_network_started, ZWaveNetwork.SIGNAL_NETWORK_STARTED)
        dispatcher.connect(self.louie_network_failed, ZWaveNetwork.SIGNAL_NETWORK_FAILED)
        dispatcher.connect(self.louie_network_ready, ZWaveNetwork.SIGNAL_NETWORK_READY)
        dispatcher.connect(self.louie_scene_message, ZWaveNetwork.SIGNAL_SCENE_EVENT)
        dispatcher.connect(self.loui_ess_q_comp, ZWaveNetwork.SIGNAL_ESSENTIAL_NODE_QUERIES_COMPLETE)
        dispatcher.connect(self.loui_mess_comp, ZWaveNetwork.SIGNAL_MSG_COMPLETE)
        self.network.start()

        #We wait for the network.
        # print("Waiting for network to become ready : ")
        for i in range(0,900):
            if self.network.state>=self.network.STATE_READY:
                print "Network is ready"
                break
            else:
                sys.stdout.write(".")
                sys.stdout.flush()
                time.sleep(1.0)

            #time.sleep(5.0)
            
            #We update the name of the controller
#.........这里部分代码省略.........
开发者ID:chrihuc,项目名称:satellite,代码行数:103,代码来源:zw_class.py

示例7: Open_zwave

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class Open_zwave(HAInterface):
    VERSION = '0.0.2'
    awake = False
    ready = False
    nodesdisplayed = False

    def louie_network_ready(network):
	self._logger.info(">>>>>>> Hello from network : I'm ready : %d nodes were found." % self._network.nodes_count)     
	self._logger.info(">>>>>>> Hello from network : my controller is : %s" % self._network.controller)
	dispatcher.connect(self.louie_node_update, ZWaveNetwork.SIGNAL_NODE)
	dispatcher.connect(self.louie_value_update, ZWaveNetwork.SIGNAL_VALUE)

    def louie_node_update(network, node):
    	self._logger.info('>>>>>>> Hello from node : %s.' % node)

    def louie_value_update(network, node, value):
    	self._logger.info('>>>>>>> Hello from value : %s.' % value)

    def __init__(self, *args, **kwargs):
        self._serialDevicePath = kwargs.get('serialDevicePath', None)
        self._options = ZWaveOption(self._serialDevicePath, \
          config_path="/usr/local/etc/openzwave/", \
          user_path=".", cmd_line="")
        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(log)
        self._options.set_save_log_level('Info')
        self._options.set_logging(True)
	self._options.set_notify_transactions(True)
        self._options.lock()

        self._network = ZWaveNetwork(self._options, log=None,autostart=False)
	dispatcher.connect(self.louie_network_ready, ZWaveNetwork.SIGNAL_NETWORK_READY)
	self._network.start()
        super(Open_zwave, self).__init__(self, *args, **kwargs)

    def _printNetwork(self, node):
        print
        print "------------------------------------------------------"
        print "%s - Name : %s" % (self._network.nodes[node].node_id,
            self._network.nodes[node].name)
        print "%s - Manufacturer name / id : %s / %s" % (
            self._network.nodes[node].node_id,
            self._network.nodes[node].manufacturer_name,
            self._network.nodes[node].manufacturer_id)
        print "%s - Product name / id / type : %s / %s / %s" % (
            self._network.nodes[node].node_id,
            self._network.nodes[node].product_name,
            self._network.nodes[node].product_id,
            self._network.nodes[node].product_type)
        print "%s - Version : %s" % (self._network.nodes[node].node_id,
            self._network.nodes[node].version)
        print "%s - Command classes : %s" % (self._network.nodes[node].node_id,
            self._network.nodes[node].command_classes_as_string)
        print "%s - Capabilities : %s" % (self._network.nodes[node].node_id,
            self._network.nodes[node].capabilities)
        print "%s - Neighbors : %s" % (self._network.nodes[node].node_id,
            self._network.nodes[node].neighbors)
        print "%s - Can sleep : %s" % (self._network.nodes[node].node_id,
            self._network.nodes[node].can_wake_up())

    def _init(self, *args, **kwargs):
        super(Open_zwave, self)._init(self, *args, **kwargs)

    def _readInterface(self, lastPacketHash):
        if (self._network.state >= self._network.STATE_AWAKED
            and not self.awake):
            self.awake = True
            self._logger.info("Network Awaked")
        if (self._network.state >= self._network.STATE_READY
            and not self.ready):
            self.ready = True
            self._logger.info("Network Ready")
	    self._logger.info("********************************* NETWORK READY ************************************")
        if not self.awake:
            time.sleep(1.0)
            self._logger.debug("Not awaked")
            return
        if self.awake and not self.ready:
            time.sleep(1.0)
            self._logger.debug("Not ready")
            return
        if not self.nodesdisplayed and self.ready:
            for node in self._network.nodes:
                self._printNetwork(node)
            self.nodesdisplayed = True
        time.sleep(1)

    def version(self):
        self._logger.info("Open_zwave Pytomation Driver version " +
                          self.VERSION)
        self._logger.info("Use openzwave library : %s" %
                          self._network.controller.ozw_library_version)
        self._logger.info("Use python library : %s" %
                          self._network.controller.python_library_version)
        self._logger.info("Use ZWave library : %s" %
                          self._network.controller.library_description)

    def on(self, address):
#.........这里部分代码省略.........
开发者ID:E3Dev,项目名称:pytomation,代码行数:103,代码来源:open_zwave.py

示例8: Network

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class Network(object):
    _instance = None

    def _init(self, device, config, timeout):
        self.network = None
        self.status = 1
        self.timeout = timeout
        self.device = device
        self.config = config

        options = ZWaveOption(self.device, config_path=self.config, user_path=".", cmd_line="")
        options.set_log_file("OZW_Log.log")
        options.set_append_log_file(False)
        options.set_console_output(False)
        options.set_save_log_level('Debug')
        options.set_logging(True)

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

        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)

        self.network.start()

    def __new__(class_, device=None, config=None, timeout=None):
        if not isinstance(class_._instance, class_):
            if not device:
                return None
            class_._instance = object.__new__(class_)
            class_._instance._init(device, config, timeout)
        return class_._instance

    def __del__(self):
        self.network.stop()

    def __iter__(self):
        return self

    def next(self):
        self.timeout -= 1
        if self.timeout == 0:
            self.status = 1
            raise StopIteration
        if self.network.state >= self.network.STATE_READY:
            self.status = 0
            raise StopIteration
        return self.timeout

    def get_timout(self):
        return self.timeout

    def get_status(self):
        return self.status

    def stop(self):
        self.network.stop()

    def get_state(self):
        return self.network.state

    def is_stopped(self):
        return self.network.state == self.network.STATE_STOPPED

    def is_running(self):
        return self.network.state == self.network.STATE_READY
开发者ID:RomanGrekov,项目名称:z_gateway,代码行数:69,代码来源:start_network.py

示例9: Backend

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class Backend():

    def __init__(self):
        device = "/dev/ttyUSB0"
        options = ZWaveOption(device, config_path="/home/rich/openzwave/config", user_path=".", cmd_line="")
        options.set_log_file("OZW_Log.log")
        options.set_append_log_file(False)
        options.set_console_output(False)
        options.set_save_log_level('Debug')
        options.set_logging(True)
        options.lock()

        self.values = {}
        dispatcher.connect(self._network_started, ZWaveNetwork.SIGNAL_NETWORK_STARTED)
        dispatcher.connect(self._network_failed, ZWaveNetwork.SIGNAL_NETWORK_FAILED)
        dispatcher.connect(self._network_ready, ZWaveNetwork.SIGNAL_NETWORK_READY)
        self.network = ZWaveNetwork(options, autostart=False)

    def _network_started(self, network):
        print("network started - %d nodes were found." % network.nodes_count)

    def _network_failed(self, network):
        print("network failed :(")

    def _network_ready(self, network):
        print("network : ready : %d nodes were found." % network.nodes_count)
        print("network : controller is : %s" % network.controller)
        dispatcher.connect(self._node_update, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(self._node_event, ZWaveNetwork.SIGNAL_NODE_EVENT)
        dispatcher.connect(self._value_update, ZWaveNetwork.SIGNAL_VALUE)

    def _node_update(self, network, node):
        print('node update: %s.' % node)

    def _node_event(self, network, node, signal, sender):
        print('node event %s from node %s.' % (signal, node.node_id))
        value = self.network.get_value(IR_SENSOR_VALUE).data
        print('value is now %s' % value)
        self.log_access_with_value(value)

    def log_access_with_value(self, value):
        print("logging sensor trigger to file")
        with open("triggers.csv", "a") as sensor_log_file:
            sensor_log_file.write("%s,%s\n" % (datetime.today().strftime("%d/%m/%Y %H:%M:%S"), value))

    def _value_update(self, network, node, value):
        print('value update: %s is %s.' % (value.label, value.data))
        self.values[value.label] = value.data
        if value.label == 'Temperature':
            self.process_temp_change(value.data)

    def process_temp_change(self, value):
        if value > 25 and not self.get_switch_status(3):
            print('too hot - turn on fan')
            self.switch_on(3)
        elif value < 25 and self.get_switch_status(3):
            print('cool enough - turn off fan')
            self.switch_off(3)

    def log_values(self):
        print('Writing sensor log')
        try:
            t = self.get_temperature()
            h = self.get_humidity()
            l = self.get_brightness()
            with open("sensors.csv", "a") as sensor_log_file:
                sensor_log_file.write("%s,%s,%s,%s\n" % (datetime.today().strftime("%d/%m/%Y %H:%M:%S"), t, h, l))
        except:
            print('Failed to log values')
        self.start_timer()

    def get_sensor_values(self):
        lines = open("sensors.csv", "r").readlines()
        return_list = []
        for line in lines:
            line = line[:-1]  # remove newline
            d = {'Date': line.split(',')[0], 'Temperature': line.split(',')[1], 'Humidity': line.split(',')[2],
                         'Lux': line.split(',')[3]}
            return_list.append(d)
        return return_list

    def switch_on(self, name):
        print("Activating switch %s" % name)
        parsed_id = 0
        try:
            parsed_id = int(name)
        except ValueError:
            pass
        for key, node in self.network.nodes.iteritems():
            if node.name == name or node.node_id == parsed_id:
                for val in node.get_switches():
                    node.set_switch(val, True)

    def switch_off(self, name):
        print("Deactivating switch %s" % name)
        parsed_id = 0
        try:
            parsed_id = int(name)
        except ValueError:
            pass
#.........这里部分代码省略.........
开发者ID:richbeales,项目名称:flask-openzwave,代码行数:103,代码来源:backend.py

示例10: Backend

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class Backend():

    def __init__(self):

	###################  instanciation de l'objet backend ########################################################


	###### options needed for python openzwave library like config files path, logging, 
        device = configpi.interface
        options = ZWaveOption(device, config_path="/home/pi/git-repo/python-openzwave/openzwave/config", user_path=".", cmd_line="")
        options.set_log_file("OZW.log")
        options.set_append_log_file(False)
        options.set_console_output(False)
        options.set_save_log_level('Warning')
        options.set_logging(True)
        options.lock()

        # creation of the object network using the options entity already created
        self.network = ZWaveNetwork(options, autostart=False)

	###### 	 These dispatchers associate a method to a signal. the signals are generated by the library python-openzwave.
	######   Once the signal is reveived. It's associated method is executed (see "_node_added" example below in "_network_started" method)
        dispatcher.connect(self._network_started, ZWaveNetwork.SIGNAL_NETWORK_STARTED)
        dispatcher.connect(self._network_failed, ZWaveNetwork.SIGNAL_NETWORK_FAILED)
        dispatcher.connect(self._network_ready, ZWaveNetwork.SIGNAL_NETWORK_READY)

	###### backend object attributes
#        self.devices = OrderedDict()  ### will contain the list of nodes in the network
#        self.sensors = OrderedDict()  ### will contain the list of sensors (only) in the network
        self.node_added = False
        self.node_removed = False
	self.timestamps = {}	      ### will contain the time of the last values' update for each sensor
        self.queryStages = {	      ### the diffrent stages that a node object gets through before being ready 
                "None"                  :  1, # Query process hasn't started for this node
                "ProtocolInfo"          :  2, # Retrieve protocol information
                "Probe"                 :  3, # Ping device 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
                "SecurityReport"        :  7, # Retrieve a list of Command Classes that require Security
                "ManufacturerSpecific2" :  8, # Retrieve manufacturer name and product ids
                "Versions"              :  9, # Retrieve version information
                "Instances"             : 10, # Retrieve information about multiple command class instances
                "Static"                : 11, # Retrieve static information (doesn't change)
                "Probe1"                : 12, # Ping a device upon starting with configuration
                "Associations"          : 13, # Retrieve information about associations
                "Neighbors"             : 14, # Retrieve node neighbor list
                "Session"               : 15, # Retrieve session information (changes infrequently)
                "Dynamic"               : 16, # Retrieve dynamic information (changes frequently)
                "Configuration"         : 17, # Retrieve configurable parameter information (only done on request)
                "Complete"              : 18  # Query process is completed for this node
        }

#######################################################################################################################
############# NETWORK #################################################################################################
#######################################################################################################################

    def _network_started(self, network):

	# executed once the software representation is started. the discovery of the network components has begun. they will be mapped into objects

        print("network started - %d nodes were found." % network.nodes_count)

	# these dispatchers associate a method to a signal. the signals are generated by the library python-openzwave.
	# a signal may contain a number of parameters that are passed to the method associated to the signal.
	# for exemple, the dispatcher below associates the signal "SIGNAL_NODE_ADDED" to the method "_node_added" that is implemented below (line 111).
	# the signal "SIGNAL_NODE_ADDED" transports two parameters which are the objects network and node.
	# once this signal is received, these two parameters will be passed to the method "_node_added" and the method will be executed.

        dispatcher.connect(self._node_added, ZWaveNetwork.SIGNAL_NODE_ADDED)
        dispatcher.connect(self._node_removed, ZWaveNetwork.SIGNAL_NODE_REMOVED)
        dispatcher.connect(self._debug_node_naming, ZWaveNetwork.SIGNAL_NODE_NAMING)
        dispatcher.connect(self._debug_node_new, ZWaveNetwork.SIGNAL_NODE_NEW)
        dispatcher.connect(self._debug_node_protocol_info, ZWaveNetwork.SIGNAL_NODE_PROTOCOL_INFO)
        
    def _network_failed(self, network):

	# executed once the software representation has failed

        print("network failed :(")

    def _network_ready(self, network):

	# executed once the software representation is ready

        print("network : ready : %d nodes were found." % network.nodes_count)
        print("network : controller is : %s" % network.controller)
#        dispatcher.connect(self._node_update, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(self._node_event, ZWaveNetwork.SIGNAL_NODE_EVENT)
        dispatcher.connect(self._value_update, ZWaveNetwork.SIGNAL_VALUE)

    def _node_added(self, network, node):

	# executed when node is added to the software representation. it's executed after the method "_debug_node_new" (see below)

        print('node added: %s.' % node.node_id)
	self.timestamps["timestamp" + str(node.node_id)] = "No Measurement received yet"
        self.node_added = True

    def _node_removed(self, network, node):
#.........这里部分代码省略.........
开发者ID:wheelin,项目名称:iot_src_report,代码行数:103,代码来源:backend_modif.py

示例11: ZWaveController

# 需要导入模块: from openzwave.network import ZWaveNetwork [as 别名]
# 或者: from openzwave.network.ZWaveNetwork import start [as 别名]
class ZWaveController():
    network = None

    def setup(self, updateCallback):
        dispatcher.connect(self.onNetworkReady, ZWaveNetwork.SIGNAL_NETWORK_READY)
        dispatcher.connect(self.onNetworkStart, ZWaveNetwork.SIGNAL_NETWORK_STARTED)
        dispatcher.connect(self.onNetworkFailed, ZWaveNetwork.SIGNAL_NETWORK_FAILED)

        # TODO: make udev.symlink rule to a specific port (USB0/1)
        # Uncomment this to run on PC (remember to update the zwave config path)
        #options = ZWaveOption("/dev/ttyUSB0", \
        #  config_path="/home/<USER>/software/python-openzwave-0.2.6/openzwave/config", \
        options = ZWaveOption("/dev/serial/by-path/platform-bcm2708_usb-usb-0:1.2:1.0-port0", \
          config_path="/home/pi/software/python-openzwave-0.2.6/openzwave/config", \
          user_path=".", cmd_line="")
        options.set_append_log_file(False)
        options.set_console_output(False)
        options.set_save_log_level('Debug')
        options.set_poll_interval(30);
        options.set_suppress_value_refresh(False)
        options.addOptionBool("AssumeAwake", True)
        options.set_logging(False)
        options.lock()
        self.network = ZWaveNetwork(options, autostart=False)
        self.onDeviceUpdateCallback = updateCallback
        self.network.start()
        self.addedConnections = False
        Timer(2*60, self.setupConnections).start()


    def tearDown(self):
        network.stop()

    def getDeviceList(self):
        devices = []
        for node in self.network.nodes:
            if node == 1: continue # don't add the controller
            devices.append(self.buildDevice(node))
        return devices

    def buildDevice(self, node):
        dev = {}
        dev['id'] = int(self.network.home_id)*1000 + node
        dev['type'] = 'unknown'
        dev['product_name'] = self.network.nodes[node].product_name
        if self.getValueForLabel(node, 'Switch'):
            dev['type'] = 'appliance'
            val = self.getValueForLabel(node, 'Energy')
            dev['consumption_accumulated'] = type(val) != "None" and val or 0
            val = self.getValueForLabel(node, 'Power')
            dev['consumption_current'] =  type(val) != "None" and val or 0
            if self.getValueForLabel(node, 'Switch') == 'True':
                dev['state'] = 'on'
            else:
                dev['state'] = 'off'
        if self.getValueForLabel(node, 'Sensor'):
            dev['type'] = 'sensor'
            dev['temperature'] = self.getValueForLabel(node, 'Temperature')
            dev['luminance']   = self.getValueForLabel(node, 'Luminance')
            dev['presence']    = "undetected"
        dev['battery_level'] = self.getValueForLabel(node, 'Battery Level')
        return dev

    def getValueForLabel(self, node, label):
        for v in self.network.nodes[node].values: 
            if self.network.nodes[node].values[v].label == label:
                #self.network.nodes[node].refresh_value(v);
                return str(self.network.nodes[node].values[v].data_as_string)
        return None

    def setDeviceState(self, device_id, state):
        node = device_id%1000
        if not self.network.nodes[node]: return
        for val in self.network.nodes[node].get_switches() :
            self.network.nodes[node].set_switch(val, True if state=='on' else False)
        
    def setupConnections(self):
        self.addedConnections = True
        dispatcher.connect(self.onNodeUpdate, ZWaveNetwork.SIGNAL_NODE)
        dispatcher.connect(self.onNodeUpdateValue, ZWaveNetwork.SIGNAL_VALUE)
        dispatcher.connect(self.onNodeUpdateValue, ZWaveNetwork.SIGNAL_NODE_EVENT)
        dispatcher.connect(self.onNodeUpdateValue, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
        dispatcher.connect(self.onNodeUpdateValue, ZWaveNetwork.SIGNAL_VALUE_REFRESHED)

    # Event Handlers

    def onNetworkStart(self, network):
        print("network started : homeid %0.8x - %d nodes were found." % \
            (network.home_id, network.nodes_count))

    def onNetworkFailed(self, network):
        print("network can't load :(")

    def onNetworkReady(self, network):
        print("network : I'm ready : %d nodes were found." % network.nodes_count)
        print("network : my controller is : %s" % network.controller)
        self.network = network
        if not self.addedConnections:
            self.setupConnections()

#.........这里部分代码省略.........
开发者ID:hoffmannmatheus,项目名称:eaZy,代码行数:103,代码来源:zwave_controller.py


注:本文中的openzwave.network.ZWaveNetwork.start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。