Skip to content

Commit

Permalink
Wikiupdate (#177)
Browse files Browse the repository at this point in the history
* Clarify app format

* Add internet connection wiki page

* Expand internet examples
  • Loading branch information
echo-lalia authored Nov 25, 2024
1 parent 8f3e5cd commit 2026074
Show file tree
Hide file tree
Showing 3 changed files with 135 additions and 24 deletions.
51 changes: 33 additions & 18 deletions wiki/App-Format.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,43 @@
## Format of MicroHydra apps:
MicroHydra apps can be placed in the apps folder on the device's main storage, or in the apps folder on an SD Card (The launcher will create these folders automatically if they don't exist.)

A MicroHydra app is basically just a MicroPython [module](https://docs.python.org/3/tutorial/modules.html) without an [import-guard](https://docs.python.org/3/library/__main__.html#name-main).
Apps can also (*optionally*) import and use MicroHydra modules, in order to simplify app development, or to integrate with core MicroHydra features.

<br/>

All that is needed to make a valid MicroHydra app, is a .py file *(or a compiled .mpy file)* with some MicroPython code placed in the apps folder.
The file name becomes the app name, and it will be imported by main.py when launched using MicroHydra.
This is the simplest form of a MH app, and several apps in the [apps](https://github.com/echo-lalia/MicroHydra-Apps) repo are designed like this.
### Basic App

All that is needed to make a valid MicroHydra app, is a .py file *(or a compiled .mpy file)* with some MicroPython code, placed in the apps folder.
The file name becomes the app name, and it will be imported by `main.py` when launched using MicroHydra.
This is the simplest form of an MH app, and several apps in the [community apps repo](https://github.com/echo-lalia/MicroHydra-Apps) are designed like this.

<br/>

Apps that are more complex can be made as a folder, instead. This can allow you to bundle in dependencies, or split the code up into multiple files for better readability. A MicroHydra app as a folder works essentially the same as a normal Python module, where a file named `__init__.py` inside that folder will be imported at launch.
### More Complex App

If you decide to format your app as a folder, you'll probably want to use 'relative' imports to access the other modules in the app folder.
However, relative imports don't work when running from the editor. My usual solution to this is to use both relative, and absolute imports, in a try/except statement. Here's what that looks like:
Apps that are more complex can be made as a folder, instead of a single file.
This can allow you to bundle in dependencies, or split the code up into multiple files for better organization.

``` Python
try:
# relative import for launching the app normally
from . import myothermodule
except:
# absolute path for launching from the editor (which causes the above to fail)
from apps.myappname import myothermodule
```
Inside your app's folder, you'll need an `__init__.py` file.
When your app is imported, `__init__.py` is the specific file that MicroPython will actually be importing on launch. From there, you can import any other modules you'd like.
*(This behavior is mostly identical to CPython)*

> **Note on relative imports**:
> *If you decide to format your app as a folder, you'll probably want to use 'relative' imports to access the other modules in the app folder.
> However, relative imports don't work when running directly from the editor. My usual solution to this is to just use both relative, and absolute imports, in a `try...except` statement. Here's what that looks like:*
> ``` Python
> try:
> # relative import for launching the app normally
> from . import myothermodule
> except ImportError:
> # absolute path for launching from the editor (which causes the above to fail)
> from apps.myappname import myothermodule
> ```
<br/><br/><br/>
## App Icons:
> Quick note:
> *The previous version of MicroHydra used a bizzare method of packing vectorized/polygonal icon definitions into a short string, which would be unpacked and executed by the launcher. This strategy was chosen for memory efficiency, but it felt awkward and is not used anymore. The script `polygon_to_raw_bmp.py` from the `tools/icons` folder has been written to convert these old polygon defs if needed.*
<br/>
**To put it simply:**
MicroHydra app icons are 32x32, 1bit, raw bitmaps (not bmp files) named `icon.raw`. Your app icon should be placed in the main directory of your app, alongside the `__init__.py` file.
Expand Down Expand Up @@ -65,3 +73,10 @@ The image can be any format supported by Pillow, and you can also specify other
python3 path/to/image_to_icon.py --output_file path/to/output_filename.raw --invert --preview path/to/your_image_file.png
```
*(use --help to see all options)*
<br/>
> Quick note on old MH icons:
> *The previous version of MicroHydra used a bizzare method of packing vectorized/polygonal icon definitions into a short string, which would be unpacked and executed by the launcher. This strategy was chosen for memory efficiency, but it felt awkward and is not used anymore. The script `polygon_to_raw_bmp.py` from the `tools/icons` folder has been written to convert these old polygon defs if needed.*
<br/>
14 changes: 8 additions & 6 deletions wiki/Home.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,15 @@
MicroHydra uses a few different ideas in order to output code for multiple devices. You can learn about this [here](https://github.com/echo-lalia/MicroHydra/wiki/multi-platform).
You can also learn more about the supported devices [here](https://github.com/echo-lalia/MicroHydra/wiki/Supported-Devices).

## Making Apps
For a basic overview of how MicroHydra apps work, see the [App Format](https://github.com/echo-lalia/MicroHydra/wiki/App-Format) section.

<br/>

## Making Apps
For a basic overview of how MicroHydra apps work, see the [App Format](https://github.com/echo-lalia/MicroHydra/wiki/App-Format) section.

## Lib

MicroHydra includes a built-in library, intended to help you easily make apps. Click on a module below to learn more about it.
### Lib:

----
MicroHydra includes a built-in library, intended to help you easily make apps, and integrate with core MicroHydra functionality. Click on a module below to learn more about it.


*MicroHydra*
Expand Down Expand Up @@ -53,3 +51,7 @@ MicroHydra includes a built-in library, intended to help you easily make apps. C
&nbsp; &nbsp; &nbsp; └── zipextractor
└── main

### Other Guides:
- Connecting to the internet

94 changes: 94 additions & 0 deletions wiki/Internet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
## Connecting to the internet

MicroPython's built-in [`network`](https://docs.micropython.org/en/latest/library/network.WLAN.html#network.WLAN) module makes it easy to connect to the internet on an ESP32 device.
You can also use MicroHydra's `hydra.config` module to easily access the user-set wifi configuration.

Here's a really simple script that connects to WiFi using these:

```Py
import network
from lib.hydra.config import Config

# Create the object for network control
nic = network.WLAN(network.STA_IF)
# Get the MicroHydra config
config = Config()

# Turn on the WiFi
if not nic.active():
nic.active(True)

# Connect to the user-set wifi network
if not nic.isconnected():
nic.connect(
config['wifi_ssid'],
config['wifi_pass'],
)
```

The `nic.connect` command doesn't block while waiting for a connection. So, your script will need to wait until the connection is made.
There can also be some unpredictable errors raised when calling the connection method.

Here's an example connection function that tries to handle these potential obsticals *(similar to the function used in `getapps.py`)*:
```Py
import time
import network
from lib.hydra.config import Config


nic = network.WLAN(network.STA_IF)
config = Config()


def connect_wifi():
"""Connect to the configured WiFi network."""
print("Enabling wifi...")

if not nic.active():
nic.active(True)

if not nic.isconnected():
# tell wifi to connect (with FORCE)
while True:
try: # keep trying until connect command works
nic.connect(config['wifi_ssid'], config['wifi_pass'])
break
except OSError as e:
print(f"Error: {e}")
time.sleep_ms(500)

# now wait until connected
attempts = 0
while not nic.isconnected():
print(f"connecting... {attempts}")
time.sleep_ms(500)
attempts += 1

print("Connected!")

connect_wifi()
```



## Getting Data From the Internet

MicroPython provides a lower-level [`socket`](https://docs.micropython.org/en/latest/library/socket.html#module-socket) module, but the easiest way to make internet requests in most cases is to use the other built-in [`requests`](https://github.com/micropython/micropython-lib/tree/e4cf09527bce7569f5db742cf6ae9db68d50c6a9/python-ecosys/requests) module.

Here's a super simple example that fetches a random cat fact from meowfacts.herokuapp.com:


```Py
import json
import requests

# Make a request to meowfacts
response = requests.get("https://meowfacts.herokuapp.com/")
# Verify that the request worked
if response.status_code != 200:
raise ValueError(f"Server returned {response.status_code}.\n{response.reason}")

# Decode the returned JSON data, and extract the random fact
fact = json.loads(response.content)['data'][0]
print(fact)
```

0 comments on commit 2026074

Please sign in to comment.