def main():
    try:
        cli_instance = ZbCliDevice({'com_port': 'COM4'})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    print("CLI device created, trying to connect ...")
    
    # # Start commissioning.
    #cli_instance.bdb.start()
    
    cmd = ""
    while cmd != "exit" :
        cmd = input("> ")
        cmdparts = cmd.split( )
        if (cmdparts[0] == "show" or cmdparts[0] == "sh"):
            if (cmdparts == "devices"[1] or cmdparts[1] == "dev"):
                #zdo match_desc 0xfffd 0xfffd 0x0104 1 0 0
                response = cli_instance.zdo.match_desc([], [], 80.0, 0xFFFd, 0xFFFd, 0x0104)
                print(response)
            
        elif (cmdparts[0] == "set"):
            if (cmdparts[1] == "device" or cmdparts[1] == "dev"):
                if(cmdparts[2] == "on"):
                    cli_instance.zcl.generic(eui64=int(cmdparts[3], 16), ep=int(cmdparts[4]), cluster=constants.ON_OFF_CLUSTER, profile=constants.DEFAULT_ZIGBEE_PROFILE_ID, cmd_id=constants.ON_OFF_ON_CMD, payload=[]) 
                elif (cmdparts[2] == "off"):
                    cli_instance.zcl.generic(eui64=int(cmdparts[3], 16), ep=int(cmdparts[4]), cluster=constants.ON_OFF_CLUSTER, profile=constants.DEFAULT_ZIGBEE_PROFILE_ID, cmd_id=constants.ON_OFF_OFF_CMD, payload=[])  
 def __init__(self, port, channel, target_id):
     self.target_id = target_id
     self.channel = channel
     self.port = port
     self.cli_instance = ZbCliDevice('', '', port)
     self.short = None
     self.entry_point = 8
def start_network():
    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        cli_instance.bdb.channel = [20]  # channel must be dictionary
        cli_instance.bdb.role = 'zc'  # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    # Start commissioning.
    cli_instance.bdb.start()

    return redirect(url_for('index'))
def control_device():
    dev = request.args.get('device')
    ep = request.args.get('endpoint')
    state = request.args.get('state')

    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #   cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    print("CLI device created, trying to connect ...")
    if (state == "on"):
        cli_instance.zcl.generic(eui64=int(dev, 16),
                                 ep=int(ep),
                                 cluster=constants.ON_OFF_CLUSTER,
                                 profile=constants.DEFAULT_ZIGBEE_PROFILE_ID,
                                 cmd_id=constants.ON_OFF_ON_CMD,
                                 payload=[])
    else:
        cli_instance.zcl.generic(eui64=int(dev, 16),
                                 ep=int(ep),
                                 cluster=constants.ON_OFF_CLUSTER,
                                 profile=constants.DEFAULT_ZIGBEE_PROFILE_ID,
                                 cmd_id=constants.ON_OFF_OFF_CMD,
                                 payload=[])
    print("set device " + request.args.get('device') + " to " +
          request.args.get('state'))
    cli_instance.close_cli()
    #return '<a href="/index"><button type="button" class="btn btn-primary">Back to devices</button></a>'
    return redirect(url_for('index'))
def group_control():
    dev = request.args.get('device')
    ep = request.args.get('endpoint')
    group = request.args.get('group')
    add = request.args.get('action')

    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #   cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    if (add == 'add'):
        cli_instance.zcl.generic(eui64=int(dev, 16),
                                 ep=int(ep),
                                 cluster=0x4,
                                 profile=constants.DEFAULT_ZIGBEE_PROFILE_ID,
                                 cmd_id=0x0,
                                 payload=[(int(group,
                                               16), constants.UINT16_TYPE)])
    else:
        cli_instance.zcl.generic(eui64=int(dev, 16),
                                 ep=int(ep),
                                 cluster=0x4,
                                 profile=constants.DEFAULT_ZIGBEE_PROFILE_ID,
                                 cmd_id=0x3,
                                 payload=[(int(group,
                                               16), constants.UINT16_TYPE)])

    cli_instance.close_cli()

    return redirect(url_for('info') + '?device=' + dev + '&endpoint=' + ep)
def index():
    # Start commissioning.
    # cli_instance.bdb.start()
    #response = [(1234, 10)]
    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #   cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    with open("nodes.txt") as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print(content)

    devices = []
    for i in range(0, len(content)):
        parts = content[i].split('|')
        attr = Attribute(cluster=0x6, id=0, type=0)
        state = 0
        try:
            state = cli_instance.zcl.readattr(eui64=int(parts[0], 16),
                                              attr=attr,
                                              ep=int(parts[1])).value
        except:
            print("couldn't get state")

        devices.append((parts[0], parts[1], state))

    with open("switches.txt") as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print(content)

    groups = []
    for i in range(0, len(content)):
        parts = content[i].split('|')
        groups.append((parts[0], parts[1]))

    print(devices)
    cli_instance.close_cli()

    return render_template('index.html',
                           nodes=devices,
                           groups=groups,
                           grouplen=len(groups),
                           nodelen=len(devices))
def info():
    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #   cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    dev = request.args.get('device')
    ep = request.args.get('endpoint')
    state = 'on'
    try:
        state = cli_instance.zcl.readattr(eui64=int(parts[0], 16),
                                          attr=attr,
                                          ep=int(parts[1])).value
    except:
        print("couldn't get state")

    #cli_instance.zcl.generic(eui64=int(dev, 16), ep=int(ep), cluster=int("0x4", 16), profile=constants.DEFAULT_ZIGBEE_PROFILE_ID, cmd_id=int("0x1", 16), payload=[ (  0x3333, 0x21)])

    with open("switches.txt") as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print(content)

    groups = []
    for i in range(0, len(content)):
        parts = content[i].split('|')
        addr = int(parts[0], 16)
        addrstr = str('{:x}'.format(addr + 1))
        #SwitchFile.write())
        groups.append((addrstr, parts[1]))

    state = 0

    #add_group_form = AddGroupForm
    #remove_group_form = RemoveGroupForm
    cli_instance.close_cli()
    return render_template(
        'info.html',
        device=dev,
        endpoint=ep,
        state=state,
        groups=groups,
        len=len(groups)
    )  # add_group_form=add_group_form, remove_group_form=remove_group_form)
def refresh():
    # a = int("BAF1", 16)
    # hexx = str('{:x}'.format(a+ 1))
    # print(hexx)

    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #   cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    #print("CLI device created, trying to connect ...")

    #devices = [(4211, 10)]
    # devices = cli_instance.zdo.match_desc([6], [], 80.0, 0xFFFd, 0xFFFd, 0x0104)
    devices = cli_instance.zdo.match_desc([0], [], 80.0, 0xFFFd, 0xFFFd,
                                          0x0104)
    print(devices)
    BulbFile = open('nodes.txt', 'w')
    SwitchFile = open('switches.txt', 'w')

    for element in devices:
        if (str(element[1]) == '10'):
            BulbFile.write(str(element[0]))
            BulbFile.write('|')
            BulbFile.write(str(element[1]))
            BulbFile.write('\n')
        else:
            #addr = int(element[0], 16)

            #SwitchFile.write(str('{:x}'.format(addr + 1)))
            SwitchFile.write(str(element[0]))
            SwitchFile.write('|')
            SwitchFile.write(str(element[1]))
            SwitchFile.write('\n')
    BulbFile.close()
    SwitchFile.close()

    cli_instance.close_cli()
    return redirect(url_for('index'))
class ZigBeeDriver():
    def __init__(self, port, channel, target_id):
        self.target_id = target_id
        self.channel = channel
        self.port = port
        self.cli_instance = ZbCliDevice('', '', port)
        self.short = None
        self.entry_point = 8

    def __del__(self):
        self.cli_instance.close_cli()

    def get_short_address(self):
        try:
            self.short = self.cli_instance.zdo.short_addr
            return self.short

        except CommandError:
            print("device was not commissioned")
            return -1

    def connect(self):
        try:
            self.cli_instance.bdb.channel = [self.channel]
            self.cli_instance.bdb.role = 'zr'  # zigbee router
            self.cli_instance.bdb.start()

            return self.get_short_address()

        except SerialTimeoutException:
            print("connect failed: {}".format('Write timeout'))

        except CommandError:  # already connected
            try:
                self.cli_instance.bdb.start()
            except CommandError:
                pass
            return self.get_short_address()

    def disconnect(self):
        self.cli_instance.bdb.factory_reset()
        self.short = None

        return self.get_short_address()

    def write_attr_command(self, cmd):
        cluster = clusters[cmd['cluster']]
        if cluster == ON_OFF_CLUSTER:
            cmd_id = commands[cmd['cluster']][cmd['command']]
        elif cluster == LVL_CTRL_CLUSTER:
            cmd_id = commands[cmd['cluster']][cmd['command']]
        elif cluster == COLOR_CTRL_CLUSTER:
            cmd_id = commands[cmd['cluster']][cmd['command']]
        self.cli_instance.zcl.generic(eui64=self.target_id,
                                      ep=self.entry_point,
                                      profile=DEFAULT_ZIGBEE_PROFILE_ID,
                                      cluster=cluster,
                                      cmd_id=cmd_id,
                                      payload=cmd['payloads'])
        try:
            time.sleep(cmd['wait'] / 1000)  # waiting for the transition
        except KeyError:
            pass

    # @hipiphock
    # made to run new command
    def new_run_command(self, cluster, taskcmd):
        self.cli_instance.zcl.generic(eui64=self.target_id,
                                      ep=self.entry_point,
                                      profile=DEFAULT_ZIGBEE_PROFILE_ID,
                                      cluster=cluster,
                                      cmd_id=taskcmd.id,
                                      payload=taskcmd.payloads)
        try:
            time.sleep(taskcmd.waittime / 1000)
        except KeyError:
            pass

    def read_attr_command(self, attribute):
        try:
            result = self.cli_instance.zcl.readattr(self.target_id,
                                                    attr=attribute,
                                                    ep=self.entry_point)
        except CommandError:
            print("request Timed out")

        return result
Example #10
0
def kick():
    dev = request.args.get('device')

    try:
        cli_instance = ZbCliDevice({'com_port': comport})
        #cli_instance.bdb.channel = [16] # channel must be dictionary
        #   cli_instance.bdb.role = 'zr' # set coordinator role
    except serial.serialutil.SerialException:
        print('Can not create CLI device')
        cli_instance.close_cli()
        return None

    print(dev)
    cli_instance.zdo.leave(short_addr=int(dev, 16))

    with open("nodes.txt") as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print(content)

    devices = []
    for i in range(0, len(content)):
        parts = content[i].split('|')
        attr = Attribute(cluster=0x6, id=0, type=0)
        state = 0
        try:
            state = cli_instance.zcl.readattr(eui64=int(parts[0], 16),
                                              attr=attr,
                                              ep=int(parts[1])).value
        except:
            print("couldn't get state")
        if (parts[0] != dev):
            devices.append((parts[0], parts[1], state))

    with open("switches.txt") as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print(content)

    groups = []
    for i in range(0, len(content)):
        parts = content[i].split('|')
        if (parts[0] != dev):
            devices.append((parts[0], parts[1]))

    BulbFile = open('nodes.txt', 'w')
    SwitchFile = open('switches.txt', 'w')

    for element in devices:
        if (str(element[1]) == '10'):
            BulbFile.write(str(element[0]))
            BulbFile.write('|')
            BulbFile.write(str(element[1]))
            BulbFile.write('\n')
        else:
            #addr = int(element[0], 16)

            #SwitchFile.write(str('{:x}'.format(addr + 1)))
            SwitchFile.write(str(element[0]))
            SwitchFile.write('|')
            SwitchFile.write(str(element[1]))
            SwitchFile.write('\n')
    BulbFile.close()
    SwitchFile.close()

    cli_instance.close_cli()

    return redirect(url_for('index'))
Example #11
0
    def start_routine(self):
        status = 1
        # Before connecting the device with the dongle,
        # the dongle must join the hub's network.
        # TODO: implement automated port selector
        # with open('resource\\dongle_status.json', "r") as dongle_file:
        #     dongle_config = json.load(dongle_file)
        #     port = dongle_config['port']
        #     status = dongle_config['status']
        #     dongle_file.close()
        time.sleep(3)
        cli_instance = ZbCliDevice('', '', self.port)
        if status == 0:
            cli_instance.bdb.channel = [24]
            cli_instance.bdb.role = 'zr'
            cli_instance.bdb.start()
            # TODO: change the directory's path
            with open('resource\\dongle_status.json', "w") as dongle_file:
                dongle_config['status'] = 1
                json.dump(dongle_config, dongle_file)
                dongle_file.close()
            print("The dongle has started commissioning.")
            print(
                "Please search for the dongle via SmartThings App within 5 seconds."
            )
            time.sleep(5.0)

        # zblogger = ZigbeeLogger()
        # log_file_name = zblogger.log_init()

        # 1. Start connection with the device.
        # The connection of the device is ruled by SmartThings hub.

        # do the task_list
        for i in range(self.iteration):
            for task in self.task_list:
                if task.task_kind == COMMAND_TASK:
                    if task.payloads == None:
                        cli_instance.zcl.generic(
                            eui64=self.device.addr,
                            ep=self.device.ep,
                            profile=DEFAULT_ZIGBEE_PROFILE_ID,
                            cluster=task.cluster,
                            cmd_id=task.command)
                    else:
                        cli_instance.zcl.generic(
                            eui64=self.device.addr,
                            ep=self.device.ep,
                            profile=DEFAULT_ZIGBEE_PROFILE_ID,
                            cluster=task.cluster,
                            cmd_id=task.command,
                            payload=task.payloads)
                    time.sleep(task.duration)
                    attr_id, attr_type = get_attr_element(
                        task.cluster, task.command)
                    param_attr = Attribute(task.cluster, attr_id, attr_type)
                    returned_attr = cli_instance.zcl.readattr(
                        self.device.addr,
                        param_attr,
                        ep=ULTRA_THIN_WAFER_ENDPOINT)
                    # zblogger.get_command_log(task)
                elif task.task_kind == READ_ATTRIBUTE_TASK:
                    param_attr = Attribute(task.cluster, task.attr_id,
                                           task.attr_type)
                    returned_attr = cli_instance.zcl.readattr(
                        self.device.addr,
                        param_attr,
                        ep=ULTRA_THIN_WAFER_ENDPOINT)
                    zblogger.get_read_attr_log(task, returned_attr.value)
                elif task.task_kind == WRITE_ATTRIBUTE_TASK:
                    param_attr = Attribute(task.cluster, task.attr_id,
                                           task.attr_type)
                    cli_instance.zcl.writeattr(self.device.addr,
                                               param_attr,
                                               ep=ULTRA_THIN_WAFER_ENDPOINT)
                    returned_attr = cli_instance.zcl.readattr(
                        self.device.addr,
                        param_attr,
                        ep=ULTRA_THIN_WAFER_ENDPOINT)
                    zblogger.get_read_attr_log(task, returned_attr.value)

        # # each task routine ends with disconnection
        # zblogger.close_logfile()
        cli_instance.close_cli()
Example #12
0
 def connect_device(self, port):
     cli_instance = ZbCliDevice('', '', port)
     cli_instance.bdb.channel = [24]
     cli_instance.bdb.role = 'zr'
     cli_instance.bdb.start()
     time.sleep(5.0)
Example #13
0
    def start_routine(self):
        if self.connection_type == ZIGBEE_CONNECTION:
            # Before connecting the device with the dongle,
            # the dongle must join the hub's network.
            # TODO: implement automated port selector
            with open('resource\\dongle_status.json', "r") as dongle_file:
                dongle_config = json.load(dongle_file)
                port = dongle_config['port']
                status = dongle_config['status']
                dongle_file.close()
            time.sleep(3)
            cli_instance = ZbCliDevice('', '', port)
            if status == 0:
                cli_instance.bdb.channel = [24]
                cli_instance.bdb.role = 'zr'
                cli_instance.bdb.start()
                # TODO: change the directory's path
                with open('resource\\dongle_status.json', "w") as dongle_file:
                    dongle_config['status'] = 1
                    json.dump(dongle_config, dongle_file)
                    dongle_file.close()
                print("The dongle has started commissioning.")
                print(
                    "Please search for the dongle via SmartThings App within 5 seconds."
                )
                time.sleep(5.0)

            zblogger = ZigbeeLogger()
            zblogger.log_init()

            # 1. Start connection with the device.
            # The connection of the device is ruled by SmartThings hub.

            # do the task_list
            for i in range(self.iteration):
                for task in self.task_list:
                    if task.task_kind == COMMAND_TASK:
                        if task.payloads == None:
                            cli_instance.zcl.generic(
                                eui64=self.device.addr,
                                ep=self.device.ep,
                                profile=DEFAULT_ZIGBEE_PROFILE_ID,
                                cluster=task.cluster,
                                cmd_id=task.command)
                        else:
                            cli_instance.zcl.generic(
                                eui64=self.device.addr,
                                ep=self.device.ep,
                                profile=DEFAULT_ZIGBEE_PROFILE_ID,
                                cluster=task.cluster,
                                cmd_id=task.command,
                                payload=task.payloads)
                        time.sleep(task.duration)
                        # TODO: change code like
                        # 1. create READ_ATTR task with respect to Cmd task
                        # 2. append READ_ATTR task to task_list
                        attr_id, attr_type = get_attr_element(
                            task.cluster, task.command)
                        param_attr = Attribute(task.cluster, attr_id,
                                               attr_type)
                        returned_attr = cli_instance.zcl.readattr(
                            self.device.addr,
                            param_attr,
                            ep=ULTRA_THIN_WAFER_ENDPOINT)
                        zblogger.get_command_log(task)
                    elif task.task_kind == READ_ATTRIBUTE_TASK:
                        param_attr = Attribute(task.cluster, task.attr_id,
                                               task.attr_type)
                        returned_attr = cli_instance.zcl.readattr(
                            self.device.addr,
                            param_attr,
                            ep=ULTRA_THIN_WAFER_ENDPOINT)
                        zblogger.get_read_attr_log(task, returned_attr.value)
                        time.sleep(task.duration)
                    elif task.task_kind == WRITE_ATTRIBUTE_TASK:
                        param_attr = Attribute(task.cluster, task.attr_id,
                                               task.attr_type)
                        cli_instance.zcl.writeattr(
                            self.device.addr,
                            param_attr,
                            ep=ULTRA_THIN_WAFER_ENDPOINT)
                        returned_attr = cli_instance.zcl.readattr(
                            self.device.addr,
                            param_attr,
                            ep=ULTRA_THIN_WAFER_ENDPOINT)
                        zblogger.get_read_attr_log(task, returned_attr.value)
                        time.sleep(task.duration)

            # # each task routine ends with disconnection
            zblogger.close_logfile()
            cli_instance.close_cli()

        ################# BLE Tasks ###################
        # Four steps for BLE
        # 1. Device scan
        #    Device scan is done by BleDevice. It searches for BLE device and gets GATT
        # 2. Connect to device
        #    It is mainly done by Peer.
        # 3. Read services and characteristics
        #    Again, it is done by BleDevice
        # 4. Read and write characteristics
        #

        elif self.connection_type == BLE_CONNECTION:
            pass