Sends an API AT command to read the lower-order address bits from
    an XBee Series 1 and looks for a response
420599
def main():
    
    try:

        # Open serial port
        ser = serial.Serial('/dev/ttyUSB0', 9600)

        # Create XBee Series 1 object
        xbee = XBee(ser)


        # Send AT packet
        xbee.send('at', frame_id='A', command='DH')

        # Wait for response
        response = xbee.wait_read_frame()
        print response

        # Send AT packet
        xbee.send('at', frame_id='B', command='DL')

        # Wait for response
        response = xbee.wait_read_frame()
        print response

        # Send AT packet
        xbee.send('at', frame_id='C', command='MY')

        # Wait for response
        response = xbee.wait_read_frame()
        print response

        # Send AT packet
        xbee.send('at', frame_id='D', command='CE')

        # Wait for response
        response = xbee.wait_read_frame()
        print response
    except KeyboardInterrupt:
        pass
    finally:
        ser.close()
24148
def _paload32(ins):
    ''' 
    '''
    output = _paddr(ins.quad[2])

    output.append('call __ILOAD32')
    output.append('push de')
    output.append('push hl')

    REQUIRES.add('iload32.asm')

    return output
913374
def execute(self, read_response=True):
        
        # // Up- and downlink packet
        # typedef struct {
        #   uint8_t bcnt;                       // Number of bytes (cmd + payload)
        #   uint8_t cmd;                        // YSM_xxx command
        #   uint8_t payload[YSM_MAX_PKT_SIZE];  // Payload
        # } YSM_PKT;
        if self.command != pyhsm.defines.YSM_NULL:
            # YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt
            cmd_buf = struct.pack('BB', len(self.payload) + 1, self.command)
        else:
            cmd_buf = chr(self.command)
        cmd_buf += self.payload
        debug_info = None
        unlock = self.stick.acquire()
        try:
            if self.stick.debug:
                debug_info = "%s (payload %i/0x%x)" % (pyhsm.defines.cmd2str(self.command), \
                                                        len(self.payload), len(self.payload))
            self.stick.write(cmd_buf, debug_info)
            if not read_response:
                return None
            return self._read_response()
        finally:
            unlock()
1141436
def run(self, oneshot=False):
        
        if not self.xbee:
            raise ValueError("Either a serial port or an XBee must be provided \
                             to __init__ to execute run()")

        while True:
            self.dispatch(self.xbee.wait_read_frame())

            if oneshot:
                break
475858
def addr(self,address):
        ''''''
        if isinstance(address,basestring):
            # If you just gave me a single string, assume its "XXXX XXXX"
            addr = address.split()
        else:
            addr = list(address)
        # Convert to actual hex if you give me strings
        for i in xrange(len(addr)):
            if isinstance(addr[i],basestring):
                addr[i] = int(addr[i],16)
        for frame in self.raw_frames:
            if frame['addr']==address:
                return frame
1315717
def _read_response(self):
        
        # // Up- and downlink packet
        # typedef struct {
        #   uint8_t bcnt;                       // Number of bytes (cmd + payload)
        #   uint8_t cmd;                        // YSM_xxx command
        #   uint8_t payload[YSM_MAX_PKT_SIZE];  // Payload
        # } YSM_PKT;

        # read YSM_PKT.bcnt and YSM_PKT.cmd
        res = self.stick.read(2, 'response length + response status')
        if len(res) != 2:
            self._handle_invalid_read_response(res, 2)
        response_len, response_status = struct.unpack('BB', res)
        response_len -= 1 # the status byte has been read already
        debug_info = None
        if response_status & pyhsm.defines.YSM_RESPONSE:
            debug_info = "%s response (%i/0x%x bytes)" \
                % (pyhsm.defines.cmd2str(response_status - pyhsm.defines.YSM_RESPONSE), \
                       response_len, response_len)
        # read YSM_PKT.payload
        res = self.stick.read(response_len, debug_info)
        if res:
            if response_status == self.command | pyhsm.defines.YSM_RESPONSE:
                self.executed = True
                self.response_status = response_status
                return self.parse_result(res)
            else:
                reset(self.stick)
                raise pyhsm.exception.YHSM_Error('YubiHSM responded to wrong command')
        else:
            raise pyhsm.exception.YHSM_Error('YubiHSM did not respond')
400530
def _aload32(ins):
    ''' 
    '''
    output = _addr(ins.quad[2])

    output.append('call __ILOAD32')
    output.append('push de')
    output.append('push hl')

    REQUIRES.add('iload32.asm')

    return output
1115385
def _pstoref16(ins):
    
    value = ins.quad[2]
    offset = ins.quad[1]
    indirect = offset[0] == '*'
    if indirect:
        offset = offset[1:]

    I = int(offset)
    if I >= 0:
        I += 4  # Return Address + "push IX"

    output = _f16_oper(value)

    if indirect:
        output.append('ld bc, %i' % I)
        output.append('call __PISTORE32')
        REQUIRES.add('pistore32.asm')
        return output

    # direct store
    output.append('ld bc, %i' % I)
    output.append('call __PSTORE32')
    REQUIRES.add('pstore32.asm')

    return output
203102
def segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver):
    
    witprog_bytes = [ord(c) for c in witprog_bin]
    ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8, 5))
    assert segwit_addr_decode(hrp, ret) is not (None, None)
    return ret
222237
def read_byte(self, addr):
        
        if addr < 0 or addr > 127:
            raise ValueError("invalid byte address")
        log.debug("read byte at address {0} ({0:02X}h)".format(addr))
        cmd = "\x01" + chr(addr) + "\x00" + self.uid
        return self.transceive(cmd)[-1]
1085043
def get_address(self):
        
        LOGGER.debug("Reading RPS01A sensor's address.",)
        return self.bus.read_byte_data(self.address, self.address_reg)
226351
def __convertRlocToRouterId(self, xRloc16):
        
        routerList = []
        routerList = self.__sendCommand('router list')[0].split()
        print routerList
        print xRloc16

        for index in routerList:
            router = []
            cmd = 'router %s' % index
            router = self.__sendCommand(cmd)

            for line in router:
                if 'Done' in line:
                    break
                elif 'Router ID' in line:
                    routerid = line.split()[2]
                elif 'Rloc' in line:
                    rloc16 = line.split()[1]
                else:
                    pass

            # process input rloc16
            if isinstance(xRloc16, str):
                rloc16 = '0x' + rloc16
                if rloc16 == xRloc16:
                    return routerid
            elif isinstance(xRloc16, int):
                if int(rloc16, 16) == xRloc16:
                    return routerid
            else:
                pass

        return None
1272375
def x10_unitcode(self):
        """"""
        unitcode = None
        if self.is_x10:
            unitcode = insteonplm.utils.byte_to_unitcode(self.addr[2])
        return unitcode
375581
def __convertRlocToRouterId(self, xRloc16):
        
        routerList = []
        routerList = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:RouterTable')
        print routerList
        print xRloc16

        for line in routerList:
            if re.match('\[|\]', line):
                continue
            if re.match(WPAN_CARRIER_PROMPT, line, re.M|re.I):
                break
            router = []
            router = self.__stripValue(line).split(',')

            for item in router:
                if 'RouterId' in item:
                    routerid = item.split(':')[1]
                elif 'RLOC16' in line:
                    rloc16 = line.split(':')[1]
                else:
                    pass

            # process input rloc16
            if isinstance(xRloc16, str):
                rloc16 = '0x' + rloc16
                if rloc16 == xRloc16:
                    return routerid
            elif isinstance(xRloc16, int):
                if int(rloc16, 16) == xRloc16:
                    return routerid
            else:
                pass

        return None
1289631
def ip_addr():
    
    log = logging.getLogger(mod_logger + '.ip_addr')
    log.debug('Running the ip addr command...')
    ip_addr_output = {}

    command = ['ip', 'addr']
    try:
        ip_addr_result = run_command(command, timeout_sec=20)
    except CommandError:
        _, ex, trace = sys.exc_info()
        msg = 'There was a problem running command: {c}'.format(c=' '.join(command))
        raise CommandError, msg, trace

    ip_addr_lines = ip_addr_result['output'].split('\n')

    for line in ip_addr_lines:
        line = line.strip()
        if line.startswith('inet6'):
            continue
        elif line.startswith('inet'):
            parts = line.split()
            try:
                ip_address = parts[1].strip().split('/')[0]
            except KeyError:
                continue
            else:
                if not validate_ip_address(ip_address):
                    continue
                else:
                    for part in parts:
                        part = part.strip()
                        if part.strip().startswith('eth') or part.strip().startswith('eno') or \
                                part.strip().startswith('ens'):
                            device = part
                            ip_addr_output[device] = ip_address
    return ip_addr_output
1173059
private void getResponse(int function, BytesOutputStream out) throws IOException {
        byte inpBuf[] = new byte[256];
        try {
            if ((function & 0x80) == 0) {
                switch (function) {
                    case Modbus.READ_COILS:
                    case Modbus.READ_INPUT_DISCRETES:
                    case Modbus.READ_MULTIPLE_REGISTERS:
                    case Modbus.READ_INPUT_REGISTERS:
                    case Modbus.READ_COMM_EVENT_LOG:
                    case Modbus.REPORT_SLAVE_ID:
                    case Modbus.READ_FILE_RECORD:
                    case Modbus.WRITE_FILE_RECORD:
                    case Modbus.READ_WRITE_MULTIPLE:
                        // Read the data payload byte count. There will be two
                        // additional CRC bytes afterwards.
                        int cnt = readByte();
                        out.write(cnt);
                        readRequestData(cnt, out);
                        break;

                    case Modbus.WRITE_COIL:
                    case Modbus.WRITE_SINGLE_REGISTER:
                    case Modbus.READ_COMM_EVENT_COUNTER:
                    case Modbus.WRITE_MULTIPLE_COILS:
                    case Modbus.WRITE_MULTIPLE_REGISTERS:
                    case Modbus.READ_SERIAL_DIAGNOSTICS:
                        // read status: only the CRC remains after the two data
                        // words.
                        readRequestData(4, out);
                        break;

                    case Modbus.READ_EXCEPTION_STATUS:
                        // read status: only the CRC remains after exception status
                        // byte.
                        readRequestData(1, out);
                        break;

                    case Modbus.MASK_WRITE_REGISTER:
                        // eight bytes in addition to the address and function codes
                        readRequestData(6, out);
                        break;

                    case Modbus.READ_FIFO_QUEUE:
                        int b1, b2;
                        b1 = (byte) (readByte() & 0xFF);
                        out.write(b1);
                        b2 = (byte) (readByte() & 0xFF);
                        out.write(b2);
                        int byteCount = ModbusUtil.makeWord(b1, b2);
                        readRequestData(byteCount, out);
                        break;

                    case Modbus.READ_MEI:
                        // read the subcode. We only support 0x0e.
                        int sc = readByte();
                        if (sc != 0x0e) {
                            throw new IOException("Invalid subfunction code");
                        }
                        out.write(sc);
                        // next few bytes are just copied.
                        int id, fieldCount;
                        readBytes(inpBuf, 5);
                        out.write(inpBuf, 0, 5);
                        fieldCount = (int) inpBuf[4];
                        for (int i = 0; i < fieldCount; i++) {
                            id = readByte();
                            out.write(id);
                            int len = readByte();
                            out.write(len);
                            readBytes(inpBuf, len);
                            out.write(inpBuf, 0, len);
                        }
                        if (fieldCount == 0) {
                            int err = readByte();
                            out.write(err);
                        }
                        // now get the 2 CRC bytes
                        readRequestData(0, out);
                        break;

                    default:
                        throw new IOException(String.format("getResponse unrecognised function code [%s]", function));

                }
            }
            else {
                // read the exception code, plus two CRC bytes.
                readRequestData(1, out);

            }
        }
        catch (IOException e) {
            throw new IOException(String.format("getResponse serial port exception - %s", e.getMessage()));
        }
    }
598710
def set_address(addr):
    """"""
    # Send DNLOAD with first byte=0x21 and page address
    buf = struct.pack("<BI", 0x21, addr)
    __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)

    # Execute last command
    if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
        raise Exception("DFU: set address failed")

    # Check command state
    if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:
        raise Exception("DFU: set address failed")