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()
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()
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)
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 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
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
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
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
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
# 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:
def getCrc(self, data): from crc import CRC crc16 = CRC() return crc16.update(data)
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
class TX(object): """ This class implements methods to handle the transmission data over the p2p fox protocol """ 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() def thread(self): """ TX thread, to send data in parallel with the code """ while not self.threadStop: if (self.threadMutex): self.transLen = self.fisica.write(self.buffer) #print("O tamanho transmitido. IMpressao dentro do thread {}" .format(self.transLen)) self.threadMutex = False def threadStart(self): """ Starts TX thread (generate and run) """ self.thread = threading.Thread(target=self.thread, args=()) self.thread.start() def threadKill(self): """ Kill TX thread """ self.threadStop = True def threadPause(self): """ Stops the TX thread to run This must be used when manipulating the tx buffer """ self.threadMutex = False def threadResume(self): """ Resume the TX thread (after suspended) """ self.threadMutex = True def sendBuffer(self, data): """ Write a new data to the transmission buffer. This function is non blocked. This function must be called only after the end of transmission, this erase all content of the buffer in order to save the new value. """ self.transLen = 0 self.buffer = data self.threadMutex = True def getBufferLen(self): """ Return the total size of bytes in the TX buffer """ return (len(self.buffer)) def getStatus(self): """ Return the last transmission size """ #print("O tamanho transmitido. Impressao fora do thread {}" .format(self.transLen)) return (self.transLen) def getIsBussy(self): """ Return true if a transmission is ongoing """ return (self.threadMutex) def cria_package(self, payload, tipo, n_pacote, total_pacotes, pacote_esperado): #pega os dados e empacota com HEAD, EOP e byte Stuffing byte_stuff = bytes.fromhex("AA") eop = bytes.fromhex("FF FE FD FC") payload_size = len(payload) crc_payload = self.crc.encodeData(payload) crc_payload = int(crc_payload, 2) for i in range(len(payload)): if payload[i:i + 4] == eop: p1 = payload[0:i] p2 = byte_stuff + payload[i:] payload = p1 + p2 msg_type = (tipo).to_bytes(1, byteorder="big") msg_size = (payload_size).to_bytes(3, byteorder="big") msg_n = (n_pacote).to_bytes(1, byteorder="big") total_n = (total_pacotes).to_bytes(1, byteorder="big") pacote_e = (pacote_esperado).to_bytes(1, byteorder="big") msg_crc = (crc_payload).to_bytes(3, byteorder="big") head = msg_type + msg_size + msg_n + total_n + pacote_e + msg_crc package = head + payload + eop overhead = len(package) / len(payload) print("OverHead:{0}".format(overhead)) print(len(payload)) return package
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
print("index mark option ignored, as HP M2FM doesn't use index marks") args.index = False if args.imagedisk_image is not None: if args.comment is not None: 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
# Write to File def f_write(decoded, f_name): with open(f_name, 'a') as f: f.write(decoded) if __name__ == '__main__': # Collect CLI arguments port = int(sys.argv[1]) output_file = sys.argv[2] probability = float(sys.argv[3]) hostname = "" # Setup CRC crc = CRC() # data_pkt = namedtuple('data_pkt', 'seq_num frame') # ack_pkt = namedtuple('ack_pkt', 'seq_num ack') # Communication s = socket(AF_INET, SOCK_DGRAM) s.bind((hostname, port)) print("Listening for client requests ... ") exp_seq_no = 0 while 1: msg, client_address = s.recvfrom(65535) data = pickle.loads(msg) got_seq_no, frame = data['seq_num'], data['frame'] print('Packet Recv seq_no {} '.format(got_seq_no)) if random() < probability: # Random packet drop simulation decoded = crc.decode([frame], verbose=True)
from crc import CRC data = input("Enter Binary Data: ") crc_polynomial = input("Enter CRC Polynomial: ") crc = CRC(data, crc_polynomial) print(crc)
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, }
class RX(object): """ This class implements methods to handle the reception data over the p2p fox protocol """ 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() def thread(self): """ RX thread, to send data in parallel with the code essa é a funcao executada quando o thread é chamado. """ while not self.threadStop: if (self.threadMutex == True): rxTemp, nRx = self.fisica.read(self.READLEN) if (nRx > 0): self.buffer += rxTemp time.sleep(0.01) def threadStart(self): """ Starts RX thread (generate and run) """ self.thread = threading.Thread(target=self.thread, args=()) self.thread.start() def threadKill(self): """ Kill RX thread """ self.threadStop = True def threadPause(self): """ Stops the RX thread to run This must be used when manipulating the Rx buffer """ self.threadMutex = False def threadResume(self): """ Resume the RX thread (after suspended) """ self.threadMutex = True def getIsEmpty(self): """ Return if the reception buffer is empty """ if (self.getBufferLen() == 0): return (True) else: return (False) def getBufferLen(self): """ Return the total number of bytes in the reception buffer """ return (len(self.buffer)) def getAllBuffer(self, len): """ Read ALL reception buffer and clears it """ self.threadPause() b = self.buffer[:] self.clearBuffer() self.threadResume() return (b) def getBuffer(self, nData): """ Remove n data from buffer """ self.threadPause() b = self.buffer[0:nData] self.buffer = self.buffer[nData:] self.threadResume() return (b) def getNData(self): """ Read N bytes of data from the reception buffer This function blocks until the number of bytes is received """ # temPraLer = self.getBufferLen() # print('leu %s ' + str(temPraLer) ) #if self.getBufferLen() < size: #print("ERROS!!! TERIA DE LER %s E LEU APENAS %s", (size,temPraLer)) size = 0 time_out = time.time() package_arbitrario = bytes.fromhex("F5 A3 AA C3 C3 B5 B4") while (self.getBufferLen() > size or self.getBufferLen() == 0): time.sleep(0.5) size = self.getBufferLen() run_time = time.time() - time_out if run_time > 4: return (package_arbitrario, len(package_arbitrario)) return (self.getBuffer(size), size) def clearBuffer(self): """ Clear the reception buffer """ self.buffer = b"" def desfaz_package(self, package): #Faz o desempacotamento dos dados baseado-se no protocolo GG7. #Separa o payload do restante e verifica se o tamanho do payload esta correto ok = True found_eop = False byte_stuff = bytes.fromhex("AA") eop = bytes.fromhex("FF FE FD FC") head = package[0:10] tipo = int(head[0]) n_pacote = int(head[4]) total_pacotes = int(head[5]) pacote_esperado = int(head[6]) crc_chegou = int.from_bytes(head[7:], byteorder="big") package = package[10:] payload_size = int.from_bytes(head[1:4], byteorder="big") for i in range(len(package)): if package[i:i + 4] == eop: if package[i - 1] == byte_stuff: #retira os bytes stuff p1 = package[0:i - 1] p2 = package[i:] package = p1 + p2 else: found_eop = True print("EOP encontrado na posição:{0}".format(i)) package = package[0:-4] if len(package) != payload_size: ok = False print( "ERRO! Número de Bytes do Payload diferentes do informado no HEAD. Bytes Payload recebido:{0}" .format(len(package))) print("Bytes que foram enviados:{0}".format( payload_size)) break if not found_eop: ok = False print("ERRO! EOP não encontrado") payload = package crc_calculado = self.crc.encodeData(payload) crc_calculado = int(crc_calculado, 2) if crc_calculado == crc_chegou: encoding = True else: encoding = False print(len(payload)) return payload, tipo, ok, n_pacote, total_pacotes, pacote_esperado, encoding
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()
# 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')
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 }
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')
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: