Send Message / file with micro python

3

I raise the plot to see if you can help me. Is the next: I'm linking two devices that work with micro-python language and have chips to use Wi-Fi as scheduled. Well basically the idea is to develop a program that on the server chip (hereafter chipS) Wi-Fi is activated in AP (Access Point) mode as a server so that the client chip (hereinafter chipC) connects to the and this one sends a file.txt to him by means of socket since to realize a coexion type FTP there is no library of this one in micropython. Although it's funny because from Windows with the Filezilla client if I can connect to the chipS and upload a file. That's basically what I want to do but with the chipC.

Finally, if someone knows how to use an FTP library adapted to micropython and explains how it is used, I also accept it.

Well at the moment I am trying with socket but I do not know what is wrong or how it would be done, for examples that I have read I have made the following programming but it also gives me errors.

In the case of chipS the code used is:

import socket                   # Import socket module
import network
import gc
from network import WLAN
from network import Server

def iniciarFTP():
    try:
        wlan = network.WLAN(mode=network.WLAN.STA)
        wlan.init(mode=WLAN.AP, ssid='Gateway1', auth=(WLAN.WPA2,'witeklab@2018'), channel=7, antenna=WLAN.INT_ANT)
        server = Server(login=('micro', 'python'), timeout=600)
        #server.timeout(300)
        #print(server.isrunning())
        print(wlan.ifconfig())
        return True
    except:
        return False

#Iniciamos servidor:
iniciarFTP()
host = ''
port = 60000                     # Reserve a port for your service.
s = socket.socket()             # Create a socket object
gc.collect()
s.bind((host, port))            # Bind to the port
s.listen(5)                     # Now wait for client connection.

print ('Server listening....')

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print ('Got connection from', addr)
    data = conn.recv(256)
    print('Server received', repr(data))

    with open('received_file.txt', 'wb') as f:
        print ('file opened')
        while True:
            print('receiving data...')
            s.setblocking(True)
            print('Memoria->',str(gc.mem_free()))
            data = s.recv(256)
            print('M despues->',str(gc.mem_free()))
            print('data=%s', (data))
            if not data:
                break
            # write data to a file
            f.write(data)

        f.close()
        print('Successfully get the file')
        s.close()
        print('connection closed')

        conn.send('Thank you for connecting')
    conn.close()
    gc.collect()

And upon receiving the client's connection it indicates' Got connection from ('192.168.4.2', 49429) But the client has already failed:

This is the code used in the chipC:

from network import WLAN

import socket
import sys


def buscarWifi(ssid):
    #Ponemos el wifi en modo estacion:
    wlan = WLAN(mode=WLAN.STA)

    #Buscamos wifi:
    redes = wlan.scan()
    print('Redes disponibles: ',len(redes))
    #for c in range(len(redes)):
        #print(c,'->',redes[c])

        #if ssid in redes[c]: //Otra opción de encontrar el ssid
        #print("Encontrado en:",redes[c])
        #return True
    for red in redes:
        if red.ssid == ssid:
            wlan.connect(red.ssid, auth=(red.sec,'witeklab@2018'), timeout=5000)
            while not wlan.isconnected():
                machine.idle() # save power while waiting
            print('WLAN connection succeeded!')
            return True,wlan
            break
        else:
            return False,wlan
ok,w = buscarWifi('Gateway1')
if ok:
    ip = w.ifconfig()
    #(ip, subnet, gateway, dns)
    print('ip destino = ',ip[2]) #ip del servidor wifi que tambien es la ip al que le quiero enviar el socket/archivo
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = ip[2]
    port = 60000
    client.connect((host, port)) ## <-- Failure
    filepath = 'prueba.txt'
    with open(filepath) as fp:
       line = fp.readline()
       while line:
           print("Line {}".format(line.strip()))
           line = fp.readline()
           client.send(line)
    client.close()

To add comment that the chips are: Lopy Pycom company and that both this test and others tambén I have raised in their official forum but have not helped me to see if here and in Spanish I have more luck, likewise I leave the link: link

    
asked by Zceld 17.04.2018 в 17:23
source

1 answer

0

I do not have your hardware, so I can not verify if it's just what I'm going to explain, or if there are more specific details of micro-python and the platform, but taking for granted the configuration of the Wifi, and focusing only on communication at the socket level, I see the following problems:

ChipS

  • You are trying to receive data by socket s , which is the passive socket by which you support clients. The data comes from the socket conn that returned accept() .
  • The first block of 256 bytes you receive is not being written to the file. You should move the f.write(data) to the beginning of the loop while , because when you enter the loop data already has the result of the first recv() that you make outside the loop (which by the way you do it right, about conn ).
  • Just in case that first recv() already returned an end of transmission, better than while True: I would put while data: .
  • You should not send that "Thank you for connecting" to the socket, since the client does not read it.

ChipC

I do not know exactly what returns ip = w.ifconfig() but judging from its later use, I guess that in ip[2] you have a text string with the server IP.

This may not be the case ... check the type of ip[2] just in case, since you say that it breaks in connect() . However, I do not think the error occurs in connect() . In the screenshot that you attach, it points out an exception on line 41 (and that is not seen in the list, but it is not the connect() , which would be 38). I suspect that it is the open() of the file, especially because you get an error ENOENT (which indicates No such file or directory , that is, that the file you are trying to open does not exist).

Apart from that, I do not know if micropython is Python2 or Python3. If it is Python3, by default it opens the file in text mode, so you would read strings, whereas what you write in the socket are bytes and you would fail in the send() . Better the file in binary mode.

Example

The next version of ChipS and ChipC works on my machine, but with normal Python and omitting all the setup part of the wifi, to focus only on communication by sockets:

ChipS

import socket                   # Import socket module
import gc


#Iniciamos servidor:
host = ''
port = 60000                    # Reserve a port for your service.
s = socket.socket()             # Create a socket object
gc.collect()
s.bind((host, port))            # Bind to the port
s.listen(5)                     # Now wait for client connection.

print ('Server listening....')

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print ('Got connection from', addr)
    data = conn.recv(256)
    print('Server received', repr(data))

    with open('received_file.txt', 'wb') as f:
        print ('file opened')
        while data:
            print('data=%s', (data))
            print('receiving data...')
            # write data to a file
            f.write(data)
            conn.setblocking(True)
            #print('Memoria->',str(gc.mem_free()))
            data = conn.recv(256)
            #print('M despues->',str(gc.mem_free()))
            if not data:
                break

        f.close()
        print('Successfully get the file')
        print('connection closed')

        # conn.send('Thank you for connecting')
    conn.close()
    gc.collect()

ChipC

The class MockWifi is to simulate what your class WLAN would do, which I lack. It's just so that when I call ifconfig() me an IP, in this case the localhost that is where I have the previous server.

import socket
import sys

class MockWifi:
    def ifconfig(self):
        return None, None, "127.0.0.1"

def buscarWifi(ssid):
    return True, MockWifi()

ok,w = buscarWifi('Gateway1')
if ok:
    ip = w.ifconfig()
    #(ip, subnet, gateway, dns)
    print('ip destino = ',ip[2]) #ip del servidor wifi que tambien es la ip al   → que le quiero enviar el socket/archivo
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = ip[2]
    port = 60000
    client.connect((host, port)) ## <-- Failure
    filepath = 'prueba.txt'
    with open(filepath) as fp:
       line = fp.readline()
       while line:
           print("Line {}".format(line.strip()))
           client.send(line.encode("utf8"))
           line = fp.readline()
    client.close()
    
answered by 17.04.2018 в 18:17