micropython-brainelectronics-helpers


Namemicropython-brainelectronics-helpers JSON
Version 1.7.0 PyPI version JSON
download
home_pagehttps://github.com/brainelectronics/micropython-modules
SummaryMicroPython brainelectronics helpers library
upload_time2023-05-27 10:52:02
maintainer
docs_urlNone
authorbrainelectronics
requires_python
licenseMIT
keywords micropython brainelectronics modules library
VCS
bugtrack_url
requirements rshell
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # MicroPython modules

[![Downloads](https://pepy.tech/badge/micropython-brainelectronics-helpers)](https://pepy.tech/project/micropython-brainelectronics-helpers)
![Release](https://img.shields.io/github/v/release/brainelectronics/micropython-modules?include_prereleases&color=success)
![MicroPython](https://img.shields.io/badge/micropython-Ok-green.svg)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![CI](https://github.com/brainelectronics/micropython-brainelectronics-helpers/actions/workflows/release.yml/badge.svg)](https://github.com/brainelectronics/micropython-brainelectronics-helpers/actions/workflows/release.yml)

Custom brainelectronics MicroPython helpers, modules and wrappers

---------------

## About

This is a collection of MicroPython modules required for the BE32-01 and other
brainelectronics projects.

<!-- MarkdownTOC -->

- [Available generators](#available-generators)
- [Installation](#installation)
    - [Install required tools](#install-required-tools)
- [Setup](#setup)
    - [Install package](#install-package)
        - [General](#general)
        - [Specific version](#specific-version)
        - [Test version](#test-version)
    - [Manually](#manually)
    - [Generic Helper](#generic-helper)
    - [LED Helper](#led-helper)
        - [Onboard LED](#onboard-led)
            - [Basics](#basics)
            - [Advanced](#advanced)
        - [Neopixel](#neopixel)
            - [Basics](#basics-1)
            - [Advanced](#advanced-1)
    - [Modbus Bridge](#modbus-bridge)
    - [Path Helper](#path-helper)
    - [Time Helper](#time-helper)
    - [WiFi Helper](#wifi-helper)

<!-- /MarkdownTOC -->

## Available generators

For the individual usage of a helper, module or wrapper read the brief
description and usage instructions of each module.

## Installation

### Install required tools

Python3 must be installed on your system. Check the current Python version
with the following command

```bash
python --version
python3 --version
```

Depending on which command `Python 3.x.y` (with x.y as some numbers) is
returned, use that command to proceed.

```bash
python3 -m venv .venv
source .venv/bin/activate

pip install -r requirements.txt
```

## Setup

### Install package

Connect your MicroPython board to a network

```python
import network
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect('SSID', 'PASSWORD')
station.isconnected()
```

#### General

Install the latest package version of this lib on the MicroPython device

```python
import mip
mip.install("github:brainelectronics/micropython-modules")
```

For MicroPython versions below 1.19.1 use the `upip` package instead of `mip`

```python
import upip
upip.install('micropython-brainelectronics-helpers')
```

#### Specific version

Install a specific, fixed package version of this lib on the MicroPython device

```python
import mip
# install a verions of a specific branch
mip.install("github:brainelectronics/micropython-modules", version="feature/support-mip")
# install a tag version
mip.install("github:brainelectronics/micropython-modules", version="1.7.0")
```

#### Test version

Install a specific release candidate version uploaded to
[Test Python Package Index](https://test.pypi.org/) on every PR on the
MicroPython device. If no specific version is set, the latest stable version
will be used.

```python
import mip
mip.install("github:brainelectronics/micropython-modules", version="1.7.0-rc5.dev22")
```

For MicroPython versions below 1.19.1 use the `upip` package instead of `mip`

```python
import upip
# overwrite index_urls to only take artifacts from test.pypi.org
upip.index_urls = ['https://test.pypi.org/pypi']
upip.install('micropython-brainelectronics-helpers')
```

See also [brainelectronics Test PyPi Server in Docker][ref-brainelectronics-test-pypiserver]
for a test PyPi server running on Docker.

### Manually

Copy the module to the MicroPython board and import them as shown below
using [Remote MicroPython shell][ref-remote-upy-shell]

Open the remote shell with the following command. Additionally use `-b 115200`
in case no CP210x is used but a CH34x.

```bash
rshell -p /dev/tty.SLAB_USBtoUART --editor nano
```

Perform the following command to copy all files and folders to the device

```bash
mkdir /pyboard/lib
mkdir /pyboard/lib/be_helpers
cp be_helpers/* /pyboard/lib/be_helpers
```

Install required dependencies (requires network connection, see may use the
[`WifiHelper`][ref-wifi-helper])

### Generic Helper

Generic helper class with different usecases and functions.

```python
from be_helpers.generic_helper import GenericHelper

# get a random value between zero and 100 (inclusive)
GenericHelper.get_random_value(0, 100)
# >>> 72

# get amount of free disk space in kilobytes
GenericHelper.df(path='/', unit='kb')
# >>> '1984.000 kB'

# get dict of free RAM with total, free and percentage used
GenericHelper.get_free_memory()
# >>> {'percentage': '99.76%', 'total': 4098240, 'free': 4088400}

# get UUID of default length, might be different on PyCOM, MicroPython, ...
GenericHelper.get_uuid()
# >>> b'308398d9eefc'
# GenericHelper.get_uuid(length=18)
# >>> b'308398d9eefc308398'

# get detailed info (full == True) RAM informations
GenericHelper.free(full=True)
# >>> 'Total: 4006.1 kB, Free: 3992.56 kB (99.76%)'

# interpret a string as dictionary
some_string = "{'klaus': 123}"
d = GenericHelper.str_to_dict(data=some_string)
type(d)
# >>> <class 'dict'>

# save a dictionary as JSON file
GenericHelper.save_json(path='/test.json', data=d)

# load a JSON file as dictionary
read_back_dict = GenericHelper.load_json(path='/test.json')
read_back_dict
# >>> {'klaus': 123}

read_back_dict == d
# >>> True

# save a string to file in non binary mode
GenericHelper.save_file(path='/test.txt', data=some_string, mode='w')

# load the content of a file in non binary mode
read_back_str = GenericHelper.load_file(path='/test.txt', mode='r')
read_back_str
# >>> "{'klaus': 123}"

read_back_str == some_string
# >>> True
```

### LED Helper

Handle the onbaord LED on a BE32-01, ESP32 or ESP8266 as well as Neopixel LEDs.

#### Onboard LED

This example demonstrates how to interact with the onboard LED on the BE32-01

##### Basics

The onboard LED is availabe on Pin 4 on the BE32-01 board in inverted mode.
For the Raspberry Pi Pico (W) initialise the LED like this:
```python
from be_helpers.led_helper import Led
led = Led(led_pin="LED", inverted=False)
```

```python
from be_helpers.led_helper import Led

# Onboard LED is availabe on Pin 4 on BE32-01 in inverted mode
led = Led()
print('Onboard LED is ON: {}'.format(led.on))
# Onboard LED is ON: False

# turn onboard LED on
led.state = True

# alternative way to turn onboard LED on
led.turn_on()

# turn onboard LED off
led.state = False

# alternative way to turn onboard LED off
led.turn_off()

# flash LED for 5 times, with 100ms delay between on and off states
# this is blocking other actions until flashing operation finished
led.flash(amount=5, delay_ms=100)
```

##### Advanced

Other (LED) pins can be used by specifiying them at the beginning

```python
from be_helpers.led_helper import Led

# LED at pin 12 will be active if pin is HIGH
led = Led(led_pin=12, inverted=False)
print('LED is ON: {}'.format(led.on))
```

```python
from be_helpers.led_helper import Led

# Onboard LED is availabe on Pin 4 on BE32-01
led = Led()
print('LED is ON: {}'.format(led.on))

# let LED blink in a seperate thread with 100ms between on and off
led.blink(delay_ms=100)
print('LED is blinking: {}'.format(led.blinking))
# LED is blinking: True

# stop the LED blinking
led.blinking = False

# set different blinking delay
print('Current blinking delay: {}ms'.format(led.blink_delay))
# Current blinking delay: 100ms
led.blink_delay = 50

# start blinking again (with 50ms delay)
led.blinking = True
```

#### Neopixel

This example demonstrates how to interact with the Neopixel LED on the BE32-01.

##### Basics

The one Neopixel LED is availabe on Pin 27 on the BE32-01 board.

```python
from be_helpers.led_helper import Neopixel

# Neopixel is by default attached to Pin 27 on BE32-01
pixel = Neopixel()
print('Neopixel is active: {}'.format(pixel.active))

# turn Neopixel red with 50/255 intensity
pixel.red(50)
# pixel.green(50)
# pixel.blue(50)

pixel.active = False
# turn Neopixel off

# get the current Neopixel color
print('Neopixel color (RGB): {}'.format(pixel.color))
# Neopixel color (RGB): [50, 0, 0]

# get all available neopixel colors
pixel.colors
# >>> {'red': [30, 0, 0], 'green': [0, 30, 0], ...}

# turn Neopixel yellow
pixel.color = 'yellow'

# get current intensity of Neopixel
print('Neopixel intensity: {}/255'.format(pixel.intensity))
# Neopixel intensity: 30/255

# reduce Neopixel intensity to 10/255
pixel.intensity = 10

# turn Neopixel off, but remember last active color
pixel.clear()
```

##### Advanced

Other Neopixel pin can be used by specifiying them at the beginning

```python
from be_helpers.led_helper import Neopixel

# Neopixel at pin 37 will be active if pin is HIGH
pixel = Neopixel(neopixel_pin=37, neopixels=3)
print('Neopixel is active: {}'.format(pixel.active))
```

```python
from be_helpers.led_helper import Neopixel

# Neopixel is by default attached to Pin 27 on BE32-01
pixel = Neopixel()

# set custom RGB color
pixel.set(rgb=[10, 20, 30])

# let Neopixel fade the currently set color in a seperate thread with 100ms
# between intensity changes, 50ms is default and quite smooth
pixel.fade(delay_ms=100)

# stop the Neopixel fading
pixel.fading = False

# set different fading delay
print('Current fading delay: {}ms'.format(pixel.fade_delay))
# Current fading delay: 100ms
pixel.fade_delay = 50

# start fading again (with 50ms delay)
pixel.fading = True

# stop the Neopixel fading
pixel.fading = False

# define a custom color and set the Neopixel to it
pixel.colors = {'DarlingColor': [26, 3, 18]}
pixel.color = 'DarlingColor'
```

### Modbus Bridge

This requires [brainelectronics MicroPython Modbus][ref-be-upy-modbus]. Forked
and extended from [SFERALABS Exo Sense Py][ref-sferalabs-exo-sense].

Connect the board to a network and install the package like this for
MicroPython 1.20.0 or never

```python
import mip
mip.install("github:brainelectronics/micropython-modbus")
```

For MicroPython versions below 1.19.1 use the `upip` package instead of `mip`

```python
import upip
upip.install('micropython-modbus')
```

```python
import time
import machine

from be_helpers.modbus_bridge import ModbusBridge

register_file = 'registers/modbusRegisters-MyEVSE.json'
rtu_pins = (25, 26)     # (TX, RX)
tcp_port = 180          # TCP port for Modbus connection
run_time = 60           # run this example for this amount of seconds

# default level is 'warning', may use custom logger to get initial log data
mb_bridge = ModbusBridge(register_file=register_file)

# define and apply Modbus TCP host settings
host_settings = {
    'type': 'tcp',
    'unit': tcp_port,
    'address': -1,
    'baudrate': -1,
    'mode': 'master'
}
mb_bridge.connection_settings_host = host_settings

# setup Modbus connections to host and client
mb_bridge.setup_connection(pins=rtu_pins)   # (TX, RX)

print('Modbus instances:')
print('\t Act as Host: {} on {}'.format(mb_bridge.host, mb_bridge.host_unit))
print('\t Act as Client: {} on {}'.format(mb_bridge.client, mb_bridge.client_unit))

# readout the client registers once manually
# mb_bridge.read_all_registers()

# start collecting latest RTU client data in thread and TCP data provision
mb_bridge.collecting_client_data = True
mb_bridge.provisioning_host_data = True

print('Run client and host for {} seconds'.format(run_time))
print('Collect latest client data every {} seconds'.format(mb_bridge.collection_interval))
print('Synchronize Host-Client every {} seconds'.format(mb_bridge.synchronisation_interval))

start_time = time.time()
while time.time() < (start_time + run_time):
    try:
        machine.idle()
    except KeyboardInterrupt:
        print('KeyboardInterrupt, stop collection + provisioning after {}'.
              format(time.time() - start_time))
        break
    except Exception as e:
        print('Exception: {}'.format(e))

# stop collecting latest client data in thread and data provision via TCP
mb_bridge.collecting_client_data = False
mb_bridge.provisioning_host_data = False

# wait for 5 more seconds to safely finish the may still running threads
time.sleep(5)
```

### Path Helper

MicroPython does not have an `os.path.exists()` function. This small module
adds this function.

```python
from be_helpers.path_helper import PathHelper

path = 'registers/modbusRegisters.json'
result = PathHelper.exists(path=path)
print('File at path "{}" does exist: {}'.format(path, result))
```

### Time Helper

```python
from be_helpers.time_helper import TimeHelper

# set the timezone offset to +2, default is +1
th = TimeHelper(tz=2)

# sync the RTC with the NTP server (valid network connection required)
th.sync_time()

# get current timestamp in ISO8601 format
th.current_timestamp_iso8601
# >>> '21:23:55 2021-10-04'

# get current hour from RTC
th.hour
# >>> 21
```

### WiFi Helper

```python
from be_helpers.wifi_helper import WifiHelper

# connect to the network 'MyNet' and it's password 'realPassword1'
result = WifiHelper.connect(ssid='MyNet', password='realPassword1', timedout=3)
print('Connection result is: {}'.format(result))

# create an accesspoint named 'MyAP' with a password 'wpa_wpa2_valid_pw'
result = WifiHelper.create_ap(ssid='MyAP', password='wpa_wpa2_valid_pw', channel=10)
print('AP creation result is: {}'.format(result))

wh = WifiHelper()
found_networks = wh.get_wifi_networks_sorted(scan_if_empty=True)
print('Found these networks: {}'.format(found_networks))

# after a scan the networks are available as list of NamedTuple
strongest_net = wh.networks[0].ssid
print('SSID of strongest network: {}'.format(strongest_net))

# convert dBm (RRSI) to quality index in percent
quality = WifiHelper.dbm_to_quality(dBm=wh.networks[0].RSSI)
print('Quality of strongest network {}: {}%'.format(strongest_net, quality))
```

<!-- Links -->
[ref-remote-upy-shell]: https://github.com/dhylands/rshell
[ref-brainelectronics-test-pypiserver]: https://github.com/brainelectronics/test-pypiserver
[ref-wifi-helper]: wifi_helper.py
[ref-be-upy-modbus]: https://github.com/brainelectronics/micropython-modbus
[ref-sferalabs-exo-sense]: https://github.com/sfera-labs/exo-sense-py-modbus



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/brainelectronics/micropython-modules",
    "name": "micropython-brainelectronics-helpers",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "micropython,brainelectronics,modules,library",
    "author": "brainelectronics",
    "author_email": "info@brainelectronics.de",
    "download_url": "https://files.pythonhosted.org/packages/fe/74/6d483ff5d8ab1f8116ae7720501698484c31e590a05e70197ad69cee159f/micropython-brainelectronics-helpers-1.7.0.tar.gz",
    "platform": null,
    "description": "# MicroPython modules\n\n[![Downloads](https://pepy.tech/badge/micropython-brainelectronics-helpers)](https://pepy.tech/project/micropython-brainelectronics-helpers)\n![Release](https://img.shields.io/github/v/release/brainelectronics/micropython-modules?include_prereleases&color=success)\n![MicroPython](https://img.shields.io/badge/micropython-Ok-green.svg)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![CI](https://github.com/brainelectronics/micropython-brainelectronics-helpers/actions/workflows/release.yml/badge.svg)](https://github.com/brainelectronics/micropython-brainelectronics-helpers/actions/workflows/release.yml)\n\nCustom brainelectronics MicroPython helpers, modules and wrappers\n\n---------------\n\n## About\n\nThis is a collection of MicroPython modules required for the BE32-01 and other\nbrainelectronics projects.\n\n<!-- MarkdownTOC -->\n\n- [Available generators](#available-generators)\n- [Installation](#installation)\n    - [Install required tools](#install-required-tools)\n- [Setup](#setup)\n    - [Install package](#install-package)\n        - [General](#general)\n        - [Specific version](#specific-version)\n        - [Test version](#test-version)\n    - [Manually](#manually)\n    - [Generic Helper](#generic-helper)\n    - [LED Helper](#led-helper)\n        - [Onboard LED](#onboard-led)\n            - [Basics](#basics)\n            - [Advanced](#advanced)\n        - [Neopixel](#neopixel)\n            - [Basics](#basics-1)\n            - [Advanced](#advanced-1)\n    - [Modbus Bridge](#modbus-bridge)\n    - [Path Helper](#path-helper)\n    - [Time Helper](#time-helper)\n    - [WiFi Helper](#wifi-helper)\n\n<!-- /MarkdownTOC -->\n\n## Available generators\n\nFor the individual usage of a helper, module or wrapper read the brief\ndescription and usage instructions of each module.\n\n## Installation\n\n### Install required tools\n\nPython3 must be installed on your system. Check the current Python version\nwith the following command\n\n```bash\npython --version\npython3 --version\n```\n\nDepending on which command `Python 3.x.y` (with x.y as some numbers) is\nreturned, use that command to proceed.\n\n```bash\npython3 -m venv .venv\nsource .venv/bin/activate\n\npip install -r requirements.txt\n```\n\n## Setup\n\n### Install package\n\nConnect your MicroPython board to a network\n\n```python\nimport network\nstation = network.WLAN(network.STA_IF)\nstation.active(True)\nstation.connect('SSID', 'PASSWORD')\nstation.isconnected()\n```\n\n#### General\n\nInstall the latest package version of this lib on the MicroPython device\n\n```python\nimport mip\nmip.install(\"github:brainelectronics/micropython-modules\")\n```\n\nFor MicroPython versions below 1.19.1 use the `upip` package instead of `mip`\n\n```python\nimport upip\nupip.install('micropython-brainelectronics-helpers')\n```\n\n#### Specific version\n\nInstall a specific, fixed package version of this lib on the MicroPython device\n\n```python\nimport mip\n# install a verions of a specific branch\nmip.install(\"github:brainelectronics/micropython-modules\", version=\"feature/support-mip\")\n# install a tag version\nmip.install(\"github:brainelectronics/micropython-modules\", version=\"1.7.0\")\n```\n\n#### Test version\n\nInstall a specific release candidate version uploaded to\n[Test Python Package Index](https://test.pypi.org/) on every PR on the\nMicroPython device. If no specific version is set, the latest stable version\nwill be used.\n\n```python\nimport mip\nmip.install(\"github:brainelectronics/micropython-modules\", version=\"1.7.0-rc5.dev22\")\n```\n\nFor MicroPython versions below 1.19.1 use the `upip` package instead of `mip`\n\n```python\nimport upip\n# overwrite index_urls to only take artifacts from test.pypi.org\nupip.index_urls = ['https://test.pypi.org/pypi']\nupip.install('micropython-brainelectronics-helpers')\n```\n\nSee also [brainelectronics Test PyPi Server in Docker][ref-brainelectronics-test-pypiserver]\nfor a test PyPi server running on Docker.\n\n### Manually\n\nCopy the module to the MicroPython board and import them as shown below\nusing [Remote MicroPython shell][ref-remote-upy-shell]\n\nOpen the remote shell with the following command. Additionally use `-b 115200`\nin case no CP210x is used but a CH34x.\n\n```bash\nrshell -p /dev/tty.SLAB_USBtoUART --editor nano\n```\n\nPerform the following command to copy all files and folders to the device\n\n```bash\nmkdir /pyboard/lib\nmkdir /pyboard/lib/be_helpers\ncp be_helpers/* /pyboard/lib/be_helpers\n```\n\nInstall required dependencies (requires network connection, see may use the\n[`WifiHelper`][ref-wifi-helper])\n\n### Generic Helper\n\nGeneric helper class with different usecases and functions.\n\n```python\nfrom be_helpers.generic_helper import GenericHelper\n\n# get a random value between zero and 100 (inclusive)\nGenericHelper.get_random_value(0, 100)\n# >>> 72\n\n# get amount of free disk space in kilobytes\nGenericHelper.df(path='/', unit='kb')\n# >>> '1984.000 kB'\n\n# get dict of free RAM with total, free and percentage used\nGenericHelper.get_free_memory()\n# >>> {'percentage': '99.76%', 'total': 4098240, 'free': 4088400}\n\n# get UUID of default length, might be different on PyCOM, MicroPython, ...\nGenericHelper.get_uuid()\n# >>> b'308398d9eefc'\n# GenericHelper.get_uuid(length=18)\n# >>> b'308398d9eefc308398'\n\n# get detailed info (full == True) RAM informations\nGenericHelper.free(full=True)\n# >>> 'Total: 4006.1 kB, Free: 3992.56 kB (99.76%)'\n\n# interpret a string as dictionary\nsome_string = \"{'klaus': 123}\"\nd = GenericHelper.str_to_dict(data=some_string)\ntype(d)\n# >>> <class 'dict'>\n\n# save a dictionary as JSON file\nGenericHelper.save_json(path='/test.json', data=d)\n\n# load a JSON file as dictionary\nread_back_dict = GenericHelper.load_json(path='/test.json')\nread_back_dict\n# >>> {'klaus': 123}\n\nread_back_dict == d\n# >>> True\n\n# save a string to file in non binary mode\nGenericHelper.save_file(path='/test.txt', data=some_string, mode='w')\n\n# load the content of a file in non binary mode\nread_back_str = GenericHelper.load_file(path='/test.txt', mode='r')\nread_back_str\n# >>> \"{'klaus': 123}\"\n\nread_back_str == some_string\n# >>> True\n```\n\n### LED Helper\n\nHandle the onbaord LED on a BE32-01, ESP32 or ESP8266 as well as Neopixel LEDs.\n\n#### Onboard LED\n\nThis example demonstrates how to interact with the onboard LED on the BE32-01\n\n##### Basics\n\nThe onboard LED is availabe on Pin 4 on the BE32-01 board in inverted mode.\nFor the Raspberry Pi Pico (W) initialise the LED like this:\n```python\nfrom be_helpers.led_helper import Led\nled = Led(led_pin=\"LED\", inverted=False)\n```\n\n```python\nfrom be_helpers.led_helper import Led\n\n# Onboard LED is availabe on Pin 4 on BE32-01 in inverted mode\nled = Led()\nprint('Onboard LED is ON: {}'.format(led.on))\n# Onboard LED is ON: False\n\n# turn onboard LED on\nled.state = True\n\n# alternative way to turn onboard LED on\nled.turn_on()\n\n# turn onboard LED off\nled.state = False\n\n# alternative way to turn onboard LED off\nled.turn_off()\n\n# flash LED for 5 times, with 100ms delay between on and off states\n# this is blocking other actions until flashing operation finished\nled.flash(amount=5, delay_ms=100)\n```\n\n##### Advanced\n\nOther (LED) pins can be used by specifiying them at the beginning\n\n```python\nfrom be_helpers.led_helper import Led\n\n# LED at pin 12 will be active if pin is HIGH\nled = Led(led_pin=12, inverted=False)\nprint('LED is ON: {}'.format(led.on))\n```\n\n```python\nfrom be_helpers.led_helper import Led\n\n# Onboard LED is availabe on Pin 4 on BE32-01\nled = Led()\nprint('LED is ON: {}'.format(led.on))\n\n# let LED blink in a seperate thread with 100ms between on and off\nled.blink(delay_ms=100)\nprint('LED is blinking: {}'.format(led.blinking))\n# LED is blinking: True\n\n# stop the LED blinking\nled.blinking = False\n\n# set different blinking delay\nprint('Current blinking delay: {}ms'.format(led.blink_delay))\n# Current blinking delay: 100ms\nled.blink_delay = 50\n\n# start blinking again (with 50ms delay)\nled.blinking = True\n```\n\n#### Neopixel\n\nThis example demonstrates how to interact with the Neopixel LED on the BE32-01.\n\n##### Basics\n\nThe one Neopixel LED is availabe on Pin 27 on the BE32-01 board.\n\n```python\nfrom be_helpers.led_helper import Neopixel\n\n# Neopixel is by default attached to Pin 27 on BE32-01\npixel = Neopixel()\nprint('Neopixel is active: {}'.format(pixel.active))\n\n# turn Neopixel red with 50/255 intensity\npixel.red(50)\n# pixel.green(50)\n# pixel.blue(50)\n\npixel.active = False\n# turn Neopixel off\n\n# get the current Neopixel color\nprint('Neopixel color (RGB): {}'.format(pixel.color))\n# Neopixel color (RGB): [50, 0, 0]\n\n# get all available neopixel colors\npixel.colors\n# >>> {'red': [30, 0, 0], 'green': [0, 30, 0], ...}\n\n# turn Neopixel yellow\npixel.color = 'yellow'\n\n# get current intensity of Neopixel\nprint('Neopixel intensity: {}/255'.format(pixel.intensity))\n# Neopixel intensity: 30/255\n\n# reduce Neopixel intensity to 10/255\npixel.intensity = 10\n\n# turn Neopixel off, but remember last active color\npixel.clear()\n```\n\n##### Advanced\n\nOther Neopixel pin can be used by specifiying them at the beginning\n\n```python\nfrom be_helpers.led_helper import Neopixel\n\n# Neopixel at pin 37 will be active if pin is HIGH\npixel = Neopixel(neopixel_pin=37, neopixels=3)\nprint('Neopixel is active: {}'.format(pixel.active))\n```\n\n```python\nfrom be_helpers.led_helper import Neopixel\n\n# Neopixel is by default attached to Pin 27 on BE32-01\npixel = Neopixel()\n\n# set custom RGB color\npixel.set(rgb=[10, 20, 30])\n\n# let Neopixel fade the currently set color in a seperate thread with 100ms\n# between intensity changes, 50ms is default and quite smooth\npixel.fade(delay_ms=100)\n\n# stop the Neopixel fading\npixel.fading = False\n\n# set different fading delay\nprint('Current fading delay: {}ms'.format(pixel.fade_delay))\n# Current fading delay: 100ms\npixel.fade_delay = 50\n\n# start fading again (with 50ms delay)\npixel.fading = True\n\n# stop the Neopixel fading\npixel.fading = False\n\n# define a custom color and set the Neopixel to it\npixel.colors = {'DarlingColor': [26, 3, 18]}\npixel.color = 'DarlingColor'\n```\n\n### Modbus Bridge\n\nThis requires [brainelectronics MicroPython Modbus][ref-be-upy-modbus]. Forked\nand extended from [SFERALABS Exo Sense Py][ref-sferalabs-exo-sense].\n\nConnect the board to a network and install the package like this for\nMicroPython 1.20.0 or never\n\n```python\nimport mip\nmip.install(\"github:brainelectronics/micropython-modbus\")\n```\n\nFor MicroPython versions below 1.19.1 use the `upip` package instead of `mip`\n\n```python\nimport upip\nupip.install('micropython-modbus')\n```\n\n```python\nimport time\nimport machine\n\nfrom be_helpers.modbus_bridge import ModbusBridge\n\nregister_file = 'registers/modbusRegisters-MyEVSE.json'\nrtu_pins = (25, 26)     # (TX, RX)\ntcp_port = 180          # TCP port for Modbus connection\nrun_time = 60           # run this example for this amount of seconds\n\n# default level is 'warning', may use custom logger to get initial log data\nmb_bridge = ModbusBridge(register_file=register_file)\n\n# define and apply Modbus TCP host settings\nhost_settings = {\n    'type': 'tcp',\n    'unit': tcp_port,\n    'address': -1,\n    'baudrate': -1,\n    'mode': 'master'\n}\nmb_bridge.connection_settings_host = host_settings\n\n# setup Modbus connections to host and client\nmb_bridge.setup_connection(pins=rtu_pins)   # (TX, RX)\n\nprint('Modbus instances:')\nprint('\\t Act as Host: {} on {}'.format(mb_bridge.host, mb_bridge.host_unit))\nprint('\\t Act as Client: {} on {}'.format(mb_bridge.client, mb_bridge.client_unit))\n\n# readout the client registers once manually\n# mb_bridge.read_all_registers()\n\n# start collecting latest RTU client data in thread and TCP data provision\nmb_bridge.collecting_client_data = True\nmb_bridge.provisioning_host_data = True\n\nprint('Run client and host for {} seconds'.format(run_time))\nprint('Collect latest client data every {} seconds'.format(mb_bridge.collection_interval))\nprint('Synchronize Host-Client every {} seconds'.format(mb_bridge.synchronisation_interval))\n\nstart_time = time.time()\nwhile time.time() < (start_time + run_time):\n    try:\n        machine.idle()\n    except KeyboardInterrupt:\n        print('KeyboardInterrupt, stop collection + provisioning after {}'.\n              format(time.time() - start_time))\n        break\n    except Exception as e:\n        print('Exception: {}'.format(e))\n\n# stop collecting latest client data in thread and data provision via TCP\nmb_bridge.collecting_client_data = False\nmb_bridge.provisioning_host_data = False\n\n# wait for 5 more seconds to safely finish the may still running threads\ntime.sleep(5)\n```\n\n### Path Helper\n\nMicroPython does not have an `os.path.exists()` function. This small module\nadds this function.\n\n```python\nfrom be_helpers.path_helper import PathHelper\n\npath = 'registers/modbusRegisters.json'\nresult = PathHelper.exists(path=path)\nprint('File at path \"{}\" does exist: {}'.format(path, result))\n```\n\n### Time Helper\n\n```python\nfrom be_helpers.time_helper import TimeHelper\n\n# set the timezone offset to +2, default is +1\nth = TimeHelper(tz=2)\n\n# sync the RTC with the NTP server (valid network connection required)\nth.sync_time()\n\n# get current timestamp in ISO8601 format\nth.current_timestamp_iso8601\n# >>> '21:23:55 2021-10-04'\n\n# get current hour from RTC\nth.hour\n# >>> 21\n```\n\n### WiFi Helper\n\n```python\nfrom be_helpers.wifi_helper import WifiHelper\n\n# connect to the network 'MyNet' and it's password 'realPassword1'\nresult = WifiHelper.connect(ssid='MyNet', password='realPassword1', timedout=3)\nprint('Connection result is: {}'.format(result))\n\n# create an accesspoint named 'MyAP' with a password 'wpa_wpa2_valid_pw'\nresult = WifiHelper.create_ap(ssid='MyAP', password='wpa_wpa2_valid_pw', channel=10)\nprint('AP creation result is: {}'.format(result))\n\nwh = WifiHelper()\nfound_networks = wh.get_wifi_networks_sorted(scan_if_empty=True)\nprint('Found these networks: {}'.format(found_networks))\n\n# after a scan the networks are available as list of NamedTuple\nstrongest_net = wh.networks[0].ssid\nprint('SSID of strongest network: {}'.format(strongest_net))\n\n# convert dBm (RRSI) to quality index in percent\nquality = WifiHelper.dbm_to_quality(dBm=wh.networks[0].RSSI)\nprint('Quality of strongest network {}: {}%'.format(strongest_net, quality))\n```\n\n<!-- Links -->\n[ref-remote-upy-shell]: https://github.com/dhylands/rshell\n[ref-brainelectronics-test-pypiserver]: https://github.com/brainelectronics/test-pypiserver\n[ref-wifi-helper]: wifi_helper.py\n[ref-be-upy-modbus]: https://github.com/brainelectronics/micropython-modbus\n[ref-sferalabs-exo-sense]: https://github.com/sfera-labs/exo-sense-py-modbus\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "MicroPython brainelectronics helpers library",
    "version": "1.7.0",
    "project_urls": {
        "Bug Reports": "https://github.com/brainelectronics/micropython-modules/issues",
        "Homepage": "https://github.com/brainelectronics/micropython-modules",
        "Source": "https://github.com/brainelectronics/micropython-modules"
    },
    "split_keywords": [
        "micropython",
        "brainelectronics",
        "modules",
        "library"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fe746d483ff5d8ab1f8116ae7720501698484c31e590a05e70197ad69cee159f",
                "md5": "17d5a6cd0565ed9358c83f19ede81cc6",
                "sha256": "eae17ac82cf04d3520ccc567217b164d8563037de98b07b271d5d8728078f567"
            },
            "downloads": -1,
            "filename": "micropython-brainelectronics-helpers-1.7.0.tar.gz",
            "has_sig": false,
            "md5_digest": "17d5a6cd0565ed9358c83f19ede81cc6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 32391,
            "upload_time": "2023-05-27T10:52:02",
            "upload_time_iso_8601": "2023-05-27T10:52:02.077724Z",
            "url": "https://files.pythonhosted.org/packages/fe/74/6d483ff5d8ab1f8116ae7720501698484c31e590a05e70197ad69cee159f/micropython-brainelectronics-helpers-1.7.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-27 10:52:02",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "brainelectronics",
    "github_project": "micropython-modules",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "rshell",
            "specs": [
                [
                    ">=",
                    "0.0.30"
                ],
                [
                    "<",
                    "1.0.0"
                ]
            ]
        }
    ],
    "lcname": "micropython-brainelectronics-helpers"
}
        
Elapsed time: 0.09423s