예제 #1
0
def cmd_set_basic_multi(args):
    driver, controller = InitController(args, True)
    translator = CommandTranslator(driver)
    logging.info("sending command to %s", args.node)
    translator.SendMultiCommand(args.node, z.Basic_Set, {"level": args.level},
                                ControllerPriority(), XMIT_OPTIONS)

    driver.Terminate()
예제 #2
0
def cmd_get_basic(args):
    driver, controller = InitController(args, True)
    translator = CommandTranslator(driver)
    translator.AddListener(NodeUpdateListener())
    for n in args.node:
        translator.SendCommand(n, z.Basic_Get, {}, ControllerPriority(),
                               XMIT_OPTIONS)
    time.sleep(2)
    driver.Terminate()
예제 #3
0
def InitializeDevices(stdscr, driver, controller):
    """If stdscr is not None we use curses and must not use print
        With curses the left side shows interesting info and the right
        side show loggging.
    """
    translator = CommandTranslator(driver)
    nodeset = Nodeset(translator, controller.GetNodeId())
    translator.AddListener(TestListener())
    # n.InitializeExternally(CONTROLLER.props.product, CONTROLLER.props.library_type, True)

    if stdscr:
        screen = Screen(stdscr, driver, controller, nodeset)
        logger = logging.getLogger()
        logger.handlers.clear()
        logger.addHandler(screen)
    else:
        screen = 0
    logging.info("Pinging %d nodes", len(controller.nodes))
    for n in controller.nodes:
        translator.Ping(n, 5, False, "initial")
        time.sleep(0.5)

    logging.info("Waiting for all nodes to be interviewed")
    all_nodes = set(controller.nodes)
    ready_nodes = set([controller.GetNodeId()]) | set(controller.failed_nodes)

    while len(all_nodes) > len(ready_nodes):
        # we may create new pseudo nodes
        for n in nodeset.nodes:
            all_nodes.add(n)

        by_state = {}
        for node in nodeset.nodes.values():
            if node.state not in by_state:
                by_state[node.state] = set()
            by_state[node.state].add(node.Name())

        if stdscr:
            screen.Redraw()
        else:
            for k, v in by_state.items():
                print(k, v)

        for n, node in nodeset.nodes.items():
            node = nodeset.GetNode(n)
            if node.IsInterviewed():
                ready_nodes.add(n)
            elif node.state == NODE_STATE_NONE:
                translator.Ping(n, 3, False, "undiscovered")
            elif node.state == NODE_STATE_DISCOVERED:
                if driver.OutQueueSizeForNode(n) < 10 and random.randint(
                        0, 5) == 0:
                    node.RefreshStaticValues()

        time.sleep(3.0)
예제 #4
0
def cmd_secure_pair(args):
    # experimental - make sure you enable security in node.py
    driver, controller = InitController(args)
    translator = CommandTranslator(driver)
    translator.AddListener(TestListener())
    nodeset = Nodeset(translator, controller.GetNodeId())
    controller.StopAddNodeToNetwork(ControllerEventCallback)
    time.sleep(1.0)
    controller.AddNodeToNetwork(ControllerEventCallback)
    controller.StopAddNodeToNetwork(ControllerEventCallback)
    time.sleep(5.0)
예제 #5
0
def main():
    global DRIVER, CONTROLLER, TRANSLATOR, NODESET, DB
    # note: this makes sure we have at least one handler
    # logging.basicConfig(level=logging.WARNING)
    # logging.basicConfig(level=logging.ERROR)

    tornado.options.parse_command_line()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.setLevel(logging.WARNING)
    #logger.setLevel(logging.ERROR)
    for h in logger.handlers:
        h.setFormatter(MyFormatter())

    logging.info("opening shelf: %s", OPTIONS.db)
    DB = Db(OPTIONS.db)

    application = tornado.web.Application(
        HANDLERS,
        # debug=True,
        task_pool=multiprocessing.Pool(OPTIONS.tasks),
        # map static/xxx to Static/xxx
        static_path="Static/",
    )

    logging.info("opening serial")
    device = MakeSerialDevice(OPTIONS.serial_port)

    DRIVER = Driver(device)
    CONTROLLER = Controller(DRIVER,
                            pairing_timeout_secs=OPTIONS.pairing_timeout_secs)
    CONTROLLER.Initialize()
    CONTROLLER.WaitUntilInitialized()
    CONTROLLER.UpdateRoutingInfo()
    DRIVER.WaitUntilAllPreviousMessagesHaveBeenHandled()
    print(CONTROLLER)
    TRANSLATOR = CommandTranslator(DRIVER)
    NODESET = Nodeset(TRANSLATOR, CONTROLLER.GetNodeId())

    cp = CONTROLLER.props.product
    NODESET.put(CONTROLLER.GetNodeId(), time.time(),
                z.ManufacturerSpecific_Report, {
                    'manufacturer': cp[0],
                    'type': cp[1],
                    'product': cp[2]
                })
    # The updater will do the initial pings of the nodes
    TRANSLATOR.AddListener(NodeUpdater())
    logging.warning("listening on port %d", OPTIONS.port)
    application.listen(OPTIONS.port)
    tornado.ioloop.IOLoop.instance().start()
    return 0
예제 #6
0
def main():
    global DRIVER, CONTROLLER, TRANSLATOR, NODESET, DB
    tornado.options.parse_command_line()
    # use --logging command line option to control verbosity
    # logging.basicConfig(level=logging.WARNING)
    logger = logging.getLogger()
    for h in logger.handlers:
        h.setFormatter(MyFormatter())

    # used to persist certain settings like node names
    logging.info("opening shelf: %s", OPTIONS.db)
    DB = Db(OPTIONS.db)

    application = tornado.web.Application(_HANDLERS, **_SETTINGS)

    logging.info("opening serial")
    device = MakeSerialDevice(OPTIONS.serial_port)

    DRIVER = Driver(device)
    CONTROLLER = Controller(DRIVER,
                            pairing_timeout_secs=OPTIONS.pairing_timeout_secs)
    CONTROLLER.Initialize()
    CONTROLLER.WaitUntilInitialized()
    CONTROLLER.UpdateRoutingInfo()
    DRIVER.WaitUntilAllPreviousMessagesHaveBeenHandled()
    print(CONTROLLER)
    TRANSLATOR = CommandTranslator(DRIVER)
    NODESET = Nodeset(TRANSLATOR, CONTROLLER.GetNodeId())

    cp = CONTROLLER.props.product
    NODESET.put(CONTROLLER.GetNodeId(), time.time(),
                z.ManufacturerSpecific_Report, {
                    'manufacturer': cp[0],
                    'type': cp[1],
                    'product': cp[2]
                })
    for n in CONTROLLER.nodes:
        TRANSLATOR.Ping(n, 3, False, "refresher")
    updater = NodeUpdater()
    TRANSLATOR.AddListener(updater)
    logging.warning("listening on port %d", OPTIONS.port)
    application.listen(OPTIONS.port)
    tornado.ioloop.PeriodicCallback(updater.Periodic, 2000).start()
    tornado.ioloop.IOLoop.instance().start()
    return 0
예제 #7
0
def _main(argv):
    logger = logging.getLogger()
    logger.setLevel(logging.WARNING)

    fake_driver = FakeDriver()
    translator = CommandTranslator(fake_driver)
    nodeset = Nodeset(translator, 1)
    ts = 0
    for line in sys.stdin:
        ts += 1
        if line.startswith("#"): continue
        token = line.split()
        if len(token) == 0: continue

        print()
        print("incoming: ", line[:-1])
        mesg = [ParseToken(t) for t in token]
        print("hex: ", Hexify(mesg))
        translator.put(ts, mesg)

    for n in nodeset.nodes.values():
        Banner("Node %s" % n.n)
        values: NodeValues = n.values
        print("########### VALUES")
        for v in sorted(values.Values()):
            print(v)
        print("########### VERSIONS")
        for v in sorted(values.CommandVersions()):
            print(v)
        print("########### CONFIGURATIONS")
        for v in sorted(values.Configuration()):
            print(v)
        print("########### ASSOCIATIONS")
        for v in sorted(values.Associations()):
            print(v)
        print("########### METERS")
        for v in sorted(values.Meters()):
            print(v)
        print("########### SENSORS")
        for v in sorted(values.Sensors()):
            print(v)

    print("OK")
    return 0
def main():
    fake_driver = FakeDriver()
    translator = CommandTranslator(fake_driver)
    nodeset = Nodeset(translator, 1)

    node = nodeset.GetNode(2)

    assert not node.values.HasCommandClass(z.Basic)
    node.put(0, z.Version_CommandClassReport, {
        "class": z.Basic,
        "version": 10
    })
    assert node.values.HasCommandClass(z.Basic)

    print("OK")
    return 0
예제 #9
0
def main():
    global driver, controller, translator, nodeset

    parser = argparse.ArgumentParser(description='Process some integers.')

    parser.add_argument(
        '--serial_port',
        type=str,
        default="/dev/ttyUSB0",
        help='The USB serial device representing the Z-Wave controller stick. ' +
        'Common settings are: dev/ttyUSB0, dev/ttyACM0')
    parser.add_argument('--mqtt_broker_host', type=str,
                        default="localhost",
                        help='mqtt broker host')
    parser.add_argument('--mqtt_broker_port', type=int,
                        default=1883,
                        help='mqtt broker port')
    parser.add_argument('--verbosity', type=int,
                        default=30,  # = logging.WARNING
                        help='Lower numbers mean more verbosity')

    args = parser.parse_args()
    # note: this makes sure we have at least one handler
    logging.basicConfig(level=args.verbosity)
    logger = logging.getLogger()
    logger.setLevel(args.verbosity)
    for h in logger.handlers:
        h.setFormatter(MyFormatter())

    logging.warning("opening serial: [%s]", args.serial_port)
    device = MakeSerialDevice(args.serial_port)

    driver = Driver(device)

    logging.warning("controller initializing")
    controller = Controller(driver, pairing_timeout_secs=60)
    controller.Initialize()
    controller.WaitUntilInitialized()
    controller.UpdateRoutingInfo()
    time.sleep(2)
    logging.warning("controller initialized:\n" + str(controller))

    translator = CommandTranslator(driver)
    nodeset = Nodeset(translator, controller.GetNodeId())

    def on_connect(client, _userdata, _rc, _dummy):
        logging.warning("Initialized MQTT client")
        logging.warning("Pinging %d nodes", len(controller.nodes))
        for n in controller.nodes:
            translator.Ping(n, 5, False, "initial")
            time.sleep(0.5)
            client.subscribe("zwave_out/%d/#" % controller.props.home_id)

    def on_message(client, _userdata, msg):
        tokens = msg.topic.split("/")
        key_int = STRING_TO_SUBCMD.get(tokens[3])
        if key_int is None:
            logging.error("unknown command: %s", tokens[3])
        key = ((key_int >> 8) & 255, key_int & 255)
        n = int(tokens[2])
        values = json.loads(msg.payload)
        logging.warning(
            "command received: %d [%s] %s",
            n,
            tokens[3],
            msg.payload)
        translator.SendCommand(n, key, values, NodePriorityHi(n), XMIT_OPTIONS)
        # print(n, key, data)

    logging.info("Initializing MQTT client")
    client = mqtt.Client("zwave-client")
    client.on_connect = on_connect
    client.on_message = on_message

    translator.AddListener(EventListener(controller.props.home_id, client))
    client.connect(
        args.mqtt_broker_host,
        port=args.mqtt_broker_port,
        keepalive=60)
    client.loop_forever()

    driver.Terminate()
    return 0
예제 #10
0
파일: node.py 프로젝트: Eagle1707/PyZwaver
 def __init__(self, translator: CommandTranslator, controller_n):
     self._controller_n = controller_n
     self._translator = translator
     self.nodes: Mapping[int, Node] = {}
     translator.AddListener(self)
예제 #11
0
def main():
    global driver, controller, translator, nodeset

    parser = argparse.ArgumentParser(description='Process some integers.')

    parser.add_argument(
        '--serial_port',
        type=str,
        default="/dev/ttyUSB0",
        help='The USB serial device representing the Z-Wave controller stick. '
        + 'Common settings are: dev/ttyUSB0, dev/ttyACM0')

    parser.add_argument('--verbosity',
                        type=int,
                        default=30,
                        help='Lower numbers mean more verbosity')

    args = parser.parse_args()
    # note: this makes sure we have at least one handler
    logging.basicConfig(level=logging.ERROR)
    logger = logging.getLogger()
    logger.setLevel(args.verbosity)
    for h in logger.handlers:
        h.setFormatter(MyFormatter())

    logging.info("opening serial: [%s]", args.serial_port)
    device = MakeSerialDevice(args.serial_port)

    driver = Driver(device)
    controller = Controller(driver, pairing_timeout_secs=60)
    controller.Initialize()
    controller.WaitUntilInitialized()
    controller.UpdateRoutingInfo()
    time.sleep(2)
    Banner("Initialized Controller")
    print(controller)

    translator = CommandTranslator(driver)
    nodeset = Nodeset(translator, controller.GetNodeId())
    translator.AddListener(TestListener())
    # n.InitializeExternally(CONTROLLER.props.product, CONTROLLER.props.library_type, True)

    logging.info("Pinging %d nodes", len(controller.nodes))
    for n in controller.nodes:
        translator.Ping(n, 5, False, "initial")
        time.sleep(0.5)

    logging.info("Waiting for all nodes to be interviewed")
    not_ready = controller.nodes.copy()
    not_ready.remove(controller.GetNodeId())
    while not_ready:
        interviewed = set()
        for n in not_ready:
            node = nodeset.GetNode(n)
            if node.IsInterviewed():
                interviewed.add(node)
        time.sleep(2.0)
        for node in interviewed:
            Banner("Node %s has been interviewed" % node.n)
            print(node)
            not_ready.remove(node.n)
            if not_ready:
                print("\nStill waiting for %s" % str(not_ready))
    driver.Terminate()
    return 0