I’m trying to build a robust hard-wired ethernet socket connection to stream data to a PC. Ideally it will reconnect automatically after cable disconnects and re-connects, but also would be nice to trigger outputs based on socket connection status. Currently seems like system is required to wait on all s.accept() in order to catch incoming socket connections. Is there any way to multi-thread the program to allow the socket connection to run in parallel to sensor/IO code? Or a better way to do this?
Current example code:
import sensor, image, time, network
import usocket as socket
ip = '10.0.0.199'
# Initialize the camera sensor
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=500)
#create a readable Ethernet node (so can check by ping)
lan = network.LAN()
lan.active(True)
lan.ifconfig((ip, "255.255.255.0", "10.0.0.1", "10.0.0.1"))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, 12345))
s.listen(1)
conn, addr = s.accept()
while True:
img = sensor.snapshot()
try:
data_value = img.get_statistics().l_mean()
conn.sendall("{:.2f}\n".format(data_value))
time.sleep(0.02)
except Exception as e:
print(e)
conn.close()
time.sleep(1.0)
print("Retrying")
conn, addr = s.accept()
conn.close()
s.close()