Webserial in PyScript
Published February 8, 2023
A user came along the PyScipt GitHub Discussions the other day with an interesting question - can you use PySerial (or similar) in PyScript? That got my wheels a turning; this post is the answer to that question.
The short answer is no, PySerial doesn't work in PyScript - PySerial and other serial libraries rely on low-level features of their host operating systems which just aren't present in the browser window.
But just because PySerial doesn't work, doesn't mean that serial connections can't work. Using the new-ish WebSerial Browser API, we can ask web users for permission to access their local serial devices. If it's granted, we can access those devices via a serial connection. And if you'd like to try it out live in your browser, hit the load PyScript button below:
This isn't a particularly full-featured demo. As you'll see in the code below, it doesn't contain much provision for error handling, and only the barest of UI. But it does work!
Below are three source files for a working demo using WebSerial in PyScript. The first (webPageSerial.html
) is a (minimally formatted) HTML page with two buttons - "Open a Serial Port" and "Write to the Serial Port" - as well as an input box. Clicking the "Open" button prompts the user (if their browser supports WebSerial) to select an available serial port, connects to it, and begins listening for incoming bytes on that port. Once the port is open, when the user clicks the "write" button, the contents of the text box are written to the open serial port.
webserialPage.html
|
|
The second file (webSerialDemo.py
) contains the actual Python/PyScript code that makes this demo work. It wraps the WebSerial API in a new class, SerialManager
, for the purpose of managing the state of the serial connection. It also creates an instance of this class, called sm
, which is referenced by the py-click
attributes in the above HTML document.
Finally, a single helper function sendValueFromInputBox()
is defined, which is used by the "Write" button - it fetches the contents of the input box, asks the SerialManager to write that value to the serial port, then clears the input box.
webSerialDemo.py
|
|
Finally, because a serial demo isn't all that exciting without something to actually communicate with, the final bit of code is an Arduino Sketch. When run on an Arduino Uno or similar, the code simply echos back what it receives on its serial port, with a slight delay.
arduinoSerialEcho.ino
|
|