In this guide, we will cover the best way to monitor the Raspberry Pi USB in real-time and receive alerts in case we detect a USB disconnect
Time to read:
In this guide, we will cover the best way to monitor the Raspberry Pi USB in real-time and receive alerts in case we detect a USB disconnected or connected.
This guide based on Upswift.io IoT platform, Upswift platform provides one place to manage and maintain Raspberry Pi's or any other edge Linux based devices remotely.
This guide doesn't require any expert software understanding. We will use the most basic and known technics and technologies that are available out there which don't require any special packages or heavy software design.
Here are part of what we are going to use:
*This guide will also work with any other embedded or edge Linux based device.
Before writing our monitoring python script, the Raspberry Pi has to be connected to Upswift platform - it takes 60 seconds to connect any edge Linux device to Upswift platform - join here.
At the end of this guide, you will get alerts on every new USB connected or disconnected via Upswift platform and email.
Let's start our 4 steps guide:
After connecting your Raspberry Pi device to Upswift platform, please create the next python script and save it on the Raspberry Pi file system at '/home/' under the name - Monitor_USB.py
What does the script do?
Monitor the Linux device USBs in a loop. Pulling the unique Upswift tokens of the device and send the USBs state to Upswift app monitor tool.
The python script uses a small library named pyudev, therefore, we have to install it using PIP install manager with the next command:
pip install pyudev
The python script should run in a loop and send the USB state continuously on every hardware USB change. We want to make sure that even in case the python process crashes, the script will start up again. This can be done by using the Crontab system.
Run the next command on the device terminal:
echo "* * * * * root ps -aux | grep -v grep | grep Monitor_USB.py || python /home/Monitor_USB.py &" >> /etc/crontab
This command pushes a BASH command to the crontab that makes a check every minute if our script is alive. In case the script is alive, it will not do anything, in case the python script process doesn't exist, it will start it up again.
From now on, your device will continuously check and send the USB status to Upswift servers!
Go to Upswift dashboard and click on the App Monitor category. Set 1 app parameter as a string with the name USB and save it.
Let's check it out!
Try to connect or disconnect a USB device from your Raspberry Pi and refresh the App Monitor page - a new App monitor record will show up immediately!
You can use the App Monitor tool to monitor any important parameter from your product application easily, here are just a few nice examples: