Previous
Drive a rover (2 min)
In this tutorial you will learn how to set up a fleet of devices for yourself or third parties to collect air quality data. You will then create a web app that shows the most recent reading for any device a user has access to.
By completing this project, you will learn to:
You can create one or more machines to measure air quality. For each machine, you need the following hardware:
viam-server
In this section we’ll set up one air sensing machine as our development device.
Navigate to the Viam app in a web browser. Create an account and log in.
Click the dropdown in the upper-right corner of the FLEET page and use the + button to create a new organization for your air quality machine company. Name the organization and click Create.
Click FLEET in the upper-left corner of the page and click LOCATIONS.
A new location called First Location
is automatically generated for you.
Use the … menu next to edit the location name to Development
, then click Save.
Connect a PM sensor to a USB port on the machine’s SBC. Then connect your device to power.
If the computer does not already have a Viam-compatible operating system installed, follow the operating system setup section of the Quickstart guide to install a compatible operating system.
You do not need to follow the “Install viam-server
” section; you will do that in the next step!
Enable serial communication so that the SBC can communicate with the air quality sensor.
For example, if you are using a Raspberry Pi, SSH to it and enable serial communication in raspi-config
.
Add a new machine using the button in the top right corner of the LOCATIONS tab in the app.
Follow the Set up your machine part instructions to install viam-server
on the machine and connect it to the Viam app.
When your machine shows as connected, continue to the next step.
Navigate to the CONFIGURE tab of the machine, click the + button and select Component or service.
Click sensor, then search for sds011
and add the sds001:v1 module.
Name the sensor PM_sensor
and click Create.
In the newly created PM_sensor card, replace the contents of the attributes box (the empty curly braces {}
) with the following:
{
"usb_interface": "<REPLACE WITH THE PATH YOU IDENTIFY>"
}
To figure out which port your sensor is connected to on your board, SSH to your board and run the following command:
ls /dev/serial/by-id
This should output a list of one or more USB devices attached to your board, for example usb-1a86_USB_Serial-if00-port0
.
If the air quality sensor is the only device plugged into your board, you can be confident that the only device listed is the correct one.
If you have multiple devices plugged into different USB ports, you may need to choose one path and test it, or unplug something, to figure out which path to use.
Now that you have found the identifier, put the full path to the device into your config, for example:
{
"usb_interface": "/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0"
}
Save the config.
On your sensor configuration panel, click on the TEST panel to check that you are getting readings from your sensor.
If you do not see readings, check the LOGS tab for errors, double-check that serial communication is enabled on the single board computer, and check that the usb_interface
path is correctly specified.
You have configured the sensor so the board can communicate with it, but sensor data is not yet being saved anywhere. Viam’s data management service lets you capture data locally from each sensor and then sync it to the cloud where you can access historical sensor data and see trends over time. As you configure more sensing machines, you’ll be able to remotely access data from all machines.
Click + and add the data management service.
On the data manager panel:
0.05
minutes (every 3 seconds).air-quality
.
This tag will now automatically be applied to all data collected by this data manager which will make querying data easier.On the PM_sensor panel, click Add method to add data capture.
0.1
(every 10 seconds).Save the config.
You can check that your sensor data is being synced by clicking on the … menu and clicking View captured data.
Congratulations. If you made it this far, you now have a functional air sensing machine. Let’s create a dashboard for its measurements next.
The Viam TypeScript SDK allows you to build custom web interfaces to interact with your machines. For this project, you’ll use it to build a page that displays air quality sensor data for a given location. You’ll host the website on Viam Apps.
The full code is available for reference on GitHub.
If you’d like to graph your data using a Grafana dashboard, try our Visualize Data with Grafana tutorial next.
Complete the following steps on your laptop or desktop.
You don’t need to install or edit anything else on your machine’s single-board computer (aside from viam-server
which you already did); you’ll be developing your TypeScript app from your personal computer and deploying it to Viam.
Make sure you have the latest version of Node.JS installed on your computer.
Create a directory on your laptop or desktop for your project.
Name it
Create a file in your
{
"name": "air-quality-dashboard",
"description": "A dashboard for visualizing data from air quality sensors.",
"scripts": {
"start": "esbuild ./main.ts --bundle --outfile=static/main.js --servedir=static --format=esm",
"build": "esbuild ./main.ts --bundle --outfile=static/main.js --format=esm"
},
"author": "<YOUR NAME>",
"license": "ISC",
"devDependencies": {
"esbuild": "*"
},
"dependencies": {
"@viamrobotics/sdk": "^0.42.0",
"bson": "^6.6.0",
"js-cookie": "^3.0.5"
}
}
The --format=esm
flag in the "start"
script is important because the ECMAScript module format is necessary to support the BSON dependency this project uses for data query formatting.
If you don’t know what the proceeding sentence means, don’t worry about it; just copy-paste the JSON above and it’ll work.
Install the project’s dependencies by running the following command in your terminal:
npm install
Viam apps provide access to a machine by placing its API key in your local storage. You can access the data from your browser’s local storage with the following code.
Currently, Viam apps only provide access to single machines but in future you will be able to access entire locations or organizations.
Create another file inside the
// Air quality dashboard
import * as VIAM from "@viamrobotics/sdk";
import { BSON } from "bson";
import Cookies from "js-cookie";
let apiKeyId = "";
let apiKeySecret = "";
let hostname = "";
let machineId = "";
async function main() {
const opts: VIAM.ViamClientOptions = {
serviceHost: "https://app.viam.com",
credentials: {
type: "api-key",
payload: apiKeySecret,
authEntity: apiKeyId,
},
};
// <Insert data client and query code here in later steps>
// <Insert HTML block code here in later steps>
}
// <Insert getLastFewAv function definition here in later steps>
document.addEventListener("DOMContentLoaded", async () => {
machineId = window.location.pathname.split("/")[2];
({
id: apiKeyId,
key: apiKeySecret,
hostname: hostname,
} = JSON.parse(Cookies.get(machineId)!));
main().catch((error) => {
console.error("encountered an error:", error);
});
});
For developing your app on localhost, add the same information to your browser’s local storage.
Navigate to Camera Viewer and log in, then select your development machine.
Open Developer Tools, go to the console and paste the following JavaScript to obtain the cookies you need:
function generateCookieSetterScript() {
// Get all cookies from current page
const currentCookies = document.cookie.split(";");
let cookieSetterCode = "// Cookie setter script for localhost\n";
cookieSetterCode +=
"// Copy and paste this entire script into your browser console when on localhost\n\n";
// Process each cookie
let cookieCount = 0;
currentCookies.forEach((cookie) => {
if (cookie.trim()) {
// Extract name and value from the cookie
const [name, value] = cookie.trim().split("=");
// Add code to set this cookie
cookieSetterCode += `document.cookie = "${name}=${value}; path=/";\n`;
cookieCount++;
}
});
// Add summary comment
cookieSetterCode += `\nconsole.log("Set ${cookieCount} cookies on localhost");\n`;
// Display the generated code
console.log(cookieSetterCode);
// Create a textarea element to make copying easier
const textarea = document.createElement("textarea");
textarea.value = cookieSetterCode;
textarea.style.position = "fixed";
textarea.style.top = "0";
textarea.style.left = "0";
textarea.style.width = "100%";
textarea.style.height = "250px";
textarea.style.zIndex = "9999";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
}
// Execute the function
generateCookieSetterScript();
Copy the resulting script. It will look like this:
// Cookie setter script for localhost
// Copy and paste this entire script into your browser console when on localhost
document.cookie = "<SECRET COOKIE INFO>; path=/";
document.cookie = "machinesWhoseCredentialsAreStored=<MACHINE ID>; path=/";
console.log("Set 2 cookies on localhost");
Run the following command to serve the app you are building:
npm run start
Open the app in your browser at http://127.0.0.1:8000/
.
Then, open developer tools, go to the console and paste the copied JavaScript code to set your cookies.
Now that you have the connection code, you are ready to add code that establishes a connection from the computer running the code to the Viam Cloud where the air quality sensor data is stored.
You’ll first create a client to obtain the organization and location ID. Then you’ll get a dataClient
instance which accesses all the data in your location, and then query this data to get only the data tagged with the air-quality
tag you applied with your data service configuration.
The following code also queries the data for a list of the machines that have collected air quality data so that later, depending on the API key used with the code, your dashboard can show the data from any number of machines.
Paste the following code into the main function of your locationID
line, in place of // <Insert data client and query code here in later steps>
:
// Instantiate data_client and get all
// data tagged with "air-quality" from your location
const client = await VIAM.createViamClient(opts);
const machine = await client.appClient.getRobot(machineId);
const locationID = machine?.location;
const orgID = (await client.appClient.listOrganizations())[0].id;
const myDataClient = client.dataClient;
const query = {
$match: {
tags: "air-quality",
location_id: locationID,
organization_id: orgID,
},
};
const match = { $group: { _id: "$robot_id" } };
// Get a list of all the IDs of machines that have collected air quality data
const BSONQueryForMachineIDList = [
BSON.serialize(query),
BSON.serialize(match),
];
let machineIDs: any = await myDataClient?.tabularDataByMQL(
orgID,
BSONQueryForMachineIDList,
);
// Get all the air quality data
const BSONQueryForData = [BSON.serialize(query)];
let measurements: any = await myDataClient?.tabularDataByMQL(
orgID,
BSONQueryForData,
);
For this project, your dashboard will display the average of the last five readings from each air sensor. You need a function to calculate that average. The data returned by the query is not necessarily returned in order, so this function must put the data in order based on timestamps before averaging the last five readings.
Paste the following code into // <Insert getLastFewAv function definition here in later steps>
:
// Get the average of the last five readings from a given sensor
async function getLastFewAv(all_measurements: any[], machineID: string) {
// Get just the data from this machine
let measurements = new Array();
for (const entry of all_measurements) {
if (entry.robot_id == machineID) {
measurements.push({
PM25: entry.data.readings["pm_2.5"],
time: entry.time_received,
});
}
}
// Sort the air quality data from this machine
// by timestamp
measurements = measurements.sort(function (a, b) {
let x = a.time.toString();
let y = b.time.toString();
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
// Add up the last 5 readings collected.
// If there are fewer than 5 readings, add all of them.
let x = 5; // The number of readings to average over
if (x > measurements.length) {
x = measurements.length;
}
let total = 0;
for (let i = 1; i <= x; i++) {
const reading: number = measurements[measurements.length - i].PM25;
total += reading;
}
// Return the average of the last few readings
return total / x;
}
Now that you’ve defined the function to sort and average the data for each machine, you’re done with all the dataClient
code.
The final piece you need to add to this script is a way to create some HTML to display data from each machine in your dashboard.
Paste the following code into the main function of // <Insert HTML block code here in later steps>
:
// Instantiate the HTML block that will be returned
// once everything is appended to it
let htmlblock: HTMLElement = document.createElement("div");
// Display the relevant data from each machine to the dashboard
for (let m of machineIDs) {
let insideDiv: HTMLElement = document.createElement("div");
let avgPM: number = await getLastFewAv(measurements, m._id);
// Color-code the dashboard based on air quality category
let level: string = "blue";
switch (true) {
case avgPM < 12.1: {
level = "good";
break;
}
case avgPM < 35.5: {
level = "moderate";
break;
}
case avgPM < 55.5: {
level = "unhealthy-sensitive";
break;
}
case avgPM < 150.5: {
level = "unhealthy";
break;
}
case avgPM < 250.5: {
level = "very-unhealthy";
break;
}
case avgPM >= 250.5: {
level = "hazardous";
break;
}
}
let machineName = (await client.appClient.getRobot(m._id))?.name;
// Create the HTML output for this machine
insideDiv.className = "inner-div " + level;
insideDiv.innerHTML =
"<p>" +
machineName +
": " +
avgPM.toFixed(2).toString() +
" μg/m<sup>3</sup></p>";
htmlblock.appendChild(insideDiv);
}
// Output a block of HTML with color-coded boxes for each machine
return document.getElementById("insert-readings")?.replaceWith(htmlblock);
You have completed the main TypeScript file that gathers and sorts the data. Now, you’ll create a page to display the data.
The complete code is available on GitHub as a reference.
Create a folder called
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="main">
<div>
<h1>Air Quality Dashboard</h1>
</div>
<script type="module" src="main.js"></script>
<div>
<h2>PM 2.5 readings</h2>
<p>The following are averages of the last few readings from each machine:</p>
</div>
<div id="insert-readings">
<p><i>Loading data...
It may take a few moments for the data to load.
Do not refresh page.</i></p>
</div>
<br>
<div class="key">
<h4 style="margin:5px 0px">Key:</h4>
<p class="good">Good air quality</p>
<p class="moderate">Moderate</p>
<p class="unhealthy-sensitive">Unhealthy for sensitive groups</p>
<p class="unhealthy">Unhealthy</p>
<p class="very-unhealthy">Very unhealthy</p>
<p class="hazardous">Hazardous</p>
</div>
<p>
After the data has loaded, you can refresh the page for the latest readings.
</p>
</div>
</body>
</html>
Line 11, highlighted above, is where the HTML output of the TypeScript file
TypeScript is a superset of JavaScript with added functionality, and it transpiles to JavaScript, which is why your file is called src="main.js"
.
If you look at line 5 of ./main.ts
builds out to static/main.js
.
Now you’ll create a style sheet to specify the fonts, colors, and spacing of your dashboard.
Create a new file inside your
Paste the following into
body {
font-family: Helvetica;
margin-left: 20px;
}
div {
background-color: whitesmoke;
}
h1 {
color: black;
}
h2 {
font-family: Helvetica;
}
.inner-div {
font-family: monospace;
border: .2px solid;
background-color: lightblue;
padding: 20px;
margin-top: 10px;
max-width: 320px;
font-size: large;
}
.key {
max-width: 200px;
padding: 0px 5px 5px;
}
.key p {
padding: 4px;
margin: 0px;
}
.good {
background-color: lightgreen;
}
.moderate {
background-color: yellow;
}
.unhealthy-sensitive {
background-color: orange;
}
.unhealthy {
background-color: red;
}
.very-unhealthy {
background-color: violet;
}
.hazardous {
color: white;
background-color: purple;
}
#main {
max-width:600px;
padding:10px 30px 10px;
}
You can find all the code in the GitHub repo for this tutorial.
In a command prompt terminal, navigate to your
npm start
The terminal should output a line such as Local: http://127.0.0.1:8000/
.
Copy the URL the terminal displays and paste it into the address bar in your web browser.
The data may take up to approximately 5 seconds to load, then you should see air quality data from all of your sensors.
If the dashboard does not appear, right-click the page, select Inspect, and check for errors in the console.
Great work. You’ve learned how to configure a machine and you can view its data in a custom TypeScript dashboard.
Let’s deploy this dashboard so you don’t have to run it locally. This will also allow others to use the dashboard.
Create a
{
"module_id": "<your-namespace>:air-quality",
"visibility": "public",
"url": "https://github.com/viam-labs/air-quality-fleet/",
"description": "Display air quality data from a machine",
"applications": [
{
"name": "air-quality",
"type": "single_machine",
"entrypoint": "static/index.html"
}
]
}
In the Viam app, navigate to your organization settings through the menu in upper right corner of the page.
Find the Public namespace and copy that string.
Replace <your-namespace>
with your public namespace.
Register your module with Viam:
viam module create --name="air-quality" --public-namespace="your-namespace"
Package your static files and your
npm run build
tar -czvf module.tar.gz static meta.json
viam module upload --upload=module.tar.gz --platform=any --version=0.0.1
For subsequent updates run these commands again with an updated version number.
Try your app by navigating to:
https://air-quality_your-public-namespace.viamapplications.com
Log in and select your development machine. Your dashboard should now load your data.
The following example shows how you can use organizations and locations to provide users access to the right groups of machines.
Imagine you create an air quality monitoring company called Pollution Monitoring Made Simple. Anyone can sign up and order one of your sensing machines. When a new customer signs up, you assemble a new machine with a sensor, SBC, and power supply.
Before shipping the sensor machine to your new client, you provision the machine, so that the recipient only needs to connect the machine to their WiFi network for it to work.
To manage all your company’s air quality sensing machines together, you create one organization called Pollution Monitoring Made Simple. An organization is the highest level grouping, and often contains all the locations (and machines) of an entire company.
Inside that organization, you create a location for each customer. A location can represent either a physical location or some other conceptual grouping. You have some individual customers, for example Antonia, who has one sensor machine in her home and one outside. You have other customers who are businesses, for example RobotsRUs, who have two offices, one in New York and one in Oregon, with multiple sensor machines in each.
Organization and locations allow you to manage permissions:
Antonia's Home
and grant Antonia operator access to the location.
This will later allow her to view data from the air sensors at her home.RobotsRUs
and two sub-locations for New York Office
and Oregon Office
.
Then you create the machines in the sub-locations and grant RobotsRUs operator access to the RobotsRUs
machines location.You, as the organization owner, will be able to manage any necessary configuration changes for all air sensing machines in all locations created within the Pollution Monitoring Made Simple organization.
For more information, see Fleet Management and provisioning.
If you want to follow along, create the following locations:
Antonia's Home
RobotsRUs
For RobotsRUs
crate two sublocations:
Oregon Office
using the same Add location button.Repeat to add the New York office: Add a new location called New York Office
, then change its parent location to RobotsRUs.
Continuing with our fictitious company, let’s assume you want to ship air sensing machines to customers as ready-to-go as possible. In other words, you want to provision devices.
Before an air sensing machine leaves your factory, you’d complete the following steps:
viam-agent
Once a customer receives your machine, they will:
viam-agent
will start a WiFi network.In this section you will create the fragment: the configuration template that all other machines will use.
Navigate to the FLEET page and go to the FRAGMENTS tab.
Click Create fragment.
Name the fragment air-quality-configuration
.
Add the same components that you added to the development machine when you set up one device for development.
As a shortcut, you can use the JSON mode on the machine you already configured and copy the machine’s configuration to the fragment.
Specify the version for the sds011
module.
At the point of writing the version is 0.2.1
.
Specifying a specific version or a specific minor or major version of a module will ensure that even if the module you use changes, your machines remain functional.
You can update your fragment at any point, and any machines using it will update to use the new configuration.
To avoid differences between fragment and development machines, we recommend you remove the configured resources from the development machine, and instead use the + button to add the fragment you just created.
For each machine, flash the operating system to the device’s SD card. If you are using the Raspberry Pi Imager, you must customize at least the hostname for the next steps to work.
Then run the following commands to download the preinstall script and make the script executable:
wget https://storage.googleapis.com/packages.viam.com/apps/viam-agent/preinstall.sh
chmod 755 preinstall.sh
Create a file called
{
"network_configuration": {
"manufacturer": "Pollution Monitoring Made Simple",
"model": "v1",
"fragment_id": "<FRAGMENT-ID>",
"hotspot_prefix": "air-quality",
"hotspot_password": "WeLoveCleanAir123"
}
}
Replace "<FRAGMENT-ID>"
with the fragment ID from your fragment.
In Organize your fleet you created several locations. Navigate to one of the locations and create a machine. Select the part status dropdown to the right of your machine’s name on the top of the page.
Click the copy icon next to Machine cloud credentials. Paste the machine cloud credentials into a file on your hard drive called FILE>viam.json.
You can create locations and machines programmatically, with the Fleet management API.
Run the preinstall script without options and it will attempt to auto-detect a mounted root filesystem (or for Raspberry Pi, bootfs) and also automatically determine the architecture.
sudo ./preinstall.sh
Follow the instructions and provide the
That’s it! Your device is now provisioned and ready for your end user!
Having trouble? See Provisioning for more information and troubleshooting.
You can now set up one or more air quality sensors for yourself or others and access them with your dashboard. If you are selling your air quality sensing machines, they can also use your dashboard to view their data.
If you’re wondering what to do next, why not set up a text or email alert when your air quality passes a certain threshold? For instructions on setting up an email alert, see the Monitor Helmet Usage tutorial as an example. For an example of setting up text alerts, see the Detect a Person and Send a Photo tutorial.
Was this page helpful?
Glad to hear it! If you have any other feedback please let us know:
We're sorry about that. To help us improve, please tell us what we can do better:
Thank you!