In my previous post, I wrote the Raspberry Pi Node.js code to upload data from Pippa’s dog bed scale to data.sparkfun.com. This post covers how to make a Node.js program run automatically when the Pi is turned on. Oh, and at the end I installed the finished scale under Pippa’s bed.
Advice to bloggers: Date your posts! I wasted a day trying to follow advice from a blog entry labeled “Dec 31” – no year – that described how to use /etc/init.d to create a Daemon (a process that starts on power-up and runs continuously). When I ran into problems, one of the (dated) StackOverflow comments I found pointed out that /etc/init.d has been obsoleted in Raspbian (the Raspberry Pi default OS) for a while.
Once I learned that systemd is the path to pursue, things went together pretty quickly. I found a wonderful post by Ralph Slooten describing almost exactly what I wanted to do.
Here is the file I created and put in /etc/systemd/system/scalegateway.service:
Description=scalegateway Dog Bed Weight uploader
ExecStart=/usr/bin/node –use_strict /home/pi/Documents/CurieBLEWeightMonitor/scalegateway/scalegateway.js
The really nice thing about this is that by saying “User=pi”, the script runs as the user “pi” – so it understands how to find the .cfg file I created in /home/pi, and (miraculously) understands how to find the Noble node BLE package in /home/pi/node_modules.
A few things to point out in the script above:
- The Requires= and After= lines tell the system to start this service sometime after the bluetooth service is running – that’s because my script uses BLE (Bluetooth Low Energy).
- This service description has no comments. I had a lot of trouble caused by systemd trying to interpret my comments as commands. So I removed all the comments.
- Notice that I added NODE_PATH to the environment, copied from running “echo $NODE_PATH” as user pi. I’m not sure whether this is strictly necessary for my particular script, but it didn’t hurt.
- The Install block is necessary to inform systemd that this is a service that can be manually installed. Without this, systemctl complained when I tried to enable the service.
All the details are in my CurieBleWeightMonitor git repo, in the scalegateway directory.
Once I was sure that my Node.js script was running automatically at boot time, I unplugged the scale and the Raspberry Pi and moved both of them out of my office and to Pippa’s bed. The scale is under the bed and the Pi is plugged in to a wall socket behind Pippa’s crate (to the left of the bed in the photo).
A quick check of my stream on Sparkfun showed the live data was being uploaded from the bed to the Pi, and from there to Sparkfun’s data warehouse. The whole system is now uploading live, continuous weight from the scale – score!
In my next post I get to find out how much time Pippa spends in her bed at night while we’re asleep. Does she sack out the whole night? Does she get up and wander around? Does she flop about in the bed? We’ll see.