I have attached sensors to my Pyboard D, and I am trying to collect the data from the sensors over wifi from a computer. This is the idea in brief.
1) The pyboard and my laptop connect to my local wifi network
2) The pyboard opens a socket and waits for a single connection
3) My laptop opens a socket connecting to the pyboard
4) If the board receives a connection, it collects that data from the sensor and places the data in a buffer
5) The data are sent to the laptop over the socket
6) The socket is closed, both on the computer and the pyboard
Steps 2-6 are repeated every time I want to get some data (~every 2 seconds).
This works 90% of the time. However, sometimes steps 2-3 raise an issue. Usually, I can open the socket almost immediately. But sometimes, it takes seconds (>10). And sometimes, the connection fails. This made me wonder whether opening and closing the socket for each data exchange is maybe not the best way to do this.
I've thought about keeping the socket open. However, that would mean I need to accept a new connection to the socket every 2 seconds in step 2, leading to many open connections.
This is the main code running on my pyboard. The Server() object is defined below.
Code: Select all
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('MyWIFINetworkName', 'MyWIFIpassword')
while not sta_if.isconnected(): pass
print('network config:', sta_if.ifconfig())
while True:
data_server = server.Server()
buffer = get_data()
data_server.send_data(buffer)
data_server.disconnect()
Code: Select all
class Server:
def __init__(self):
self.break_character = '*'
self.buffer = 1024
self.connection = None
self.address = None
self.skt = socket.socket()
self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.skt.bind(('', 1000))
self.skt.listen(1)
connection, address = self.skt.accept()
self.connection = connection
self.address = address
def disconnect(self):
self.connection.close()
def receive_data(self):
data = ''
while 1:
packet = self.connection.recv(self.buffer)
packet = packet.decode()
#if not packet: break
data += packet
if data.endswith(self.break_character): break
data = data.rstrip(self.break_character + '\n')
return data
def send_data(self, message):
if not message.endswith(self.break_character): message = message + self.break_character
encoded_message = message.encode()
self.connection.sendall(encoded_message)