Author Archives: Marc

m2ag-thing-builder alpha 6

January 23, 2021

The m2ag.labs thing builder has reached alpha 6. The jump in the number from 3 to 6 is because of some fast rework for the client, thing builder and modules. The installer currently installs functional code and several modules are available for download and use. This will be the last alpha before beta 1.

The biggest changes are:


  • The custom web components I had built for use on the config page ( service controllers and component map) have been replaced with vue.js components. Custom components are too hard to maintain, so vue is the way to go.
  • Even though vue.js is being used, there are still no build steps needed to modify the the client. The vue components that were created are for interfacing with the back end flask api, and not geared towards using with things.
  • Where ever possible jquery has been eliminated and vanilla javascript used. Bootstrap 4 and the jstree component still require jquery so it is still included. The goal is to completely eliminate jquery by transitioning to bootstrap 5 and a vue js version of jstree.

Thing Builder:

  • JWT authentication for thing access
  • generic classes for i2c devices and things
  • nginx to serve api, client and proxy other services (for example: provide internal ssl for the webthings gateway and use of pagekite).


  • Has been updated to install the current code. Text on Raspbian Full and Lite with the latest updates. Tested on a Raspberry PI 3 B+ but should work without issue on all current Raspberry PI (previous versions of framework are running on Pi Zeros and PI 3 A).
  • Extras installers for Node (arm7 only for now) and a lite version of the gateway.
  • Not all extras are ready, check the for each one


Several things and related components are available for download and use now. These include:

  • airnow – a thing that monitors air quality. An airnow api key is required
  • alert – a method of sounding a buzzer
  • bmp280 – a wrapper for adafruit’s circuitpython driver
  • buttons – an example for using buttons and events
  • htu21d – a wrapper for adafruit’s circuitpython driver
  • lis3dh – a wrapper for adafruit’s circuitpython driver that overrides the the generic i2c wrapper class to return x, y, z acceleration
  • raspi – a system monitor for Raspberry pi
  • veml7700 – a wrapper for adafruit’s circuitpython driver

Check the of each module.

Documentation and how to guides are the immediate focus, as well as adding more things.

Air Quality Sensor

Source code is on github. Ceramic cap is 104M, base resistor is 500 ohms, switch resistor is 1k. Electrolytic is 47 micro-farad

With the recent wildfires here in California and the on-going Covid crisis making us all stay indoors, indoor air quality has become a very important consideration. Working in a back bedroom all day can subject you to some really bad air. Mostly volatile organic compounds — you know the stuff that smells — can build up and make a room unhealthy.

What I want, ultimately, is to monitor the indoor and outdoor air quality and generate alerts and run automation to deal with bad air. This sensor project is a key component for indoor air quality monitoring. But I wanted the sensor to provide some limited stand alone functionality. By using the trinket’s dot star, a piezo buzzer and a button some basic functionality can be implemented.

The dot star on the Trinket serves as a visual indicator of the 10 minute rolling average of both pm 2.5 and eCo2 levels. Steady on is the current level of co2 — green, yellow, orange, red, purple, maroon. Flashing on is the current levels of pm 2.5.

The levels are set as follows:


Warning colorLevEL eCo2
green < 1000 ppm
yellow< 1500 ppm
orange< 2000 ppm
red< 3000 ppm
purple< 5000 ppm
maroon> 5000 ppm
If enabled the alert will sound on orange and above. Solid on led displays eCO2 level.

pm 2.5

Warning LEVELPm2.5 ppb
green< 12.1
yellow< 35.4
orange< 55.4
red< 150.4
purple< 250.4
maroon > 250.4
Blinking dot star is showing the pm25 warning level.

The button has 3 functions. If the alert is sounding 1 press will cancel it. Double click will toggle the alert buzzer on or off. Default is off. There is an increasing or decreasing tone to denote which happened. So a hi to low tone means the alert is off. A long press will set the brightness of the dotstar. Default brightness is 90%. These settings revert to defaults on reset/power on.

A buzzer provides audible feedback of button presses and alerts. If enabled an alert tone will sound for 1 minute when a level goes above level 2 for either monitored compound.

The CCS811 measures VOC that are normally found indoor environments and provides an equivalent CO2 level. VOC levels vary by the atomic weight of the compound in question so it is hard to pin down levels that require actions to be taken. But CO2 has well defined levels (such as this) that can be used for triggers.

For pm 2.5 measurement I chose the PMSA003I sensor. Adafruit sells this sensor on a breakout board which would be the way to go it you can get them. Otherwise you will need to either solder some wires on the very fine pitch connector Adafruit includes or you can use a swd breakout connector and a cable like I did. You will need to use a dremel to cut the connector to fit the PMSA003I. It’s really easy:

Start with this
Grind it down to this. The key has to go.
Ready for test. Can be glued and mounted as is or moved to another board.

A BME280 completes the package. The temperature and humidity are passed to the CCS811 to compensate the measurements.

This is sort of a stew — the project takes advantage of components I had on hand as much as possible. If I were buying all the parts for this I would probably go with a BME680 and reduce the component count.

To utilize the project as a sensor for an HVAC system, we connect to it via the USB serial port. Command Messenger is used to pass messages to the device and retrieve data from the device. A python app is included that can help set measurement offsets and monitor data. It requires PyCmdMessenger. The m2ag.labs thing maker can make aqsensor things for this to allow integration with home automation. Otherwise the data can be retrieved from the device in json format:

See the python source to see how offsets can be set for sensor readings. These are stored in flash when changed and will be valid after restarts.

The Arduino code is set up as a project. Change trinket_aqs.cpp to trinket_aqs.ino to use in Arduino ide. See the source for required libraries.

m2ag-thing-framework alpha 3

The m2ag-thing-framework (formerly m2ag-iot-framework) has reached alpha 3. The functionality of this release represents MVP for the project. The framework generates (RFC?) compliant webthings and is compatible with the Mozilla IoT gateway.

Designed with security and privacy in mind the m2ag-thing-framework comes out of the box pre-configured for ssl for every thing and http basic auth for the api and management app. Coming in beta one will be a jwt implementation for the webthing security to provide peace of mind that devices can not be easily hijacked.

The device side implementation can happily run inside your firewall and never connect to the internet after the initial install. All data is kept locally. Data logging and rules engine support can be provided by the Mozilla IoT gateway. All files needed to run the thing are local after configuration.

The html5 management app is used to configure and monitor the device. Custom devices pages are automatically generated for installed things allowing debug and monitoring. The pages can be individually addressed to they can be used as ui’s for simple cases. The management app needs to be connected to the cloud while modules are being added to a thing, but afterwards does not.

The project consists of four separate projects :

The framework consist of custom python, html as well as nginx, flask and other services.

Work has already started on beta 1. This will bring a jwt implementation for securely accessing things.

m2ag.labs webthing framework alpha2

The m2ag.labs webthing framework now has enough example functionality to enable a demo. A new Raspberry PI can be setup as web thing with no coding (not much coding) required.

The alpha expects self signed certificates in .m2ag-labs/ssl. The installer currently only will install the system to use ssl. If you need to learn how to create self signed certificates checkout this post –> .

Start the install with:

/bin/bash -c “$(curl -fsSL”

Installer ends with enabling services. The rest-api is running.
Browsing to the device home page shows the thing is not running.
Use the helper to add and remove modules
Components are the hardware implementation. Device drivers are installed when possible.
Things are the webthing implementation A thing will be associated with a component.
With things and components available a component map is created.
Add things and associated component.
When the map is complete start the thing
The thing is configured and running.
Add to the Mozilla webthings gateway like any other web thing

Configurations can be modified with ease. The things git hub repo will contain predefined things and components that can used. Custom modules can be created by following a simple pattern. Alpha 2 will only support making properties available. Future releases will address events and actions.

m2ag.labs iot framework alpha 1

July 7, 2020

The m2ag.labs iot framework reaches alpha 1.

The m2ag.labs iot framework is intended as a way to remove tedium from the iot development experience as well as make low cost diy IoT projects feasible for people who may not otherwise pursue them.

Given that a majority of projects are generally geared towards similar ends, a lot of boilerplate can be automatically generated to take care of the basics. These basics include security, communication, installation and remote control.

Security first architecture. With the prevalence of network connected devices making it into the wild there is a good chance one will be a trojan. Any connected device could monitor network traffic and poke at ports on discovered devices. With that in mind this framework defaults to ssl and at least minimal authentication. For alpha 1 there is ssl on all external connections, and HTTP basic auth on the framework api. JWT auth for the webthing will be coming in alpha2.

Self signed certificates must be used. I understand this can be difficult for some users to tackle but it will have to be diy for alpha 1. This will entail generating the certificate authority and distributing a root certificate to all systems/browsers/node apps/ that need to verify thing connections. I have a post here about that — and a good link to follow is here. There will be an option for m2ag.labs to manage this in the future (probably beta 1 or 2 — a couple of months).

Configure your device without coding (well kinda). This is done by specifying configuration and then dynamically constructing the needed classes at runtime. Each things element will get a thing description. This description will include all things related entries to generate a w3c compliant webthing. Each thing will take a component class that will provide an interface to the actual device drivers. The component class is really just a wrapper around the actual device library to provide a standard interface for exchanging data. Adafruit circuit python libraries and gpio zero will be favored in my implementations, but most python driver libraries and i/o access can be used.

The above configuration builds these things:

Common things/components will be available in a repo (coming soon) but it is pretty simple to create the required files. The needed circuit python files need to be installed separately for now.

Opensource implementation:

The m2ag.labs IoT framework will be MIT licensed.

Preliminary installer available. After placing your self singed certificates in .m2ag-labs/ssl run:

/bin/bash -c "$(curl -fsSL"

The installer is a rough version, and will run for quite some time. Check the console for errors. If all goes well you can browse to https://(your thing) and load the config page. The installer assumes a fresh install of Raspbian Buster. It will do an update before starting.

The framework can be installed on the Mozilla Gateway image, but will conflict with the iptables the image implements. The config page expects to be at 443, so the gateway has to move to use it’s default port. In the m2ag-labs/installer/extras/nginx folder there is a config to run the gateway on 8443 using your self signed certificates. The external Mozilla connection (via page kite) is not affected by this. Alpha 2 installer will look for the gateway image and adjust things accordingly. Alpha 2 will also implement stricter control over the systems ports to only allow those needed. No insecure connections will be allowed.

Does not load down the device. Resource usage is relatively light. The framework and things do not over tax even the Raspberry PI zero w.

A B3+ barely notices the framework:

There is plenty of head room to add other services. Any thing that runs on a PI can be used as a thing (a little coaxing maybe required).

It’s all on github:

I have to use a slightly modified version of for the webthing framework to get things to work behind a proxy. I’ll be following up with the webthing folks about this for alpha 2. You can see those tweaks here:

You are welcome to try the framework out. It’s totally at your risk, and expect breaking changes until we hit beta. But I find the framework useful in its current state. Support will be limited to the comments section here for now.

Currently the use of properties is only supported by the dynamic thing builder. Events and actions will have to be added by hand. Dynamically generated events are slated for Alpha 2, actions will be addressed in beta 1.

Code quality: It’s a little of the hack and burn variety. Future releases will see the ui become more componentized with webcomponents and more abstraction of the generated python classes.

m2ag.labs iot framework reloaded

I realize it has been quite sometime since my last post detailing how to install the m2ag.labs iot framework. After that post I looked over my progress and goals and did research in to existing projects. I came across Mozillia’s IoT project and was happy to find something I can work with.

Part of my goal was to provide for automatic ui configuration of common controls, easy web access and standard way of defining IoT devices. Mozilla’s project does that and more while supporting proposed w3c standards. This covers a large part of my development effort so I am definitely adopting the webthings and gateway for my project.

I still have the management interface to workout, including a point and click configuration mechanism and easy certificate generation and installation. These will be my milestone 1 goals. I will also be developing examples and documentation for the project.

The new architecture will use webthings as a standard

m2ag.lab iot framework

Installing the pre-alpha m2ag.labs IoT framework

The m2ag.labs IoT framework currently targets the Raspberry PI and Raspbian. The framework is in pre-alpha but us useable with custom modules installed. Custom modules will be the topic of next weeks post, along with some example code.

The usual warnings apply — this framework may not be compatible with the alpha or later versions of the framework. Some the of the internals need some work, but the framework can be made to work for you now.


  1. Install Raspbian Lite
  2. Perform initial start up
  3. Configure WIFI, SSH, i2c,  change password and hostname
  4. Reboot and login via SSH
  5. Update OS via apt
  6. Generate and place X509 certificates
  7. Get  installer and run

Install Raspian:

Use the Raspberry PI imager  to write Raspbian Lite to your sd card. I use 32 gb Samsung Evo cards. There is direction for choosing a micro sd at the Raspberry PI site.

I use Raspbian Lite unless there is a need for desktop UI on the device. Generally the stuff I do runs headless and is controlled via a web app.

After the image is written do the initial start up for the PI. The easiest way is to add a ssh file to the boot directory of the image we just created and connect the device to an ethernet hub. Just ssh to pi@raspberrypy.local and go. Another way is to plug in a monitor and keyboard but I am too lazy to go get one. The RaspberryPI  site has  instructions on setting up headless with wifi but I haven’t had much luck getting this to work lately (the wifi won’t start) .

After we get logged in (pi/raspberry) we need to configure wifi and enable ssh (if we haven’t already) It’s a good idea to go a head a change:

  •  the default password
  • the time zone
  • enable i2c

Next –  install the X509 certificates. This has been discussed previously on I haven’t decided if I will add a configuration option to run without ssh. I’m not thinking it is a good idea. But — ssh can be turned off with a little manual file editing. For the device, it is in the file device/comm/ The logger is just one file. For the client look in device/api/static/js/comm.js. I don’t think it is a good idea to not use ssh, even in a controlled network.

To create and deploy the certificates follow the instructions in this link or use the tool at to generate the certs. Remember — the root CA has to be imported to each OS that wants to access the IoT device securely. The blog post at contains links to instructions for the most common systems. I use Mac, IOS and Linux around here but Windows and Android are all good.

After the certificates are generated place them in the pi users home directory in a .certs subdirectory. Both the Flask app and Mosquitto MQTT server will access them from here. We are looking for the filenames server.crt and server.key.

Next – cd to home/pi and get the with wget :

chmod +x

This script does apt update and upgrade first, then the install. It can take quite a while to complete. When the script is complete the system should be installed and running. Check the script results for errors. Then navigate to your device on port 5000 (raspib.local:5000) and get the client page opened (be sure to have imported the root CA so ssl will work.

You will get a warning about no user name password. Click on ‘credentials’ in the upper right and enter the default username/password (pi/raspberry).

provide default credentials (pi/raspberry) and click ‘close’

The device will use the hostname as a login for mqtt, default password is raspberry. When we get the page and the login we can see that the api app is running and ssl is correctly recognized by the browser.

Click on ‘Get Device’ list to populate the list. You should see a listing for the device that you can click on:

Select the device to proceed.

This selects the device setup us up for an mqtt connection to the IoT core of or device. Commands can be sent via the Communications tab:

command to sound a sample alert

If you have a piezo buzzer attached to pin 13 the preceding command will make it play a tone. In the command — the prm object can carry your custom command to your IoT device. Returned data will be available in the output area. I have a post here that details how I set my buzzer up.

Limited DB access via Database tab,

registry and users are currently implemented.

The code is pre-alpha so there are plenty of warts. There is a problem with the HTML5 app that make the initial mqtt connection a little contrary but it can be made to work. Just try sending a command a couple of times if you can’t get the initial command to work. Much work needs to be done to HTML5 app ( would you like to help? ).

The UI and accompanying API are going to get some usability improvements next, followed by some work on the IoT device.

The repos are here.

If you are working on COVID related projects and would like to use this framework to boot strap your effort I would be happy to assist in getting you going. Contact me here.

If you find this work helpful perhaps you would consider supporting m2ag.labs open source efforts by buying us coffee. Any amount would be appreciated. Please use this link to do so:

Small Donate Button

Thanks for stopping by.

m2ag.labs iot framework block diagram

m2ag.labs IoT framework

The m2ag.labs IoT framework is a collection of techniques for running very capable IoT devices completely disconnected from any specific cloud provider. The framework, currently in pre-alpha, is an moderately opinionated implementation that seeks to cover the basics of communication, security and configuration of most IoT devices needs. The implementor will have a consistent framework with which to start projects with and only need to focus on the IoT functionality to be implemented.

The framework itself is intended to be used inside a controlled firewall with no access to the internet. Because of this the self signed X509 certificates are used to provide SSL and MQTTS connectivity for the device.

The framework consists of several distinct parts:

  • API
  • UI
  • Action Engine
  • Logger
  • Device
  • COMM module
  • Device manager
  • Hardware interface
  • Multiple component modules to implement functionality


A basic install script will ensure required elements are installed and put in a basic configuration. Initially there will be some configuration that is manually completed but as the framework matures a more complex installation and configuration system will be implemented.


A REST API to allow access to logs database and configuration pages for the device. In general configuration is set through this API.

The API includes the device database which serves as the persistent memory for the device as well as configuration registers.


HTML5 based app to provide default access to both the config API and the Device. If device is a HUB, will coordinate a fleet of devices.

Initially just basic connectivity will be implemented. As the framework matures preconfigured modules will be used to allow basic UI of common components to displayed.


A device is the implementation of the IoT functionality. As the python app service is concerned – it manages MQTT comm, configuration changes and general live activities the specific application requires. Monitor a temperature or pressure and send an alarm. Did a position sensor change — send a message. Basic IoT stuff. Other aspects of the device implementation – the support services – are basic Linux/Raspberry PI configurations. The non-python functions of the device will require separate setup steps. These steps will be documented in the installer.

The device coordinates:

COMM module:

Is a generic interface to allow MQTT access. MQTTs is the mechanism for interacting with the IoT functionality.

Each device may be its own MQTT server, or it may connect to a central MQTT server so that events can be aggregated.  The architecture supports connecting to cloud services in a on your own terms manner. The implementor has complete control of what data gets sent to the cloud, if any.

Device manager:

The device manager coordinates activity between the COMM, API and Hardware. Events are monitored and generated here (TBD a better location — probably on the logger service)

Hardware manager:

Handles command processing amongst the python monitored modules. This module contains a list of submodules that comprise the actual implementation of functionality. An object representing the exposed functionality of a module can be addressed in a simple yet expressive manner that can cause any state change that may be required for the implementation.

Component Modules:

 Generally the object will wrap an hardware item – like a bmp280. The framework will generally wrap an Adafruit Circuit Python library for the module with helpers to facilitate standardized data transfer over the mqtt interface.

Component modules may aggregate components to abstract an more complicated component. The comm framework strives to be agnostic to message traffic.

In general — gpizero will be wrapped to implement desired functionality. One of the framework goals is to be as simple as possible to allow easy adoption of the framework with a minimum of technical ability. You won’t need to necessarily be a software engineer to be able to make use of the framework.

Action Engine:

A separate process that monitors MQTT topics for programmed events. Can collect data and trigger actions. This process also logs the MQTT traffic. Each device in a fleet can run it’s own action engine, or they can defer to a central point.


A  logger task monitors MQTT traffic to gather telemetry about the IoT system. Will aggregate traffic and log to a SQLite database of the hub.  This is a separate python app that is running as a service on the hub device (a solo device is its own hub).

The idea is to provide a standardized implementation of the common aspects of getting a system running. Control and monitoring, combining components and events can be coordinated in a easy to implement pattern. 

An installer process will do the preliminary install. This will get the api, logger and device services installed as and enabled as well as getting mosquitto mqtt, circuit python, etc.

Some critical tasks — like generating and staging X509 certificates need to take place before install. The frame work strives to be reasonably secure without too much effort.

Alpha versions of the framework will be available in the upcoming weeks.

If you find this work helpful perhaps you would consider supporting m2ag.labs open source efforts by buying us coffee. Any amount would be appreciated. Please use this link to do so:

Small Donate Button

Thanks for stopping by.

Embedded audio alerts with gpizero and simple circuit

For the devices I tend to make the Raspberry PI is intended to be a controller or sensor of some sort that does not usually have a visual interface attached. It is nice to have the device setup so that all critical functions are easily accessible, and the device be able to give indications of type. Certainly LEDS are easy to implement on the PI. A simple transistor allows us to interface a wide assortment of devices. In this case I want to interface a piezo buzzer to provide audible alerts for device activity.

Now granted, I could attach a plain speaker to the appropriate port and play audio files. There is a lot of overhead to doing that and it would be way overkill for what I am trying to accomplish. Generally I am looking for a beep at power up, maybe a tone when the network is down, an alarm for a sensor – you know.

A simple circuit is all you need –

A few pennies worth of discrete components implements the buzzer

6.8 K worked for me, but you should match R1 to the transistor you are using. This makes for an audible tone that is not too loud. If you need a reference to calculate R1 this is a good source:

Python code to implement tones could not be simpler. Using gpiozero‘s buzzer can give basic beep or tonal buzzer can be used to create compelling tones. Pwmled can also be used to give an attention getting alert.

from gpiozero import PWMLED
import time

buzzer = PWMLED(13)
buzzer.pulse(fade_in_time=0.5, fade_out_time=0.2, n=10, background=True)

Vary the fade_in_time and fade_out_time to experiment with tones. I’ll be using some variation of this implementation in the upcoming m2ag.labs IoT framework for general device side alerting. As I develop tones I will add them the the m2ag.labs example repo. I’d be happy to include your tones of you create a pull request.

If you find this work helpful perhaps you would consider supporting m2ag.labs open source efforts by buying us coffee. Any amount would be appreciated. Please use this link to do so:

Small Donate Button

Thanks for stopping by.

a simple circuit to implement a run indicator and shutdown button

Raspberry PI running indicator and shutdown button

One of the things I want for my IoT devices is a smart power button. When off or in low power I would like to be able to press the button and have the device power on. If the device is on I want to press the power button and have the device shutdown safely and either power off or indicate that power can be shut off.

The PI has built in support for the seed of my solution in the form of device tree overlays  (dto) that can activate kernel support for a shut down signal and a powered down signal. I will be using these two features to implement a simple shutdown button and running indicator led. Not quite the feature set I am looking for, but this may be useful to pull out for some circumstances. Besides, if I can control a led at shut down I could send a signal to put the PI in low power or have it’s UPS shutdown.

There are many sources on the web that detail these two dto’s . The two I found most helpful were:

shutdown signal:
toggling gpio at shutdown:

It should be noted that specifying the gpio pin to use is different in these two overlays. My implementation looks like this (in /boot/config.txt):


With this configuration I am monitoring pin 17 for a low signal to initiate system shut down. When the system has halted, pin 19 will go low. Pin 19 will go from low to high on startup.

When pin 19 signals shut down there are two low to high transitions that look like this:

the has shut down signal toggles low to high once before staying low
The has shut down signal toggles low to high once before staying low

So — using this line to control a running led would have the led on while running. When the system shuts down the led will blink once and then go out indicating it is safe to power off. Keeping the led lit adds 10 ma to the measured current draw of the PI. If this is a concern the logic could be reversed and the led could be made to illuminate at system shutdown. I’m going to be using the led as a running indicator, on while running.

These simple circuits are all that we need to implement our running indicator and shutdown switch.

a simple circuit to implement a run indicator and shutdown button
For a dollars worth of parts we can add some helpful features.

In case it is not clear — those upside diamonds are grounds at the bottom of the schematic. I like the other style ground symbols better.

D1 is a generic led I had on my desk. R1 is 500 ohms because I have so many of them. R3 and C1 are for switch debounce. You can leave these out if you want. I added them because my switch was glitchy when activated:

Without r3/c1:

glitchy shutdown signal
With out R3/C1 my shutdown signals usually look like this

With r3/c1

glitch free shutdown signal
With r3/c1 installed the shutdown signal is glitch free

And there you have it. With a simple file edit and circuit we now have a shutdown switch and a running indicator for our PI. We no longer have to log in and issue a shutdown command and have to assume it is safe to power off our PI. This is a good first step, but it would be handy if we could get this to be a smart power switch. We will be looking at this in an up coming post.

These links are relevant for what was done here:

These links are relevant for what was done here:
Logic captures by the awesome Saleae logic analyzer

If you find this work helpful perhaps you would consider supporting m2ag.labs open source efforts by buying us coffee. Any amount would be appreciated. Please use this link to do so:

Small Donate Button

Thanks for stopping by.