<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Unknown fault]]></title><description><![CDATA[<p dir="auto">I do not understand what is happening, I put you capture of the beginning of the program in its normal functionality:</p>
<p dir="auto"><img src="/assets/uploads/files/1528714907695-problema1-resized.png" alt="0_1528714912019_problema1.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">But when a Wi-Fi connection arrives, the program fails and starts to put the following (despite having &quot;controlled&quot; with the try and catch):</p>
<p dir="auto"><img src="/assets/uploads/files/1528715959822-problema2-resized.png" alt="0_1528715959477_problema2.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">Follow with a few paragraphs like this:<br />
<img src="/assets/uploads/files/1528716004839-problema3.png" alt="0_1528716004663_problema3.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">and so ends:<br />
<img src="/assets/uploads/files/1528716033140-problema4-resized.png" alt="0_1528716033015_problema4.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">the used code:</p>
<pre><code>#Generado el 07-06-2018
from network import LoRa
from machine import Timer
import socket
import machine
import time
import os
import pycom
import _thread
import gc
import select

###     Funciones
def existe(arg):
    try:
        fichero = open(arg)
        fichero.close()
        return True
    except:
        return False

def iniciarWifi(pssid):
    try:
        import network
        from network import WLAN
        wlan = network.WLAN(mode=network.WLAN.STA)
        wlan.init(mode=WLAN.AP, ssid=pssid, auth=(WLAN.WPA2,'witeklab@2018'), channel=7, antenna=WLAN.INT_ANT)
        from network import Server
        server = Server(login=('micro', 'python'), timeout=600)
        server.timeout(300)
        server.timeout()
        server.isrunning()
        ConfirmacionLed('wifi')
        return True
    except:
        return False

def resetDocument():
    #Lista de documentos posible: alerta.txt | dorsal.txt | myposition.txt | registro.txt | seguidores.txt
    lista = ['alertas','dorsal','myposition','registro','seguidores','alertapersonalizada']
    for i in lista:
        if existe(i+'.txt'):
            print('Borrando',i+'.txt')
            os.remove(i+'.txt')

def pulsaciones(color):
    for x in range(3):
        pycom.rgbled(color)
        time.sleep(0.1)
        pycom.heartbeat(False)
        time.sleep(0.2)

def ConfirmacionLed(funcion):
    funciones={'wifi':0x0007F,'recibido':0xfffe02,'nogps':0x7f0000,'encendido':0x7f700,'sendalert':0xC011EB}# wifi(azul) | recibido(Amarillo) | nogps(rojo) | encendido(verde) | sendalert(lila) -gpsok()
    pulsaciones(funciones[funcion])

def enviarAlertas(s,listalertas=[]):
    a = open('alertas.txt')
    j = a.read()
    j = j.strip(&quot;|&quot;)
    j = j.split(&quot;|&quot;)
    b= len(j)
    print(&quot;N alertas=&quot;,b)
    for x in range(b):
        j[x] = j[x].replace('\n','')
        j[x] = j[x].replace('\r','')
        if j[x] not in listalertas:
            listalertas.append(j[x])
            cuenta = 0
            for z in j[x]:
                if z ==&quot;-&quot;:
                    cuenta+=1
            print(&quot;Cuenta--&gt;&quot;,cuenta)
            if cuenta == 1:
                print(&quot;Mensaje Personalizado no estaba guardado:&quot;,j[x])
                p=j[x].split(&quot;-&quot;)
                msg = &quot;alerta-&quot;+p[1].replace(' ','')+&quot;;&quot;+p[0]
                s.send(msg)
            else:
                j[x]
                print(&quot;Mensaje no estaba guardado:&quot;,j[x])
                msg = &quot;alerta-&quot;+j[x]
                s.send(msg)
            #Mostramos para comprobar el mensaje enviado:
            print(&quot;Mensaje enviado:&quot;,msg)
            ConfirmacionLed('sendalert')
            print(&quot;Asi esta la lista: &quot;,listalertas)
    return listalertas

def inciarAlertas(lora,s):
    listalertas=[]
    s.setblocking(False)
    tiempo=time.time()
    tmp2=tiempo
    re=0
    print('2-&gt; Iniciamos seguno hilo con la busqueda de alertas:')
    while True:
        try:
            time.sleep(30)
            tiempo=time.time()
            if existe('alertas.txt'):
                if re==0:
                    listalertas = enviarAlertas(s,listalertas)
                    tmp2=tiempo
                    re+=1
                elif tiempo-tmp2&gt;=60 and re !=0:
                    tmp2=tiempo
                    print(&quot;Reenviando la lista de alertas&quot;)
                    del listalertas[:] #Borro la lista y reenvio leyendo de nuevo.
                    listalertas = enviarAlertas(s,listalertas)
                else:
                    print(&quot;Alertas existe, pero aun no ha pasado los 60 segundos=&quot;, tiempo-tmp2)
            else:
                print(&quot;- No hay alertas(Archivo 'alertas.txt' no existe.)&quot;)
                del listalertas[:]
                re=0
        except:
            print(&quot;*** - Algo ha fallado en IniciarAlertas - ***&quot;)

def iniciarSeguidores(lora,s,tiempoEnvioSeguidores):
    s.setblocking(False)
    tiempo = time.time()
    tmp=tiempo
    print('3-&gt; Iniciamos el tercer hilo con la busqueda de seguidores')
    while True:
        try:
            time.sleep(12)
            tiempo=time.time()
            if existe('seguidores.txt'):
                if tiempo-tmp &gt;= tiempoEnvioSeguidores:
                    tmp=tiempo
                    a = open('seguidores.txt')
                    j = a.read()
                    j = j.replace('\r','')
                    j = j.replace('\n','')
                    j = j.strip(&quot;|&quot;)
                    j = j.split(&quot;|&quot;)
                    b= len(j)
                    print(&quot;N seguidores&quot;,b)
                    for x in range(b):
                        msg = &quot;seguidores-&quot;+j[x]
                        s.send(msg)
                        print(&quot;Mensaje enviado:&quot;,msg)
                        ConfirmacionLed('sendalert')
                else:
                    print(&quot;Seguidores.txt existe pero Aun no han pasado X segundos&quot;,tiempo-tmp)
            else:
                print(&quot;- No hay Seguidores(Archivo 'seguidores.txt' no existe.)&quot;)
        except:
            print('*** - Algo ha fallado en IniciarSeguidores - ***')

def iniciarCorredores(lora,s,tiempoVaciarBasura):
    print('1-&gt; Iniciamos primer hilo el registro de corredores:')
    corredores=[]
    while True:
        try:
            actualizado = 0
            s.setblocking(True)
            data = s.recv(64) #socket.recv (bufsize [, flags])  Reciba datos del socket. El valor de retorno es una cadena que representa los datos recibidos. La cantidad máxima de datos que se recibirán a la vez se especifica mediante bufsize
            j =data.decode(&quot;utf-8&quot;)
            j = j.split('-')
            if j[0] == 'witeklab':
                #j[dorsalDefault],j[dorsalactual],j[contador],j[latitud],j[Longitud]
                print('mensaje entrante-&gt;',data)
                for c in range(len(corredores)):
                    if j[2] in corredores[c]:
                        if int(j[1]) &gt; int(corredores[c][2]):
                            corredores[c]=([j[2],j[3],j[1],j[4],j[5&rsqb;&rsqb;)
                            ConfirmacionLed('recibido')
                            actualizado=1
                            break
                if actualizado==0:
                    corredores.append([j[2],j[3],j[1],j[4],j[5&rsqb;&rsqb;)
                    msj = &quot;baseConfirma-&quot;+j[2]+&quot;;OK&quot;
                    s.send(msj)
                    ConfirmacionLed('recibido')

            print(&quot;Corredores:&quot;,len(corredores))
            print(corredores)
            print(&quot;Memoria libre actual-&gt;&quot;,gc.mem_free())
            #print(gc.isenabled())
            #print(&quot;crono-&gt;&quot;,crono.read())
            if crono.read() &gt; tiempoVaciarBasura :
                gc.collect()
                crono.reset()
                print(&quot;Vaciando papelera...Memoria disponible:&quot;,gc.mem_free())

            #linea = j[2]+&quot;;&quot;+j[1]+&quot;;&quot;+j[3]&quot;;&quot;+j[4]+&quot;|&quot; #ID;NºRegistro;Latitud;Longitud|
            f = open ('registro.txt', 'w')#Modo 'a' Para añadir no sobre escribir
            for c in range(len(corredores)):
                if len(corredores)!=0:
                    d = corredores[c]
                    texto = d[1]+&quot;;&quot;+d[3]+&quot;;&quot;+d[4]+&quot;|&quot;
                    f.write(texto)
            f.close()
        except Exception as e:
            print(&quot;*** - Algo ha fallado en IniciarCorredores - *** -&gt; &quot;,e)

def escucharBaseRepetidora():
    port = 12345
    print('4-&gt; Iniciamos el cuarto hilo con la espera de recibir el registro de la base repetidora')
    while True:
        try:
            while True:
                s = socket.socket()
                s.bind(socket.getaddrinfo(&quot;0.0.0.0&quot;, port)[0][4])
                s.listen(2)
                print(&quot;Mostramos listado:&quot;,os.listdir())
                if existe('registro2.txt'):
                    print(&quot;Mostramos contenido fichero registro2.txt:&quot;)
                    print(open('registro2.txt').read())
                    pass

                print(&quot;\n\nEsperando conexion&quot;)
                readable, writable, errored = select.select([s], [], [])
                for s in readable:
                    cl, remote_addr = s.accept()
                    cl.setblocking(True)
                    cl.settimeout(2)
                    print(&quot;Client connection from:&quot;, remote_addr)
                    file = &quot;/flash/registro2.txt&quot;
                    print(&quot;writing: &quot;, file)

                    with open(file, 'wb') as f:
                        while True:
                            try:
                                data = cl.recv(1024)
                                print(data)
                                f.write(data)
                                f.close()
                            except TimeoutError:
                                break
                print(&quot;Recibido...Faltaría actualizar corredores.&quot;)
                s.close()
        except Exception as e:
            print(&quot;*** - Algo ha fallado en escucharBaseRepetidora - ***&quot;)
            print(&quot;Except-&gt;&quot;,e)


###     Variables
pssid = &quot;Gateway1&quot;
tiempoEnvioSeguidores = 20
tiempoVaciarBasura = 100
lora = LoRa(mode=LoRa.LORA)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
crono = Timer.Chrono()
crono.start()
###     Main
pycom.heartbeat(False)
resetDocument()
iniciarWifi(pssid)
time.sleep(0.2)
a = _thread.start_new_thread(iniciarCorredores,(lora,s,tiempoVaciarBasura,))
time.sleep(0.3)
b = _thread.start_new_thread(inciarAlertas,(lora,s,))
time.sleep(0.2)
c = _thread.start_new_thread(iniciarSeguidores,(lora,s,tiempoEnvioSeguidores,))
time.sleep(0.3)
#Pendiente implantacion:
_thread.start_new_thread(escucharBaseRepetidora,())
time.sleep(0.2)
</code></pre>
<p dir="auto">The added function of where this happens is: <code>def escucharBaseRepetidora():</code></p>
<p dir="auto">Since without this function the rest of the code works correctly.</p>
<p dir="auto">On the other hand I will add that using the code in an independent and unique way. In other words, testing only the piece of code that I put below works perfectly. I do not finish understanding the failure and because it only happens when I put it with the complete program and it does not happen when I only execute the following:</p>
<p dir="auto">Test code that works perfectly:<br />
Lopy transmitter:</p>
<pre><code>from network import WLAN
import socket
import select
import machine
import time

# Connect to server AP
wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
for net in nets:
    if net.ssid == 'Gateway1':
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, 'password'), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break
else:
    raise Exception(&quot;WiFi network not found&quot;)

# sleep just to make sure the wifi is connected
time.sleep(1)

ip, subnet, gateway, dns = wlan.ifconfig()
print(&quot;wlan-&gt;&quot;,wlan.ifconfig())
# Connect to server
port = 12345
s = socket.socket()
print(&quot;g-&gt;&quot;,gateway)
print(&quot;Connecting to: &quot;, gateway, port)
s.connect((gateway, port))
s.setblocking(True)
s.settimeout(2)

file = &quot;/flash/registro.txt&quot;
print(&quot;Sending: &quot;, file)

with open(file, 'rb') as f:
    data = f.read(1024)
    while(data):
        print(&quot;sending&quot;, data)
        s.sendall(data)
        data = f.read(1024)
print(&quot;Done Sending&quot;)
s.close()
wlan.disconnect()
</code></pre>
<p dir="auto">Lopy receiver:</p>
<pre><code>from network import WLAN
import socket
import select
import time

#Setup WiFi AP
wlan = WLAN(mode=WLAN.AP,
            ssid='Gateway1',
            auth=(WLAN.WPA2,'password'),
            antenna=WLAN.INT_ANT)

def existe(fichero):
    try:
        f = open(fichero, &quot;r&quot;)
        exists = True
        f.close()
    except:
        exists = False
    return exists


# Bind to the port
port = 12345
while True:
    s = socket.socket()
    s.bind(socket.getaddrinfo(&quot;0.0.0.0&quot;, port)[0][4])
    s.listen(1)
    print(&quot;Mostramos listado:&quot;,os.listdir())
    if existe('testeando.txt'):
        print(&quot;Mostramos contenido fichero testeando.txt:&quot;)
        print(open('testeando.txt').read())
        pass

    print(&quot;\n\nEsperando conexion&quot;)
    readable, writable, errored = select.select([s], [], [])
    for s in readable:
        cl, remote_addr = s.accept()
        cl.setblocking(True)
        cl.settimeout(2)
        print(&quot;Client connection from:&quot;, remote_addr)
        file = &quot;/flash/testeando.txt&quot;
        print(&quot;writing: &quot;, file)

        with open(file, 'wb') as f:
            while True:
                try:
                    data = cl.recv(1024)
                    print(data)
                    f.write(data)
                    f.close()
                except TimeoutError:
                    break
    print(&quot;Recibido...&quot;)
    s.close()
</code></pre>
<p dir="auto">If someone can tell me what kind of error that is happening and because it only fails in the entire program, I would greatly appreciate it! a greeting</p>
]]></description><link>https://forum.pycom.io/topic/3356/unknown-fault</link><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Jul 2026 12:31:02 GMT</lastBuildDate><atom:link href="https://forum.pycom.io/topic/3356.rss" rel="self" type="application/rss+xml"/><pubDate>Mon, 11 Jun 2018 11:28:59 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Unknown fault on Mon, 11 Jun 2018 11:28:59 GMT]]></title><description><![CDATA[<p dir="auto">I do not understand what is happening, I put you capture of the beginning of the program in its normal functionality:</p>
<p dir="auto"><img src="/assets/uploads/files/1528714907695-problema1-resized.png" alt="0_1528714912019_problema1.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">But when a Wi-Fi connection arrives, the program fails and starts to put the following (despite having &quot;controlled&quot; with the try and catch):</p>
<p dir="auto"><img src="/assets/uploads/files/1528715959822-problema2-resized.png" alt="0_1528715959477_problema2.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">Follow with a few paragraphs like this:<br />
<img src="/assets/uploads/files/1528716004839-problema3.png" alt="0_1528716004663_problema3.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">and so ends:<br />
<img src="/assets/uploads/files/1528716033140-problema4-resized.png" alt="0_1528716033015_problema4.PNG" class="img-responsive img-markdown" /></p>
<p dir="auto">the used code:</p>
<pre><code>#Generado el 07-06-2018
from network import LoRa
from machine import Timer
import socket
import machine
import time
import os
import pycom
import _thread
import gc
import select

###     Funciones
def existe(arg):
    try:
        fichero = open(arg)
        fichero.close()
        return True
    except:
        return False

def iniciarWifi(pssid):
    try:
        import network
        from network import WLAN
        wlan = network.WLAN(mode=network.WLAN.STA)
        wlan.init(mode=WLAN.AP, ssid=pssid, auth=(WLAN.WPA2,'witeklab@2018'), channel=7, antenna=WLAN.INT_ANT)
        from network import Server
        server = Server(login=('micro', 'python'), timeout=600)
        server.timeout(300)
        server.timeout()
        server.isrunning()
        ConfirmacionLed('wifi')
        return True
    except:
        return False

def resetDocument():
    #Lista de documentos posible: alerta.txt | dorsal.txt | myposition.txt | registro.txt | seguidores.txt
    lista = ['alertas','dorsal','myposition','registro','seguidores','alertapersonalizada']
    for i in lista:
        if existe(i+'.txt'):
            print('Borrando',i+'.txt')
            os.remove(i+'.txt')

def pulsaciones(color):
    for x in range(3):
        pycom.rgbled(color)
        time.sleep(0.1)
        pycom.heartbeat(False)
        time.sleep(0.2)

def ConfirmacionLed(funcion):
    funciones={'wifi':0x0007F,'recibido':0xfffe02,'nogps':0x7f0000,'encendido':0x7f700,'sendalert':0xC011EB}# wifi(azul) | recibido(Amarillo) | nogps(rojo) | encendido(verde) | sendalert(lila) -gpsok()
    pulsaciones(funciones[funcion])

def enviarAlertas(s,listalertas=[]):
    a = open('alertas.txt')
    j = a.read()
    j = j.strip(&quot;|&quot;)
    j = j.split(&quot;|&quot;)
    b= len(j)
    print(&quot;N alertas=&quot;,b)
    for x in range(b):
        j[x] = j[x].replace('\n','')
        j[x] = j[x].replace('\r','')
        if j[x] not in listalertas:
            listalertas.append(j[x])
            cuenta = 0
            for z in j[x]:
                if z ==&quot;-&quot;:
                    cuenta+=1
            print(&quot;Cuenta--&gt;&quot;,cuenta)
            if cuenta == 1:
                print(&quot;Mensaje Personalizado no estaba guardado:&quot;,j[x])
                p=j[x].split(&quot;-&quot;)
                msg = &quot;alerta-&quot;+p[1].replace(' ','')+&quot;;&quot;+p[0]
                s.send(msg)
            else:
                j[x]
                print(&quot;Mensaje no estaba guardado:&quot;,j[x])
                msg = &quot;alerta-&quot;+j[x]
                s.send(msg)
            #Mostramos para comprobar el mensaje enviado:
            print(&quot;Mensaje enviado:&quot;,msg)
            ConfirmacionLed('sendalert')
            print(&quot;Asi esta la lista: &quot;,listalertas)
    return listalertas

def inciarAlertas(lora,s):
    listalertas=[]
    s.setblocking(False)
    tiempo=time.time()
    tmp2=tiempo
    re=0
    print('2-&gt; Iniciamos seguno hilo con la busqueda de alertas:')
    while True:
        try:
            time.sleep(30)
            tiempo=time.time()
            if existe('alertas.txt'):
                if re==0:
                    listalertas = enviarAlertas(s,listalertas)
                    tmp2=tiempo
                    re+=1
                elif tiempo-tmp2&gt;=60 and re !=0:
                    tmp2=tiempo
                    print(&quot;Reenviando la lista de alertas&quot;)
                    del listalertas[:] #Borro la lista y reenvio leyendo de nuevo.
                    listalertas = enviarAlertas(s,listalertas)
                else:
                    print(&quot;Alertas existe, pero aun no ha pasado los 60 segundos=&quot;, tiempo-tmp2)
            else:
                print(&quot;- No hay alertas(Archivo 'alertas.txt' no existe.)&quot;)
                del listalertas[:]
                re=0
        except:
            print(&quot;*** - Algo ha fallado en IniciarAlertas - ***&quot;)

def iniciarSeguidores(lora,s,tiempoEnvioSeguidores):
    s.setblocking(False)
    tiempo = time.time()
    tmp=tiempo
    print('3-&gt; Iniciamos el tercer hilo con la busqueda de seguidores')
    while True:
        try:
            time.sleep(12)
            tiempo=time.time()
            if existe('seguidores.txt'):
                if tiempo-tmp &gt;= tiempoEnvioSeguidores:
                    tmp=tiempo
                    a = open('seguidores.txt')
                    j = a.read()
                    j = j.replace('\r','')
                    j = j.replace('\n','')
                    j = j.strip(&quot;|&quot;)
                    j = j.split(&quot;|&quot;)
                    b= len(j)
                    print(&quot;N seguidores&quot;,b)
                    for x in range(b):
                        msg = &quot;seguidores-&quot;+j[x]
                        s.send(msg)
                        print(&quot;Mensaje enviado:&quot;,msg)
                        ConfirmacionLed('sendalert')
                else:
                    print(&quot;Seguidores.txt existe pero Aun no han pasado X segundos&quot;,tiempo-tmp)
            else:
                print(&quot;- No hay Seguidores(Archivo 'seguidores.txt' no existe.)&quot;)
        except:
            print('*** - Algo ha fallado en IniciarSeguidores - ***')

def iniciarCorredores(lora,s,tiempoVaciarBasura):
    print('1-&gt; Iniciamos primer hilo el registro de corredores:')
    corredores=[]
    while True:
        try:
            actualizado = 0
            s.setblocking(True)
            data = s.recv(64) #socket.recv (bufsize [, flags])  Reciba datos del socket. El valor de retorno es una cadena que representa los datos recibidos. La cantidad máxima de datos que se recibirán a la vez se especifica mediante bufsize
            j =data.decode(&quot;utf-8&quot;)
            j = j.split('-')
            if j[0] == 'witeklab':
                #j[dorsalDefault],j[dorsalactual],j[contador],j[latitud],j[Longitud]
                print('mensaje entrante-&gt;',data)
                for c in range(len(corredores)):
                    if j[2] in corredores[c]:
                        if int(j[1]) &gt; int(corredores[c][2]):
                            corredores[c]=([j[2],j[3],j[1],j[4],j[5&rsqb;&rsqb;)
                            ConfirmacionLed('recibido')
                            actualizado=1
                            break
                if actualizado==0:
                    corredores.append([j[2],j[3],j[1],j[4],j[5&rsqb;&rsqb;)
                    msj = &quot;baseConfirma-&quot;+j[2]+&quot;;OK&quot;
                    s.send(msj)
                    ConfirmacionLed('recibido')

            print(&quot;Corredores:&quot;,len(corredores))
            print(corredores)
            print(&quot;Memoria libre actual-&gt;&quot;,gc.mem_free())
            #print(gc.isenabled())
            #print(&quot;crono-&gt;&quot;,crono.read())
            if crono.read() &gt; tiempoVaciarBasura :
                gc.collect()
                crono.reset()
                print(&quot;Vaciando papelera...Memoria disponible:&quot;,gc.mem_free())

            #linea = j[2]+&quot;;&quot;+j[1]+&quot;;&quot;+j[3]&quot;;&quot;+j[4]+&quot;|&quot; #ID;NºRegistro;Latitud;Longitud|
            f = open ('registro.txt', 'w')#Modo 'a' Para añadir no sobre escribir
            for c in range(len(corredores)):
                if len(corredores)!=0:
                    d = corredores[c]
                    texto = d[1]+&quot;;&quot;+d[3]+&quot;;&quot;+d[4]+&quot;|&quot;
                    f.write(texto)
            f.close()
        except Exception as e:
            print(&quot;*** - Algo ha fallado en IniciarCorredores - *** -&gt; &quot;,e)

def escucharBaseRepetidora():
    port = 12345
    print('4-&gt; Iniciamos el cuarto hilo con la espera de recibir el registro de la base repetidora')
    while True:
        try:
            while True:
                s = socket.socket()
                s.bind(socket.getaddrinfo(&quot;0.0.0.0&quot;, port)[0][4])
                s.listen(2)
                print(&quot;Mostramos listado:&quot;,os.listdir())
                if existe('registro2.txt'):
                    print(&quot;Mostramos contenido fichero registro2.txt:&quot;)
                    print(open('registro2.txt').read())
                    pass

                print(&quot;\n\nEsperando conexion&quot;)
                readable, writable, errored = select.select([s], [], [])
                for s in readable:
                    cl, remote_addr = s.accept()
                    cl.setblocking(True)
                    cl.settimeout(2)
                    print(&quot;Client connection from:&quot;, remote_addr)
                    file = &quot;/flash/registro2.txt&quot;
                    print(&quot;writing: &quot;, file)

                    with open(file, 'wb') as f:
                        while True:
                            try:
                                data = cl.recv(1024)
                                print(data)
                                f.write(data)
                                f.close()
                            except TimeoutError:
                                break
                print(&quot;Recibido...Faltaría actualizar corredores.&quot;)
                s.close()
        except Exception as e:
            print(&quot;*** - Algo ha fallado en escucharBaseRepetidora - ***&quot;)
            print(&quot;Except-&gt;&quot;,e)


###     Variables
pssid = &quot;Gateway1&quot;
tiempoEnvioSeguidores = 20
tiempoVaciarBasura = 100
lora = LoRa(mode=LoRa.LORA)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
crono = Timer.Chrono()
crono.start()
###     Main
pycom.heartbeat(False)
resetDocument()
iniciarWifi(pssid)
time.sleep(0.2)
a = _thread.start_new_thread(iniciarCorredores,(lora,s,tiempoVaciarBasura,))
time.sleep(0.3)
b = _thread.start_new_thread(inciarAlertas,(lora,s,))
time.sleep(0.2)
c = _thread.start_new_thread(iniciarSeguidores,(lora,s,tiempoEnvioSeguidores,))
time.sleep(0.3)
#Pendiente implantacion:
_thread.start_new_thread(escucharBaseRepetidora,())
time.sleep(0.2)
</code></pre>
<p dir="auto">The added function of where this happens is: <code>def escucharBaseRepetidora():</code></p>
<p dir="auto">Since without this function the rest of the code works correctly.</p>
<p dir="auto">On the other hand I will add that using the code in an independent and unique way. In other words, testing only the piece of code that I put below works perfectly. I do not finish understanding the failure and because it only happens when I put it with the complete program and it does not happen when I only execute the following:</p>
<p dir="auto">Test code that works perfectly:<br />
Lopy transmitter:</p>
<pre><code>from network import WLAN
import socket
import select
import machine
import time

# Connect to server AP
wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
for net in nets:
    if net.ssid == 'Gateway1':
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, 'password'), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break
else:
    raise Exception(&quot;WiFi network not found&quot;)

# sleep just to make sure the wifi is connected
time.sleep(1)

ip, subnet, gateway, dns = wlan.ifconfig()
print(&quot;wlan-&gt;&quot;,wlan.ifconfig())
# Connect to server
port = 12345
s = socket.socket()
print(&quot;g-&gt;&quot;,gateway)
print(&quot;Connecting to: &quot;, gateway, port)
s.connect((gateway, port))
s.setblocking(True)
s.settimeout(2)

file = &quot;/flash/registro.txt&quot;
print(&quot;Sending: &quot;, file)

with open(file, 'rb') as f:
    data = f.read(1024)
    while(data):
        print(&quot;sending&quot;, data)
        s.sendall(data)
        data = f.read(1024)
print(&quot;Done Sending&quot;)
s.close()
wlan.disconnect()
</code></pre>
<p dir="auto">Lopy receiver:</p>
<pre><code>from network import WLAN
import socket
import select
import time

#Setup WiFi AP
wlan = WLAN(mode=WLAN.AP,
            ssid='Gateway1',
            auth=(WLAN.WPA2,'password'),
            antenna=WLAN.INT_ANT)

def existe(fichero):
    try:
        f = open(fichero, &quot;r&quot;)
        exists = True
        f.close()
    except:
        exists = False
    return exists


# Bind to the port
port = 12345
while True:
    s = socket.socket()
    s.bind(socket.getaddrinfo(&quot;0.0.0.0&quot;, port)[0][4])
    s.listen(1)
    print(&quot;Mostramos listado:&quot;,os.listdir())
    if existe('testeando.txt'):
        print(&quot;Mostramos contenido fichero testeando.txt:&quot;)
        print(open('testeando.txt').read())
        pass

    print(&quot;\n\nEsperando conexion&quot;)
    readable, writable, errored = select.select([s], [], [])
    for s in readable:
        cl, remote_addr = s.accept()
        cl.setblocking(True)
        cl.settimeout(2)
        print(&quot;Client connection from:&quot;, remote_addr)
        file = &quot;/flash/testeando.txt&quot;
        print(&quot;writing: &quot;, file)

        with open(file, 'wb') as f:
            while True:
                try:
                    data = cl.recv(1024)
                    print(data)
                    f.write(data)
                    f.close()
                except TimeoutError:
                    break
    print(&quot;Recibido...&quot;)
    s.close()
</code></pre>
<p dir="auto">If someone can tell me what kind of error that is happening and because it only fails in the entire program, I would greatly appreciate it! a greeting</p>
]]></description><link>https://forum.pycom.io/post/20225</link><guid isPermaLink="true">https://forum.pycom.io/post/20225</guid><dc:creator><![CDATA[zceld]]></dc:creator><pubDate>Mon, 11 Jun 2018 11:28:59 GMT</pubDate></item></channel></rss>