Secure workspace aims to create a peer to peer network, where a bunch of AWS IoT EduKit will share a common interface. The interface will be created by BLE(Bluetooth LOW ENERGY) UART protocol. These devices can share messages among themselves one at a time.
When one device(Sender) wants to send message, it connects with other device(Recipient) and collect it's GATT attributes. These attributes are services and characteristics, provided by the recipient device. After collecting those attributes, the sender device can read/write data on that interface, which the recipient device will be listening to.
An android application will act as an admin device is also associated in that interface. If any device wants to send message to the admin application, it is also possible.
Why Secure WorkspaceIn recent times, raise of natural disaster has become a terrifying situation for most of the countries. These natural disasters include earthquakes, landslides due to excessive rain, tsunamis causing huge loss to populating areas, specially if there is any working place situated nearby. Also, we can't deny about the fact that, deaths related to these events take heavy toll on society.
Sometimes the offices and workplaces fail to acknowledge the severity of the situation. Even the weather forecasts fail to predict what will be the exact time of impact and severity of the situation. Here are some of the cases where earthquake made terrifying situation. The 6.4 magnitude earthquake that collapsed a building | Source. And the collapsed building, which took lives of 14 peoples due to major quake | Source.
In most of the cases, people who got stuck under the rubbles of collapsed building stays alive for a certain time period but they can't get to notify their presence to the people outside or their representative authority. Though the rescue team comes in time and tries their best but the problem is, they don't know where to look for and find those who are still alive. As a consequence, those who were merely survived the situation can't escape alive from the collapsed building.
Even not only for office or workplace, during Covid-19, many employees had to work from home. But it is also not safe as housing colony or, residential area may get affected when any natural disaster strikes.
Furthermore, man-made faulty buildings and issues like- structural failure, building set on fire where escape door isn't found can cause the same trouble as earthquake or any natural disaster does. The rana plaza incident took a death toll of 1134 and another thousands injured | Source. Also the accidents occured in mining operations have been taking a lot of lives since past decade | Source.
That's where Secure Workspace comes to play. In the modern era of IoT and advanced connectivity options like Bluetooth/Bluetooth Low Energy(BLE), makes communication options easy and reliable. Small scale integrated devices like: AWS IoT EduKit has IoT cloud access and BLE UART communication protocol. So, it is possible to build a communication network and deliver or receive messages from one device to another.
Whenever someone gets stuck at a precarious situation or falls into problem, he/she can notify by sending SOS message to the nearest AWS IoT EduKit device connected with BLE. Also, there will be an admin android application which can search for active devices and connect with it and listen for response.
Features of Secure Workspace- Personalized Registration: Registration process includes providing name, password and message.
- One Device per User: Secure Workspace aims to build a network at workplace, where every employee has an AWS IoT EduKit and he/she can send SOS message when emergency. For this purpose, it is necessary to have authenticated login and user profile for each user.
- Admin Application and Active Searching: User has the privilege to send SOS message directly to admin app. Also, the admin can search for active device and connect with it, after a disaster or menacing incident has taken place .
- Point to Point Connection: One device can send message to another device with the same BLE UART protocol used for admin application.
- AWS IoT Core: AWS IoT Core is used to listen for MQTT messages from the device and act accordingly.
- AWS DynamoDB: AWS DynamoDB is used for storing user profile such as name, password and message.
- AWS Lambda Function: AWS Lambda function is used as a server less computer which is bind with AWS IoT Core events. When MQTT message arrives, we can trigger some event with lambda function such as: fetching data from DynamoDB and send to the device.
- BLE UART: An universal asynchronous receiver/transmitter (UART) is the most popular protocol used for talking to a computer device over serial port. What we will be using is BLE over UART protocol. It is easy to integrate and listen for data changes or, writing data over the port.
- AWS Account: This project tutorial strongly suggests to have an AWS account. We can use AWS Educate account with our teacher's assistance. Or, we can create our own with gmail address, like I have created mine with rahulmohoto.icpc@gmail.com, and start AWS Free Tier package. The project is AWS Free Tier compatible.
- Setting up Roles and Policy: It is necessary to know, what we are doing with the AWS service, before we are using it. Roles and Policy needs to be set according to our need. Otherwise, doing all the things right won't get our desired result.
- Admin Application: Go through the section "Some Notes about Admin Application" to have a brief understanding about the app.
- About Codes: Codes of both AWS IoT EduKit and Android Application, are available in the attached GitHub repository.
Before we proceed further, we need to setup the environment for AWS IoT EduKit Device. Some key points to focus:
- The app is built with UIFlow MicroPython Firmware 1.12. Build version 1.8.1.
- For this project, I will be using Microsoft Visual Studio Code as my code editor. Link to download the software.
- We have to install a plugin for Microsoft Visual Studio Code, which name is vscode-m5stack-mpy. Follow this link to get that plug-in.
- How my environment setup looks like -
- To flash the memory and burn the firmware in AWS IoT EduKit device, another software is used, named M5 Burner. Follow this link to have the software.
- To know more about UIFlow and MicroPython library, see their official documentation. Follow this link will direct to their official documents.
For the ease of understanding, we can divide the system in two segments.
- if we have found no user data exists on the database -> Registration Process(Section: 1.1)
- if we have found user data exists on the database -> Dashboard Operations(Section:1.2)
- Section 1.1.1: Check on existing user data
- Section 1.1.2: After completing keyboard input for name, password and message to get registered
To check whether user data exists on DynamoDB or not, we need to create an event where we can invoke a trigger. In return we will have a record from DynamoDB. There is no available action like: fetching data from DynamoDB in "AWS IoT Core Rules" section for the task we need to perform.
For this, what we can do is creating an AWS Lambda Function. Lambda function works as a server less computer, which can perform a task when some kind of event is triggered. For our case we will use a formatted MQTT message to trigger the event. In output, what we'll have is also an MQTT response but loaded with JSON data of the record we want from DynamoDB.
Let's focus on "SendMQTTtoCORE2AWS" function from the listed lambda functions.
# SendMQTTtoCORE2AWS Lambda Function
# Python 3.8
...
# TODO implement
client = boto3.resource("dynamodb")
table = client.Table("Save_User_Data")
data = table.scan()["Items"]
client = boto3.client('iot-data', region_name='us-west-2', endpoint_url='https://a25wmxf9jzsaoa-ats.iot.us-west-2.amazonaws.com')
# Change topic, qos and payload
response = client.publish(
topic='env/core',
qos=0,
payload=json.dumps(data[0]["User_Data"])
)
...
Not only a lambda function, we also require an IoT rule which will work as a trigger to invoke that function. Here is my IoT rule "Fetch_Data" to invoke "SendMQTTtoCORE2AWS" lambda function.
What's on "Fetch_Data" rule:
- The Rule about: Function of this rule is to invoke the lambda function "SendMQTTtoCORE2AWS", fetch data from DynamoDB and send as MQTT message to the device.
- Event Trigger:
SELECT Tag FROM 'env/msg' WHERE Tag = "Fetch_Data"
- Action: Invoke the lambda function.
What's happening on AWS IoT EduKit:
# UiFlow MicroPython 1.12 Firmware
# .. Dictionary["Tag"]="Fetch_Data" this is must otherwise, SQL query won't match
...
aws = AWS(things_name='AWS_CORE2', host='a25wmxf9jzsaoa-ats.iot.us-west-2.amazonaws.com', port=8883, keepalive=60, cert_file_path="/flash/res/certificate.pem.crt", private_key_path="/flash/res/private.pem.key")
aws.start()
aws.publish(str('env/msg'),str((json.dumps((Dictionary)))))
...
**See here on how to setup DynamoDB table and store device data
**See here on how to create Lambda function with python
**See here on how to MQTT publish and subscribe on AWS
This way, we can get data from dynamoDB and send it as a MQTT message to AWS IoT EduKit.
Search for existing data and getting result on the device section is completed. Now, we can head to next section, that is inserting data into database, that we just provided via keyboard.
1.1.2 When We Have Completed Data Input for Name, Password and MessageAfter we are done providing input for name, message and password, a dictionary[a python data structure to hold key and value pair] is created with that name, message and password.
# Uiflow MicroPython 1.12 Firmware
...
DictionaryOfSendingInfo={"Name_Data":listOfInputs[0],"Password":listOfInputs[1],"Message":listOfInputs[2],"Tag":"Send_Data"}
...
Later, the dictionary is sent to AWS DynamoDB and stored as a record under the table Save_User_Data.
But, to have an action like storing data on DynamoDB, there must be some event to be triggered. So, we need to have a rule for that in AWS IoT Core.
These are my IoT rules. For now, the concentration will be on "Save_Data" rule only.
What's on "Save_Data" rule:
- The Rule about: Function of this rule will be inserting device data(MQTT message) on DynamoDB, sent from AWS IoT EduKit.
- Event Trigger:
SELECT Name_Data, Password, Message, Tag FROM 'env/msg' WHERE Tag = "Send_Data"
- Action: Insert a message into DynamoDB table.
**See here on how to setup DynamoDB table and store device data
What's happening on AWS IoT EduKit:
# UiFlow MicroPython 1.12 Firmware
# .. Dictionary["Tag"]="Send_Data" this is must otherwise, SQL query won't match
...
aws = AWS(things_name='AWS_CORE2', host='a25wmxf9jzsaoa-ats.iot.us-west-2.amazonaws.com', port=8883, keepalive=60, cert_file_path="/flash/res/certificate.pem.crt", private_key_path="/flash/res/private.pem.key")
aws.start()
aws.publish(str('env/msg'),str((json.dumps((Dictionary)))))
...
This way, the dictionary data(name, password and message) will travel as MQTT message(JSON payload) and stored on DynamoDB. That's all for user registration part if no existing data found.
**See here on how to MQTT publish and subscribe on AWS
1.2 Dashboard Actions if User Data FoundWhat's Happening Behind Dashboard
Profile view and edit button:
Like earlier, data is fetched from AWS DynamoDB using "SendMQTTtoCORE2AWS" Lambda function. Output can be seen on "Profile ViewPage" if the profile view button is pressed. From here, we can edit the registered data if necessary. To edit the data, we need another event unlike insert operation we had done earlier with DynamoDB. Now, we will have to create another rule, where the earlier saved data can be edited.
To meet our purpose, we will use this lambda function "EditFunctionDynamoDB".
# EditFunctionDynamoDB Lambda Function
# Python 3.8
...
client = boto3.resource("dynamodb")
table = client.Table("Save_User_Data")
response = table.update_item(
Key={
'Record_Time': data[0]["Record_Time"],
},
UpdateExpression="set User_Data.Name_Data=:n, User_Data.Message=:m, User_Data.Password=:p, User_Data.Tag=:t",
ExpressionAttributeValues={
':n': event["Name_Data"]
':m': event["Message"],
':p': event["Password"],
':t': event["Tag"]
},
ReturnValues="UPDATED_NEW"
)
...
But to invoke that function, there must be a rule on "AWS IoT Core". Here we'll be using "Edit_Data" rule.
What's on "Edit_Data" rule:
- The Rule about: Function of this rule will be updating existing data on AWS DynamoDB.
- Event Trigger:
SELECT Name_Data, Password, Message, Tag FROM 'env/msg' WHERE Tag = "Edit_Data"
- Action: Invoke the lambda function "EditFunctionDynamoDB".
With this, we can update earlier saved record on AWS DynamoDB. Now, we head to the next section.
SOS button:
In case of emergency, we can directly send our earlier stored SOS message to nearby device using this button. The communication will be made with BLE UART.
# UiFlow Micropython 1.12 Firmware
...
uart_ble = ble_uart.init(user_info["Name_Data"])
uart_ble.write(message)
...
Wait!!We have reached the point, where we can send SOS message to either AWS IoT EduKit device or, admin app. So, we part into two sections.
- Send to another AWS IoT EduKit device(Section 2.1)
- Send to admin android app(Section 2.2)
Although, in both cases sending message via BLE UART will be the same but receiving devices are different. that's why differentiating between them, will make our understanding better.
2.1 Point to Point Communication between two AWS IoT EduKit deviceFrom sender:
# Sample Code Snippet
# UiFlow Micropython 1.12 Firmware
# From Sender
from ble import ble_uart
...
uart_ble = ble_uart.init("Device 1")
uart_ble.write(message)
...
To recipient:
# Sample Code Snippet
# UiFlow Micropython 1.12 Firmware
# Receive data on recipient
from ble import ble_uart
label0 = M5Label('Received Data', x=133, y=99, color=0x000, font=FONT_MONT_14, parent=None)
...
def on_recv():
# global params
global label0
# Show the received text and make an alarm
speaker.playWAV("res/Alarm.wav")
label0.set_text(str(uart_ble.read()))
...
From sender:
# UiFlow Micropython 1.12 Firmware
# From Sender
from ble import ble_uart
...
uart_ble = ble_uart.init(user_info["Name_Data"])
uart_ble.write(message)
...
To recipient:
// Java 8 Android API - 23
// On recipient
...
if(Read.equals(characteristic.getUuid().toString()))
{
value = characteristic.getStringValue(0);
Log.w(TAG, "Value--> "+ value);
// receives data when GATT characteristics match with device service UUID
...
- In the dashboard section, we can add the device to connect and listen for data changes instantly.
- Clicking on the particular one from the list of available devices after searching, will pop up a dialogue box. Two options can be seen there. Select to connect: to connect with the device instantly. Add to favorites: this will add the device to favorites list. All these data will be stored on Firebase real-time database.
- How The App Is Interacting with FireBase:
- Right now, the GATT characteristic - "READ" of my AWS IoT EduKit device is hard coded on the android project(We need to change it for another device). So, reading/receiving message with that particular device is only possible now. When we want to connect with some device via BLE, we must know which GATT(Generic Attribute Profile) services the device provide, and which characteristic is acknowledged. As this is hard-coded now, it will work for one to one connectivity but for multiple devices, this approach must be dynamic.
Here, the important topics of discussion will be:
- How "Secure Workspace" app runs on AWS IoT EduKit.
- How admin app functions on android device.
- How BLE over UART protocol establishes communication and send message from AWS IoT EduKit to the android device.
BLE or, in simple terms Bluetooth Low Energy connectivity provides short range communication protocol between two devices. While connected, both device can share data. Either of them can act as a sender(server) and another can act as a receiver(client). And it doesn't need any centralized server to get connected with each other.
Till both the devices have enough battery to turn on their BLE module, they can communicate. When any natural disaster happens, the first thing which is disconnected is internet connectivity. For this reason, we can't communicate with others and inform them about the desperate situation, we are going through. But with BLE, it is possible to seek help.
That's why BLE is the backbone of Secure Workspace.
Future WorkRight now, Secure Workspace is tested and run with one to one device(either with another AWS IoT EduKit device or, Admin Application) for transmitting SOS message. But, there will be a lot of these AWS IoT EduKit devices in the network paradigm. So, there should be some operation to know which one wants to send data.
So, building a polling operation will be the next task of successful implementation of Secure Workspace.
ConclusionProjects like Secure Workspace is much required for third world countries with vulnerable building infrastructure to deal with the increasing rate of natural calamities/disasters as it can create a good impact on finding out the survivors and they can be rescued when those disasters strike at workplace or home.
Tried to make the project documentation as detailed as possible and attached useful links after every section. Hope it helps :)
Happy Making!!
Comments