The Workplace Health and Safety Demo provides the ability to identify unsafe work conditions using AI on Edge and Location Analytics IoT architecture patterns.
The AI on Edge pattern utilizes the Vision AI DevKit which utilizes the Azure IoT Edge Runtime with a custom IoT Edge python module that runs the Vision AI model and an Azure Stream Analytics (ASA) edge module. The Vision AI model has been trained to identify a hard hat and a safety vests. The ASA edge module logic sends only those events where a worker is identified not wearing a hard hat or a vest. The ASA module aggregates / buffers the data so not every frame generates an alert.
The Location Analytics pattern is implemented through Azure Maps geofencing capability. An Azure Web App has been developed to behave like a client that submits GPS information to Azure Maps. The Azure Web App is used to create the geofence and register a client that submits coordinates of the device that is used to register (via the web app). Controls on the Web App can be used to simulate the client moving in and out of the Geofence.
After deploying the demo, a sample demonstration script can be found here
Troubleshooting information at the end of this document.
Git will be used to copy all the files for the demo to your local computer.
- Install Git from here
- Open a command prompt and navigate to a folder where the files should be downloaded
- Issue the command
git clone https://github.com/Azure-Samples/IoTDemos.git
An Azure Resource Manager (ARM) template will be used to deploy all the required resources in the solution. Click on the link below to start the deployment.
Follow the steps to deploy the required Azure resources:
BASICS
- Subscription: Select the Subscription.
- Resource group: Click on 'Create new' and provide a unique name for the Resource Group
- Location: Select the Region where to deploy the resources. Keep in mind that all resources will be deployed to this region so make sure it supports all of the required services. The template has been confirmed to work in West US 2.
SETTINGS
- Prefix: This value will be added to the resource names.
- Administrator Login: Username account for the SQL Server (default: theadmin).
- Administrator Login Password: Password for the administrator account of the SQL Server (default: M1cro$oft2020).
- Notifications Email: Email where to send notifications from the logic apps.
- Read and accept the
TERMS AND CONDITIONS
by checking the box. - Click the
Purchase
button and wait for the deployment to finish. - Review the output values:
- Go to your
Resource group
and clickDeployments
from the left navigation. - Click
Microsoft.Template
- Click
Outputs
from the left navigation. - Save values for future use.
- Go to your
IMPORTANT: You will need these values later in the setup.
NOTE: Connection to the SQL server is allowed from all IP Addresses by default. To update this rule, follow the instructions in the
Optional Steps
section.
Some resources require some extra configuration.
Here we will create cosumer groups for Time Series Insights (TSI) and Azure Stream Analytics (ASA)
- In the Azure portal select the
Resource Group
you created earlier. - Select the
IoT Hub
resource. - Click on
Built-in endpoints
in the left menu - In the blade that opens, find the `Consumer Groups' section
- Create new consumer group called tsi (for use later by Time Series Insights)
- Create a new consumer group called asa (for use later by Azure Stream Analytics)
- Press
Tab
to navigate off the consumer group (this saves the configuration) ![Consumer Groups)(./images/consumergroups.png)
Here we will setup the event for the IoT Hub that will send the data to the Logic App to handle the alerts.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
IoT Hub
resource. - Click the
Events
option in the left menu. - Click the
+ Event subscription
button in the top of the panel. - Enter the name
iothubalerts
to theName
input field. - Leave
Event Schema
asEvent Grid Schema
- For 'System Topic', you can put in anything between 3-128 Characters long.
- Ensure ONLY
Device Telemetry
is selected from theFilter to Event Types
dropdown. - For the
Endpoint Type
select theWeb Hook
option. - Click the
Select an endpoint
link. - In the new panel update the
Subscriber Endpoint
field with the value from the deploy outputdevice Alerts Logic App Endpoint
. - Click the
Confirm Selection
button. - Click the
Create
button.
Here we will run the script for the creation of the tables required by the solution.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
SQL database
resource. - Click the
Query Editor
option in the menu. - Enter the username and password that you used as parameters during deployment and click the
Connect
button. - Copy the following script to the Query area:
CREATE TABLE alerts (
IncidentId UNIQUEIDENTIFIER DEFAULT NEWID(),
DeviceId NVARCHAR(50) NOT NULL,
IncidentType NVARCHAR(50) NOT NULL,
Status NVARCHAR(50) NOT NULL,
ReportedTime DATETIME NOT NULL,
LastUpdated DATETIME
);
CREATE TABLE metrics (
MetricId UNIQUEIDENTIFIER DEFAULT NEWID(),
DeviceId NVARCHAR(50) NOT NULL,
CurrentTime DATETIME NOT NULL,
NumberOfMessages INT NOT NULL,
PersonHardHatMin DECIMAL(2) NOT NULL,
PersonHardHatMax DECIMAL(2) NOT NULL,
PersonHardHatSum DECIMAL(2) NOT NULL,
PersonHardHatAvg DECIMAL(2) NOT NULL,
PersonSafetyVestMin DECIMAL(2) NOT NULL,
PersonSafetyVestMax DECIMAL(2) NOT NULL,
PersonSafetyVestSum DECIMAL(2) NOT NULL,
PersonSafetyVestAvg DECIMAL(2) NOT NULL,
PersonNoPPEMin DECIMAL(2) NOT NULL,
PersonNoPPEMax DECIMAL(2) NOT NULL,
PersonNoPPESum DECIMAL(2) NOT NULL,
PersonNoPPEAvg DECIMAL(2) NOT NULL
);
CREATE TABLE geofencealerts (
AlertId UNIQUEIDENTIFIER DEFAULT NEWID(),
DeviceId NVARCHAR(50) NOT NULL,
AlertType NVARCHAR(50) NOT NULL,
AlertTime DATETIME NOT NULL,
NearestLat DECIMAL(10, 5) NOT NULL,
NearestLon DECIMAL(10, 5) NOT NULL,
);
- Click the
Run
button. - You should be able to see the created tables in the database.
Here we need to authorize the connection for the Office365 API resource with the account that will be used to send the alert notification emails via the Logic Apps.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
office365
API connection resource. - Click the
Edit API connection
option in the left menu. - Click the
Authorize
button to start the authorization process. - Follow the steps with the account you want to use.
- When the process is finished, click the
Save
button.
Follow the next steps to setup the metrics stream job.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Stream Analytics job
resource with the name ending withmetricscloud
. - Click on
Inputs
option in the left menu. - Click on
edgemetricsimput
in the blade that opens - Change the options at the top to
Select IoT Hub from your subscriptions
- Accept the defaults and under
Consumer group
choose: ASA - Click
Save
at the bottom - Click the
Overview
option in the left menu. - Click the
Start
button to start the job. - Click the
Start
button in the right panel and wait for the job to start.
Follow the next steps to setup the metrics stream job.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Stream Analytics Job
resource with the name ending withedgestreamanalytics
. - Click
Storage account settings
from the left navigation. - Click
Add storage account
. - Select the storage account created in the ARM setup and add a new container named
edgemodules
. - Under Container*, select Create new and enter the name edgemodules
- Click
Save
. - Select
Publish
from the left navigation. - Click
Publish
and wait for the operation to complete. - Save the
SAS URL
as you will need this later in the device deployment.
Here we will setup an event subscription for the Azure Maps account in order to notify the geofence events to our Logic App.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Azure Maps Account
resource. - Click the
Events
option in the left menu. - Click the
+ Event Subscription
button in the top of the panel. - Enter
logicappalerts
to theName
input field. - Leave
Event Schema
asEvent Grid Schema
- For 'System Topic', you can put in anything between 3-128 Characters long
- Uncheck the
Geofence Result
option in theFilter to Event Types
dropdown. Ensure that only the following 2 events are selected:- Geofence Entered
- Geofence Exited
- For the
Endpoint Type
select theWeb Hook
option. - Click the
Select an endpoint
link. - In the new panel update the
Subscriber Endpoint
field with the value from the deployment output namedgeofence Alerts Logic App Endpoint
. - Click the
Confirm Selection
button. - Click the
Create
button.
Follow the next steps to setup the event source for the Time Series Insights environment.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Time Series Insights environment
resource. - Click the
Event Sources
option in the left menu. - Click the
+ Add
button on the top of the panel. - Set the following information:
- Event source name: Set as
IoTEdgeTSEventSource
. - Source: Select
IoT Hub
. - IoT Hub name:
<name of your IoT Hub>
- IoT Hub Policy name:
Take the default
- IoT Hub consumer group:
tsi
(DO NOT use $Default) - Timestamp property name:
timestamp
. Note: If values dont appear, give it a minute for the system to populate.
- Event source name: Set as
- Click the
Create
button.
Here we will set the data access policy to allow yourself to view data in the TSI environment
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Time Series Insights environment
resource. - Select
Data Access Policies
in the left menu. - Click
+ Add
from the top of the panel. - Enter your username in the
Select user
section. - Select
Reader
andContributor
from theSelect role
section. - Click
Ok
to add the policy.
Here we will setup the model defining the Types, Hierarchies and Instances.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Time Series Insights environment
resource. - Click the
Go to TSI Explorer
button. - From the left navigation within the environment click the
Model
button. - Click the
Types
tab option.- Click the
Upload JSON
button. - Click the
Choose file
button and find thetypes.json
file inside thedeployment\tsi
folder of the project. - Click the
Upload
button and wait for the type to be loaded in the list.
- Click the
- Click the
Hierarchies
tab option.- Click the
Upload JSON
button. - Click the
Choose file
button and find thehierarchies.json
file inside thedeployment\tsi
folder of the project. - Click the
Upload
button and wait for the hierarchies list to be loaded.
- Click the
NOTE: Complete the following steps after you have connected your AI DevKit device later in the setup.
- Select the
Time Series Insights environment
resource. - Click the
Go to Environment
button. - From the left navigation within the environment click the
Model
button. - Find your device and click
Edit
from theActions
menu. - From the
Properties
tab, selectCamera
from theType
dropdown. - From the
Instance fields
tab, selectWorkplace Safety
as the Hierarchy. - Complete the
Instance fields
values. - Click
Save
.
IMPORTANT: If you would like to add additional mock devices, please refer to the
Time Series Environment data load
in theOptional Steps
section.
In this section, we will set up your Vision AI Dev Kit to be connected to the demo environment.
NOTE: We suggest before completing the following steps you update the firmware on your device using the following instructions. The firmware update process requires a device have at least 50% battery utilization. You can find the find the battery level using the command: adb shell cat /sys/class/power_supply/battery/capacity
- In the Azure portal select the
Resource Group
you created earlier. - Select the
IoT Hub
resource. - Click on
IoT Edge
from the left navigation. - Click
+ Add an IoT Edge Device
. - Enter a
Device ID
and leave all other fields as default. - Click
Save
. - Once the device has been created, select the device and copy the
Primary Connection String
for later in this setup.
Important: If the Visual Studio Code steps below don't work on your PC, consider using an Azure VM. The steps to setup the VM are outside the scope of this but are well documented here
-
Install Visual Studio Code (VS Code).
-
Install 64 bit Anaconda with Python version 3.7.
-
Install the following extensions for VS Code:
- Azure Machine Learning (Azure Account and the Microsoft Python will be automatically installed)
- Azure IoT Tools
-
Restart VS Code.
-
Select [View > Command Palette…] to open the command palette box, then enter [Python: Select Interpreter] command in the command palette box to select your Python interpreter.
-
Enter [Azure: Sign In] command in the command palette box to sign in Azure account and select your subscription.
-
Install Docker Community Edition (CE). Don't sign in to Docker Desktop after Docker CE is installed.
-
Install Docker Extension to Visual Studio Code. This must be done from the VSCode termainal: View -> Terminal.
code --install-extension ms-azuretools.vscode-docker
-
Launch Visual Studio Code, and select File > Open Workspace... command to open the
devkit\VisionModules.code-workspace
. -
Update the .env file with the values for your container registry.
-
In the Azure portal select the
Resource Group
you created earlier. -
Select the
Container Registry
resource. -
Select
Access Keys
from the left navigation. -
Update the following in
devkit/.env
with the following values fromAccess Keys
within the Container Registry:REGISTRY_NAME=
<Login Server>
(Ensure this is the login server and NOT the Registry Name)REGISTRY_USER_NAME=
<Username>
REGISTRY_PASSWORD=
<Password>
-
Update the following in
devkit/.env
with the following value you got earlier in the Step 9 ofEdge Stream Analytics Job
sectionASA_BLOB_URL=
SAS URL
-
Save the file.
-
-
Sign in to your Azure Container Registry by entering the following command in the Visual Studio Code integrated terminal (replace <REGISTRY_USER_NAME>, <REGISTRY_PASSWORD>, and <REGISTRY_NAME> with your container registry values set in the .env file).
docker login -u <REGISTRY_USER_NAME> -p <REGISTRY_PASSWORD> <REGISTRY_NAME>
IMPORTANT: If you would llke to deploy your own model please refer to the
Custom Vision project setup
section in theOptional Steps
section later in this document. You will need to increment the version number in tag property ofAIVisionDevKitGetStartedModule\module.json
if you wish to push another model after the initial one. -
IMPORTANT: Ensure you have
arm32v7
selected as the architecture in the bottom navigation bar of VS Code. -
Right-click on
deployment.template.json
and select theBuild and Push IoT Edge Solution
command to generate a newdeployment.json
file in the config folder, build a module image, and push the image to the specified ACR repositoryIMPORTANT: If you have amended code in your module, you will need to increment the version number in
module.json
so the new version will get deployed to the device in the next steps.NOTE: Some red warnings "/usr/bin/find: '/proc/XXX': No such file or directory" and "debconf: delaying package configuration, since apt-utils is not installed" displayed during the building process can be ignored.
-
Ensure you have the correct Iot Hub selected in VS Code.
- In the Azure IoT Hub extenstion, click
Select IoT Hub
from the hamburger menu. - Select your
Subscription
. - Select the
IoT Hub
you created earlier in the setup.
- In the Azure IoT Hub extenstion, click
-
Right-click
config\deployment.arm32v7.json
and selectCreate Deployment for a Single Device
. -
Select the device you created earlier.
-
Wait for deployment to be completed.
-
Follow the instuctions at outlined Here.
IMPORTANT: Enter the
connection string
from the stepSetup a new Edge device
when promptedAlready have a connection string?
. -
Complete any remaining steps.
-
Your device will be updated with all the modules setup in this section.
- Ensure your Dev Kit has power and is turned on.
- Create a PPE violation by removing a Safety Vest OR a Hard Hat.
NOTE: The demo will work with a single piece of PPE and not both at the same time. Therefore, use a safety vest OR a hard hat.
- You will recieve an email notification regarding the violation.
- Put back on your PPE equipment.
- You will recieve and email notification regarding the violation has been resolved.
- Log into your SQL enviroment to observe metrics and alerts.
- Log into your TSI environment to observe device history.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
App Service
resource. - Click browse to go the application on a desktop machine. Take note of the domain for the next step.
- Open
<yourwebdomain>/register
on a mobile device.NOTE: You can use another web browser window if it is more convenient).
- Enter your name and select
Submit
. - In the web browser, you will see your location has been updated.
- Create a geofence using the
Set Geofence
button. Create this fence outside of where your user is situated. - Use the
Adjust position
controls in the register view to move your user into the geofence. - You will get a toast notification and email regarding the unauthorized entry.
- You can move your user outside the geofence to receive notifications that the user has left.
NOTE: The user will expire after 10 minutes of inactivity.
In this section we will describe some steps that are not required for the demo but allow for further customization if required.
Follow the next steps to update or remove the rule that allow the connection from all IP addresses.
- In the Azure portal select the
Resource Group
you created earlier. - Find the
SQL server
resource and click it to see the detail. - Click the
Firewalls and virtual networks
option in the menu on the left under theSecurity
section. - Check the
AllowAllIps
rule. - If you want to remove click the
...
button next to the rule and click theDelete
button. - If you want to update the rule, click and update the values of the
Start IP
andEnd IP
columns of the rule with the values you want.
Note: For a single IP set both values with the required IP.
- Click the
Save
button.
In this section we will use the Custom Vision Project Generator App to create a Custom Vision project with all images and a trained iteration. This model is already provided in the solution, however, this will give you the flexibility to add more images if required.
NOTE: You will require Visual Studio 2017 or later for this setup.
- Open Visual Studio.
- From the top menu click the
File | Open | Project/Solution
. - Open
customvision\CustomVisionLoaderApp\CustomVisionLoaderApp.sln
. - Open the
App.Config
file and set the following settings values from ARM deployment output:- Key: Cognitive Services Account Key
- Endpoint: Cognitive Services Account Endpoint
- ResourceId: Cognitive Services Account Resource Id
- In Visual Studio click the
Play
button and wait for the console app to start. - The app will go over all the required steps for the project generation using the information from the config file:
- Load model from local file.
- Create the project using the name in the config file.
- Create the tags from the model.
- Upload all the images one by one setting the tags.
- Train the model.
- Publish the iteration for the model to be ready for use.
Note: this process may take several minutes depending on your connection.
- Following output should be display if all the setup is correct:
***********************************************************
* Custom Vision Project Setup *
* *
***********************************************************
*** Loading local custom vision model from: C:\...\customvision\CustomVisionLoaderApp\CustomVisionLoaderApp\Resources\cv_data_model.json ***
Tags to create: 2
Image to tag: 119
** Starting Setup of project **
Creating new object detection project: <project name>
Creating tags
Reading and Uploading images
Uploading image 1 of 119
...
Uploading image 118 of 119
Uploading image 119 of 119
Images upload is done.
Training
Done training!
If you would like to add more training data to better suit your environment. We recommend leveraging the Camera Tagging Module
outlined here.
We've created a walkthrough of how to use the Camera Tagging module to create a new Vision AI model. You can find the walkthrough here
After the project generation is finished we need to export the model from the portal.
- Go to the Custom Vision portal and log in if you are not already.
- Click the new created project from the projects list.
- Click the
Performance
option from the menu. - Click the
Iteration 1
if it's not selected (should be by default). - Click the
Export
button for the iteration. - Click the
Vision AI Dev Kit
icon button in the list. - Click the
Export
button. - Click the
Download
button. - Save the
.zip
file and extract the contents. - Copy and paste the contents of the file to
devkit\modules\AIVisionDevKitGetStartedModule\model
NOTE: If you have already deployed the provided model, you will need to increase the version value in
module.json
and create a new deployment to the device. These steps are outlined in theAI DevKit Setup
section.
In this section we will describe how to input some sample data into the Time Series Environment.
NOTE: You will require Visual Studio 2017 or later for this setup.
To run the app we will need the valid connection string to the IoTHub.
- Open Visual Studio.
- From the top menu click the
File | Open | Project/Solution
. - Open
tsi-data-generator\TSIDataGenerator.sln
. - Open the
App.Config
file and set the following value from the ARM deployment output:- IoTHubConnectionString: IoTHub Connection String
- In Visual Studio click the
Play
button and wait for the console app to start. - The app will start the generation of the example data, a log with each message will be display in the console.
- Wait until the process is finished.
- In the Azure portal select the
Resource Group
you created earlier. - Select the
Time Series Insights environment
resource. - Click the
Go to Environment
button. - From the left navigation within the environment click the
Model
button. - Click the
Instances
tab option.- Click the
Upload JSON
button. - Click the
Choose file
button and find theinstances.json
file inside thedeployment/tsi
folder of the project. - Make sure to check the
Update only
box. - Click the
Upload
button and wait for the instances list to be loaded.
- Click the
If you would like to customize the Azure Maps solution, the source code is available under azuremaps\src
.
To deploy your updated solution to the existing resource via Visual Studio, complete the following steps:
- In the Azure portal select the
Resource Group
you created earlier. - Select the
App Service
resource. - Select
Get Publish Profile
from the top navigation. - Open Visual Studio.
- From the top menu click the
File | Open | Project/Solution
. - Open
azuremaps\src\AzureMapsDemo.sln
. - From the left navigation, right click on
AzureMapsDemo.Web
and clickPublish
. - Click
Import Profile
from the bottom left. - Select the publish profile you downloaded in the earlier step.
- Wait for the deployment to be completed.
We've seen issues with different subscription types: MSDN, AIRS, etc... not being able to deploy certain resources to certain regions. We've found that deploying to East US works consistently. If you have a deployment error, try deploying to East US. The resources inherit their deployment region from the Resource Group location.