Package: micropython-brainelectronics-helpers
MicroPython modulesCustom brainelectronics MicroPython helpers, modules and wrappersAboutThis is a collection of MicroPython modules required for the BE32-01 and other
brainelectronics projects.Available generatorsInstallationInstall required toolsSetupInstall packageGeneralSpecific versionTest versionManuallyGeneric HelperLED HelperOnboard LEDBasicsAdvancedNeopixelBasicsAdvancedModbus BridgePath HelperTime HelperWiFi HelperAvailable generatorsFor the individual usage of a helper, module or wrapper read the brief
description and usage instructions of each module.InstallationInstall required toolsPython3 must be installed on your system. Check the current Python version
with the following commandpython--version
python3--versionDepending on which commandPython 3.x.y(with x.y as some numbers) is
returned, use that command to proceed.python3-mvenv.venvsource.venv/bin/activate

pipinstall-rrequirements.txtSetupInstall packageConnect your MicroPython board to a networkimportnetworkstation=network.WLAN(network.STA_IF)station.active(True)station.connect('SSID','PASSWORD')station.isconnected()GeneralInstall the latest package version of this lib on the MicroPython deviceimportmipmip.install("github:brainelectronics/micropython-modules")For MicroPython versions below 1.19.1 use theupippackage instead ofmipimportupipupip.install('micropython-brainelectronics-helpers')Specific versionInstall a specific, fixed package version of this lib on the MicroPython deviceimportmip# install a verions of a specific branchmip.install("github:brainelectronics/micropython-modules",version="feature/support-mip")# install a tag versionmip.install("github:brainelectronics/micropython-modules",version="1.7.0")Test versionInstall a specific release candidate version uploaded toTest Python Package Indexon every PR on the
MicroPython device. If no specific version is set, the latest stable version
will be used.importmipmip.install("github:brainelectronics/micropython-modules",version="1.7.0-rc5.dev22")For MicroPython versions below 1.19.1 use theupippackage instead ofmipimportupip# overwrite index_urls to only take artifacts from test.pypi.orgupip.index_urls=['https://test.pypi.org/pypi']upip.install('micropython-brainelectronics-helpers')See alsobrainelectronics Test PyPi Server in Dockerfor a test PyPi server running on Docker.ManuallyCopy the module to the MicroPython board and import them as shown below
usingRemote MicroPython shellOpen the remote shell with the following command. Additionally use-b 115200in case no CP210x is used but a CH34x.rshell-p/dev/tty.SLAB_USBtoUART--editornanoPerform the following command to copy all files and folders to the devicemkdir/pyboard/lib
mkdir/pyboard/lib/be_helpers
cpbe_helpers/*/pyboard/lib/be_helpersInstall required dependencies (requires network connection, see may use theWifiHelper)Generic HelperGeneric helper class with different usecases and functions.frombe_helpers.generic_helperimportGenericHelper# get a random value between zero and 100 (inclusive)GenericHelper.get_random_value(0,100)# >>> 72# get amount of free disk space in kilobytesGenericHelper.df(path='/',unit='kb')# >>> '1984.000 kB'# get dict of free RAM with total, free and percentage usedGenericHelper.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 informationsGenericHelper.free(full=True)# >>> 'Total: 4006.1 kB, Free: 3992.56 kB (99.76%)'# interpret a string as dictionarysome_string="{'klaus': 123}"d=GenericHelper.str_to_dict(data=some_string)type(d)# >>> <class 'dict'># save a dictionary as JSON fileGenericHelper.save_json(path='/test.json',data=d)# load a JSON file as dictionaryread_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 modeGenericHelper.save_file(path='/test.txt',data=some_string,mode='w')# load the content of a file in non binary moderead_back_str=GenericHelper.load_file(path='/test.txt',mode='r')read_back_str# >>> "{'klaus': 123}"read_back_str==some_string# >>> TrueLED HelperHandle the onbaord LED on a BE32-01, ESP32 or ESP8266 as well as Neopixel LEDs.Onboard LEDThis example demonstrates how to interact with the onboard LED on the BE32-01BasicsThe 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:frombe_helpers.led_helperimportLedled=Led(led_pin="LED",inverted=False)frombe_helpers.led_helperimportLed# Onboard LED is availabe on Pin 4 on BE32-01 in inverted modeled=Led()print('Onboard LED is ON:{}'.format(led.on))# Onboard LED is ON: False# turn onboard LED onled.state=True# alternative way to turn onboard LED onled.turn_on()# turn onboard LED offled.state=False# alternative way to turn onboard LED offled.turn_off()# flash LED for 5 times, with 100ms delay between on and off states# this is blocking other actions until flashing operation finishedled.flash(amount=5,delay_ms=100)AdvancedOther (LED) pins can be used by specifiying them at the beginningfrombe_helpers.led_helperimportLed# LED at pin 12 will be active if pin is HIGHled=Led(led_pin=12,inverted=False)print('LED is ON:{}'.format(led.on))frombe_helpers.led_helperimportLed# Onboard LED is availabe on Pin 4 on BE32-01led=Led()print('LED is ON:{}'.format(led.on))# let LED blink in a seperate thread with 100ms between on and offled.blink(delay_ms=100)print('LED is blinking:{}'.format(led.blinking))# LED is blinking: True# stop the LED blinkingled.blinking=False# set different blinking delayprint('Current blinking delay:{}ms'.format(led.blink_delay))# Current blinking delay: 100msled.blink_delay=50# start blinking again (with 50ms delay)led.blinking=TrueNeopixelThis example demonstrates how to interact with the Neopixel LED on the BE32-01.BasicsThe one Neopixel LED is availabe on Pin 27 on the BE32-01 board.frombe_helpers.led_helperimportNeopixel# Neopixel is by default attached to Pin 27 on BE32-01pixel=Neopixel()print('Neopixel is active:{}'.format(pixel.active))# turn Neopixel red with 50/255 intensitypixel.red(50)# pixel.green(50)# pixel.blue(50)pixel.active=False# turn Neopixel off# get the current Neopixel colorprint('Neopixel color (RGB):{}'.format(pixel.color))# Neopixel color (RGB): [50, 0, 0]# get all available neopixel colorspixel.colors# >>> {'red': [30, 0, 0], 'green': [0, 30, 0], ...}# turn Neopixel yellowpixel.color='yellow'# get current intensity of Neopixelprint('Neopixel intensity:{}/255'.format(pixel.intensity))# Neopixel intensity: 30/255# reduce Neopixel intensity to 10/255pixel.intensity=10# turn Neopixel off, but remember last active colorpixel.clear()AdvancedOther Neopixel pin can be used by specifiying them at the beginningfrombe_helpers.led_helperimportNeopixel# Neopixel at pin 37 will be active if pin is HIGHpixel=Neopixel(neopixel_pin=37,neopixels=3)print('Neopixel is active:{}'.format(pixel.active))frombe_helpers.led_helperimportNeopixel# Neopixel is by default attached to Pin 27 on BE32-01pixel=Neopixel()# set custom RGB colorpixel.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 smoothpixel.fade(delay_ms=100)# stop the Neopixel fadingpixel.fading=False# set different fading delayprint('Current fading delay:{}ms'.format(pixel.fade_delay))# Current fading delay: 100mspixel.fade_delay=50# start fading again (with 50ms delay)pixel.fading=True# stop the Neopixel fadingpixel.fading=False# define a custom color and set the Neopixel to itpixel.colors={'DarlingColor':[26,3,18]}pixel.color='DarlingColor'Modbus BridgeThis requiresbrainelectronics MicroPython Modbus. Forked
and extended fromSFERALABS Exo Sense Py.Connect the board to a network and install the package like this for
MicroPython 1.20.0 or neverimportmipmip.install("github:brainelectronics/micropython-modbus")For MicroPython versions below 1.19.1 use theupippackage instead ofmipimportupipupip.install('micropython-modbus')importtimeimportmachinefrombe_helpers.modbus_bridgeimportModbusBridgeregister_file='registers/modbusRegisters-MyEVSE.json'rtu_pins=(25,26)# (TX, RX)tcp_port=180# TCP port for Modbus connectionrun_time=60# run this example for this amount of seconds# default level is 'warning', may use custom logger to get initial log datamb_bridge=ModbusBridge(register_file=register_file)# define and apply Modbus TCP host settingshost_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 clientmb_bridge.setup_connection(pins=rtu_pins)# (TX, RX)print('Modbus instances:')print('\tAct as Host:{}on{}'.format(mb_bridge.host,mb_bridge.host_unit))print('\tAct 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 provisionmb_bridge.collecting_client_data=Truemb_bridge.provisioning_host_data=Trueprint('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()whiletime.time()<(start_time+run_time):try:machine.idle()exceptKeyboardInterrupt:print('KeyboardInterrupt, stop collection + provisioning after{}'.format(time.time()-start_time))breakexceptExceptionase:print('Exception:{}'.format(e))# stop collecting latest client data in thread and data provision via TCPmb_bridge.collecting_client_data=Falsemb_bridge.provisioning_host_data=False# wait for 5 more seconds to safely finish the may still running threadstime.sleep(5)Path HelperMicroPython does not have anos.path.exists()function. This small module
adds this function.frombe_helpers.path_helperimportPathHelperpath='registers/modbusRegisters.json'result=PathHelper.exists(path=path)print('File at path "{}" does exist:{}'.format(path,result))Time Helperfrombe_helpers.time_helperimportTimeHelper# set the timezone offset to +2, default is +1th=TimeHelper(tz=2)# sync the RTC with the NTP server (valid network connection required)th.sync_time()# get current timestamp in ISO8601 formatth.current_timestamp_iso8601# >>> '21:23:55 2021-10-04'# get current hour from RTCth.hour# >>> 21WiFi Helperfrombe_helpers.wifi_helperimportWifiHelper# 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 NamedTuplestrongest_net=wh.networks[0].ssidprint('SSID of strongest network:{}'.format(strongest_net))# convert dBm (RRSI) to quality index in percentquality=WifiHelper.dbm_to_quality(dBm=wh.networks[0].RSSI)print('Quality of strongest network{}:{}%'.format(strongest_net,quality))