2023.12.01 Fri 更新

Raspberry Pi Infant Monitoring System with Splunk

Prerequisite Linux skills Raspberry Pi 2b Raspberry Pi camera module AM2302 DHT22 temperature and humidity sensor Raspberry Pi WiFi adapter Server hosting Splunk Universal Repeater Software

Step 1: Set up the Raspberry Pi

The cornerstone of this baby monitor setup is the Raspberry Pi, an affordable and versatile Linux platform available for approximately $50 from various online sources. While I'm utilizing a Model 2B, newer versions, including the Raspberry Pi 3 with integrated WiFi, should work as well.

Here's a quick guide to get you started:

Order your Raspberry Pi, camera, and SD card.

Be patient while waiting for the shipment.

Install Raspbian Linux on the SD card by following the Raspberry Pi guide.

Confirm your ability to connect, and then use your preferred SSH program for remote log-in after installation.

Execute the update command for system updates:

sudo apt-get update

Once this process is complete, you'll have a foundational operating system ready for further customization.

Step 2: Connect the Camera

Pi NoIR is the night vision variant of the camera, featuring a "no IR" filter. This means that in the presence of infrared light sources, the camera can capture images in the dark. As our primary use case is monitoring the baby during nighttime sleep, we've opted for this camera. Keep in mind that if you desire vibrant color vision, this camera may not be the ideal choice.

Follow these steps to set up the Pi NoIR camera:

Open the Raspberry Pi case by gently pushing back the lever on the clip next to the HDMI port. Apply firm pressure but avoid bending.

Log in to the Raspberry Pi, either through SSH or the console.

Enter the command:

sudo raspi-config

Choose "Enable camera" from the configuration menu.

Press Enter, and after completion, the system will prompt you to reboot. Follow the instructions to reboot the Raspberry Pi.

This configuration enables the camera for your night vision baby monitor setup.

Step 3: Connect the Temperature and Humidity Sensor

Initially, using a sensor is recommended for this purpose. The linked sensor comes with embedded components, specifically resistors. There is another version, the blue variant, which lacks these embedded components and might require additional components to prevent issues. The following instructions are for the red AM2302 sensor with onboard components, but other sensors may work with caution.

Here's how to connect the sensor to the Raspberry Pi:

Connect jumpers to the 3 connectors on the sensor:
Orange = ground
Red = VCC
Brown = DAT

Connect the other end of the jumpers to the Raspberry Pi, referring to the Raspberry Pi's connection reference diagram:
Connect Orange to Pin 6 (Third from top left)
Connect Red to Pin 1 (Bottom Left)
Connect Brown to Pin 22 (GPIO 8)

Close the Raspberry Pi case, connect the power, and proceed to write the necessary software to read the sensor data and ensure its functionality.

These steps set up the sensor connection for monitoring purposes.

Step 4: Install required libraries

To develop software capable of reading the sensor, several steps are required.

Ensure the compiler is installed:

sudo apt-get install git-core

Next, install the WiringPi module with the following commands:

git clone git://git.drogon.net/wiringPi

Navigate to the WiringPi directory and update the repository:

cd wiringPi
git pull origin

Finally, compile and install WiringPi:

cd wiringPi
./build

These steps set up the necessary environment for developing software to interact with the sensor.

Step 5: Read the Data

I've utilized this website as a reference to create software capable of reading sensors. They recommend using a C program to ensure consistent sensor readings. I've adjusted their original code to eliminate the looping and format the readings more suitably for later integration with Splunk. Splunk prefers the format variable_name=value for easy identification in logs.

Open your preferred Linux text editor and create a file named dat.c. Insert the following code into the dat.c file:

c

/*
* dat.c:
* Read temperature and humidity from DHT11 or DHT22 sensor
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <wiringPi.h>

#define MAX_TIMINGS 85
#define DHT_PIN 3 /* GPIO-22 */

int data[5] = { 0, 0, 0, 0, 0 };

void read_dht_data()
{
uint8_t last_state = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;

data[0] = data[1] = data[2] = data[3] = data[4] = 0;

/* pull pin low for 18 milliseconds */
pinMode(DHT_PIN, OUTPUT);
digitalWrite(DHT_PIN, LOW);
delay(18);

/* Prepare to read pin */
pinMode(DHT_PIN, INPUT);

/* Detect changes and read data */
for (i = 0; i < MAX_TIMINGS; i++)
{
counter = 0;
while (digitalRead(DHT_PIN) == last_state)
{
counter++;
delayMicroseconds(1);
if (counter == 255)
{
break;
}
}
last_state = digitalRead(DHT_PIN);

if (counter == 255)
break;

/* Ignore first 3 transitions */
if ((i >= 4) && (i % 2 == 0))
{
/* Shift bits into storage byte */
data[j / 8] <<= 1;
if (counter > 16)
data[j / 8] |= 1;
j++;
}
}

/*
* Check that we read 40 bits (8bit x 5) + Verify the checksum in the last byte
* If the data is good, print it out
*/
if ((j >= 40) &&
(data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)))
{
float h = (float)((data[0] << 8) + data[1]) / 10;
if (h > 100)
{
h = data[0]; // for DHT11
}
float c = (float)(((data[2] & 0x7F) << 8) + data[3]) / 10;
if (c > 125)
{
c = data[2]; // for DHT11
}
if (data[2] & 0x80)
{
c = -c;
}
float f = c * 1.8f + 32;
printf("Humidity=%.1f Temperature=%.1f\n", h, c);
}
else
{
printf("The data is not good, skip\n");
}
}

int main(void)
{
if (wiringPiSetup() == -1)
exit(1);

read_dht_data();

return (0);
}

These modifications ensure that the code doesn't loop continuously and formats the readings appropriately for Splunk integration.

Step 6: Compile the Reader Software

Now, you must compile the code saved in the dat.c file. Execute the following command:

cc -Wall dat.c -o dat -lwiringPi

You can run the program with the command:

sudo ./dat

You should observe some output. Please note that this will only work if the sensor is correctly connected and the code functions as intended. It will display readings such as:

makefile

Humidity=66.9 Temperature=18.3

Feel free to replace the readings with values suitable for your local temperature. I've excluded the Fahrenheit reading as it may not be relevant.

Step 7: Write Data to Log File

Next, create a directory named "logs" in the home folder of the Raspberry Pi to store the files:

mkdir /home/pi/logs

Now, create a bash script file in your home directory:

touch /home/pi/Temperature_script.sh

Edit the file using your preferred text editor (vim, etc.) and insert the following code:

#!/bin/bash

log="/home/pi/logs/"

# Run the client
"/home/pi/dat" > temperature.txt

OUTPUT=$(cat temperature.txt)

# Write value to screen
temperature=$(echo "$OUTPUT")

# Output data to log file
echo "$(date +"%Y-%m-%d %T" ): $TEMPERATURE" >> "$log"Temperature.log

This script runs the client (your temperature data collection program), saves the output to a file named temperature.txt, reads the temperature value, and then appends the temperature data along with a timestamp to the log file named Temperature.log in the "logs" directory.

Step 8: Schedule the Script

We will utilize Cron on the Raspberry Pi to execute this job, providing flexibility for when each script runs.

Since the temperature sensor requires sudo (root) access to run, we need to edit the root crontab. Type the following command:

sudo crontab -e

Add the following line to the file:

*/5 * * * * /home/pi/Temperature_script.sh

This configuration runs the temperature program every five minutes. You can check if the log file is being written using the following command:

cat /home/pi/logs/Temperature.log

Your log should begin to resemble the attached log.

Step 9: Setup Webcam

Now, let's configure the webcam. Although we enabled it earlier, we now need to install software to utilize its functionality.

The software, "motion," serves as a web server for viewing, motion detection, and recording frames and pictures. In this setup, I disable video file storage due to limited space, using the live feed for monitoring and relying on logs to track sleep activity.

The default Motion installation doesn't support Pi cameras, so we'll use a specialized build. Here's a concise guide:

sudo apt-get install motion

Download the special version:

wget https://www.dropbox.com/s/0gzxtkxhvwgfocs/motion-mmal.tar.gz

Unzip the file:

tar zxvf motion-mmal.tar.gz

Open the configuration file motion-mmalcam.conf using your preferred text editor. Update the following settings:

Set daemon to run in the background.
Increase video height and quality.
Set the log file to a specific location.
Add the log level for events.

daemon on

width 1280

height 720

logfile /home/pi/logs/motion.log

loglevel 7

Turn off streaming for localhost to allow remote connections:

stream_localhost off

Set the text that appears on the feed:

text_left baby room %t

If facing the internet, set up a username and password; otherwise, leave it as is.

Save the file and start Motion:

sudo motion

This will launch Motion with the specified configurations.

Step 10: Connect to the Network Flow

You should now be able to access the camera stream over the network.

Open your web browser (preferably Chrome or Firefox) and navigate to:

http://your.ip.address:8081

You should receive real-time feedback. Additionally, you can check the motion log to see if events were recorded:

cat /home/pi/logs/motion.log

We'll identify sleep motion by counting these events.

If you want to turn off the red LED to make the camera less noticeable, edit the boot configuration:

sudo vim /boot/config.txt

Add the following lines, and the LED won't appear after restarting:

# Turn off camera red LED
disable_camera_led=1

Save the file, and the changes will take effect upon restarting.

Step 11: Install Splunk and Universal Forwarder

I won't delve into the details of the Splunk server installation, as it can be installed on various operating systems. I have successfully installed it on both Mac OSX and Linux, and it works well on both. Simply follow Splunk's guidelines for installation.

Once Splunk is installed, ensure it has at least one receive connection, typically on port 9997. You can configure the universal forwarder to send data, assuming there are no firewall issues.

Obtain the Splunk universal forwarder for Linux from Splunk, making sure to get the ARM version.
Follow Splunk's instructions for installation.
After obtaining the files, run the Splunk installer:

tar xvzf splunkforwarder-<…>-Linux-arm.tgz -C /opt

Configure the forwarder to point to your Splunk server. Edit the configuration file:

sudo vim /opt/splunkforwarder/etc/system/local/outputs.conf

Assuming your server is at IP address 192.168.0.10:

[tcpout:default-autolb-group]
server = 192.168.0.10:9997

Save and close the file. You can now start the Splunk forwarder:

/opt/splunkforwarder/bin/splunk start

Optionally, add the logs to your Splunk forwarder's log file location:

sudo /opt/splunkforwarder/bin/splunk add monitor /home/pi/logs

Your Splunk forwarder should start collecting logs from this directory. If you encounter any issues, check the Splunk forwarder log:

sudo cat /opt/splunkforwarder/var/log/splunk/splunkd.log

Step 12: Create Dashboard

Now, log in to your Splunk server and ensure that the data is being received.

Perform an event search:

index=primary source="/home/pi/logs/temperature.log"

If you've enabled verbose mode in Splunk, it should recognize the temperature and humidity variables. You can now visualize them using Splunk Search. For example:

index=main source="/home/pi/logs/temperature.log" | stats max(temperature)

You can create a temperature dial by running the following search and saving it to a new dashboard named "Baby Monitor":

index=main source="/home/pi/logs/temperature.log" | stats latest(temperature)

Similarly, for Humidity, select Visualization, Radial Gauge. Save it as a Dashboard Panel, adding it to the existing panel "Baby Monitor":

index=main source="/home/pi/logs/temperature.log" | stats latest(humidity)

These searches and visualizations will help you monitor and chart the temperature and humidity data collected from your Raspberry Pi baby monitor.

Step 13: Add More Content

If the motion detection events are successfully logged, we should now observe these events in Splunk. A search for detected events would look like:

index=main detected

Once we have the results, we can create a graph of the event volume to visualize the amount of movement detected over time. The query for this would be:

index=detected primary | timechart count span=5min

By combining these searches and adding them to the dashboard, we can generate various useful metrics related to internal and external temperatures as well as baby movement.

The query for internal and external temperature could look like:

index=main source="/home/pi/logs/outside_weather.log" OR source="/home/pi/logs/temperature.log" | stats max(Temperature) AS "nursery" max(OtherTemperature) AS "outside"

These searches and visualizations contribute to building a comprehensive dashboard providing insights into internal and external temperatures and baby movement.

Step 14: Connect the APP and Install It

Splunk App

Splunk has developed a free iOS app that you can install. It allows you to input your password and URL, enabling you to search for dashboards on your tablet.

For remote connections, you can use port forwarding on your home router to open the necessary addresses. Splunk requires ports 8000 and 8089 to connect to the Splunk server, and the webcam requires port 8081 to connect directly to the Raspberry Pi since that's where it is hosted.

Installation

I affixed it to the back of the crib using tape, and the Pi is quite lightweight. While this is suitable for now, it can become hazardous once your baby can sit up. In such a case, you'll need to mount it out of their reach!

More Raspberry Pi projects

How to Install Mosquitto MQTT Broker on Raspberry Pi: https://www.tech-sparks.com/install-mosquitto-on-raspberry-pi/

Raspberry Pi Servo Pan-Tilt Project with Remote Control: https://www.tech-sparks.com/raspberry-pi-servo-pan-tilt-project-with-remote-control/

9 Best Raspberry Pi Operating Systems: https://www.tech-sparks.com/raspberry-pi-operating-system/

このまとめに関する記事

ランキング

ページトップへ