コード例 #1
0
ファイル: window.py プロジェクト: JassonRM/Hamming
    def convert(self):
        regex = r'[0+1]{12}'
        input = self.input.text()
        if (re.fullmatch(regex, input)):
            self.hexaLabel.setText(conversion.binahexa(input))
            decimal = conversion.binarioDeci(input)
            self.decimalLabel.setText(str(decimal))
            self.bcdLabel.setText(conversion.deciBCD(decimal))

            result = Hamming.calcular_hamming(input, self.radioPar.isChecked())
            self.fillHammingTable(result)
            strResult = ""
            for char in result:
                strResult += char
            self.hammingResult.setText(strResult)
            self.hammingResult.repaint()

        else:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Entrada inválida")
            msg.setInformativeText(
                "La entrada debe ser un número binario de 12 bits")
            msg.setWindowTitle("Error")
            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
            msg.exec_()
コード例 #2
0
    def shouldStop(self, partialResult, iterationCount):
        partialResult = partialResult.flatten()
        if iterationCount > 250:
            return True
        if self.timeCount < 8:
            self.timeCount += 1
            return False

        self.partialResults.append(partialResult)
        self.timeCount = 0
        self.timeCountLoops += 1

        if self.timeCountLoops > 10:
            hitPercentage = sum([1
                                 for vector
                                 in self.partialResults
                                 if Hamming.distance(vector, partialResult)/100.0 < self.hammingPercentage
                                ]) \
                            / float(len(self.partialResults))
            #print 'hit percentage: ' + str(hitPercentage)
            itsAMatch = hitPercentage > 0.7
            if itsAMatch:
                self.partialResults = []
            return itsAMatch
        return False
コード例 #3
0
 def _convert(self):
     #BLOCKING BLOCKING BLOCKING
     string = self.input_text.get()
     if string == '':
         messagebox.showerror("Lỗi", "Bạn chưa nhập đủ các trường!")
         return
     result = ''.join([str(c) for c in Hamming.hammingCodes(string)])
     self.result['text'] = "Kết quả"
     self.result_text.delete('0', tk.END)
     self.result_text.insert(tk.END, result)
コード例 #4
0
 def __init__(self,frame = None):
     self.bitStuffing = bit_stuffing()
     self.hamming = Hamming()
     self.frame = frame
     if not frame:
         self.FI = bitarray(8)
         self.FI.setall(False)
         self.DA = None
         self.SA= None
     else:
         self.extractFrameInfo()
コード例 #5
0
    def __init__(self, frame=None):
        self.bitStuffing = bit_stuffing()
        self.hamming = Hamming()
        self.frame = frame
        self.fi_size = 8  #bit
        self.addr_size = 6  #byte
        self.fi_pos = 1
        self.da_pos = 2
        self.sa_pos = 8
        self.payload_pos = 14
        self.da_addr = None
        self.sa_addr = None

        if not frame:
            self.FI = bitarray(self.fi_size)
            self.FI.setall(False)
            self.b_DA = None
            self.b_SA = None
        else:
            self.extractFrameInfo()
コード例 #6
0
def memoryCheck(hopfieldStochastic, trainingSet, checkingSet, dim, temperature, noiseFactor):
    check = MemoryCheck(temperature, noiseFactor, trainingSet, checkingSet)

    #Activation
    for i in range(0, len(trainingSet)):
        trainingVector = trainingSet[i]
        checkingVector = checkingSet[i].flatten()
        hopfieldStochastic.temperature = temperature
        hopfieldActivation = hopfieldStochastic.activate(trainingVector)
        equalityReached = (checkingVector == hopfieldActivation).all()
        hammingDist = Hamming.distance(hopfieldActivation.flatten(), checkingVector)
        check.addActivationResult(i, equalityReached, hammingDist)

    return check
コード例 #7
0
ファイル: repeatingKey.py プロジェクト: WalrusCow/cryptopals
def _getKeysizeDistances(byteArray, *, keyMin=2, keyMax=50, samples=2):
    ''' Get normalized Hamming distances between first and second byte groups.
    of likely key lengths. '''

    distances = dict()
    for size in range(keyMin, keyMax):
        d = 0
        # Avoid over sampling
        for i in range(min(samples, size // 2)):
            b1 = byteArray[size*i*2:size*(i*2 + 1)]
            b2 = byteArray[size*(i*2 + 1):size*2*(i + 1)]
            d += Hamming.distance(b1, b2) / size
        distances[size] = d / samples

    return distances
コード例 #8
0
def _getKeysizeDistances(byteArray, *, keyMin=2, keyMax=50, samples=2):
    ''' Get normalized Hamming distances between first and second byte groups.
    of likely key lengths. '''

    distances = dict()
    for size in range(keyMin, keyMax):
        d = 0
        # Avoid over sampling
        for i in range(min(samples, size // 2)):
            b1 = byteArray[size * i * 2:size * (i * 2 + 1)]
            b2 = byteArray[size * (i * 2 + 1):size * 2 * (i + 1)]
            d += Hamming.distance(b1, b2) / size
        distances[size] = d / samples

    return distances
コード例 #9
0
 def _convert(self):
     #BLOCKING BLOCKING BLOCKING
     string = self.input_text.get()
     if string == '':
         messagebox.showerror("Lỗi", "Bạn chưa nhập đủ các trường!")
         return
     er_bit, orginal_bits = Hamming.hammingCorrection(string)
     result = ''.join([str(c) for c in orginal_bits])
     if er_bit > 0:
         result_text = "Bit lỗi là bit thứ " + str(int(er_bit))
     else:
         result_text = "Không có bit nào bị lỗi"
     
     self.result['text'] = "Kết quả"
     self.result_text1['text'] = result_text
     
     self.result_text2.delete('0', tk.END)
     self.result_text2.insert(tk.END, result)
コード例 #10
0
    def __init__(self,frame = None):
        self.bitStuffing = bit_stuffing()
        self.hamming = Hamming()
        self.frame = frame
        self.fi_size = 8 #bit
        self.addr_size = 6 #byte
        self.fi_pos =  1
        self.da_pos = 2
        self.sa_pos = 8
        self.payload_pos = 14
        self.da_addr = None
        self.sa_addr = None

        if not frame:
            self.FI = bitarray(self.fi_size)
            self.FI.setall(False)
            self.b_DA = None
            self.b_SA= None
        else:
            self.extractFrameInfo()
コード例 #11
0
ファイル: window.py プロジェクト: JassonRM/Hamming
    def check(self):

        regex = r'[0+1]{17}'
        input = self.input.text()
        inputList = list(input)
        if (re.fullmatch(regex, input)):
            try:
                result = Hamming.arreglar_hamming(inputList,
                                                  self.radioPar.isChecked())
                self.fillRepairTable(result)
            except:
                self.errorLabel.setText("Existen 2 o mas errores")
                self.fillReceiveData(inputList)
                self.repairTable.repaint()

        else:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Entrada inválida")
            msg.setInformativeText(
                "La entrada debe ser un número binario de 17 bits")
            msg.setWindowTitle("Error")
            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
            msg.exec_()
コード例 #12
0
class Packet:
    '''
    FI - frame info             - 8 bit                              
    DA - destination Address    - 6 byte
    SA - source address         - 6 byte
    M - monitor bit
    A - address recognized bit    
    C - frame-copied bit
    '''

    # packet = FD + FI + DA + SA + payload + FD

    def __init__(self, frame=None):
        self.bitStuffing = bit_stuffing()
        self.hamming = Hamming()
        self.frame = frame
        self.fi_size = 8  #bit
        self.addr_size = 6  #byte
        self.fi_pos = 1
        self.da_pos = 2
        self.sa_pos = 8
        self.payload_pos = 14
        self.da_addr = None
        self.sa_addr = None

        if not frame:
            self.FI = bitarray(self.fi_size)
            self.FI.setall(False)
            self.b_DA = None
            self.b_SA = None
        else:
            self.extractFrameInfo()

    @property
    def Frame(self):
        return self.frame

    @Frame.setter
    def Frame(self, frame):
        self.frame = frame
        self.extractFrameInfo()

    @property
    def monitor(self):
        return self.FI[2]

    @monitor.setter
    def monitor(self, value):
        self.FI[2] = value

    @property
    def addrRecognized(self):
        return self.FI[1]

    @addrRecognized.setter
    def addrRecognized(self, value):
        self.FI[1] = value

    @property
    def frameCopied(self):
        return self.FI[0]

    @frameCopied.setter
    def frameCopied(self, value):
        self.FI[0] = value

    @property
    def da(self):
        return self.da_addr

    @da.setter
    def da(self, addr):
        self.da_addr = addr
        self.b_DA = self.addrToBytes(addr)

    @property
    def sa(self):
        return self.sa_addr

    @sa.setter
    def sa(self, addr):
        self.sa_addr = addr
        self.b_SA = self.addrToBytes(addr)

    def pack(self, payload):
        #bit stuffing
        payload, pBitStuffed = self.bitStuffing.encode(payload)
        #hamming encode
        payload = self.hamming.encode(payload)
        # packet = FD + FI + DA + SA + payload + FD
        b_FD = self.bitStuffing.byteFD
        packet = b_FD + self.FI.tobytes(
        ) + self.b_DA + self.b_SA + payload + b_FD
        self.frame = packet
        return self.frame

    def repack(self):
        b_FD = self.bitStuffing.byteFD
        self.frame = b_FD + self.FI.tobytes(
        ) + self.b_DA + self.b_SA + self.frame[self.
                                               payload_pos:len(self.frame) -
                                               1] + b_FD

    def extractFrameInfo(self):
        self.FI = bitarray()
        self.FI.frombytes(self.frame[self.fi_pos:self.fi_pos + 1])
        self.b_DA = self.frame[self.da_pos:self.da_pos + self.addr_size]
        self.b_SA = self.frame[self.sa_pos:self.sa_pos + self.addr_size]
        self.da_addr = self.addrFromBytes(self.b_DA)
        self.sa_addr = self.addrFromBytes(self.b_SA)

    def unpack(self):
        payload = self.frame[self.payload_pos:len(self.frame) - 1]
        #hemming decode
        payload = self.hamming.decode(bytes(payload))
        #bit stuffing decode
        payload, pBitStuffed = self.bitStuffing.decode(payload)
        return payload

    def addrToBytes(self, addr):
        #4 + 2 bytes ASCII
        ip, port = addr
        str_quartet = ip.split('.')
        num_quartet = [int(byte) for byte in str_quartet]
        byte_quartet = [el.to_bytes(1, byteorder='big') for el in num_quartet]
        num_port = int(port)
        return b''.join(byte_quartet) + num_port.to_bytes(2, byteorder='big')

    def addrFromBytes(self, bAddr):
        int_quartet = list(bAddr[:4])
        port = int.from_bytes(bAddr[4:], byteorder='big')
        IP = '.'.join([str(el) for el in int_quartet])
        return (IP, str(port))
コード例 #13
0
    packet.append(bit)  # generuje pakiet

    counter += 1
    if (counter == wielkoscPakietu):  # pakiet po 8 bitow
        packets.append(packet)  # tworzy liste pakietow
        packet = []
        counter = 0

if (
        len(packet) > 0
):  # mozliwe tworzenie pakietow wiekszych niz 8 bitow. po prostu ostatni pakiet, bedzie malutki
    packets.append(packet)

# DODANIE BITU PARZYSTOSCI DO KAZDEGO Z PAKIETOW
tmr = TMR()
hamming = Hamming()
parity = ParityBit()
crc = ParityBit()
channel = Channel(float(str(EBSC.get())), float(str(EG1.get())),
                  float(str(EG2.get())), float(str(EG3.get())),
                  float(str(EG4.get())))

packetsWithParityBit = []
for pack in packets:
    if varPACK.get() == 1:
        pack = tmr.codeTMR(pack)  # DODANIE TMR
        pack = parity.addParityBit(pack)
    if varPACK.get() == 2:
        pack = hamming.codeHamming(pack)  # DODANIE Hamming
        pack = crc.addParityBit(pack)
コード例 #14
0
 def matchesInHammingPercentage(self, vector):
     return sum([1 for trainingVector
                 in self.trainingSet
                 if (Hamming.distance(trainingVector, vector) /100.0) < self.hammingPercentage ]) \
            > 0
コード例 #15
0
    def listenpackage(self):
        x = True
        quadro = []
        while x:
            x = False
            recebido = 0
            quadro = []
            # self.executor = thrd.thread(target=self._writing, args=[data])

            while not self.transmiting:
                self.camadafisica.sincronizacao()
                recebido = self.camadafisica.read()
                if recebido == 2:
                    self.receiving = True
                    print("Recebido {}".format(recebido))
                    break
            if self.transmiting:
                return None
            while not self.transmiting and self.receiving:
                inicio = time()
                recebido = self.camadafisica.read()
                print("Tempo pacote:{} ".format(time() - inicio))
                print("Recebido {}".format(recebido))
                if recebido != 2:
                    quadro.insert(0, recebido)
                elif recebido == None:
                    return None
                else:
                    recebido = self.camadafisica.read()
                    if recebido == 2:
                        x = True
                        self.receiving = False
                    else:
                        self.receiving = False
        if len(quadro) > 11:
            quadro = quadro[::-1]
            partes = [quadro[x:x + 11] for x in range(0, len(quadro), 8)]
            for p in partes:
                print(p)
            destino = self.listToString(hamm.hammingCodes(partes[0]))
            origem = self.listToString(hamm.hammingCodes(partes[1]))

            pacoteretorno = pacote()
            pacoteretorno.setDestino(self.decodeInt(destino[:3]),
                                     self.decodeInt(destino[4:]))
            pacoteretorno.setOrigem(self.decodeInt(origem[:3]),
                                    self.decodeInt(origem[4:]))
            pacoteretorno.tamanhodados = self.decodeInt(
                self.listToString(hamm.hammingCodes(partes[2])))
            final = []
            for a in partes[3:]:
                final += self.decodeChar(
                    self.listToString(hamm.hammingCodes(a)))
            pacoteretorno.dados = final
            # processar o quadro para retornar o pacote
            print("Detino: {}, Origem: {}, Dados: {}".format(
                pacoteretorno.destino, pacoteretorno.origem,
                pacoteretorno.dados))
            return pacoteretorno
        else:
            return None
コード例 #16
0
    def send(self, pacote):
        """
        quando receber um dado tenta transmistir os dados pela camada física
        quando consegiur, retorna verdadeiro, caso não consiga, retorna falso
        esta classe considera uma quantidade de tentativas como limite, e após essa quantidade, é dado como timeout
        :param data:
        :return:
        """
        destino = list(self.encodeEndereco(pacote.destino))
        destino = list(map(int, destino))

        origem = list(self.encodeEndereco(pacote.origem))
        origem = list(map(int, origem))

        tamanhodados = list(self.encode(pacote.tamanhodados))
        tamanhodados = list(map(int, tamanhodados))

        dadospacote = list(self.encode(pacote.dados))
        dadospacote = list(map(int, dadospacote))

        bytes = hamm.hammingCodes(destino)
        bytes += hamm.hammingCodes(origem)
        bytes += hamm.hammingCodes(tamanhodados)
        bytes += self.hammingDados(dadospacote)
        bytes.append(2)
        bytes.insert(0, 2)
        print("A ser impresso: {}".format(bytes))
        t = 0
        while t < self.tries:  # verifica a disponibilidade da rede uma certa quantidade de vezes antes de expirar
            lido = self.camadafisica.read()
            print("Meio verificado: {}".format(lido))
            if lido is None:
                self.transmiting = True
                #self.camadafisica.debug = True
                inicio = 0
                sleep(1)
                for bit in bytes:
                    inicio = time()
                    self.camadafisica.write(bit)
                    lido = self.camadafisica.read()
                    print("Tempo W&R: {} ".format(time() - inicio))
                    #print("Lido {} : Esperado {}".format(b, bit))
                    if lido != bit:  # se foi lido algo diferente do que foi escrito, então houve colisão
                        print("colisão! emitindo jam")
                        self.camadafisica.write(2)
                        sleep(self.camadafisica.intervalo)
                        self.camadafisica.write(2)
                        self.transmiting = False
                        t = 0
                        sleep(random.randint(1, 5))
                        break
                if self.transmiting:
                    break
            else:
                print("Meio em uso! espera aleatória")
                t += 1
                sleep(
                    random.randint(1, 5)
                )  #espera aleatória para verificar novamente se o meio está livre

        if self.transmiting:
            self.transmiting = False
            return True
        else:
            print("excedeu as tentativas - camada de enlace")
            return False
コード例 #17
0
class Packet:
    '''
    FI - frame info
    DA - destination Address
    SA - source address
    M - monitor bit
    A - address recognized bit    
    C - frame-copied bit
    '''
    def __init__(self,frame = None):
        self.bitStuffing = bit_stuffing()
        self.hamming = Hamming()
        self.frame = frame
        if not frame:
            self.FI = bitarray(8)
            self.FI.setall(False)
            self.DA = None
            self.SA= None
        else:
            self.extractFrameInfo()

    @property
    def Frame(self):
        return self.frame
    @Frame.setter
    def Frame(self,frame):
        self.frame = frame
        self.extractFrameInfo()

    @property
    def monitor(self):
        return self.FI[2]

    @monitor.setter
    def monitor(self,value):
        self.FI[2] = value       

    @property
    def addrRecognized(self):
        return self.FI[1]

    @addrRecognized.setter
    def addrRecognized(self,value):
        self.FI[1] = value
    
    @property
    def frameCopied(self):
        return self.FI[0]

    @frameCopied.setter
    def frameCopied(self,value):
        self.FI[0] = value

    def pack(self,payload):
        #bit stuffing
        payload,pBitStuffed = self.bitStuffing.encode(payload) 
        #hamming encode
        payload  = self.hamming.encode(payload)
        # packet = FD + FI + DA + SA + payload + FD
        FD = self.bitStuffing.byteFD
        packet = FD + self.FI.tobytes() + self.DA.to_bytes(1,byteorder = 'big') + self.SA.to_bytes(1,byteorder = 'big') + payload + FD
        self.frame =  packet
        return self.frame

    def repack(self):
        FD = self.bitStuffing.byteFD
        self.frame = FD + self.FI.tobytes() + self.DA.to_bytes(1,byteorder = 'big') + self.SA.to_bytes(1,byteorder = 'big') + self.frame[4:len(self.frame)-1] + FD

    def extractFrameInfo(self):
        self.FI = bitarray()
        self.FI.frombytes(self.frame[1:2])
        self.DA = int.from_bytes(self.frame[2:3],byteorder='big')
        self.SA = int.from_bytes(self.frame[3:4],byteorder='big')


    def unpack(self):
        payload = self.frame[4 : len(self.frame)-1]
        #hemming decode
        payload = self.hamming.decode(bytes(payload))
        #bit stuffing decode
        payload,pBitStuffed = self.bitStuffing.decode(payload)
        return payload
コード例 #18
0
ファイル: Channel.py プロジェクト: CheshireTsui/Encode-Decode
        # input file which needs transmission
        fin = open(input_file_name, "r")
        raw_file = fin.read()
        fin.close()
        # fake transmission
        message_out = str()
        for i in raw_file:
            if random() > Z[int(i)][0]:
                message_out = message_out + "1"
            else:
                message_out = message_out + "0"
        # check, not necessary
        # print message_out
        print "[*]Length after transport:", len(message_out)
        # write output-file
        f = open(output_file_name, "w+")
        f.write(message_out)
        f.close()

    except Exception, e:
        raise e


#test if function is correct
if __name__ == "__main__":
    transmission("hamming_out.txt", "channel_out.txt")
    import Hamming, Huffman
    # Hamming is decoding ;D
    Hamming.decode("hamming_table_out.txt", "channel_out.txt", "hamming_decode_out_from_channel.txt")
    # Huffman is decoding XD
    Huffman.decode("huffman_table_out.txt", "hamming_decode_out_from_channel.txt", "huffman_decode_out_from_channel.txt")
コード例 #19
0
        packet.append(bit)  # generuje pakiet

        counter += 1
        if (counter == wielkoscPakietu):  # pakiet po 8 bitow
            packets.append(packet)  # tworzy liste pakietow
            packet = []
            counter = 0

    if (
            len(packet) > 0
    ):  # mozliwe tworzenie pakietow wiekszych niz 8 bitow. po prostu ostatni pakiet, bedzie malutki
        packets.append(packet)

    # DODANIE BITU PARZYSTOSCI DO KAZDEGO Z PAKIETOW
    tmr = TMR()
    hamming = Hamming()
    crc = CRC()
    parity = ParityBit()
    channel = Channel(prawdopodobienstwoBSC, channelS0, channelS1, channelP01,
                      channelP10)

    # print(packets)
    packetsWithParityBit = []
    for pack in packets:
        pack = tmr.codeTMR(pack)  # DODANIE TMR
        pack = parity.addParityBit(pack)  # DODANIE PARITY BIT
        # pack = hamming.codeHamming(pack)   # DODANIE Hamminga
        # pack = crc.addCRC(pack)            # DODANIE CRC

        packetsWithParityBit.append(pack)
コード例 #20
0
ファイル: test.py プロジェクト: CheshireTsui/Encode-Decode
# -*- coding:utf-8 -*-

import Huffman, Hamming, Channel

#test if function is correct
if __name__ == "__main__":
    # Huffman is encoding XD
    Huffman.make_code_table("frequency.txt", "huffman_table.out")
    Huffman.encode("huffman_table.out", "raw_file.txt", "huffman.out", 4)
    # Hamming is encoding ;D
    print "=====message with Hamming-coding====="
    Hamming.error_flag("error_flag.out")
    Hamming.make_code_table("hamming_table.out")
    Hamming.encode("hamming_table.out", "huffman.out", "hamming.out")
    # message is in the channel
    Channel.transmission("hamming.out", "channel.out")
    # Hamming is decoding ;D
    Hamming.decode("hamming_table.out", "channel.out", "hamming_decode_out_from_channel.out", "error_flag.out")
    # Huffman is decoding XD
    Huffman.decode("huffman_table.out", "hamming_decode_out_from_channel.out", "huffman_decode_out_from_channel.out")
    print "=====message *without* Hamming-coding====="
    # message is in the channel
    Channel.transmission("hamming.out", "channel.out")
    # Huffman is decoding XD
    Huffman.decode("huffman_table.out", "channel.out", "huffman_decode_out_from_channel2.out")
    print "=====Huffman====="
    Huffman.efficiency("huffman_table.out", "frequency.txt")
コード例 #21
0
class Packet:
    '''
    FI - frame info             - 8 bit                              
    DA - destination Address    - 6 byte
    SA - source address         - 6 byte
    M - monitor bit
    A - address recognized bit    
    C - frame-copied bit
    '''
    # packet = FD + FI + DA + SA + payload + FD

    def __init__(self,frame = None):
        self.bitStuffing = bit_stuffing()
        self.hamming = Hamming()
        self.frame = frame
        self.fi_size = 8 #bit
        self.addr_size = 6 #byte
        self.fi_pos =  1
        self.da_pos = 2
        self.sa_pos = 8
        self.payload_pos = 14
        self.da_addr = None
        self.sa_addr = None

        if not frame:
            self.FI = bitarray(self.fi_size)
            self.FI.setall(False)
            self.b_DA = None
            self.b_SA= None
        else:
            self.extractFrameInfo()

    @property
    def Frame(self):
        return self.frame
    @Frame.setter
    def Frame(self,frame):
        self.frame = frame
        self.extractFrameInfo()

    @property
    def monitor(self):
        return self.FI[2]

    @monitor.setter
    def monitor(self,value):
        self.FI[2] = value       

    @property
    def addrRecognized(self):
        return self.FI[1]

    @addrRecognized.setter
    def addrRecognized(self,value):
        self.FI[1] = value
    
    @property
    def frameCopied(self):
        return self.FI[0]

    @frameCopied.setter
    def frameCopied(self,value):
        self.FI[0] = value

    @property
    def da(self):
        return self.da_addr
    @da.setter
    def da(self,addr):
        self.da_addr = addr
        self.b_DA = self.addrToBytes(addr)

    @property
    def sa(self):
        return self.sa_addr

    @sa.setter
    def sa(self,addr):
        self.sa_addr = addr
        self.b_SA = self.addrToBytes(addr)

    def pack(self,payload):
        #bit stuffing
        payload,pBitStuffed = self.bitStuffing.encode(payload) 
        #hamming encode
        payload  = self.hamming.encode(payload)
        # packet = FD + FI + DA + SA + payload + FD
        b_FD = self.bitStuffing.byteFD
        packet = b_FD + self.FI.tobytes() + self.b_DA + self.b_SA + payload + b_FD 
        self.frame =  packet
        return self.frame

    def repack(self):
        b_FD = self.bitStuffing.byteFD
        self.frame = b_FD + self.FI.tobytes() + self.b_DA + self.b_SA + self.frame[self.payload_pos : len(self.frame)-1] + b_FD

    def extractFrameInfo(self):
        self.FI = bitarray()
        self.FI.frombytes(self.frame[ self.fi_pos : self.fi_pos + 1 ])
        self.b_DA = self.frame[self.da_pos : self.da_pos + self.addr_size]
        self.b_SA = self.frame[self.sa_pos : self.sa_pos + self.addr_size]
        self.da_addr = self.addrFromBytes(self.b_DA)
        self.sa_addr = self.addrFromBytes(self.b_SA)

    def unpack(self):
        payload = self.frame[self.payload_pos : len(self.frame)-1]
        #hemming decode
        payload = self.hamming.decode(bytes(payload))
        #bit stuffing decode
        payload,pBitStuffed = self.bitStuffing.decode(payload)
        return payload

    def addrToBytes(self,addr):
        #4 + 2 bytes ASCII
        ip,port = addr
        str_quartet = ip.split('.')
        num_quartet = [int(byte) for byte in str_quartet]
        byte_quartet = [el.to_bytes(1,byteorder='big') for el in num_quartet]
        num_port = int(port)
        return b''.join(byte_quartet) + num_port.to_bytes(2,byteorder='big')
   
    def addrFromBytes(self,bAddr):
        int_quartet = list(bAddr[:4])
        port = int.from_bytes(bAddr[4:],byteorder='big')
        IP = '.'.join([str(el) for el in int_quartet])
        return (IP,str(port))
コード例 #22
0
 def shouldStop(self, s, previousS):
     if self.stopCondition == HopefieldStochastic.ACTIVATION_STOP_BY_HAMMING_CONDITION:
         maxDifference = int(self.n * self.hammingPercentageDifference)
         return Hamming.distance(s.flatten(), previousS.flatten()) <= maxDifference
     else:
         return self.randomActivationConditionStopper.shouldStop(s, self.iEnergy)
コード例 #23
0
    # print("audio values coded on 8 bits : \n" )
    # print(audioCodedValue)

    # Q10
    # we will stock the coded values of the audio file (coded on 8 bits as duo of half words in
    # the codedAudio lists. The first one has all the first half part of every value
    # coded under Hamming code, the second codedAudio list has the coded second half.
    codedAudio1 = []
    codedAudio2 = []
    # reminder : audioCodedValue : list of 8 bits string
    for codeWord in audioCodedValue:
        halfCodedWord1 = codeWord[0:4]
        halfCodedWord2 = codeWord[4:]

        # coded1,2 = string of 7 bits
        coded1 = Hamming.hamming7_4(halfCodedWord1)
        coded2 = Hamming.hamming7_4(halfCodedWord2)

        # codedAudio1,2 = list of strings (7bits long)
        codedAudio1.append(coded1)
        codedAudio2.append(coded2)

    # Q11
    # get the audio values coded on 8 bits through the channel
    # with a bit error probability of 'errorRate' percent
    errorRate = 1

    # reminder :audioCodedValue : list of 8 bits strings
    channel = Channel.Channel(audioCodedValue, errorRate)
    # print("audioCodedValue : ")
    # print(audioCodedValue)
コード例 #24
0
 def hammingDados(self, dados):
     partes = [dados[x:x + 8] for x in range(0, len(dados), 8)]
     final = []
     for a in partes:
         final += hamm.hammingCodes(a)
     return final