diff --git a/assets/tutorials/air-quality-fleet/add-fragment.png b/assets/tutorials/air-quality-fleet/add-fragment.png deleted file mode 100644 index 91454c5bad..0000000000 Binary files a/assets/tutorials/air-quality-fleet/add-fragment.png and /dev/null differ diff --git a/docs/manage/reference/organize.md b/docs/manage/reference/organize.md index 8d85499129..b55af809cb 100644 --- a/docs/manage/reference/organize.md +++ b/docs/manage/reference/organize.md @@ -78,7 +78,7 @@ You can nest locations up to three levels deep. ## Example -If you'd like to look at an example, see [Monitor Air Quality with a Fleet of Sensors](/tutorials/control/air-quality-fleet/#example). +If you'd like to look at an example, see [Monitor Air Quality with a Fleet of Sensors](/tutorials/control/air-quality-fleet/#organizing-devices-for-third-party-usage). ## Frequently asked questions diff --git a/docs/tutorials/control/air-quality-fleet.md b/docs/tutorials/control/air-quality-fleet.md index 0bea49f7c6..92a0ba3a79 100644 --- a/docs/tutorials/control/air-quality-fleet.md +++ b/docs/tutorials/control/air-quality-fleet.md @@ -20,766 +20,719 @@ cost: 200 # 2. The reader can identify when to use fragments and evaluate when it is worth using fragments. # The reader can create their own fragments for their projects and knows what to include and exclude from them. # 3. The reader recognizes how permissions enable the management of data for a business across multiple customers while providing each customer access to their own data. +# 4. The reader can deploy custom front ends that end users can use to operate their machines. --- -In this tutorial you will use a fleet of devices to collect air quality data from different places and display the most recent readings from each device in a custom viewing dashboard. +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. {{< alert title="Learning Goals" color="info" >}} By completing this project, you will learn to: -- Configure a fleet of identical machines +- Configure a fleet of machines - Organize your fleet using {{< glossary_tooltip term_id="location" text="locations" >}} - Collect and sync data from multiple machines -- Use the Viam TypeScript SDK to query sensor data and create a custom dashboard -- Use API keys to provide access to different groups of machines +- Use the Viam TypeScript SDK to query sensor data +- Create a custom dashboard that you and third parties can use to view data for their respective machines {{< /alert >}} -![Air quality dashboard in a web browser with PM2.5 readings from three different sensor machines displayed.](/tutorials/air-quality-fleet/three-sensor-dash-wide.png) +{{}} ## Requirements -You can complete this tutorial using any number of air quality sensing machines. +You can create one or more machines to measure air quality. +For each machine, you need the following hardware: -For each machine, you will need the following hardware: - -- [SDS011 Nova PM sensor](https://www.amazon.com/SDS011-Quality-Detection-Conditioning-Monitor/dp/B07FSDMRR5) +- One [SDS011 Nova PM sensors](https://www.amazon.com/SDS011-Quality-Detection-Conditioning-Monitor/dp/B07FSDMRR5) - If you choose to use a different air quality sensor, you may need to [create your own module](/operate/get-started/other-hardware/) implementing the [sensor API](/operate/reference/components/sensor/#api) for your specific hardware. - A single-board computer (SBC) [capable of running `viam-server`](https://docs.viam.com/installation/) - An appropriate power supply -Make sure all of your sensors are wired to your SBC before starting this tutorial. +## Set up one device for development -## Decide how you will organize your fleet +In this section we'll set up one air sensing machine as our development device. -Before you start connecting your devices to the Viam app, you'll need to decide how you want to group your devices. +### Create your machine -In the Viam app, {{< glossary_tooltip term_id="machine" text="machines" >}} are grouped into _locations_, and locations are grouped into _organizations_: +{{< table >}} +{{% tablestep number=1 %}} -- Each location can represent either a physical location or some other conceptual grouping. -- An organization is the highest level grouping, and often contains all the locations (and machines) of an entire company. +Navigate to the [Viam app](https://app.viam.com) in a web browser. +Create an account and log in. -These groupings allow you to manage permissions; you can grant a user access to an individual machine, to all the machines in a location, or to everything in an entire organization. -You choose how to group your machines. +{{% /tablestep %}} +{{% tablestep number=2 %}} -{{}} +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**. -
+{{% /tablestep %}} +{{% tablestep number=3 %}} -For more information, see [Fleet Management](/manage/reference/organize/). +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**. -### Example +{{% /tablestep %}} +{{% tablestep number=4 %}} -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. +Connect a PM sensor to a USB port on the machine's SBC. +Then connect your device to power. -Before shipping the sensor machine to your new client, you connect the machine to the Viam app and configure it. -To manage all your company's air quality sensing machines together, you create one organization called Pollution Monitoring Made Simple. -Inside that organization, you create a location for each customer. -You have some individual customers, for example Antonia, who have a sensor machine in their home, or perhaps one inside 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. -RobotsRUs wants to separate their sensor data by physical location, so you create a location for RobotsRUs and then create sub-locations to group their New York sensor machines and their Oregon machines. - -When you grant Antonia access to her location, she will be able to view data from the air sensors at her home. -When you grant RobotsRUs access to their location, they will be able to view data from all of their sub-locations, or they can choose to spin up a dashboard showing data from only one sub-location at a time. -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. +If the computer does not already have a Viam-compatible operating system installed, follow the [operating system setup section of the Quickstart guide](/operate/get-started/setup/) 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! -{{}} - -### Organize your fleet +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`](/operate/reference/prepare/rpi-setup/#enable-communication-protocols). -For this tutorial, we will walk through how to set up your fleet based on the example above. -You can choose to manage your fleet of machines differently based on what makes sense for your use case; if you're only configuring one or two sensors for personal use, feel free to add all your machines to one location and skip to the [next section](#connect-your-machines-to-the-viam-app). +{{% /tablestep %}} +{{% tablestep number=5 %}} -1. Navigate to the [Viam app](https://app.viam.com) in a web browser. - Create an account and log in. -1. 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**. -1. Click **FLEET** in the upper-left corner of the page and click **LOCATIONS**. - A new location called `First Location` is automatically generated for you. - Rename it so you can use it for Antonia's machines: +Add a new [_{{< glossary_tooltip term_id="machine" text="machine" >}}_](/operate/get-started/basics/#what-is-a-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. - Use the **...** menu next to edit the location name to `Antonia's Home`, then click **Save**. +When your machine shows as connected, continue to the next step. -1. Now, create a separate location for RobotsRUs: +{{% /tablestep %}} - On the left side of the **LOCATIONS** page, click the **Add location** button. - Type in `RobotsRUs` and click **Add**. +{{< /table >}} -1. Add sub-locations to the RobotsRUs location to group the machines at each of their offices: +### Configure your sensor - Add a new location called `Oregon Office` using the same **Add location** button. - Then, find the **New parent location** dropdown on the Oregon Office page. - Select **RobotsRUs** and click **Change**. +{{< table >}} - Repeat to add the New York office: Add a new location called `New York Office`, then change its parent location to **RobotsRUs**. +{{% tablestep number=1 %}} - {{}} +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** {{< glossary_tooltip term_id="module" text="module" >}}. +Name the sensor `PM_sensor` and click **Create**. - In the next section, you'll add machines to the locations. +{{}} -## Connect your machines to the Viam app +{{% /tablestep %}} +{{% tablestep number=2 %}} -With your organizational structure in place, let's add some machines: +In the newly created **PM_sensor** card, replace the contents of the attributes box (the empty curly braces `{}`) with the following: -1. Connect your first single-board computer to power. - For this tutorial, we'll treat this as the machine for our first customer, Antonia. - If the computer does not already have a Viam-compatible operating system installed, follow the [operating system setup section of the Quickstart guide](/operate/get-started/setup/) 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! +```json {class="line-numbers linkable-line-numbers"} +{ + "usb_interface": "" +} +``` -1. 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`](/operate/reference/prepare/rpi-setup/#enable-communication-protocols). +{{% /tablestep %}} +{{% tablestep number=3 %}} -1. Click **Antonia's Home** in the left navigation menu to navigate to that location's page. - In the **New machine** field near the top-right corner of the screen, type in a name for the machine, such as `Home Air Quality Sensor`, and click **Add machine**. +To figure out which port your sensor is connected to on your board, SSH to your board and run the following command: -1. You'll be taken to the machine details page and prompted to set up your machine part. - Click **View setup instructions**. - You can find these instructions later if you need them by clicking the part status indicator (which currently reads **Awaiting setup**). +```sh{class="command-line" data-prompt="$"} +ls /dev/serial/by-id +``` -1. Follow the **Set up your machine part** instructions to install `viam-server` on the machine and connect it to the Viam app. - `viam-server` is the binary that runs on the single-board computer (SBC), providing functionality including sensor data collection and connection to the Viam app. +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. - The setup page will indicate when the machine is successfully connected. +Now that you have found the identifier, put the full path to the device into your config, for example: -1. If Antonia has more than one air sensing machine, add a new machine to her location and set it up in the same way. +```json {class="line-numbers linkable-line-numbers"} +{ + "usb_interface": "/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0" +} +``` -This is how you set up one machine. -If you are following along for the RobotsRUs business from our example, create additional machines in each sub-location, that is, in the `Oregon Office` location and in the `New York Office` location. +{{% /tablestep %}} +{{% tablestep number=4 %}} -## Set up your hardware +Save the config. -{{% alert title="Note" color="note" %}} -If this were a real company and you were shipping air sensing machines to customers, you would have the customer plug in power to the machine wherever they are setting it up. -Since you already installed `viam-server`, once a customer connects the machine to power and sets up wifi, the machine will automatically re-connect to the Viam app and pull any configuration updates. -{{% /alert %}} +{{}} -For each sensing machine: +{{% /tablestep %}} +{{% tablestep number=5 %}} -1. Connect the PM sensor to a USB port on the machine's SBC. +On your sensor configuration panel, click on the **TEST** panel to check that you are getting readings from your sensor. -1. Position your sensing machines in strategic locations, and connect them to power. - Here are some ideas for where to place sensing machines: +{{}} - - At home: - - In an outdoor location protected from weather, such as under the eaves of your home - - In the kitchen, where cooking can produce pollutants - - Anywhere you spend lots of time indoors and want to measure exposure to pollutants - - At work: - - At your desk to check your exposure throughout the day - - Near a door or window to see whether pollutants are leaking in +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. -## Configure your air quality sensors +{{% /tablestep %}} -You need to [configure](/operate/get-started/supported-hardware/#configure-hardware-on-your-machine) your hardware so that each of your machines can communicate with its attached air quality [sensor](/operate/reference/components/sensor/). +{{< /table >}} -No matter how many sensing machines you use, you can configure them efficiently by using a reusable configuration block called a _{{< glossary_tooltip term_id="fragment" text="fragment" >}}_. -Fragments are a way to share and manage identical machine configurations across multiple machines. -Instead of going through all the configuration steps for each machine, you'll start by configuring just one machine and create a fragment based on that machine's configuration. -Then, you'll add the fragment to each of your machines. -With all your machines configured using the same fragment, if you need to update the config in the future, you can just update the fragment and all machines will automatically get the update. +### Configure data management -{{< alert title="Note" color="note" >}} -If this was a real company, adding the fragment to each individual machine would quickly become tiring. -We're showing you how to do this manually as a learning device. -Once you understand how to configure machines and use fragments, you can use [Provisioning](/manage/fleet/provision/setup/) to automatically set up your devices. -{{< /alert >}} +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](/data-ai/capture-data/capture-sync/) 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. -### Configure your first machine +{{< table >}} -#### Configure the sensor +{{% tablestep number=1 %}} -1. Navigate to the **CONFIGURE** tab of the machine details page in the [Viam app](https://app.viam.com) for your first machine. -2. Click the **+** (Create) button and click **Component or service** from the dropdown. - Click **sensor**, then search for `sds011` and click **sds001:v1** from the results. -3. Click **Add module**. - This adds the {{< glossary_tooltip term_id="module" text="module" >}} that provides the sensor model that supports the specific hardware we are using for this tutorial. +Click **+** and add the **data management** service. - ![The Add Module button that appears after you click the model name.](/tutorials/air-quality-fleet/add-sensor-module.png) +On the data manager panel: -4. Give the sensor a name like `PM_sensor` and click **Create**. -5. In the newly created **PM_sensor** card, replace the contents of the attributes box (the empty curly braces `{}`) with the following: +- Toggle **Syncing** to the on position. +- Set the sync interval to `0.05` minutes (every 3 seconds). +- In the **Tags** field, add `air-quality`. + This tag will now automatically be applied to all data collected by this data manager which will make querying data easier. - ```json {class="line-numbers linkable-line-numbers"} - { - "usb_interface": "" - } - ``` +{{% /tablestep %}} +{{% tablestep number=2 %}} -6. Now you need to figure out which port your sensor is connected to on your board. - SSH to your board and run the following command: +On the **PM_sensor** panel, click **Add method** to add data capture. - ```sh{class="command-line" data-prompt="$"} - ls /dev/serial/by-id - ``` +- **Type**: **Readings**. +- **Frequency**: `0.1` (every 10 seconds). - 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. +Save the config. - Now that you have found the identifier, put the full path to the device into your config, for example: +You can check that your sensor data is being synced by clicking on the **...** menu and clicking **View captured data**. - ```json {class="line-numbers linkable-line-numbers"} - { - "usb_interface": "/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0" - } - ``` +{{% /tablestep %}} +{{< /table >}} -7. Save the config. - Your machine config should now resemble the following: +Congratulations. +If you made it this far, you now have a functional air sensing machine. +Let's create a dashboard for its measurements next. - ![Configure tab showing PM sensor and the sensor module configured.](/tutorials/air-quality-fleet/configured-sensor.png) +## Create a dashboard -#### Configure data capture and sync +The [Viam TypeScript SDK](https://ts.viam.dev/) 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. -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](/data-ai/capture-data/capture-sync/) 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. -Once you configure the rest of your sensing machines, you'll be able to remotely access data from all sensors in all locations, and when you're ready, you can give customers [access](/manage/manage/access/) to the data from the sensors in their locations. - -Configure data capture and sync as follows: - -1. Click the **+** (Create) button and click **Component or service** from the dropdown. -2. Click **data management**. -3. Give your data manager a name such as the auto-populated name `data_manager-1` and click **Create**. -4. Toggle **Syncing** to the on position. - Set the sync interval to `0.05` minutes so that data syncs to the cloud every 3 seconds. - You can change the interval if you like, just don't make it too long or you will have to wait a long time before you see your data! -5. Let's add a tag to all your data so that you can query data from all your air quality sensors more easily in later steps. - In the **Tags** field, type `air-quality` and click **+ Tag: air-quality** when it appears to create a new tag. - This tag will now automatically be applied to all data collected by this data manager. -6. Now the data management service is available to any components on your machine, and you can set up data capture on the sensor: -7. On your **PM_sensor** card, click **Add method**. -8. From the **Type** dropdown, select **Readings**. -9. Set the **Frequency** to `0.1` readings per second. - This will capture air quality data once every ten seconds. - It is useful to capture data frequently for testing purposes, but you can always change this frequency later since you probably don't need to capture data this frequently all day forever. -10. Save the config. - -### Create a fragment - -{{% alert title="Note" color="note" %}} -If you are only using one air quality sensing machine for this tutorial, you do not need to create or use fragments, since fragments are useful only when configuring multiple machines. -You can skip to [Test your sensors](#test-your-sensors). -{{% /alert %}} +The full code is available for reference on [GitHub](https://github.com/viam-labs/air-quality-fleet/blob/main/main.ts). -While you configured your machine with the builder UI, the Viam app generated a JSON configuration file with all your parameters. -This is the file that tells `viam-server` what resources are available to it and how everything is connected. -Click **JSON** in the upper-left corner of the **CONFIGURE** tab to view the generated JSON file. -You can manually edit this file instead of using the builder UI if you are familiar with JSON. +{{< alert title="Tip" color="tip" >}} +If you'd like to graph your data using a Grafana dashboard, try our [Visualize Data with Grafana tutorial](/tutorials/services/visualize-data-grafana/) next. +{{< /alert >}} -In any case, now that the JSON is generated, you are ready to create a {{< glossary_tooltip term_id="fragment" text="fragment" >}}: +### Set up your TypeScript project -1. Select and copy the entire contents of the JSON config. -2. Navigate to the **FLEET** page and go to the [**FRAGMENTS** tab](https://app.viam.com/fragments). -3. Click **Create fragment** and change your fragment's name by clicking on it. We used the name `air-sensing-machine`. -4. Replace the empty curly braces `{}` with the config you copied from your machine. -5. Click **Save**. -6. Now, you can actually delete the entire config from your machine! - In the next section, you will replace it with the fragment you just created so that it gets updated alongside all your other machines when you update the fragment in the future. +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. + +{{< table >}} +{{% tablestep number=1 %}} + +Make sure you have the latest version of [Node.JS](https://nodejs.org/en) installed on your computer. + +{{% /tablestep %}} +{{% tablestep number=2 %}} + +Create a directory on your laptop or desktop for your project. +Name it aqi-dashboard. + +{{% /tablestep %}} +{{% tablestep number=3 %}} + +Create a file in your aqi-dashboard folder and name it package.json. +The package.json file holds necessary metadata about your project. +Paste the following contents into it: + +```json {class="line-numbers linkable-line-numbers"} +{ + "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": "", + "license": "ISC", + "devDependencies": { + "esbuild": "*" + }, + "dependencies": { + "@viamrobotics/sdk": "^0.42.0", + "bson": "^6.6.0", + "js-cookie": "^3.0.5" + } +} +``` - Navigate back to your machine's **CONFIGURE** tab, select **JSON** mode, and delete the entire contents of the config. - When you try to save, you'll get an invalid JSON error because it can't be empty. - Put in a set of curly braces `{}` and then save the config successfully. +{{% alert title="Fun fact" color="info" %}} -### Add the fragment to all your machines +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. -Add the fragment you just created to each of your machines including the first one: +{{% /alert %}} -1. Click the **+** button, then click **Insert fragment** in the dropdown menu. -2. Search for and click the name of your fragment, for example `air-sensing-machine`. +{{% /tablestep %}} +{{% tablestep number=4 %}} - ![The insert fragment UI.](/tutorials/air-quality-fleet/add-fragment.png) +Install the project's dependencies by running the following command in your terminal: -3. Click **Insert fragment**. - The module, sensor, and data manager will appear in your config. -4. Save the config. -5. Repeat these steps on the machine details page for each of your air quality sensing machines. +```sh {class="command-line" data-prompt="$"} +npm install +``` -## Test your sensors +{{% /tablestep %}} +{{< /table >}} -Now that all your hardware is configured, it's a good idea to make sure readings are being gathered by the sensors and sent to the cloud before proceeding with the tutorial. -For each machine: +### Access machines from your app -1. Go to the machine details page in the [Viam app](https://app.viam.com.) and navigate to the **CONTROL** tab. -2. Within the **Sensors** section, click **Get Readings** for the **PM_sensor**. - If the sensor software and hardware is working, you should see values populate the **Readings** column. +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. - ![The sensor readings on the control tab.](/tutorials/air-quality-fleet/get-readings.png) +Currently, Viam apps only provide access to single machines but in future you will be able to access entire locations or organizations. - 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 (click below). +{{< table >}} +{{% tablestep number=1 %}} - {{< expand "Click here for usb_interface troubleshooting help" >}} +Create another file inside the aqi-dashboard folder and name it main.ts. +Paste the following code into main.ts: -If you only have one USB device plugged into each of your boards, the `usb_interface` value you configured in the sensor config is likely (conveniently) the same for all of your machines. -If not, you can use [fragment overwrite](/manage/fleet/reuse-configuration/#modify-fragment-settings-on-a-machine) to modify the value on any machine for which it is different: - -1. If you're not getting sensor readings from a given machine, check the path of the USB port using the same [process by which you found the first USB path](#usb-path). -2. If the path to your sensor on one machine is different from the one you configured in the fragment, add a fragment overwrite to the config of that machine to change the path without needing to remove the entire fragment. - Follow the [instructions to add a fragment overwrite](/manage/fleet/reuse-configuration/#modify-fragment-settings-on-a-machine) to your machine's config, using the following JSON template: - - ```json {class="line-numbers linkable-line-numbers"} - "fragment_mods": [ - { - "fragment_id": "", - "mods": [ - { - "$set": { - "components.PM_sensor.attributes.usb_interface": "" - } - } - ] - } - ], - ``` +```typescript {class="line-numbers linkable-line-numbers"} +// Air quality dashboard - Replace the values with your fragment ID and with the USB path you identify. - If you named your sensor something other than `PM_sensor`, change the sensor name in the template above. +import * as VIAM from "@viamrobotics/sdk"; +import { BSON } from "bson"; +import Cookies from "js-cookie"; -3. Repeat this process for each machine that needs a different `usb_interface` value. - If you have lots of machines with one `usb_interface` value, and lots of machines with a second one, you might consider duplicating the fragment, editing that value, and using that second fragment instead of the first one for the applicable machines, rather than using a fragment overwrite for each of the machines. - You have options. +let apiKeyId = ""; +let apiKeySecret = ""; +let hostname = ""; +let machineId = ""; - {{< /expand >}} +async function main() { + const opts: VIAM.ViamClientOptions = { + serviceHost: "https://app.viam.com", + credentials: { + type: "api-key", + payload: apiKeySecret, + authEntity: apiKeyId, + }, + }; -## Test data sync + // -Next, check that data is being synced from your sensors to the cloud: + // +} -1. Open your [**DATA** page](https://app.viam.com/data). -2. Click the **Sensors** tab within the data page. -3. If you have sensor data coming from machines unrelated to this project, use the filters on the left side of the page to view data from only your air quality sensors. - Click the **Tags** dropdown and select the `air-quality` tag you applied to your data. - You can also use these filters to show the data from one of your air quality sensors at a time by typing a machine name into the **Machine name** box and clicking **Apply** in the lower-left corner. +// - ![The sensor readings that have synced to the DATA page.](/tutorials/air-quality-fleet/synced-data.png) +document.addEventListener("DOMContentLoaded", async () => { + machineId = window.location.pathname.split("/")[2]; + ({ + id: apiKeyId, + key: apiKeySecret, + hostname: hostname, + } = JSON.parse(Cookies.get(machineId)!)); -Once you've confirmed that data is being collected and synced correctly, you're ready to start building a dashboard to display the data. -If you'd like to graph your data using a Grafana dashboard, try our [Visualize Data with Grafana tutorial](/tutorials/services/visualize-data-grafana/). -If you'd like to create your own customizable dashboard using the Viam TypeScript, continue with this tutorial. + main().catch((error) => { + console.error("encountered an error:", error); + }); +}); +``` -## Code your custom TypeScript dashboard +{{% /tablestep %}} +{{% tablestep number=2 %}} -The [Viam TypeScript SDK](https://ts.viam.dev/) 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 locally on your personal computer, and view the interface in a web browser on that computer. +For developing your app on localhost, **add the same information to your browser's local storage**. -As you'll find out in the [authentication step](#authenticate-your-code-to-your-viam-app-location), you can set each customer up with credentials to access the data from only their location, or you can create a dashboard showing data from all sensors in your entire organization. +Navigate to [Camera Viewer](https://air-quality_naomi.viamapplications.com/) and log in, then select your development machine. -![The air quality dashboard you'll build. This one has PM2.5 readings from two different sensor machines displayed, and a key with categories of air quality.](/tutorials/air-quality-fleet/two-sensors.png) +Open Developer Tools, go to the console and paste the following JavaScript to obtain the cookies you need: -### Set up your TypeScript project +```js {class="line-numbers linkable-line-numbers" data-line=""} +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"; -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 running the TypeScript code from your personal computer. + // 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("="); -1. Make sure you have the latest version of [Node.JS](https://nodejs.org/en) installed on your computer. -1. Install the Viam TypeScript SDK by running the following command in your terminal: + // Add code to set this cookie + cookieSetterCode += `document.cookie = "${name}=${value}; path=/";\n`; + cookieCount++; + } + }); - ```sh {class="command-line" data-prompt="$"} - npm install --save @viamrobotics/sdk - ``` + // Add summary comment + cookieSetterCode += `\nconsole.log("Set ${cookieCount} cookies on localhost");\n`; -1. Create a directory on your laptop or desktop for your project. - Name it aqi-dashboard. + // Display the generated code + console.log(cookieSetterCode); -1. Create a file in your aqi-dashboard folder and name it package.json. - The package.json file holds necessary metadata about your project. - Paste the following contents into it: + // 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(); +} - ```json {class="line-numbers linkable-line-numbers"} - { - "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", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "devDependencies": { - "esbuild": "*" - }, - "dependencies": { - "@viamrobotics/sdk": "^0.13.0", - "bson": "^6.6.0" - } - } - ``` +// Execute the function +generateCookieSetterScript(); +``` -{{% alert title="Fun fact" color="info" %}} -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. -{{% /alert %}} +{{% /tablestep %}} +{{% tablestep number=3 %}} -### Authenticate your code to your Viam app location +Copy the resulting script. It will look like this: -Your TypeScript code requires an API key to establish a connection to your machines. -You can set up credentials to access data from all the sensor machines in your organization, or from just one location. -These API keys only need [**Operator** permissions](/manage/manage/rbac/). +```js {class="line-numbers linkable-line-numbers" data-line=""} +// Cookie setter script for localhost +// Copy and paste this entire script into your browser console when on localhost -In our example you could create a dashboard for Antonia with an API key to see the data from her location, and create a separate dashboard for RobotsRUs with a different API key to access the data from their location. -If RobotsRUs wanted to separate their dashboards by sub-locations, you could set up API keys for RobotsRUs to access data for each of their sub-locations separately, or you could modify the example code to filter data by location name. +document.cookie = "; path=/"; +document.cookie = "machinesWhoseCredentialsAreStored=; path=/"; -You can then either deploy each dashboard on a web server you manage, or add a web server on one machine per customer that hosts the dashboard for the respective customer so that they can access their data on their local network. -We leave this step to the reader. +console.log("Set 2 cookies on localhost"); +``` -The following instructions describe how to set up an API key for one location. +{{% /tablestep %}} +{{% tablestep number=4 %}} -1. Create another file inside the aqi-dashboard folder and name it main.ts. - Paste the following code into main.ts: +Run the following command to serve the app you are building: - ```typescript {class="line-numbers linkable-line-numbers"} - // Air quality dashboard +```sh {class="command-line" data-prompt="$" data-output="2-10"} +npm run start +``` - import * as VIAM from "@viamrobotics/sdk"; - import { BSON } from "bson"; +Open the app in your browser at `http://127.0.0.1:8000/`. - async function main() { - const opts: VIAM.ViamClientOptions = { - credential: { - type: "api-key", - // Key with location operator permissions - // Replace (including angle brackets) - payload: "", - // Replace (including angle brackets) - authEntity: "", - }, - }; +Then, open developer tools, go to the console and paste the copied JavaScript code to set your cookies. - const orgID: string = ""; // Replace - const locationID: string = ""; // Replace +{{% /tablestep %}} +{{< /table >}} - // +### Add functionality to your code - // +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. + +{{< table >}} +{{% tablestep number=1 %}} + +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 main.ts script, directly after the `locationID` line, in place of `// `: + +```typescript {class="line-numbers linkable-line-numbers"} +// 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, +); +``` + +{{% /tablestep %}} +{{% tablestep number=2 %}} + +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 main.ts after the end of your main function, in place of `// `: + +```typescript {class="line-numbers linkable-line-numbers"} +// 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; +} +``` + +{{% /tablestep %}} +{{% tablestep number=3 %}} + +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 main.ts, in place of `// `: + +```typescript {class="line-numbers linkable-line-numbers"} +// 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 = + "

" + + machineName + + ": " + + avgPM.toFixed(2).toString() + + " μg/m3

"; + htmlblock.appendChild(insideDiv); +} + +// Output a block of HTML with color-coded boxes for each machine +return document.getElementById("insert-readings")?.replaceWith(htmlblock); +``` + +{{% /tablestep %}} +{{< /table >}} - // +### Style your dashboard - main().catch((error) => { - console.error("encountered an error:", error); - }); - ``` +You have completed the main TypeScript file that gathers and sorts the data. +Now, you'll create a page to display the data. -1. Now you need to get the API key and the {{< glossary_tooltip term_id="organization" text="organization" >}} and {{< glossary_tooltip term_id="location" text="location" >}} IDs to replace the placeholder strings in the code you just pasted. +{{% alert title="Tip" color="tip" %}} +The complete code is available on [GitHub](https://github.com/viam-labs/air-quality-fleet) as a reference. +{{% /alert %}} - In the [Viam app](https://app.viam.com), navigate to the location page for the location containing your air quality machines. +{{< table >}} +{{% tablestep number=1 %}} + +Create a folder called static inside your aqi-dashboard folder. +Inside the static folder, create a file called index.html. +This file specifies the contents of the webpage that you will see when you run your code. +Paste the following into index.html: + +```{class="line-numbers linkable-line-numbers" data-line="11"} + + + + + + +
+
+

Air Quality Dashboard

+
+ +
+

PM 2.5 readings

+

The following are averages of the last few readings from each machine:

+
+
+

Loading data... + It may take a few moments for the data to load. + Do not refresh page.

+
+
+
+

Key:

+

Good air quality

+

Moderate

+

Unhealthy for sensitive groups

+

Unhealthy

+

Very unhealthy

+

Hazardous

+
+

+ After the data has loaded, you can refresh the page for the latest readings. +

+
+ + +``` - ![The location secret with a Copy button next to it.](/tutorials/air-quality-fleet/loc-secret-button.png) +{{% alert title="Fun fact" color="info" %}} - Copy the **Location ID** and paste it into your code in place of ``, so that the line resembles `const orgID: string = "abcde12345"`. +Line 11, highlighted above, is where the HTML output of the TypeScript file main.ts will get pulled in. -1. Use the dropdown menu in the upper-right corner of the page to navigate to your organization settings page. - Copy the **Organization ID** found under **Details** near the top of the page. - Paste it in place of `` in your code. +TypeScript is a superset of JavaScript with added functionality, and it transpiles to JavaScript, which is why your file is called main.ts even though line 11 indicates `src="main.js"`. +If you look at line 5 of package.json, you can see that `./main.ts` builds out to `static/main.js`. -1. Under the **API Keys** heading, click **Generate Key**. +{{% /alert %}} -1. Name your key something such as `air-sensors-key`. +{{% /tablestep %}} +{{% tablestep number=2 %}} -1. Select **Entity** and choose the location you have all your air quality sensing machines in. +Now you'll create a style sheet to specify the fonts, colors, and spacing of your dashboard. +Create a new file inside your static folder and name it style.css. -1. Set the **Role** to **Owner**, then click **Generate key**. +{{% /tablestep %}} +{{% tablestep number=3 %}} -1. Copy the ID and corresponding key you just created and paste them in place of `` and `` in your code. - For example, you'll now have something of the form +Paste the following into style.css: - ```json {class="line-numbers linkable-line-numbers"} - authEntity: '1234abcd-123a-987b-1234567890abc', - payload: 'abcdefg987654321abcdefghi' - ``` +```{class="line-numbers linkable-line-numbers"} +body { + font-family: Helvetica; + margin-left: 20px; +} - {{% snippet "secret-share.md" %}} +div { + background-color: whitesmoke; +} -### Add functionality to your code +h1 { + color: black; +} -1. Now that you have the API key and org and location IDs, 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 create a Viam `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, you can make a dashboard that has a place for the latest data from each of them. - - Paste the following code into the main function of your main.ts script, directly after the `locationID` line, in place of `// `: - - ```typescript {class="line-numbers linkable-line-numbers"} - // Instantiate data_client and get all - // data tagged with "air-quality" from your location - const client = await VIAM.createViamClient(opts); - 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 thedata: any = await myDataClient?.tabularDataByMQL( - orgID, - BSONQueryForData, - ); - ``` +h2 { + font-family: Helvetica; +} -1. 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 main.ts after the end of your main function, in place of `// `: - - ```typescript {class="line-numbers linkable-line-numbers"} - // Get the average of the last few readings from a given sensor - async function getLastFewAv(alltheData: any[], machineID: string) { - // Get just the data from this machine - let thedata = new Array(); - for (const entry of alltheData) { - if (entry.robot_id == machineID) { - thedata.push({ - PM25: entry.data.readings["pm_2_5"], - time: entry.time_received, - }); - } - } - - // Sort the air quality data from this machine - // by timestamp - thedata = thedata.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 > thedata.length) { - x = thedata.length; - } - let total = 0; - for (let i = 1; i <= x; i++) { - const reading: number = thedata[thedata.length - i].PM25; - total += reading; - } - // Return the average of the last few readings - return total / x; - } - ``` +.inner-div { + font-family: monospace; + border: .2px solid; + background-color: lightblue; + padding: 20px; + margin-top: 10px; + max-width: 320px; + font-size: large; +} -1. 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 main.ts, in place of `// `: - - ```typescript {class="line-numbers linkable-line-numbers"} - // 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 (const mach of machineIDs) { - let insideDiv: HTMLElement = document.createElement("div"); - let avgPM: number = await getLastFewAv(thedata, mach._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; - } - } - // Create the HTML output for this machine - insideDiv.className = "inner-div " + level; - insideDiv.innerHTML = - "

" + - mach._id + - ": " + - avgPM.toFixed(2).toString() + - " μg/m3

"; - htmlblock.appendChild(insideDiv); - } - - // Output a block of HTML with color-coded boxes for each machine - return document.getElementById("insert-readings").replaceWith(htmlblock); - ``` +.key { + max-width: 200px; + padding: 0px 5px 5px; +} -The full code is available for reference on [GitHub](https://github.com/viam-labs/air-quality-fleet/blob/main/main.ts). +.key p { + padding: 4px; + margin: 0px; +} -### Style your dashboard +.good { + background-color: lightgreen; +} -You have completed the main TypeScript file that gathers and sorts the data. -Now, you'll create a page to display the data. +.moderate { + background-color: yellow; +} -{{% alert title="Tip" color="tip" %}} -The complete code is available on [GitHub](https://github.com/viam-labs/air-quality-fleet) as a reference. -{{% /alert %}} +.unhealthy-sensitive { + background-color: orange; +} -1. Create a folder called static inside your aqi-dashboard folder. - Inside the static folder, create a file called index.html. - This file specifies the contents of the webpage that you will see when you run your code. - Paste the following into index.html: - - ```{class="line-numbers linkable-line-numbers" data-line="11"} - - - - - - -
-
-

Air Quality Dashboard

-
- -
-

PM 2.5 readings

-

The following are averages of the last few readings from each machine:

-
-
-

Loading data... - It may take a few moments for the data to load. - Do not refresh page.

-
-
-
-

Key:

-

Good air quality

-

Moderate

-

Unhealthy for sensitive groups

-

Unhealthy

-

Very unhealthy

-

Hazardous

-
-

- After the data has loaded, you can refresh the page for the latest readings. -

-
- - - ``` +.unhealthy { + background-color: red; +} -{{% alert title="Fun fact" color="info" %}} -Line 11, highlighted above, is where the HTML output of the TypeScript file main.ts will get pulled in. +.very-unhealthy { + background-color: violet; +} -TypeScript is a superset of JavaScript with added functionality, and it transpiles to JavaScript, which is why your file is called main.ts even though line 11 indicates `src="main.js"`. -If you look at line 5 of package.json, you can see that `./main.ts` builds out to `static/main.js`. -{{% /alert %}} +.hazardous { + color: white; + background-color: purple; +} -2. Now you'll create a style sheet to specify the fonts, colors, and spacing of your dashboard. - Create a new file inside your static folder and name it style.css. -3. Paste the following into style.css: - - ```{class="line-numbers linkable-line-numbers"} - 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; - } - ``` +#main { + max-width:600px; + padding:10px 30px 10px; +} +``` - Feel free to adjust any of the colors, margins, fonts, and other specifications in style.css based on your preferences. +{{% /tablestep %}} +{{< /table >}} -## Full tutorial code +### Full tutorial code You can find all the code in the [GitHub repo for this tutorial](https://github.com/viam-labs/air-quality-fleet). -## Run the code +### Run the code 1. In a command prompt terminal, navigate to your aqi-dashboard directory. Run the following command to start up your air quality dashboard: @@ -788,7 +741,7 @@ You can find all the code in the [GitHub repo for this tutorial](https://github. npm start ``` - ![Terminal window with the command 'npm start' run inside the aqi-dashboard folder. The output says 'start' and then 'esbuild' followed by the esbuild string from the package.json file you configured. Then there's 'Local:' followed by a URL and 'Network:' followed by a different URL.](/tutorials/air-quality-fleet/terminal-url.png) + {{}} 1. 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. @@ -797,28 +750,251 @@ You can find all the code in the [GitHub repo for this tutorial](https://github. ![Air quality dashboard in a web browser with PM2.5 readings from three different sensor machines displayed.](/tutorials/air-quality-fleet/three-sensor-dash.png) - Great work. - You've learned how to configure a fleet of machines, sync their data to one place, and pull that data into a custom dashboard using TypeScript. +Great work. +You've learned how to configure a machine and you can view its data in a custom TypeScript dashboard. + +### Deploy the app to Viam apps + +Let's deploy this dashboard so you don't have to run it locally. +This will also allow others to use the dashboard. + +{{< table >}} +{{% tablestep number=1 %}} + +**Create a meta.json** in your project folder using this template: + +```json +{ + "module_id": ":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](https://app.viam.com), navigate to your organization settings through the menu in upper right corner of the page. +Find the **Public namespace** and copy that string. +Replace `` with your public namespace. + +{{% /tablestep %}} +{{% tablestep number=2 %}} + +**Register your module** with Viam: + +```sh {class="command-line" data-prompt="$" data-output="3-10"} +viam module create --name="air-quality" --public-namespace="your-namespace" +``` + +{{% /tablestep %}} +{{% tablestep number=3 %}} + +**Package your static files and your meta.json file and upload them** to the Viam Registry: + +```sh {class="command-line" data-prompt="$" data-output=""} +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. + +{{% /tablestep %}} +{{% tablestep number=4 %}} + +**Try your app** by navigating to: + +```txt +https://air-quality_your-public-namespace.viamapplications.com +``` + +Log in and select your development machine. +Your dashboard should now load your data. + +{{% /tablestep %}} +{{< /table >}} + +## Organizing devices for third-party usage + +The following example shows how you can use {{< glossary_tooltip term_id="organization" text="organizations" >}} and {{< glossary_tooltip term_id="location" text="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: + +- When you provision Antonia's machines, you create them inside a new location called `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. +- When you provision the machines for RobotsRUs, you create a location called `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](/manage/reference/organize/) and [provisioning](/manage/fleet/provision/setup/). + +### Organize your fleet + +If you want to follow along, create the following locations: + +- `Antonia's Home` +- `RobotsRUs` + +For `RobotsRUs` crate two sublocations: + +1. Add a new location called `Oregon Office` using the same **Add location** button. +1. Then, find the **New parent location** dropdown on the Oregon Office page. +1. Select **RobotsRUs** and click **Change**. + +Repeat to add the New York office: Add a new location called `New York Office`, then change its parent location to **RobotsRUs**. + +{{}} + +## Getting machines ready for third parties + +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: + +1. You'd flash the single-board computer with an operating system +2. You'd install `viam-agent` +3. You'd provide a machine configuration template, a fragment. + +Once a customer receives your machine, they will: + +1. Plug it in and turn it on. +2. `viam-agent` will start a WiFi network. +3. The customer uses another device to connect to the machine's WiFi network and the user gives the machine the password for their WiFi network. +4. The machine can now connect to the internet and complete setup based on the fragment it knows about. + +### Create the fragment for air sensing machines + +In this section you will create the {{< glossary_tooltip term_id="fragment" text="fragment" >}}: the configuration template that all other machines will use. + +1. Navigate to the **FLEET** page and go to the [**FRAGMENTS** tab](https://app.viam.com/fragments). +1. Click **Create fragment**. +1. Name the fragment `air-quality-configuration`. +1. Add the same components that you added to the development machine when you [set up one device for development](#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. + + {{< expand "Click here for info about the usb_interface value." >}} + +If you only have one USB device plugged into each of your boards, the `usb_interface` value you configured in the sensor config is likely (conveniently) the same for all of your machines. + +If not, you can use [fragment overwrite](/manage/fleet/reuse-configuration/#modify-fragment-settings-on-a-machine) to modify the value on any machine for which it is different. + +{{< /expand >}} + +1. 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. + +{{< alert title="Tip: Use the fragment on your development machine" color="tip" >}} +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. +{{< /alert >}} + +### Provision your machines + +{{< table >}} +{{% tablestep number=1 %}} + +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: + +```sh {class="command-line" data-prompt="$"} +wget https://storage.googleapis.com/packages.viam.com/apps/viam-agent/preinstall.sh +chmod 755 preinstall.sh +``` + +{{% /tablestep %}} +{{% tablestep number=2 %}} + +Create a file called viam-defaults.json with the following configuration: + +```json {class="line-numbers linkable-line-numbers"} +{ + "network_configuration": { + "manufacturer": "Pollution Monitoring Made Simple", + "model": "v1", + "fragment_id": "", + "hotspot_prefix": "air-quality", + "hotspot_password": "WeLoveCleanAir123" + } +} +``` + +Replace `""` with the fragment ID from your fragment. + +{{% /tablestep %}} +{{% tablestep number=3 %}} + +In [Organize your fleet](#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. + +{{< alert title="Tip: Fleet management API" color="tip" >}} +You can create locations and machines programmatically, with the [Fleet management API](/dev/reference/apis/fleet/). +{{< /alert >}} + +{{% /tablestep %}} +{{% tablestep number=4 %}} + +**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. + +```sh {class="command-line" data-prompt="$"} +sudo ./preinstall.sh +``` + +Follow the instructions and provide the viam-defaults.json file and the machine cloud credentials file when prompted. + +{{% /tablestep %}} +{{< /table >}} + +That's it! +Your device is now provisioned and ready for your end user! + +Having trouble? +See [Provisioning](/manage/fleet/provision/setup/) for more information and troubleshooting.
## Next steps -Now that you can monitor your air quality, you can try to improve it and see if your efforts are effective. -You might try putting an air filter in your home or office and comparing the air quality data before you start running the filter with air quality after you have run the filter for a while. -Or, try sealing gaps around doors, and check whether your seal is working by looking at your dashboard. +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. -You could set up a text or email alert when your air quality passes a certain threshold. +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](/tutorials/projects/helmet/) as an example. For an example of setting up text alerts, see the [Detect a Person and Send a Photo tutorial](/tutorials/projects/send-security-photo/). -For another example of a custom TypeScript interface, check out the [Claw Game tutorial](/tutorials/projects/claw-game/). -Instead of displaying data, the claw game interface has buttons to control a robotic arm. - -In this tutorial we covered configuring a fleet of machines using fragments, but to automate the setup process further, you can [use the Viam Agent to provision machines](/manage/fleet/provision/setup/). - {{< cards >}} -{{% card link="/manage/fleet/provision/end-user-setup/" %}} -{{% card link="/tutorials/services/visualize-data-grafana/" %}} {{% card link="/tutorials/projects/helmet/" %}} +{{% card link="/tutorials/projects/send-security-photo/" %}} +{{% card link="/tutorials/services/visualize-data-grafana/" %}} {{< /cards >}}