MicroPython Socket sends strings without encoding

31 views Asked by At

I am trying to write code which runs a Raspberry Pi 4 and a Pico. The only problem has been with the socket library. On the Pico this works:

cl.send("<p>Clock: " + strClk + "</p>")

On the Raspberry Pi 4 it is necessary to do something like:

cl.send(str.encode("<p>Clock:" + chr(32) + strClk + "</p>"))

Simple strings can be dealt with by casting:

cl.send(b"<p>Clock</p>"

It seems that the Pico is treating strings as bytearrays. Any suggestions about how to handle this gratefully appreciated.

1

There are 1 answers

0
larsks On

In regular Python, the socket send method requires a byte string. According to the MicroPython documentation, the requirement is the same:

socket.send(bytes)

Send data to the socket. The socket must be connected to a remote socket. Returns number of bytes sent, which may be smaller than the length of data (“short write”).

It looks like MicroPython will also accept a string argument, but in this case it's unclear exactly what you're transmitting (does the string get encoded to utf-8? To something else?), so I would just avoid that and in both MicroPython and Python always encode your strings to byte:

cl.send(f"Clock: {strClk}".encode())

That will do the correct thing in both Python implementations.