Пример #1
0
    def __unpack_inventory_buffer( self, data ):
        try:
            count, length = struct.unpack( '>HB', data[0:3] )
        except BaseException as err:
            logging.error( err )
            return ''

        if (length + 6) != len( data ):
            return ''

        pc   = struct.unpack( '>H', data[3:5] )[0]
        size = ( ( pc & 0xF800 ) >> 10 ) & 0x003E
        epc  = ''.join( [ '%02X' % x for x in data[5:size+5] ] )

        crc  = struct.unpack( '>H', data[size+5:size+5+2] )[0]
        if crc != ( libscrc.xmodem( data[3:size+5], 0xFFFF ) ^ 0xFFFF ):
            logging.error( 'TAGS CRC16 is ERROR.')
            return ''

        rssi = ( data[-3] - 129  )
        ant  = ( data[-2] & 0x03 ) + 1 # Bugfix:20200303
        invcount = data[-1]

        logging.debug( '*'*50 )
        logging.debug( 'COUNT    : {}'.format( count ) )
        logging.debug( 'EPC      : {}'.format( epc   ) )
        logging.debug( 'CRC      : {:X}'.format( crc ) )
        logging.debug( 'RSSI     : {}'.format( rssi  ) )
        logging.debug( 'ANT      : {}'.format( ant   ) )
        logging.debug( 'INVCOUNT : {}'.format( invcount ) )

        return ( ant, rssi, epc )
Пример #2
0
 def getCk(self,ck,data):
     result = libscrc.xmodem(data)
     print("计算校验值高8位")
     cka = hex(int(bin(result)[2:10], 2))
     print("计算校验值低8位")
     ckb = hex(int(bin(result)[11:18], 2))
     print("校验结果,高8位,低8为分别为:",cka,"",ckb)
Пример #3
0
def createqr_promptpay(account,
                       one_time=True,
                       country="TH",
                       money="",
                       currency="THB"):
    Version = "0002" + "01"  # เวชั่นของ  PromptPay
    if one_time == True:  # one_time คือ ต้องการให้โค้ดนี้ครั้งเดียวหรือไม่
        one_time = "010212"  # 12 ใช้ครั้งเดียว
    else:
        one_time = "010211"  # 11 ใช้ได้้หลายครั้ง

    if len(account) == 10 or len(account) == 13:
        merchant_account_information = "2937"  # ข้อมูลผู้ขาย
    else:
        merchant_account_information = "2939"  # ข้อมูลผู้ขาย

    merchant_account_information += "0016" + "A000000677010111"  # หมายเลขแอปพลิเคชั่น PromptPay
    if len(account) == 10:  #ถ้าบัญชีนี้เป็นเบอร์โทร
        account = list(account)
        merchant_account_information += "011300"  # 01 หมายเลขโทรศัพท์ ความยาว 13 ขึ้นต้น 00
        if country == "TH":
            merchant_account_information += "66"  # รหัสประเทศ 66 คือประเทศไทย
        del account[0]  # ตัดเลข 0 หน้าเบอร์ออก
        merchant_account_information += ''.join(account)

    elif len(account) == 13:  #ถ้าบัญชีนี้เป็นบัตรประชาชน
        merchant_account_information += "0213" + account.replace('-', '')
    else:  #ไม่ใช่เบอร์โทร และ บัตรประชาชน เป็นเลขอ้างอิง
        merchant_account_information += "0315" + account + "5303764"

    country = "5802" + country  # ประเทศ
    if currency == "THB":
        currency = "5303" + "764"  # "764"  คือเงินบาทไทย ตาม https://en.wikipedia.org/wiki/ISO_4217
    if money != "":  # กรณีกำหนดเงิน
        check_money = money.split('.')  # แยกจาก .
        if len(check_money) == 1 or len(
                check_money[1]
        ) == 1:  # กรณีที่ไม่มี . หรือ มีทศนิยมแค่หลักเดียว
            money = "54" + "0" + str(len(str(float(money))) + 1) + str(
                float(money)) + "0"
        else:
            money = "54" + "0" + str(len(str(float(money)))) + str(
                float(money))  # กรณีที่มีทศนิยมครบ

    check_sum = Version + one_time + merchant_account_information + country + currency + money + "6304"  # เช็คค่า check sum

    check_sum1 = hex(libscrc.xmodem(check_sum.encode('ascii'),
                                    0xffff)).replace('0x', '')
    if len(check_sum1) < 4:  # # แก้ไขข้อมูล check_sum ไม่ครบ 4 หลัก
        check_sum1 = ("0" * (4 - len(check_sum1))) + check_sum1
    check_sum += check_sum1

    img = qrcode.make(check_sum.upper())
    buffered = io.BytesIO()
    img.save(buffered, format="PNG")
    buffered.seek(0)
    img_byte = buffered.getvalue()

    return "data:image/png;base64," + base64.b64encode(img_byte).decode()
Пример #4
0
    def program(self, p):
        self.select_aid()
        self.verify_adm_keys()

        # EF.IMSI
        if p.get('imsi'):
            sw = self.update_imsi(p['imsi'])
            if sw != '9000':
                print("Programming IMSI failed with code %s" % sw)

        # EF.HPLMNwACT
        if p.get('mcc') and p.get('mnc'):
            sw = self.update_hplmn_act(p['mcc'], p['mnc'])
            if sw != '9000':
                print("Programming HPLMNwAcT failed with code %s" % sw)

        # EF.AD
        if p.get('mcc') and p.get('mnc'):
            sw = self.update_ad(p['mnc'])
            if sw != '9000':
                print("Programming AD failed with code %s" % sw)

        # Set the Ki using proprietary command
        r = self._scc.select_file(['3f00', '7fff'])
        data, sw = self._scc._tp.send_apdu(self._scc.cla_byte + "a4" + "090c" +
                                           "02" + self._EF_num['Ki'])
        data, sw = self._scc._tp.send_apdu(
            self.APDU_UPDATE_KI_OPC_PREFIX + p['ki'] +
            self.pad_crc(format(libscrc.xmodem(p['ki'].decode("hex")), 'x')))

        # Set the OPc using proprietary command
        data, sw = self._scc._tp.send_apdu(self._scc.cla_byte + "a4" + "090c" +
                                           "02" + self._EF_num['OPc'])
        data, sw = self._scc._tp.send_apdu(
            self.APDU_UPDATE_KI_OPC_INFIX + p['opc'] +
            self.pad_crc(format(libscrc.xmodem(p['opc'].decode("hex")), 'x')) +
            self.APDU_UPDATE_KI_OPC_SUFFIX)

        # EF.SPN
        if p.get('name'):
            sw = self.update_spn(p['name'])
            if sw != '9000':
                print("Programming SPN failed with code %s" % sw)
Пример #5
0
    def write( self, epc:str, data:str, bank='EPC', address=0, password=[ 0 ]*4 ):
        """ Write Tag to ( EPC, TID, USER )
            EPC  -> address=2, size=8
            TID  -> address=0, size=3
            USER -> address=0, size=2
        """
        assert( type( epc ) is str ) and ( type( data ) is str )

        result = self.set_access_epc_match( mode=0, epc=epc )
        if ( len(result) == 0) or (not result[0] ):
            return ''

        try:
            self.protocol.write_block( list( bytearray.fromhex( data ) ),
                                       bank=bank,
                                       addr=address,
                                       password=password )
        except BaseException:
            logging.error( 'Data must be hex string.' )
            return ''

        value = ImpinjR2KReader.analyze_data( 'DATA' )( lambda x, y : y )( self, None )

        try:
            count, length = struct.unpack( '>HB', value[0:3] )
        except BaseException:
            logging.error( ImpinjR2KGlobalErrors.to_string( value[0] ) )
            return ''

        if (length + 6) != len( value ):
            return ''

        pc   = struct.unpack( '>H', value[3:5] )[0]
        size = ( ( pc & 0xF800 ) >> 10 ) & 0x003E
        epc  = ''.join( [ '%02X' % x for x in value[5:size+5] ] )

        crc  = struct.unpack( '>H', value[size+5:size+5+2] )[0]
        if crc != ( libscrc.xmodem( value[3:size+5], 0xFFFF ) ^ 0xFFFF ):
            logging.error( 'TAGS CRC16 is ERROR.')
            return ''
        
        error  = ( True if value[-3] == ImpinjR2KGlobalErrors.SUCCESS else False, ImpinjR2KGlobalErrors.to_string( value[-3] ) )
        ant    = ( value[-2] & 0x03 ) + 1
        wcount = value[-1]

        logging.debug( '*'*50 )
        logging.debug( 'COUNT      : {}'.format( count ) )
        logging.debug( 'EPC        : {}'.format( epc   ) )
        logging.debug( 'CRC        : {:X}'.format( crc ) )
        logging.debug( 'ERROR      : {}'.format( error ) )
        logging.debug( 'ANT        : {}'.format( ant   ) )
        logging.debug( 'WriteCount : {}'.format( wcount) )

        return epc
Пример #6
0
 def getCk(self, ck, data):
     data1 = str(data).encode()
     result = libscrc.xmodem(data1)
     print("计算校验值高8位")
     cka = str(hex(int(bin(result)[2:10], 2)))
     print("计算校验值低8位")
     ckb = str(hex(int(bin(result)[11:18], 2)))
     print("校验结果,高8位,低8为分别为:", cka, "", ckb)
     if (cka[2:] == ck[0] and ckb[2:] == ck[1]):
         print("校验合格")
     else:
         print("数据包出错")
Пример #7
0
 def computeCk(self, data):
     print("计算校验值,使用有效负载,以及心跳包的额外值进行计算")
     data1 = ''
     for i in data:
         data1 = data1 + i
     data1 = data1.encode()
     print(data1)
     result = libscrc.xmodem(data1)
     print("计算校验值高8位")
     cka = int(bin(result)[2:10], 2)
     print("计算校验值低8位")
     ckb = int(bin(result)[11:18], 2)
     return [cka, ckb]
Пример #8
0
    def read( self, epc:str, bank='EPC', address=0, size=2, password=[ 0 ]*4 ):
        """
            EPC  -> address=0, size=8
            TID  -> address=0, size=3
            USER -> address=0, size=2
        """
        result = self.set_access_epc_match( mode=0, epc=epc )
        if ( len(result) == 0) or (not result[0] ):
            return ''

        self.protocol.read( bank=bank, addr=address, size=size, password=password )
        value = ImpinjR2KReader.analyze_data( 'DATA', timeout=5 )( lambda x, y : y )( self, None )

        try:
            count, length = struct.unpack( '>HB', value[0:3] )
        except BaseException:
            logging.error( ImpinjR2KGlobalErrors.to_string( value[0] ) )
            return ''

        pc   = struct.unpack( '>H', value[3:5] )[0]
        size = ( ( pc & 0xF800 ) >> 10 ) & 0x003E
        epc  = ''.join( [ '%02X' % x for x in value[5:size+5] ] )

        crc  = struct.unpack( '>H', value[size+5:size+5+2] )[0]
        if crc != ( libscrc.xmodem( value[3:size+5], 0xFFFF ) ^ 0xFFFF ):
            logging.error( 'TAGS CRC16 IS ERROR.')
            return ''

        datasize = value[-3]
        antenna  = ( value[-2] & 0x03 ) + 1
        invcount = value[-1]

        data_offset_head = size + 5 + 2
        data_offset_tail = ( data_offset_head + datasize )

        data = ''.join( [ '%02X' % x for x in value[ data_offset_head:data_offset_tail ] ] )

        logging.debug( '*'*50 )
        logging.debug( 'COUNT    : {}'.format( count  ) )
        logging.debug( 'LENGTH   : {}'.format( length ) )
        logging.debug( 'SIZE     : {}'.format( size   ) )
        logging.debug( 'EPC      : {}'.format( epc    ) )
        logging.debug( 'CRC      : {:X}'.format( crc  ) )
        logging.debug( 'DATA     : {}'.format( data   ) )
        logging.debug( 'DATASIZE : {}'.format( datasize  ) )
        logging.debug( 'ANT      : {}'.format( antenna   ) )
        logging.debug( 'INVCOUNT : {}'.format( invcount  ) )

        return data
def build_packet(command, randomByte):
    header = bytearray([0x1B])

    data = bytearray([
        0x00,
        0x02,  # byteArrayLenPlusOne # shit, had 1 here for a long time, should be 2 (command + randomByte) # should actually be len(cmd+random+data) but we dont support data :)
        command,  # command (who are you)
        randomByte,  # randombyte
    ])

    # bluelab uses xmodem-style crc16 (0x1021 poly)
    # header doesn't get crc'd
    crc = libscrc.xmodem(bytes(data))
    crcBytes = crc.to_bytes(2, byteorder='big')

    # build packet
    return header + data + crcBytes