My SDRsharp was often crashing so I wanted to use rtl_fm CLI (command line interace) to receive NOAA images. I found this post http://www.rtl-sdr.com/an-alternative-noaa-weather-satellite-tutorial-using-rtl_fm-and-wxtoimg/ which was poorly and incompletely written but it gave me a jump start.

This was tested on a 64bit Windows 7. I assume you have Zadig drivers working already (http://www.rtl-sdr.com/tag/zadig/)

The software:

Theory:

WxToImg will send commands to MCE controller which will start rtl_fm and sox applications which will pipe the audio to virtual audio cable. WxToImg will listen to virtual audio interface and capture the data.

TL;DR: WxToImg -> MCE -> rtl_fm+sox -> Virtual audio cable -> WxToImg

NOTICE: This tutorial does not include doppler shift correction but with NOAA it’s not that important.

1. Install Virtual Audio Cable

The following step is optional but recommended. We’ll need it later for the sox.

Go to playback devices (right click on the speaker in the taskbar).

Right click on your VB-Audio Virtual Cable, properties and rename it to Vcable.

 

2. Download and install sox (https://sourceforge.net/projects/sox/files/sox)

3. Download rtl_fm software and unzip it (http://osmocom.org/attachments/download/2242/RelWithDebInfo.zip)

4. Download and install Virtual Serial port driver (https://www.eltima.com/download/vspd.exe)

Open the app, select two COM ports and click add pair.

You end up with COM2 and COM3 in the left menu. You can choose different ports, but you need to reflect that in WxToImg and later in MCE controller settings.

5. Download and install MCE control (https://github.com/tig/mcec/releases/download/1.9.0/MCEController.Setup.exe)

Open it and go to Settings -> Serial server

Tick Enable serial server

Port: COM3

Baud rate: 2400

6. Install WxToImg and register it with this data:

Name: Carl Rakotondrainibe
Email: carl@Rakotondrainibe.com
Key: EA5M-N3VZ-R6HZ-CFF9-7FC2

Setup all your preferences and go to Options -> Recording options

Under Common recording options:

soundcard: Vcable

receiver type: select Baykal (unregistered version is missing this option)

receiver port: COM2

receiver baud rate: 2400

Save and exit

MCE controller and WxToImg should now be connected together with COM2 – COM3 pair we created earlier.

7. Create a file for MCE controller commands.

MCE will recognize the commands sent by WxToImg and start rtl_fm and sox.

Find your MCEcontrol.exe location (usually in “C:\Program Files (x86)\Kindel Systems\MCE Controller\”)

Go to that folder and create a new file named MCEControl.commands

Add this text to it and save it:

<?xml version="1.0" encoding="utf-8"?>
<MCEController xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Commands xmlns="http://www.kindel.com/products/mcecontroller">
<!-- Place command definitions here -->
<!--
==================================================================
StartProcess Commands
File: The full path to the executable you want to start.
==================================================================
-->
<StartProcess Cmd="RF01376200" File="F:\satreceive\noaa15.bat"/>
<StartProcess Cmd="RF01379125" File="F:\satreceive\noaa18.bat"/>
<StartProcess Cmd="RF01371000" File="F:\satreceive\noaa19.bat"/>
<StartProcess Cmd="MUA" File="F:\satreceive\killrtl.bat"/>
</Commands>
</MCEController>

IMPORTANT: Change the path of the bat files to your own location. Bat files are included in the next steps.

Just a brief explanation of the MCEcontrol.commands file:

Cmd="RF01376200"

= Command sent by WxToImg, a frequency of the NOAA15 Satellite and must be linked with noaa15.bat

Cmd="MUA" File="F:\satreceive\killrtl.bat"

= Command sent by WxToImg to start and stop recording

8. Bat files (make sure to edit them to match your sox, rtl_fm locations and rtl_fm device settings like gain and ppm correction):

noaa15.bat

REM start minimized
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit

@echo off
REM setup paths, mind the end backslash

SET sox_path="F:\Program Files (x86)\sox-14-4-2\"
SET rtl_fm_path=F:\rtl-sdr-release\x64\
REM set RTL device number, run rtl_test, usually it's device 0 with only 1 dongle connected
REM set gain
REM set ppm correction
REM set your audio device, usually virtual audio cable

SET device=0
SET gain=49.6
SET ppm_correction=1
SET audiodevice=Vcable

REM Run sox and rtl_fm
%sox_path%sox.exe -r 48000 -t raw -es -b 16 -c 1 "|%rtl_fm_path%rtl_fm.exe -d %device% -f 137.62M -s 48000 -g %gain% -p %ppm_correction% -F 9 -A fast -E DC" -t waveaudio %audiodevice%

exit

noaa18.bat

REM start minimized
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit

@echo off
REM setup paths, mind the end backslash

SET sox_path="F:\Program Files (x86)\sox-14-4-2\"
SET rtl_fm_path=F:\rtl-sdr-release\x64\

REM set RTL device number, run rtl_test, usually it's device 0 with only 1 dongle connected
REM set gain
REM set ppm correction
REM set your audio device, usually virtual audio cable

SET device=0
SET gain=49.6
SET ppm_correction=1
SET audiodevice=Vcable

REM Run sox and rtl_fm
%sox_path%sox.exe -r 48000 -t raw -es -b 16 -c 1 "|%rtl_fm_path%rtl_fm.exe -d %device% -f 137.9125M -s 48000 -g %gain% -p %ppm_correction% -F 9 -A fast -E DC" -t waveaudio %audiodevice%

exit

noaa19.bat

REM start minimized
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit

@echo off
REM setup paths, mind the end backslash

SET sox_path="F:\Program Files (x86)\sox-14-4-2\"
SET rtl_fm_path=F:\rtl-sdr-release\x64\

REM set RTL device number, run rtl_test, usually it's device 0 with only 1 dongle connected
REM set gain
REM set ppm correction
REM set your audio device, usually virtual audio cable

SET device=0
SET gain=49.6
SET ppm_correction=1
SET audiodevice=Vcable

REM Run sox and rtl_fm
%sox_path%sox.exe -r 48000 -t raw -es -b 16 -c 1 "|%rtl_fm_path%rtl_fm.exe -d %device% -f 137.1M -s 48000 -g %gain% -p %ppm_correction% -F 9 -A fast -E DC" -t waveaudio %audiodevice%

exit

killrtl.bat

@echo off
taskkill /IM rtl_fm.exe /F

Everything should be set now. You can test it by going to WxToImg File -> Manual Test

You should see some data in the MCE Controller, bat file executed and WxToImg recording:

 

 

Main apps needed:
– WxToImg
– Predict
– Rtl-SDR
– Sox
– Dropbox bash uploader
– Some essential packages
– A script to link it all together, provided by a reddit user the2belo. Check out the sources at the bottom of this post.

apt-get update
apt-get install curl git-core git cmake at predict sox libusb-1.0-0-devx-fmt-all build-essential libasound-dev libpulse-dev -y
cat <<EOF >no-rtl.conf
blacklist dvb_usb_rtl28xxu
blacklist rtl2832
blacklist rtl2830
EOF
mv no-rtl.conf /etc/modprobe.d/
git clone git://git.osmocom.org/rtl-sdr.gi
cd rtl-sdr/
mkdir build
cd build
cmake ../ -DINSTALL_UDEV_RULES=ON
make
make install
ldconfig
cd ~
cp ./rtl-sdr/rtl-sdr.rules /etc/udev/rules.d/
reboot
rtl_test

Output should look similar to this:
root@rpi:~/wxsat# rtl_test
Found 1 device(s):
0: Realtek, RTL2838UHIDIR, SN: 00000001

Using device 0: Generic RTL2832U OEM
Found Rafael Micro R820T tuner
Supported gain values (29): 0.0 0.9 1.4 2.7 3.7 7.7 8.7 12.5 14.4 15.7 16.6 19.7 20.7 22.9 25.4 28.0 29.7 32.8 33.8 36.4 37.2 38.6 40.2 42.1 43.4 43.9 44.5 48.0 49.6
[R82XX] PLL not locked!
Sampling at 2048000 S/s.

Info: This tool will continuously read from the device, and report if
samples get lost. If you observe no further output, everything is fine.

Reading samples in async mode…

wget http://www.wxtoimg.com/beta/wxtoimg-armhf-2.11.2-beta.deb
dpkg -i wxtoimg-armhf-2.11.2-beta.deb
wxtoimg

Accept.

predict

Setup your QTH.

cd ~
mkdir wxsat
wget https://raw.githubusercontent.com/the2belo/wxsat-scheduler/master/noaa-scheduler.sh
chmod +x noaa-scheduler.sh
mkdir images recordings

Edit noaa-scheduler.sh to reflect your location.

Change -L parameter
/usr/local/bin/wxmap -T “NOAA ${bird}” -H ~/wxsat/weather.txt -L “35.47/136.76/20” -p0 -o “\$mapdate” ~/wxsat/noaa${bird}map.png

Format is: (lat/lon/alt meters)
Use this site to get lat and lon for your location http://www.latlong.net/lat-long-dms.html

Edit noaa-scheduler.sh for gain and SDR dongle ppm correction:

timeout $rectime /usr/local/bin/rtl_fm -d 0 -f ${freq}M -s 48000 -g 44.5 -p 1 -F 9 -A fast -E DC ~/wxsat/recordings/NOAA${bird}-\$recdate.raw

-g = gain

-p = ppm

Play with gain settings to get the best results.

You also need to add the timezone for the script, add

export TZ='UTC date'

in a new line after #!/bin/bash and after cat << EOF > ~/wxsat/noaa${bird}.at

This is how it looks like in a final version: https://pastebin.com/3uWcp9wi

Script generates MCIR and HCVT images by default, you can change this options. I also added -c option to crop telemetry from the sides of the pictures.

/usr/local/bin/wxtoimg -c -e MCIR -m ~/wxsat/noaa${bird}map.png ~/wxsat/recordings/NOAA${bird}-\$recdate.wav ~/wxsat/images/NOAA${bird}-MCIR-\$recdate.png

mkdir Dropbox-Uploader
cd Dropbox-Uploader
curl "https://raw.githubusercontent.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh" -o dropbox_uploader.sh
chmod +x dropbox_uploader.sh
./dropbox_uploader.sh

Follow the instructions.

Automate the proces. Commands bellow will be run every 12 hours.

crontab -e

00 */12 * * * atq | awk ‘{print $1}’ | sort -n | xargs atrm
01 */12 * * * ~/wxsat/noaa-scheduler.sh 15 137.620
02 */12 * * * ~/wxsat/noaa-scheduler.sh 18 137.9125
03 */12 * * * ~/wxsat/noaa-scheduler.sh 19 137.100
00 */12 * * * wget -qr https://www.celestrak.com/NORAD/elements/weather.txt -O ~/wxsat/weather.txt

Start the jobs immediately:

wget -qr https://www.celestrak.com/NORAD/elements/weather.txt -O ~/wxsat/weather.txt
~/wxsat/noaa-scheduler.sh 15 137.620
~/wxsat/noaa-scheduler.sh 18 137.9125
~/wxsat/noaa-scheduler.sh 19 137.100

If you are going to change the file noaa-scheduler.sh, you need to kill the existing jobs and restart them. Kill the jobs with:

atq | awk '{print $1}' | sort -n | xargs atrm

Sources:
https://www.reddit.com/r/RTLSDR/comments/5iuzbl/fully_automated_raspberry_pi_noaa_satellite/
https://gist.github.com/floehopper/99a0c8931f9d779b0998
https://github.com/the2belo/wxsat-scheduler

There is another piece of software to automatically receive NOAA and Meteor satellites, I have yet to check it out.

Link: https://github.com/cyber-atomus/autowx

EDIT: I have experienced some lag with webm streaming, scroll down for swf configuration.

Live stream camera (Foscam in my case) over the internet cheat sheet:

apt-get install software-properties-common
add-apt-repository ppa:mc3man/trusty-media
apt-get update
apt-get install ffmpeg

Create ffserver.conf file

nano /etc/ffserver.conf
HTTPPort 8090 # Port to bind the server to
HTTPBindAddress 0.0.0.0
MaxHTTPConnections 2000
MaxClients 15
MaxBandwidth 50000 # Maximum bandwidth per client
 # set this high enough to exceed stream bitrate
CustomLog -

<Feed feed1.ffm>
 File /tmp/feed1.ffm
 FileMaxSize 1g
 ACL allow localhost
 ACL allow 192.168.0.0 192.168.0.255
</Feed>

<Stream live.webm>
 Format webm
 Feed feed1.ffm

 VideoCodec libvpx
 VideoSize 640x480
 VideoFrameRate 30
 VideoBitRate 512
 VideoBufferSize 512
 NoAudio
 AVOptionVideo flags +global_header
 StartSendOnKey

</Stream>

<Stream status.html> # Server status URL
 Format status
 # Only allow local people to get the status
 ACL allow localhost
 ACL allow 192.168.0.0 192.168.0.255
</Stream>

<Redirect index.html> # Just an URL redirect for index
 # Redirect index.html to the appropriate site
 URL live.webm/
</Redirect>

Save, exit and start the services

ffserver > /dev/null 2>&1 &
ffmpeg -loglevel error -r 30 -i rtsp://user:pass@camera_IP:port/url http://LAN_IP_WHERE_FFSERVER_IS_RUNNING:8090/feed1.ffm /dev/null 2>/var/log/ffmpeg.log &

Visit http://LAN_IP_WHERE_FFSERVER_IS_RUNNING:8090/live.webm
For status go to http://LAN_IP_WHERE_FFSERVER_IS_RUNNING:8090/status.html

I have experienced some lag with the above configuration, here is the config for a swf streaming:

HTTPPort 8090 # Port to bind the server to
HTTPBindAddress 0.0.0.0
MaxHTTPConnections 2000
MaxClients 15
MaxBandwidth 50000 # Maximum bandwidth per client
 # set this high enough to exceed stream bitrate
CustomLog -

<Feed feed1.ffm>
 File /tmp/feed1.ffm
 FileMaxSize 1g
 ACL allow localhost
 ACL allow 192.168.0.0 192.168.0.255
</Feed>

<Stream live.ffm>
 Feed feed1.ffm

Format swf
VideoCodec flv
VideoFrameRate 30
VideoBufferSize 80000
VideoBitRate 100
# quality ranges - 1-31 (1 = best, 31 = worst)
VideoQMin 1
VideoQMax 5
VideoSize 1024x786
PreRoll 0
Noaudio

</Stream>

<Stream status.html> # Server status URL
 Format status
 # Only allow local people to get the status
 ACL allow localhost
 ACL allow 192.168.0.0 192.168.0.255
</Stream>

<Redirect index.html> # Just an URL redirect for index
 # Redirect index.html to the appropriate site
 URL live.ffm/
</Redirect>

Save and restart ffserver and ffmpeg.

Edit your index.html file to play swf file in the browser:

<html>
<head>
<meta charset="UTF-8">
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<title>Site title</title>
<script type="text/javascript" src="swfobject.js"></script>
 <script type="text/javascript">
 swfobject.registerObject("myFlashContent", "9.0.0", "expressInstall.swf");
 </script>
 <script type="text/javascript">
 swfobject.embedSWF("http://FF_SERVER_IP:8090/live.ffm", "myContent", "1024", "786", "9.0.0");
 </script>
</head>
<body>
<p align="top">Some optional text.</p>
 <div id="myContent">
 <p>Live stream</p>
 </div>
</video>

</body>

Enable I2C with raspi-config and reboot

Check if the sensor is connected:

i2cdetect -y 1

The output should look like this:

root@rpikiosk:~# i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- 23 -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- 77

Our HTU21D device is detected as the number 40 in the line 40, so the address is 0X40.

#!/usr/bin/python
import struct, array, time, io, fcntl

I2C_SLAVE=0x0703
HTU21D_ADDR = 0x40
CMD_READ_TEMP_HOLD = "\xE3"
CMD_READ_HUM_HOLD = "\xE5"
CMD_READ_TEMP_NOHOLD = "\xF3"
CMD_READ_HUM_NOHOLD = "\xF5"
CMD_WRITE_USER_REG = "\xE6"
CMD_READ_USER_REG = "\xE7"
CMD_SOFT_RESET= "\xFE"

class i2c(object):
   def __init__(self, device, bus):

      self.fr = io.open("/dev/i2c-"+str(bus), "rb", buffering=0)
      self.fw = io.open("/dev/i2c-"+str(bus), "wb", buffering=0)

      # set device address

      fcntl.ioctl(self.fr, I2C_SLAVE, device)
      fcntl.ioctl(self.fw, I2C_SLAVE, device)

   def write(self, bytes):
      self.fw.write(bytes)

   def read(self, bytes):
      return self.fr.read(bytes)

   def close(self):
      self.fw.close()
      self.fr.close()

class HTU21D(object):
   def __init__(self):
      self.dev = i2c(HTU21D_ADDR, 1) #HTU21D 0x40, bus 1
      self.dev.write(CMD_SOFT_RESET) #soft reset
      time.sleep(.1)

   def ctemp(self, sensorTemp):
      tSensorTemp = sensorTemp / 65536.0
      return -46.85 + (175.72 * tSensorTemp)

   def chumid(self, sensorHumid):
      tSensorHumid = sensorHumid / 65536.0
      return -6.0 + (125.0 * tSensorHumid)

   def crc8check(self, value):
      # Ported from Sparkfun Arduino HTU21D Library: https://github.com/sparkfun/HTU21D_Breakout
      remainder = ( ( value[0] << 8 ) + value[1] ) << 8
      remainder |= value[2]
      
      # POLYNOMIAL = 0x0131 = x^8 + x^5 + x^4 + 1
      # divsor = 0x988000 is the 0x0131 polynomial shifted to farthest left of three bytes
      divsor = 0x988000
      
      for i in range(0, 16):
         if( remainder & 1 << (23 - i) ): remainder ^= divsor divsor = divsor >> 1
      
      if remainder == 0:
         return True
      else:
         return False
   
   def read_tmperature(self):
      self.dev.write(CMD_READ_TEMP_NOHOLD) #measure temp
      time.sleep(.1)

      data = self.dev.read(3)
      buf = array.array('B', data)

      if self.crc8check(buf):
         temp = (buf[0] << 8 | buf [1]) & 0xFFFC
         return self.ctemp(temp)
      else:
         return -255
         
   def read_humidity(self):
      self.dev.write(CMD_READ_HUM_NOHOLD) #measure humidity
      time.sleep(.1)

      data = self.dev.read(3)
      buf = array.array('B', data)
      
      if self.crc8check(buf):
         humid = (buf[0] << 8 | buf [1]) & 0xFFFC
         return self.chumid(humid)
      else:
         return -255
         
if __name__ == "__main__":
   obj = HTU21D()
   print "Temp:", obj.read_tmperature(), "C"
   print "Humid:", obj.read_humidity(), "% rH"

Run the script:

root@rpikiosk:~# ./HTU21DF.py
Temp: 22.9382104492 C
Humid: 45.0101318359 % rH

If you connect the ground wire to the wrong Rpi pin, you’ll get this error:

IOError: [Errno 5] Input/output error

 

Pi-Hole is a DNS based ad blocker. You can install it on a Debian based Linux distributions. To use it together with a PfSense firewall you need to change a few firewall settings:

  • Login to your PfSense and go to System -> General Setup:

In the first DNS Server field insert the IP of your Pi-Hole computer and save changes

  • Go to Services -> DNS Resolver:

Tick Enable DNS resolver

Tick Enable DNSSEC Support

Tick Enable Forwarding Mode (this will tell the PfSense to use a DNS server that we configured in a general settings in the previous step)

Save and that’s it.

This post will show you how to generate weather data from LA Crosse WS2300 series weather stations for submission to the APRS network.

APRS software I’m using is Xastir, but you can use this setup to push the weather data to other APRS applications also. Digipeater mode is already set up in Xastir. This post will not cover digipeating WX data.

1. Install packages

apt-get update

apt-get install  bc ncat unzip gcc build-essential

2. Download open2300 and compile fetch2300

Fetch2300 is part of open2300, it’s used to connect to the weather station and return the data. Credit goes to Kenneth Lavrsen (http://www.lavrsen.dk/foswiki/bin/view/Open2300)

wget -O "open2300-1-10.zip" https://sourceforge.net/projects/open2300/files/open2300/1.10/open2300-1.10.zip/download"

unzip open2300-1-10.zip

cd open2300-1.10

make fetch2300

cp fetch2300 /usr/local/bin/fetch2300



3. Edit  and rename open2300 config file named open2300-dist.conf or copy mine to /etc/open2300/open2300.conf

mkdir -p /etc/open2300

nano /etc/open2300/open2300.conf
SERIAL_DEVICE /dev/ttyUSB1 #/dev/ttyS0, /dev/ttyS1, COM1, COM2 etc
TIMEZONE 1 # Hours Relative to UTC. East is positive, west is negative
WIND_SPEED km/h # select MPH (miles/hour), m/s, or km/h
TEMPERATURE F # Select C or F
RAIN IN # Select mm or IN
PRESSURE hPa # Select hPa, mb or INHG

Note: make sure you select the correct SERIAL_DEVICE in the config. The station in my setup

is connected via USB to RS232 converter so the device is ttyUSB0. Also, don’t change the units, bash script will automatically convert them to be compatible with APRS network.

4. Copy bash script to desired location

mkdir -p /root/ws2300/

nano wxdata_v1.6.sh
#!/bin/bash

#This script reads weather data via fetch program which is part of Open2300 suite written by Kenneth Lavrsen (http://www.
#lavrsen.dk/foswiki/bin/view/Open2300/WebHome).
#It outputs the right data needed to feed Xastir for APRS weather reports. The scripts utilizes Ncat utility as server to
#serve the fetched output to Xastir.
#Fetched Data is pushed to Ncat server and then to Xastir. (Fetched data -> Ncat server -> Xastir)
#Ncat is part of Nmap, get it by installing Nmap.
#This script should work for LaCrosse weather stations, WS23xx series. Testing was done with WS2307.
#Written by S55MA and S56IUL, May 2016

#DEFINE VARIABLES
host="127.0.0.1"
port="1234"

#Start the Ncat server
chkncat=$(netstat -ant | grep $host:$port | grep -c LISTEN)
if [ "$chkncat" -ge "1" ]
then
echo "ncat already running, nothing to do"
else
nohup ncat -k -l --broker $host $port &>/dev/null &
fi

#Start while loop
while true; do

echo "start `date`"

datetime=$(date '+%Y%m%d%H%M%S')
ws2300config="/etc/open2300/open2300.conf"
/usr/local/bin/fetch2300 $ws2300config > /tmp/wxdata-"$datetime".tmp
fetch_path="/tmp/wxdata-$datetime.tmp"
chkfile=$(ls -la $fetch_path | awk -F ' ' '{ print $5 }')

if [ "$chkfile" -le "43" ]
then
echo "No Data"
sleep 30
else
tempF=$(cat "$fetch_path" | grep To | grep -v 'min\|max\|DRtot\|TRtot' | awk '{print $2}')
temp1=$(echo "$tempF" | awk '{ printf ("%d\n",$1 + 0.5)}')
if [ "$temp1" -ge "99" ] || [ "$temp1" -le "-99" ]
then
temp="$temp1"
else
if [ "$temp1" -le "-1" ]
then
if [ "$temp1" -ge "-9" ]
then
temp2=$(echo "$temp1" | sed 's/[-]//g')
temp=$(echo -0"$temp2")
else
temp2=$(echo "$temp1" | sed 's/[-]//g')
temp=$(echo -"$temp1")
fi
else
temp=$(echo 0"$temp1")
fi
fi

windspeed2=$(cat "$fetch_path" | grep -m1 WS | grep -v 'min\|max\|DRtot\|TRtot'| awk '{print $2/1.609344}' | awk '{ printf ("%d\n",$1 + 0.5)}')
if [ "$windspeed2" -le "9" ]
then
windspeed=$(echo 00"$windspeed2")
else
if [ "$windspeed2" -le "99" ]
then
windspeed=$(echo 0"$windspeed2")
else
windspeed=$(echo "$windspeed2")
fi
fi

winddirection2=$(cat "$fetch_path" | grep DIR0 | awk '{print $2}' | sed 's/\..*$//')
if [ "$winddirection2" -le "9" ]
then
winddirection=$(echo 00"$winddirection2")
else
if [ "$winddirection2" -le "99" ]
then
winddirection=$(echo 0"$winddirection2")
else
winddirection=$(echo "$winddirection2")
fi
fi

rain1h=$(cat "$fetch_path" | grep R1h | grep -v 'min\|max' | awk '{print $2}' | sed 's/[.]//g')
rain24h=$(cat "$fetch_path" | grep R24h | grep -v 'min\|max' | awk '{print $2}' | sed 's/[.]//g')

airpressureR=$(cat "$fetch_path" | grep RP | grep -v 'min\|max' | awk '{print $2}')
airpressure2=$(echo "scale=1;$airpressureR / 1" | bc | sed 's/[.]//g')
if [ "$airpressure2" -le "9999" ]
then
airpressure=$(echo 0"$airpressure2")
else
airpressure=$(echo "$airpressure2")
fi

relhumidity=$(cat "$fetch_path" | grep RHo | grep -v 'min\|max' | awk '{print $2}' | sed 's/\..*$//')

#Combine variables to forge Xastir string
xastir="c${winddirection}s${windspeed}t${temp}r${rain1h}p${rain24h}b${airpressure}h${relhumidity}xDvs"
printf "%s\n" "$xastir" | ncat --send-only $host $port
echo "$xastir"
sleep 3

rm -f /tmp/wxdata-*.tmp

echo "stop `date`"
echo "-----------------------------------"
fi

done

#EOS



If there are some formatting mistakes, the script is also available on pastebin: http://pastebin.com/29q8epF8

5. Start the script

/root/ws2300/wxdata_v1.6.sh

You should see output similar to that:

start Tue May 3 00:36:47 CEST 2016
c112s013t048b10037h85xDvs

Leave the script running, open another terminal and check if ncat is getting data:

ncat localhost 1234

Wait a few seconds and you should get the result similar to that:

c112s018t048b10037h85xDvs



6. Go to Xastir and add the WX interface

Interface -> Interface Control -> Add -> Networked WX

WX Host: 127.0.0.1

WX Port: 1234

Save and start the interface.

wx_interface

7. Go to Xastir, View -> Own Weather Data

You should see your own weather data from the station

wx_data

8. Start the script at boot and run it in background

Open /etc/rc.local and add

screen -d -m /root/ws2300/wxdata_v1.6.sh

Save and exit

Note: make sure you set your own path of the script location

 

My 5V RaspberryPi fan was very loud and annoying, so I wanted a solution to regulate the fan depending on the Pi temperature.

To achieve that, I used a mosfet switch, pulled out from an old computer motherboard, followed by some easy bash scripting.

Almost any mosfet from an old computer motherboard should work.

motherboard_mosfet

Wiring:

mosfet_fan_schematics

You can use any not used GPIO to connect the gate pin, in the picture above it’s #23.

mosfet_fan_schematics2

I connected the mosfet pin to GPIO 19 in my case. You can choose  your own.

Software:

sudo apt-get update
sudo apt-get install bc

Enable selected GPIO pin, In my case, GPIO 19

echo "19" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio19/direction

If you wan’t to select another GPIO and you already exported one GPIO, you need to unexport previous GPIO.

echo "19" > /sys/class/gpio/unexport

Bash script for controlling fan “speed”:

pico rpipwm.sh

Paste the script bellow, edit your GPIO pin and save:

#!/bin/bash
#Poor man's PWM
#16.11.2015 by S55MA
#Quick and dirty script for controlling fan speed on RaspberryPI
#No rights reserved

#Define GPIO pin
pin="19"

while true; do

#Read temp
temp=$(cat /sys/class/thermal/thermal_zone0/temp | awk 'NR == 1 { print $1 / 1000}' | cut -c -4)

#If temperature is equal or lower than 39.99, the fan will stop spinning
if [[ $(bc <<< "$temp <= 39.99") == 1 ]] ;
then
$(echo "0" > /sys/class/gpio/gpio$pin/value)
fi

#If temperature is between 40 and 42.99, the fan will start with 1 second burst and 1 second sleep
if [[ $(bc <<< "$temp >= 40 && $temp <= 42.99") == 1 ]] ;
then
$(echo "1" > /sys/class/gpio/gpio$pin/value; sleep 1; echo "0" > /sys/class/gpio/gpio$pin/value; sleep 1)
fi

#If temperature is between 43 and 47.99, the fan will start with 1 second burst and 0.5 second sleep
if [[ $(bc <<< "$temp > 43 && $temp <= 47.99") == 1 ]] ;
then
$(echo "1" > /sys/class/gpio/gpio$pin/value; sleep 1; echo "0" > /sys/class/gpio/gpio$pin/value; sleep 0.5)
fi

#If temperature is equal or higher than 48, the fan will start spinning constantly
if [[ $(bc <<< "$temp >= 48") == 1 ]] ;
then
$(echo "1" > /sys/class/gpio/gpio$pin/value)
fi
sleep 0.1
done
chmod +x rpipwm.sh
./rpipwm.sh

Enable auto start at boot:

sudo cp rpipwm.sh /etc/init.d/rpipwm.sh
sudo chmod +x /etc/init.d/rpipwm.sh
sudo update-rc.d /etc/init.d/rpipwm.sh defaults

or you can use crontab:

crontab -e

Add and save:

@reboot /path/to/script/rpipwm.sh
sudo update-rc.d cron defaults

The rpisystat script will report the following system parameters to your LCD:

  • Internal IP
  • External IP
  • CPU temperature
  • GPU temperature
  • CPU usage
  • Memory usage
  • Free disk space
  • Incoming and outgoing network traffic

You need:

1. Breadboard with T-Cobbler (or connect the wires directly)
2. 16×2 LCD board
3. Adjustable resistor (potentiometer) for adjusting LCD contrast

1. Wiring (source: https://learn.adafruit.com/drive-a-16×2-lcd-directly-with-a-raspberry-pi/wiring):

Pin #1 of the LCD goes to ground (black wire)
Pin #2 of the LCD goes to +5V (red wire)
Pin #3 (Vo) connects to the middle of the potentiometer (orange wire)
Pin #4 (RS) connects to the Cobbler #25 (yellow wire)
Pin #5 (RW) goes to ground (black wire)
Pin #6 (EN) connects to Cobbler #24 (green wire)
Skip LCD Pins #7, #8, #9 and #10
Pin #11 (D4) connects to cobbler #23 (blue wire)
Pin #12 (D5) connects to Cobbler #17 (violet wire)
Pin #13 (D6) connects to Cobber #21 (gray wire)
Pin #14 (D7) connects to Cobber #22 (white wire)
Pin #15 (LED +) goes to +5V (red wire)
Pin #16 (LED -) goes to ground (black wire)

raspberry_pi_pi-char-lcd

This schematics is for RaspberryPi 1 version, but you can connect to the same pins on RaspberryPi 2 (picture bellow).

16x2_lcd_display_rpi2

2. Software

Download required packages:

sudo apt-get update
sudo apt-get install python-dev python-setuptools python-pip git
sudo easy_install -U distribute
sudo pip install rpi.gpio

Download my scripts:

sudo git clone git://github.com/s55ma/16-2-LCD-rpisystat.git
cd 16-2-LCD-rpisystat
sudo ./rpisystat.py

Make sure you edit rpisystat.py to match your GPIO pins (default is for the wiring above). Also edit rx.sh and tx.sh to match your network adapter.

Check the display in action: https://www.youtube.com/watch?v=5YkLTBd5-bw

Scripts: https://github.com/s55ma/16-2-LCD-rpisystat

References: https://learn.adafruit.com/drive-a-16×2-lcd-directly-with-a-raspberry-pi/wiring

In my previous post, I was writting about how to graph temperature and humidity from AM2302 sensor on RasberryPi. In addition, we will add dewpoint monitoring. We need two variables to calculate dewpoint, temperature and humidity. I took some already made scripts and combined them together to fit my needs. I wanted to calculate dewpoint completely with bash and bc, but since I’m to lazy, I just used the python script from this blog.

Get to the root shell (we don’t want to type sudo everytime):

sudo -s

Create python script (for dewpoint calculations):

pico /opt/dewpoint.py

Paste the code, save and exit (CTRL + C), Y, ENTER

import sys
import numpy as np

# approximation valid for
# 0 degC < T < 60 degC
# 1% < RH < 100%
# 0 degC < Td < 50 degC

# constants
a = 17.271
b = 237.7 # degC

# sys.argv[0] is program name
T=float(sys.argv[1])
RH=float(sys.argv[2])


def dewpoint_approximation(T,RH):

    Td = (b * gamma(T,RH)) / (a - gamma(T,RH))

    return Td


def gamma(T,RH):

    g = (a * T / (b + T)) + np.log(RH/100.0)

    return g


Td = dewpoint_approximation(T,RH)
print Td

Make the script executable:

chmod +x /opt/dewpoint.py

Create plugin file:

pico /etc/munin/plugins/dewpoint

Paste the code, save and exit (CTRL + C), Y, ENTER

#!/bin/sh

case $1 in
config)
cat <<'EOM'
graph_title Dewpoint
graph_vlabel Celsius
graph_category AM2302
dewpoint.label Temperature
dewpoint.draw AREASTACK
dewpoint.colour 403075
EOM
exit 0;;
esac

humidity=$(/opt/lol_dht22/loldht 7 | grep -i "humidity" | cut -d ' ' -f3)
temperature=$(/opt/lol_dht22/loldht 7 | grep -i "temperature" | cut -d ' ' -f7)

printf "dewpoint.value "
python /opt/dewpoint.py $temperature $humidity
chmod +x /etc/munin/plugins/dewpoint

Open munin-node file:

pico /etc/munin/plugin-conf.d/munin-node

Add the line at the end of the file, save and exit:

[dewpoint*]

Restart services:

munin-node-configure
/etc/init.d/munin-node restart

20151021_150632

Hardware:

  • RasberryPi 2
  • AM2302 humidity/temperature sensor
  • Some wires from old PCs to connect sensor with RaspberryPi

Software:

  • Raspbian OS
  • Nginx
  • Munin
  • WiringPi
  • Lol_dht22

1. Solder wires to the sensor like on the picture above, and connect them to the correct pins:

Pin 1 on the AM2302 to pin 1 (+3.3V) on the GPIO connector (labeled P1 on the raspi)
Pin 2 on the AM2302 to pin 7 (GPIO 4) on the GPIO connector
Pin 4 on the AM2302 to pin 9 (Ground) on the GPIO connector

For detailed instructions, check this blog up to step 4: https://hackaday.io/project/3766/instructions

All shell commands will be run as root, so I will not use sudo.

2. Install Nginx (web server)

apt-get update
apt-get install nginx php5-fpm

3. Install Munin

Muning is a monitoring tool for sysadmins. It creates graphs to monitor various parameters. We will configure munin to display AM2302 sensor in graphs.

apt-get install munin munin-node munin-plugins-extra

Edit munin configuration file:

pico /etc/munin/munin.conf
[server.name]
 address 127.0.0.1
 use_node_name yes

4. Configure Nginx virtual host. Dynazoom will work with this config.

pico /etc/nginx/sites-enabled/default or pico /etc/nginx/sites-enabled/your.domain.com
server {
        listen 443 ssl;
        ssl_certificate /etc/nginx/ssl/your.domain.com.crt;
        ssl_certificate_key /etc/nginx/ssl/your.domain.com.key;
        server_name your.domain.com;
        root "/var/cache/munin/www/";
        auth_basic            "Private access";
        auth_basic_user_file  /etc/munin/munin_htpasswd;

        location ^~ /munin-cgi/munin-cgi-graph/ {
                fastcgi_split_path_info ^(/munin-cgi/munin-cgi-graph)(.*);
                fastcgi_param PATH_INFO $fastcgi_path_info;
                fastcgi_pass unix:/var/run/munin/spawn-fcgi-munin-graph.sock;
                include fastcgi_params;
        }

        location /static/ {
                alias /etc/munin/static/;
        }
}

5. Generate SSL cert

mkdir /etc/nginx/ssl
openssl req -subj '/CN=your.domain.com' -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/your.domain.com.key -out /etc/nginx/ssl/your.domain.com.crt

6. Generate website password

apt-get install apache2-utils
htpasswd -c /etc/munin/munin_htpasswd admin

You will be promted to enter a new password.

7. Add common modules to munin

cd /usr/share/munin/plugins
wget -O pisense_ https://raw.github.com/perception101/pisense/master/pisense_
chmod a+x pisense_
ln -s /usr/share/munin/plugins/pisense_ /etc/munin/plugins/pisense_temp
ln -s /usr/share/munin/plugins/pisense_ /etc/munin/plugins/pisense_clock
pico /etc/munin/plugin-conf.d/munin-node
[pisense_*]
user root

8. Configure AM2302 prerequisites

apt-get install git-core
cd /opt/
git clone git://git.drogon.net/wiringPi
cd wiringPi
./build
cd /opt/
git clone https://github.com/technion/lol_dht22
cd lol_dht22
./configure
make

9. Create plugins for munin

pico /etc/munin/plugins/DHT22-humidity
#!/bin/sh

case $1 in
 config)
 cat <<'EOM'
graph_title Relative humidity
graph_vlabel Percent
graph_category AM2302
humidity.label RH
humidity.draw AREASTACK
humidity.colour 3E9BFB
EOM
 exit 0;;
esac

printf "humidity.value "
/opt/lol_dht22/loldht 7 | grep -i "humidity" | cut -d ' ' -f3
chmod +x /etc/munin/plugins/DHT22-humidity
pico /etc/munin/plugins/DHT22-temperature
#!/bin/sh

case $1 in
 config)
 cat <<'EOM'
graph_title Temperature
graph_vlabel Celsius
graph_category AM2302
temperature.label Celsius
temperature.label Temperature
temperature.draw AREASTACK
temperature.colour 00FF00
EOM
 exit 0;;
esac

printf "temperature.value "
/opt/lol_dht22/loldht 7 | grep -i "temperature" | cut -d ' ' -f7
chmod +x /etc/munin/plugins/DHT22-temperature
pico /etc/munin/plugin-conf.d/munin-node

Add this to the end of the file:

[DHT22-*]
user root

10. Enable Dynazoom for graphs

apt-get install spawn-fcgi libcgi-fast-perl
pico /etc/init.d/munin-fastcgi
#! /bin/sh

### BEGIN INIT INFO
# Provides: spawn-fcgi-munin-graph
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: starts FastCGI for Munin-Graph
### END INIT INFO
# --------------------------------------------------------------
# Munin-CGI-Graph Spawn-FCGI Startscript by Julien Schmidt
# eMail: munin-trac at julienschmidt.com
# www: http://www.julienschmidt.com
# --------------------------------------------------------------
# Install: 
# 1. Copy this file to /etc/init.d
# 2. Edit the variables below
# 3. run "update-rc.d spawn-fcgi-munin-graph defaults"
# --------------------------------------------------------------
# Special thanks for their help to:
# Frantisek Princ
# Jérôme Warnier
# --------------------------------------------------------------
# Last Update: 14. February 2013
#
# Please change the following variables:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=spawn-fcgi-munin-graph
PID_FILE=/var/run/munin/$NAME.pid
SOCK_FILE=/var/run/munin/$NAME.sock
SOCK_USER=www-data
FCGI_USER=www-data
FCGI_GROUP=www-data
FCGI_WORKERS=2
DAEMON=/usr/bin/spawn-fcgi
DAEMON_OPTS="-s $SOCK_FILE -F $FCGI_WORKERS -U $SOCK_USER -u $FCGI_USER -g $FCGI_GROUP -P $PID_FILE -- /usr/lib/munin/cgi/munin-cgi-graph"

# --------------------------------------------------------------
# No edits necessary beyond this line
# --------------------------------------------------------------

if [ ! -x $DAEMON ]; then
 echo "File not found or is not executable: $DAEMON!"
 exit 0
fi

status() {
 if [ ! -r $PID_FILE ]; then
 return 1
 fi
 
 for FCGI_PID in `cat $PID_FILE`; do 
 if [ -z "${FCGI_PID}" ]; then
 return 1
 fi
 
 FCGI_RUNNING=`ps -p ${FCGI_PID} | grep ${FCGI_PID}`
 if [ -z "${FCGI_RUNNING}" ]; then
 return 1
 fi
 done;
 
 return 0
}
 
start() {
 if status; then
 echo "FCGI is already running!"
 exit 1
 else
 $DAEMON $DAEMON_OPTS
 fi
}

stop () { 
 if ! status; then
 echo "No PID-file at $PID_FILE found or PID not valid. Maybe not running"
 exit 1
 fi
 
 # Kill processes
 for PID_RUNNING in `cat $PID_FILE`; do
 kill -9 $PID_RUNNING
 done
 
 # Remove PID-file
 rm -f $PID_FILE
 
 # Remove Sock-File
 rm -f $SOCK_FILE
}

case "$1" in
 start)
 echo "Starting $NAME: "
 start
 echo "... DONE"
 ;;

 stop)
 echo "Stopping $NAME: "
 stop
 echo "... DONE"
 ;;

 force-reload|restart)
 echo "Stopping $NAME: "
 stop
 echo "Starting $NAME: "
 start
 echo "... DONE"
 ;;
 
 status)
 if status; then
 echo "FCGI is RUNNING"
 else
 echo "FCGI is NOT RUNNING"
 fi
 ;;
 
 *)
 echo "Usage: $0 {start|stop|force-reload|restart|status}"
 exit 1
 ;;
esac

exit 0
chmod 755 /etc/init.d/munin-fastcgi
update-rc.d munin-fastcgi defaults
/etc/init.d/munin-fastcgi start

11. Restart daemons and visit your munin site

munin-node-configure

/etc/init.d/nginx restart

/etc/init.d/munin-node restart

Go to https://your.domain.com/munin/

 

Check how to add dewpoint graph on my next post.

References: