Exemple #1
0
    def write_danish_model_patron_card(self, uid, data):
        block_number = 0
        blocks = []

        data_bytes = ['00' for x in range(32)]

        version = '1'
        usage_type = '8'
        data_bytes[0] = version + usage_type
        data_bytes[1] = '01'  # partno
        data_bytes[2] = '01'  # nparts
        userid = ['%02X' % ord(c) for c in data['user_id']]
        print('userid:', userid)
        data_bytes[3:3 + len(userid)] = userid
        data_bytes[21:23] = ['%02X' % ord(c) for c in data['country']]
        libnr = ['%02X' % ord(c) for c in data['library']]
        data_bytes[23:23 + len(libnr)] = libnr

        # CRC calculation:
        p1 = data_bytes[0:19]  # 19 bytes
        p2 = data_bytes[21:32]  # 11 bytes
        p3 = ['00', '00']  # need to add 2 empty bytes to get 19 + 13 bytes
        p = [int(x, 16) for x in p1 + p2 + p3]
        crc = CRC().calculate(p)[::-1]
        data_bytes[19:21] = crc

        print(data_bytes)

        return self.write_blocks_to_card(uid, data_bytes)
Exemple #2
0
 def __init__(self, name):
     """ Initializes the enlace class
     """
     self.fisica = fisica(name)
     self.rx = RX(self.fisica)
     self.tx = TX(self.fisica)
     self.connected = False
     self.crc = CRC()
 def __init__(self, fisica):
     """ Initializes the TX class
     """
     self.fisica = fisica
     self.buffer = bytes(bytearray())
     self.threadStop = False
     self.threadMutex = True
     self.READLEN = 1024
     self.crc = CRC()
Exemple #4
0
 def __init__(self, fisica):
     """ Initializes the TX class
     """
     self.fisica = fisica
     self.buffer = bytes(bytearray())
     self.transLen = 0
     self.empty = True
     self.threadMutex = False
     self.threadStop = False
     self.crc = CRC()
Exemple #5
0
    def __init__(self, crc=None,
                host=socket.gethostname(), port=8000,
                window_size=8, drop_prob=0.1):
        if crc == None:
            crc = CRC()
        self.crc = crc # This will act as a decoder and encoder for the protocol

        self._init_socket(host, port)
        self.host = host
        self.port = port
        self.window_size = window_size
Exemple #6
0
    def __init__(self,
                 user='******',
                 crc=None,
                 host=socket.gethostname(),
                 port=8000):
        if crc == None:
            crc = CRC()
        self.crc = crc  # This will act as a decoder and encoder for the protocol
        self.user = user

        self._init_socket(host, port)
        self.host = host
        self.port = port
Exemple #7
0
    def read_flash(self, start, len):
        crc = CRC()

        print "Reading " + str(len) + " bytes from address " + hex(start)

        data = self.spi_read(start, len)

        crc.process(data)

        local_crc = crc.get_crc()
        dev_crc = self.spi_compute_crc(start, start + len - 1)

        if (local_crc != dev_crc):
            print "CRC validation failed! Expected " + hex(
                local_crc) + ", received " + hex(dev_crc)
            return None

        return data
Exemple #8
0
    def write_segment(self, address, data):
        crc = CRC()
        length = len(data)

        # unprotect the status register
        self.spi_common_command(self.SPI_CMD_WRITE_AFTER_EWSR, 0x01, 0, 1, 0)

        # unprotect the flash
        self.spi_common_command(self.SPI_CMD_WRITE_AFTER_WREN, 0x01, 0, 1, 0)

        if (self._should_program_page(data)):
            # set program size - 1, 255 maximum
            self._i2c_write_reg(0x71, (length - 1) & 0xFF)

            # set the programming address
            self._i2c_write_reg(0x64, (address >> 16) & 0xFF)
            self._i2c_write_reg(0x65, (address >> 8) & 0xFF)
            self._i2c_write_reg(0x66, (address >> 0) & 0xFF)

            # write the content to register 0x70
            # we can only write 16 bytes at a time
            for i in range(0, length, 16):
                if (length - i >= 16):
                    self._i2c_write_bytes(0x70, data[i:i + 16])
                else:
                    self._i2c_write_bytes(0x70, data[i:i + length - i])

            # start programming
            self._i2c_write_reg(0x6F, 0xA0)

        crc.process(data)

        if (not self._wait_write_done()):
            return False

        local_crc = crc.get_crc()
        dev_crc = self.spi_compute_crc(address, address + length - 1)

        if (local_crc != dev_crc):
            print "CRC validation failed! Expected " + hex(
                local_crc) + ", received " + hex(dev_crc)
            return False

        return True
Exemple #9
0
    def write_danish_model_tag(self, uid, data, max_attempts=20):
        block_number = 0
        blocks = []

        data_bytes = ['00' for x in range(32)]
        data_bytes[0] = '11'
        data_bytes[1] = '%02X' % data['partno']
        data_bytes[2] = '%02X' % data['nparts']
        dokid = ['%02X' % ord(c) for c in data['id']]
        data_bytes[3:3 + len(dokid)] = dokid
        data_bytes[21:23] = ['%02X' % ord(c) for c in data['country']]
        libnr = ['%02X' % ord(c) for c in data['library']]
        data_bytes[23:23 + len(libnr)] = libnr

        # CRC calculation:
        p1 = data_bytes[0:19]  # 19 bytes
        p2 = data_bytes[21:32]  # 11 bytes
        p3 = ['00', '00']  # need to add 2 empty bytes to get 19 + 13 bytes
        p = [int(x, 16) for x in p1 + p2 + p3]
        crc = CRC().calculate(p)[::-1]
        data_bytes[19:21] = crc

        print(data_bytes)

        for x in range(8):
            print(data_bytes[x * 4:x * 4 + 4])
            attempt = 1
            while not self.write_block(uid, x, data_bytes[x * 4:x * 4 + 4]):
                logger.warn('Attempt %d of %d: Write failed, retrying...' %
                            (attempt, max_attempts))
                if attempt >= max_attempts:
                    return False
                else:
                    attempt += 1
                    time.sleep(1.0)
        return True
Exemple #10
0
# first of all import the socket library
import socket, sys
from sys import getsizeof
from crc import CRC
from random import randrange
encoder = CRC()
s = socket.socket()
print("Socket successfully created")

if len(sys.argv) >= 2:
    port = int(sys.argv[1])
else:
    port = 8000
host = socket.gethostname()

s.bind((host, port))
print("socket binded to {}".format(port))
# put the socket into listening mode
s.listen(5)
print("socket is listening")

# Read input text
with open('input.txt', 'r') as f:
    text = f.read()
    frames = encoder.encode(text, verbose=True)
    msglen = str(len(frames)).zfill(8)
    print(getsizeof(frames))
c, addr = s.accept()

c.sendall(msglen.encode('utf-8'))
for f in frames:
Exemple #11
0
 def getCrc(self, data):
     from crc import CRC
     crc16 = CRC()
     return crc16.update(data)
Exemple #12
0
def geraQuadro(texto, ipOrigem, ipDestino, bitNumeroSequencia):
    # flag delimitador ("~")
    DELIMITADOR = "0b01111110"

    # tamanho do texto de entrada
    tamanho = bin(len(texto))
    tamanho = tamanho[2:]

    # deixa o tamanho com 8 bits
    while (len(tamanho) < 8):
        tamanho = "0" + tamanho
    tamanho = "0b" + tamanho

    # deixa cada caractere do texto com 8 bits e junta os bits do texto
    bitsTexto = completaASCII(texto)

    # byte da sequencia-ack codificado em binário
    sequenciaACK = "0b" + bitNumeroSequencia + "0000000"

    destino = converteIpParaBinario(ipDestino)
    origem = converteIpParaBinario(ipOrigem)

    # junta os bytes do endereco de origem
    bitsEnderecoOrigem = "0b" + uneBytes(origem)

    # junta os bytes do endereco de destino
    bitsEnderecoDestino = "0b" + uneBytes(destino)

    # junta todos os bits a serem enviados, exceto o delimitador
    mensagem = tamanho + sequenciaACK[2:] + bitsEnderecoDestino[2:]
    mensagem += bitsEnderecoOrigem[2:] + bitsTexto[2:]

    # calcula o crc com a sequencia de bytes ("0's a esquerda sao incluídos")
    crc = CRC()
    mensagem = DELIMITADOR + mensagem[2:] + crc.geraCRC(mensagem)[2:]
    mensagem = mensagem[2:]

    # converte o resultado retornado pelo CRC em bytes (codificados em bits) separados
    mensagemSeparada = []
    i = 0
    while (i < len(mensagem)):
        novaMensagem = "0b"
        novaMensagem += mensagem[i:(i + 8)]
        mensagemSeparada.append(novaMensagem)
        i += 8

    # converte os bytes (codificados em bits), gerados anteriormente, em hexadecimal
    # (se necessario acrescenta 0's para que cada byte tenha dois hexas)
    for i in range(len(mensagemSeparada)):
        mensagemSeparada[i] = str(hex(int(mensagemSeparada[i], 2)))[2:]
        while (len(mensagemSeparada[i]) < 2):
            mensagemSeparada[i] = "0" + mensagemSeparada[i]

    # une todos os hexas (e consegue um Brasil hexa-campeão)
    mensagem = ""
    for item in mensagemSeparada:
        mensagem += item

    # converte os hexadecimais em um conjunto de bytes
    mensagem = bytes.fromhex(mensagem)

    return mensagem
Exemple #13
0
data_pkt = namedtuple('data_pkt', 'seq_num frame')
ack_pkt = namedtuple('ack_pkt', 'seq_num ack')

class GoBackNSender():
    '''
    Paramters
    - crc  : crc scheme. Defaults to default CRC
    - host : host
    - port : port

    '''
    def __init__(self, crc=None,
                host=socket.gethostname(), port=8000
                window_size=8):
        self.crc = crc if crc not None else CRC()
        self._init_socket(host, port)
        self.host = host
        self.port = port

    def _init_socket(self, host, port):
        self.socket = socket.socket()
        self.socket.bind((host, port))
        self.socket.listen(1)

    def _send_one_frame(self, frame, conn, corrupt_simulation=False):
        # Put in corruptions
        if randrange(0,10) <=2 and corrupt_simulation:
            frame = self.crc._corrupt_frame(frame)
        conn.sendall(str(frame).zfill(8).encode('utf-8'))
        # conn.flush()
Exemple #14
0
from crc import CRC

data = input("Enter Binary Data: ")
crc_polynomial = input("Enter CRC Polynomial: ")
crc = CRC(data, crc_polynomial)
print(crc)
Exemple #15
0
        imd = ImageDisk(comment=args.comment)
    else:
        imd = ImageDisk()

if args.bit_rate is None:
    args.bit_rate = args.modulation.default_bit_rate_kbps

crc_param = CRC.CRCParam(name='CRC-16-CCITT',
                         order=16,
                         poly=0x1021,
                         init=args.modulation.crc_init,
                         xorot=0x0000,
                         refin=args.modulation.lsb_first,
                         refot=False)

crc = CRC(crc_param)
crc.make_table(8)

hbr = args.bit_rate * 2000  # half-bit rate in Hz
hbc = 1 / hbr  # half-bit cycle in s

first_sector = args.modulation.default_first_sector
sectors_per_track = args.modulation.default_sectors_per_track

bad_sectors = 0
data_sectors = 0
deleted_sectors = 0
total_sectors = 0

#tracks = { }
for track_num in range(args.tracks):
Exemple #16
0
import socket, sys
from crc import CRC

# Set up params
if len(sys.argv)>=2:
    port = int(sys.argv[1])
else:
    port = 8000
host = socket.gethostname()
frames = []
decoder = CRC()

# Set up socket
s = socket.socket()
s.connect((host, port))


l = int(s.recv(8).decode('utf_8'))
print(l)
print(type(l))
print('Got length {}'.format(l))
text = []
while l:

    received = s.recv(8).decode('utf_8')
    if received == '':
        break
    received = int(received)
    print('Received {}'.format(received))
    decoded_frame = decoder.decode([received], verbose=True)
    if decoded_frame != None:
Exemple #17
0
if __name__ == '__main__':
    # Set the start time
    start_time = time.time()

    # Get command line arguments
    server_host = 'localhost'
    port = int(sys.argv[1])
    send_file = sys.argv[2]
    window_size = 8
    tempfile = 'tempfile.txt'
    # Set the maximum buffer size
    max_buff = 65535

    # Setup CRC
    crc = CRC()
    data_pkt = namedtuple('data_pkt', 'seq_num frame')
    ack_pkt = namedtuple('ack_pkt', 'seq_num ack')

    # Encode the frames
    frames = crc.encode(open(send_file, 'r').read())

    # Setup global vars
    total_frames = len(frames)
    ack_recv_till = 0
    seq_no_to_send = 0
    status = {
        'transfer_complete': False,
        'window_low': 0,
        'window_high': window_size - 1,
    }
Exemple #18
0
import os
import sys
import time
from crc import CRC
r_chan, w_chan = os.pipe()
r_ack, w_ack = os.pipe()
processid = os.fork()
if processid:
    # This is the parent process (receiver)
    decoder = CRC()
    os.close(w_chan)
    os.close(r_ack)
    r_chan = os.fdopen(r_chan, 'r')
    w_ack = os.fdopen(w_ack, 'w')

    print("Parent reading")
    length = r_chan.readline()[:-1]
    length = int(length)

    while length:
        c = r_chan.read()
        print(c)
        w_ack.write('1')
        length -= 1
    sys.exit(0)
else:
    # This is the child process (sender)
    encoder = CRC()
    os.close(r_chan)
    os.close(w_ack)
    w_chan = os.fdopen(w_chan, 'w')
Exemple #19
0
# from crc import CRC, CRC16, CRC32
from crc import CRC

print('Start Crc Test')
# crc16 = CRC(16, 0x8005, 0xffff, 0, False)
# crc16 = CRC(16, 0x8005, 0, 0)
crc16 = CRC()
a = list()
for i in range(0, 128):
    a.append(i)
# print(a)

b = bytearray(a)
# print(b)

result = crc16.update(a)
print(result)
#
if __name__ == '__main__':
    print('End of CRC Test')
Exemple #20
0
    def read_danish_model_tag(self, uid):
        # Command code 0x23: Read multiple blocks
        block_offset = 0
        number_of_blocks = 8
        response = self.issue_iso15693_command(
            cmd='18',
            flags=flagsbyte(address=True),  # 32 (dec) <-> 20 (hex)
            command_code='23',
            data=uid + '%02X%02X' % (block_offset, number_of_blocks))

        response = response[0]
        if response == 'z':
            return {'error': 'tag-conflict'}
        elif response == '':
            return {'error': 'read-failed'}

        response = [response[i:i + 2] for i in range(2, len(response), 2)]

        if response[0] == '00':
            is_blank = True
        else:
            is_blank = False

        # Reference:
        # RFID Data model for libraries : Doc 067 (July 2005), p. 30
        # <http://www.biblev.no/RFID/dansk_rfid_datamodel.pdf>

        # RFID Data model for libraries (February 2009), p. 30
        # http://biblstandard.dk/rfid/dk/RFID_Data_Model_for_Libraries_February_2009.pdf
        version = response[0][0]  # not sure if this is really the way to do it
        if version != '0' and version != '1':
            print(response)
            return {'error': 'unknown-version: %s' % version}

        usage_type = {
            '0': 'acquisition',
            '1': 'for-circulation',
            '2': 'not-for-circulation',
            '7': 'discarded',
            '8': 'patron-card'
        }[response[0][1]]  # not sure if this is really the way to do it

        nparts = int(response[1], 16)
        partno = int(response[2], 16)
        itemid = ''.join([chr(int(x, 16)) for x in response[3:19]])
        crc = response[19:21]
        country = ''.join([chr(int(x, 16)) for x in response[21:23]])
        library = ''.join([chr(int(x, 16)) for x in response[23:32]])

        # CRC calculation:
        p1 = response[0:19]  # 19 bytes
        p2 = response[21:32]  # 11 bytes
        p3 = ['00', '00']  # need to add 2 empty bytes to get 19 + 13 bytes
        p = [int(x, 16) for x in p1 + p2 + p3]
        calc_crc = ''.join(CRC().calculate(p)[::-1])
        crc = ''.join(crc)

        return {
            'error': '',
            'is_blank': is_blank,
            'usage_type': usage_type,
            'uid': uid,
            'id': itemid.strip('\0'),
            'partno': partno,
            'nparts': nparts,
            'country': country,
            'library': library.strip('\0'),
            'crc': crc,
            'crc_ok': calc_crc == crc
        }