Baby Logger

[Update 10/7] Added OneDrive Backup and RaspberryPi shutdown page

This project logs baby’s bodily functions and displays them on a webpage. Many pediatricians recommend tracking your baby’s feeding patterns, wet and dirty diapers to help know if he/she are eating enough – at least for the first few weeks. This is valuable information if there is a problem early on. The doctor can use this information to help with a diagnosis.

For the tech/geek parents, Baby Logger is Raspberry Pi based on Python and PHP using 3 switches.

Here is some photo of the result, 100% Reduce – Reuse – Recycle approach: 😊

Here is the video of testing version, with 5sec delay in the script between switch activation and LED turning on:

Hardware Configuration

3 pin switch with LED

LED Switch configuration has 3 pin used as reported below:

Pin NumberPin ColorRoleConnectionState
1GoldGNDGND (-)Stable at GND
2SilverSwitch OUTVCC (+) FloatClosed = LED ON = VCC
Open = LED OFF = Float
3SilverSwitch INVCC (+)Stable at VCC
pinout switch configuration

Base hardware and engine is based on Raspberry PI Zero W pre-assembled and Electronics Fun kit or anything else to simplify cables and connectors between switch, LED and Pi with correct 10kΩ pull down resistor.

Pull Down switch configuration

Finally, RGB LED part of fun kit to report the status of the 3 switch back to user. Remember to add 220 Ohm resistor on the V+ wire:

Raspberry Pi Zero W – GPIO configuration

Raspberry Pi Zero W

List of GPIO pins used for the project. There 2 main groups:

  • Group #1 to control RGB Led
  • Group #2 to read status of switches for pee, fed and poo
  • Others are +3.3VCC and GND to power on/off
Variable NameGPIOTypeFunction
pee_led_pin20OUT#Green LED
PIN #34#GND
fed_led_pin16OUT#Blue LED
poo_led_pin12OUT#Red LED
PIN #9GND
pee_switch_pin17IN#Green Switch
fed_switch_pin27IN#Blue Switch
poo_switch_pin22IN#Red Switch
PIN #17VCC +3.3V
GPIO configuration

Software configuration

Raspberry PI OS

Make sure you have latest Bullseye OS version, install it from Raspberry Pi OS – Raspberry Pi

Perform an update to latest pages and remove unused one:

sudo apt update
sudo apt upgrade
sudo apt autoremove --purge -y
sudo apt autoclean

Python setup

Install Python library and MySQL SDK for Python

#setup python
sudo apt-get install python3-pip

#setup MySQL SDK
sudo pip3 install pymysql

#Verify installation
pip3 show PyMySQL

MySQL MariaDB setup

Install MariaDB as MySQL – you can follow this guide: Setup a Raspberry Pi MYSQL Database

#Install MariaDB
sudo apt install mariadb-server 

#Answer Y to all questions for best security
sudo mysql_secure_installation  

Once MariaDB is installed, login, create user and configure DB and Table

#Login to MariaDB as root
sudo mysql -u root -p 

#Create User
CREATE DATABASE babylogger;
USE babylogger;
CREATE USER 'logger'@'localhost' IDENTIFIED BY 'YourPassword!';
GRANT ALL PRIVILEGES ON babylogger.* TO 'logger'@'localhost';
FLUSH PRIVILEGES;
quit

#Create Table
USE babylogger;
CREATE TABLE buttondata
	(
	id INT PRIMARY KEY auto_increment,
	created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	category TEXT,
	state TEXT
	);
SHOW TABLES;
quit

After initial DB setup, you can login to DB using this:

mysql -u logger -p -D babylogger

#Show existing table
SHOW TABLES;

#Show existing records
SELECT * FROM buttondata;

Webserver NGINX setup

We need to setup web server to display PHP page with result of data. You can follow this guide: Build your own Raspberry Pi NGINX Web Server

#Remove Apache 2 if there
sudo apt remove apache2

#Install NGINX and start service
sudo apt install nginx
sudo systemctl start nginx

#Install PHP
sudo apt install php7.4-fpm php7.4-mbstring php7.4-mysql php7.4-curl php7.4-gd php7.4-curl php7.4-zip php7.4-xml -y

#Configure NGINX to process PHP
sudo nano /etc/nginx/sites-enabled/default

#Uncomment this section of the file
location ~ \.php$ {
               include snippets/fastcgi-php.conf;
               fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        }

Test the webpage connecting to http://raspberrypi/ from your computer.

GIT configuration

Download the Repo via GIT to Raspberry PI:

#Instal GIT
sudo apt install git
>>> git is already the newest version (1:2.30.2-1).

git --version

#configure your login information
git config --global user.name "username
git config --global user.email "username@email.com"

git config --list

#close repo
cd ~
git clone https://github.com/inglele/Baby-logger.git
cd Baby-logger/
ls

If you need to get an updated copy of the repo:

cd ~/Baby-logger/
git pull origin master

Set parameters files

Once all software is installed and repo downloaded in ~/Baby-logger, update the 2 files holding configuration for MySQL DB:

#Edit MySQL settings for Python
nano ~/Baby-logger/script/mysql_variables.py

#Edit MySQL settings for PHP
nano ~/Baby-logger/website/mysql_variables.php

Testing HW, Script and Website

Raspberry PI + Python Testing

Test Raspberry PI configuration with switch_test.py, it’s a simple script used to test Switch and LED without writing to DB with all log printed in console:

python3 ~/Baby-logger/script/switch_test.py

Web Server + PHP Testing

Copy the website folder in the GitHub repo to /var/www/html/ so NGINX can execute it

sudo cp ~/Baby-logger/website/* /var/www/html/

Test PHP and NGINX via:

If you need to restart NGINX or get more logs:

# Restart NGINX + PHP
sudo systemctl status nginx # Status
sudo systemctl restart nginx #Restart
sudo service php7.4-fpm restart

# Print NGINX error log
tail -f /var/log/nginx/error.log
sudo tail -f /var/log/php7.4-fpm.log

Baby-Logger main script Testing

Execute the mail baby_logger.py script from console to confirm all events are tracked and webpage is updating according:

python3 ~/Baby-logger/script/baby_logger.py

# Example of startup logs:
Sep 28 14:17:47 raspberrypi python3[509]: DEBUG - Set GPIO PIN configuration
Sep 28 14:17:47 raspberrypi python3[509]: DEBUG - DB Connection settings: localhost logger YourPassword! babylogger
Sep 28 14:17:47 raspberrypi python3[509]: DEBUG - Set INPUT GPIO
Sep 28 14:17:47 raspberrypi python3[509]: DEBUG - Setup LED GPIO
Sep 28 14:17:47 raspberrypi python3[509]: DEBUG - Reset LED GPIO
Sep 28 14:17:47 raspberrypi python3[509]: DEBUG - Flash RGB LED - Category: STARTING -
Sep 28 14:17:50 raspberrypi python3[509]: LOG - Baby Logger running...
Sep 28 14:17:50 raspberrypi python3[509]: DEBUG - File: /home/pi/Baby-logger/script/buttondata_2022-09-28.csv
Sep 28 14:17:50 raspberrypi python3[509]: LOG - Backup to /home/pi/Baby-logger/script/buttondata_2022-09-28.csv
Sep 28 14:17:50 raspberrypi python3[509]: LOG - 76 rows written successfully to /home/pi/Baby-logger/script/buttond>

Website should looks like this:

Configure Baby Logger as service

Next step is to automate startup during boot as service.

Create a new file: sudo nano /lib/systemd/system/babylogger.service with the following content:

[Unit]
Description=Baby Logger Service
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/Baby-logger/script/baby_logger.py
User=pi
Restart=always
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target

Reload daemon and start the babylogger.service:

sudo systemctl daemon-reload
sudo systemctl start babylogger.service

Enable autorun:

sudo systemctl enable babylogger.service

Check on the status of service:

#Check service status
sudo systemctl status babylogger.service

#Print last 30 rows of log
sudo journalctl -r -u babylogger.service -n 30 --no-page

OneDrive backup script

Follow these steps to setup rclone on Microsoft OneDrive (rclone.org) and allow you to backup CSV file in backup folder directly into OneDrive in case your MicroSD get corrupted or fail:

curl -L https://raw.github.com/pageauc/rclone4pi/master/rclone-install.sh | bash
rclone config

Follow the steps for onedrive and authenticate it via Windows is super easy.

Once done with initial configuration, you can use script/rsync.sh to automate the sync between backup folder and ondrive folder on PI:

rclone sync -v /home/pi/Baby-logger/backup "onedrive:Documents/Baby-logger/Backup"

Remember to mark as eXecutable with the following:

chmod +x rsync.sh
crontab -e

Add the following entry in cron file:

0 * * * * /home/pi/Baby-logger/script/rsync.sh

This will automatically trigger the sync between RaspberryPi and Onedrive and you will get the file available remotely.

Remote shutdown

Raspberry Pi runs Linux, so clean shutdown is required to avoid corruptions.

Enable Reboot/Shutdown RPI from Web explains all steps.

Main PHP page has link to off.php to trigger a Python script shutdown.py

There are few steps to allow PHP to execute a script in SUDO mode:

sudo visudo
 
pi ALL=(ALL) NOPASSWD: ALL
www-data ALL=/sbin/reboot
www-data ALL=NOPASSWD: /sbin/reboot
www-data ALL=/sbin/shutdown
www-data ALL=NOPASSWD: /sbin/shutdown

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.