Sunday, November 22, 2015

Network Control of the Pi (WebSockets) 2

Some success with WebSockets, finally.

I shied away from using asyncio support for WebSockets for several reasons:

  • I don't know much Python programming and don't understand the examples
  • It seems to be a much lower-level implementation than I want (maybe mistaken)
  • I don't want to require Python 3.4, which is required for asyncio.  I want to be able to use Python 2.7 in the event that I get some less-capable or less-modern devices involved.
I tried several libraries, and in the end had difficulty getting them to work properly on Pi.

In the end I fell back to use Tornado libraries, which is among many things, lets you implement and use:
  • An event manager
  • WebServer libs
  • WebSocket client libs

With these I've been able to build a basic set of libraries which allow me to write very short Python programs which can:
  • Listen on arbitrary WebSocket addresses (eg ws://127.0.01:4000/).
  • Connect to any arbitrary WebSocket adddress.
  • Handle console input while doing any of the above.
  • Do all of the above via an Event Loop, no blocking required.

Difficulties came up understanding how various events fire in association with WebSocket connections working, etc, and how that fit into the interface I wanted to build.

An example being - What if your program tries to connect outbound (async) and wants to cancel the attempt before finding out whether it worked.  Not supported (from what I can tell).  I had to implement a wrapper to fake it.