Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 4 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,12 @@ If you have any questions, it is recommended to check the [examples directory](/

Generally there are two possibilities to use this framework in your project:

### prebuild
### pipkin

You can go to the releases page and check for the latest .mpy file. You can simply add this file on your controller and it will be used just as the package itself. This is the most efficient version to use uAPI, since it is precompiled bytecode.
I recommend using [pipkin](https://github.com/aivarannamaa/pipkin) to install the package on your controller.

### upip

If your use-case allows it you can use uAPI with upip (only when the device has internet connection).

```python3
import upip
upip.install("micropython-uAPI")
```

For your local port of micropython you can also call:

```
micropython -m upip install micropython-uAPI
```
`pipkin --port /dev/ttyACM0 instal
l git+https://github.com/edmcman/uAPI`

### with code

Expand Down
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from setuptools import setup
import sdist_upip

with open("README.md", encoding="utf-8") as f:
long_description = f.read()
Expand All @@ -9,7 +8,6 @@


setup(
cmdclass={"sdist": sdist_upip.sdist},
name="micropython-uAPI",
packages=["uAPI"],
version=version,
Expand Down
47 changes: 14 additions & 33 deletions uAPI/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,14 +184,13 @@ def _swagger_ui(self) -> HTTPResponse:
"""
return HTTPResponse(data=_SWAGGER_UI_HTML, content_type="text/html")

async def _process_connection(self, connection: socket.socket):
async def _process_connection(self, reader, writer):
"""Processes a request on a new connection.

Args:
connection (socket.socket): The connection to process communication on.
"""

try:
request = connection.recv(8 * 1024).decode("ASCII")
request = await reader.read(8 * 1024)
request = request.decode()

lines = request.split("\r\n")
method, path, _ = lines[0].split(" ")
Expand Down Expand Up @@ -279,54 +278,36 @@ async def _process_connection(self, connection: socket.socket):
if not isinstance(result, HTTPResponse):
result = HTTPResponse(data=result)

connection.send(result.to_HTTP())
connection.close()
writer.write(result.to_HTTP())
return

except HTTPError as e:
connection.send(e.to_HTTP())
connection.close()
writer.write(e.to_HTTP())
return
except Exception as e:
error = HTTPError(500, str(e))
print(e)
connection.send(error.to_HTTP())
connection.close()
writer.write(error.to_HTTP())

async def run(self) -> None:
"""Runs the server while running is set to True. Also sets the running_variable to true.

Raises:
Exception: If the server is already running..
Exception: If the server is already running.
"""
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = socket.getaddrinfo("0.0.0.0", self.port)[0][-1]
self._socket.bind(addr)
self._socket.listen(5)
self.server = await asyncio.start_server(self._process_connection, "0.0.0.0", self.port)

if self.running:
raise Exception("The uAPI server is already running!")
self.running = True
self._stopped = False
# this allows other tasks to run in the background
self._socket.setblocking(False)
while self.running:
try:

async with self.server:
while True:
gc.collect()
conn, addr = self._socket.accept()
print("Got a connection from %s" % str(addr))
asyncio.create_task(self._process_connection(conn))
await asyncio.sleep_ms(100)
except:
# allow task change
await asyncio.sleep_ms(100)
self._stopped = False
self.running = False

async def stop(self) -> None:
"""Can be called as an blocking function that sets running to false and waits for the server to actually stop."""
await self.server.wait_closed()
self.running = False
while not self._stopped:
await asyncio.sleep_ms(100)

self._socket.close()
self._socket = None