Quick feature highlight: `system.serial.port` function

New in 8.0.15, we’ve added a system.serial.port function that returns a “context manager” object that’s useful for scripting. Briefly, context managers are useful with the with statement (PEP 343) for automatic handling of resources. The new function acts as a complement to the existing functions - no existing code is deprecated, there’s just a new syntax that makes things a little cleaner to write.

So, with the exist functions, you first have to configure the serial port, then specifically open it, then perform your operations on that open port, then close it.

system.serial.configureSerialPort("COM1", bitRate=system.serial.BIT_RATE_9600)
system.serial.openSerialPort("COM1")
line = system.serial.readLine("COM1", 60000)
system.serial.closeSerialPort("COM1")

Notice the repetition of the COM1 constant.
The chief advantage of the new style is avoiding repetition; the system.serial.port function accepts all the same arguments as system.serial.configureSerialPort, but once you’ve used it you don’t have to manually open or close ports, nor call fully prefixed functions to interact with the port.
The above example becomes, with the new syntax:

with system.serial.port("COM1", bitRate=system.serial.BIT_RATE_9600) as port:
    line = port.readLine(60000)

The context manager returned by system.serial.port itself returns a SerialPort object, with special “partial” implementations of the system.serial functions - so port.readLine is valid in the above, as well as port.write, port.sendBreak, etc. There’s no need (and indeed, no capability) to specify a different port with this syntax.

The other chief advantage of the with statement is that even if an exception is thrown inside your code, the serial port will always be closed; it’s equivalent to a try/finally block in Python.

3 Likes