Package: biplane
BiplaneBiplane is an HTTP server library for Python/CircuitPython.Compared to common alternatives such asAmpule,circuitpython-native-wsgiserver, andAdafruit_CircuitPython_HTTPServer, it has several unique features:Non-blocking concurrent I/O: can process multiple requests at the same time, even whenasync/await/asyncioisn't available!While circuitpython-native-wsgiserver does non-blocking I/O as well, it performs certain operations in a blocking loop, making soft-realtime use difficult (e.g. displaying animations, driving motors).To make this work withoutasyncio, we expose the entire server as a generator, where each step of the generator is O(1).More performant: 10ms per request on a 160MHz ESP32C3, thanks to buffered reads/writes and avoiding common issues such as bytes concatenation.Comparable to blocking I/O servers such as Ampule and Adafruit_CircuitPython_HTTPServer.Much faster than non-blocking I/O servers such as circuitpython-native-wsgiserver, which can take up to 100ms per request on a 160MHz ESP32C3 due to 1-byte recv() calls.More robust: correctly handles binary data, overly-large paths/headers/requests, too-slow/dropped connections, etc.Strictly bounds untrusted input size during request processing using themax_request_line_sizeandmax_body_bytessettings.Strictly bounds request processing time using therequest_timeout_secondssetting.Correctly handles unusual cases such as binary data, dropped connections with no TCP RST, and incomplete writes from the client.Smaller: single-file implementation with ~200 SLOC.Around the same size as Ampule, and much smaller than the other options.Few dependencies: relies only on thetimeanderrnolibraries, both of which are built into Python/CircuitPython (as well aswifi,mdns, andsocketpoolif using the WiFi helpers).However, compared to those libraries, it intentionally doesn't include some features in order to keep the codebase small:Helpers for parsing query parameters and dealing with URL encoding/decoding.Helpers for building HTTP responses, such as header formatting, templating, and more.Helpers for dealing with MIME types (Adafruit_CircuitPython_HTTPServer has this).Support for chunked transfer encoding (Adafruit_CircuitPython_HTTPServer has this).Support for serving static files (Adafruit_CircuitPython_HTTPServer has this).InstallationPythonInstall via Pip:pipinstallbiplaneCircuitPythonTo install Biplane using CircUp, ensure you have set it up according to theAdafruit CircUp guide. Then:circupinstallbiplaneFor CircuitPython devices that don't support the CIRCUITPY drive used to upload code, you can instead manually uploadbiplane.pyfrom this folder tolib/biplane.pyon the board using one of the following methods:Using the Web Workflow via Bluetooth or WiFi. See theAdaFruit Web Workflow guidefor more details.UsingThonny, which supports uploading code to CircuitPython.As a last-resort slow-but-simple option, using the CircuitPython REPL that you can access over the serial port:Runpython3 -c 'f=open("biplane.py");code=f.read();print(f"code={repr(code)};open(\"lib/biplane.py\",\"w\").write(code) if len(code)=={len(code)} else print(\"CODE CORRUPTED\")")'in this folder, and copy the output of that command to the clipboard. This output is CircuitPython code that createslib/biplane.pywith the correct contents inside.Paste the copied output into the CircuitPython REPL and run it. If it outputs "CODE CORRUPTED", that means the code changed between when you pasted it and when it arrived in CircuitPython, which means your serial terminal is sending the characters too quickly and CircuitPython can't keep up (common when usingscreenorminicom); to fix this, configure your terminal to wait 2ms-4ms after sending each character and try again (2ms is usually good enough). Also, make sure that you do this after freshly resetting the board.Lastly, Biplane is part of theCircuitPython Community Bundle, so if you have that installed, then you already have Biplane installed too.ExamplesBasic example (CircuitPython)Starts a WiFi network called "test" (password is "some_password") - when connected, you can see a Hello World page athttp://app.local/(tested on an ESP32C3):importbiplaneserver=biplane.Server()@server.route("/","GET")defmain(query_parameters,headers,body):returnbiplane.Response("<b>Hello, world!</b>",content_type="text/html")for_inserver.circuitpython_start_wifi_ap("test","some_password","app"):passBasic example (Python)Starts a server that displays a Hello World page athttp://localhost:8000, similar to the CircuitPython example above:importbiplaneserver=biplane.Server()@server.route("/","POST")defmain(query_parameters,headers,body):returnbiplane.Response("<b>Hello, world!</b>",content_type="text/html")server_socket=socket.socket()server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)# allow the server to reuse the address immediately after it's been closedfor_inserver.start(server_socket,listen_on=('127.0.0.1',8000)):passThe usage is almost exactly the same, but we pass in a socket from the Pythonsocketlibrary instead of from CircuitPython'ssocketpoollibrary.Parallel execution (CircuitPython)Blinks an LED consistently at ~100Hz while serving HTTP requests, keeping a ~100Hz frequency regardless of how quickly HTTP requests are coming in:importtimeimportboardimportdigitalioimportbiplaneserver=biplane.Server()@server.route("/","GET")defmain(query_parameters,headers,body):returnbiplane.Response("<b>Hello, world!</b>",content_type="text/html")defasyncio_sleep(seconds):# minimal implementation of asyncio.sleep() as a generatorstart_time=time.monotonic()whiletime.monotonic()-start_time<seconds:yielddefblink_builtin_led():withdigitalio.DigitalInOut(pin)asled:led.switch_to_output(value=False)whileTrue:led.value=notled.valueyield fromasyncio_sleep(0.01)for_inzip(blink_builtin_led(),server.circuitpython_start_wifi_ap("test","some_password")):# run through both generators at the same time using zip()passWith other HTTP servers, blinking the LED while serving requests would either be impossible, or would become inconsistent when many HTTP requests are coming in.Note that CircuitPython's GC pauses may cause occasional longer pauses - to mitigate this, runimport gc; gc.collect()at regular, predictable intervals, so that the GC never has to be invoked at unpredictable times.Parallel execution with async/await (CircuitPython)Many CircuitPython implementations, especially those for boards with less RAM/flash, don't include theasynciolibrary. However, ifasynciois available, Biplane works well with it as well:importtimeimportboardimportdigitalioimportbiplaneserver=biplane.Server()@server.route("/","GET")defmain(query_parameters,headers,body):returnbiplane.Response("<b>Hello, world!</b>",content_type="text/html")asyncdefrun_server():for_inserver.circuitpython_start_wifi_ap("test","some_password")awaitasyncio.sleep(0)# let other tasks runasyncdefblink_builtin_led():withdigitalio.DigitalInOut(pin)asled:led.switch_to_output(value=False)whileTrue:led.value=notled.valueawaitasyncio.sleep(0.01)asyncio.run(asyncio.gather(blink_builtin_led(),run_server()))# run both coroutines at the same timeEssentially, we just need to loop through the generator as usual while callingawait asyncio.sleep(0)each iteration to let other tasks run.DevelopmentAll of the application code lives inbiplane.py. Run tests usingpython3 tests/test_basic.py.LicenseCopyright 2023Anthony Zhang (Uberi).The source code is available online atGitHub.This program is made available under the MIT license. SeeLICENSE.txtin the project's root directory for more information.