Created
March 12, 2017 16:30
-
-
Save boverby/a02cd6a81746bd6d7a7134b47bed33e5 to your computer and use it in GitHub Desktop.
simple script to read ds18b20 on ntc chip, requires 4.4.13 kernel for w1_therm module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# "ds18b20.pl" collect data from ds18b20 via one-wire modules | |
# and save in mysql and mqtt | |
use strict; | |
use warnings; | |
# most logic lifted from http://webshed.org/wiki/RaspberryPI_DS1820 | |
# required mysql permissions like: | |
# GRANT ALL ON environ.* to rh@'192.168.1.XXX' IDENTIFIED BY 'rh'; | |
use DBI; | |
use Net::MQTT::Simple "192.168.1.91"; | |
my $user="rh"; | |
my $password="rh"; | |
my $dsn = "DBI:mysql:database=environ;host=192.168.1.91"; | |
my $dbh = DBI->connect($dsn, $user, $password); | |
die( "Unable to connect:\n $DBI::errstr\n") unless $dbh; | |
my $dt = `date '+%Y-%m-%d %H:%M:%S'`; chomp $dt; | |
my $mods = `cat /proc/modules`; | |
if ($mods =~ /w1_gpio/ && $mods =~ /w1_therm/) { | |
#print STDERR "w1 modules already loaded \n"; | |
} else { | |
`logger w1 modules not loaded`; | |
die "w1 modules not loaded\n"; | |
} | |
my @devices = `cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves`; | |
chomp @devices; | |
for my $device ( @devices ){ | |
next unless ( $device =~ m/^28-/ ); | |
my $sensor_temp = `cat /sys/bus/w1/devices/${device}/w1_slave 2>&1`; | |
if ($sensor_temp !~ /No such file or directory/) { | |
if ($sensor_temp !~ /NO/) { | |
$sensor_temp =~ /t=(\d+)/i; | |
my $tempInC = sprintf("%3.2f",($1/1000)); | |
my $tempInF = sprintf("%3.1f", ( $tempInC * 1.8) + 32 ) ; | |
#-- persist to mysql ----------------- | |
my $insertSQL = qq[insert into measures | |
(evtime,sernum,meas,val) | |
values (?,?,?,?)]; | |
my $insertCursor = $dbh->prepare( $insertSQL ) || die DBI::errstr; | |
$insertCursor->execute( $dt,$device,'temperature',$tempInF); | |
#-- persist to mqtt ------------------- | |
retain "temperature/study" => "$tempInF"; | |
#-- save to /var/log/messages --------- | |
`logger $0 temperature/study $tempInF `; | |
exit; | |
} | |
die "Error locating sensor file or sensor CRC was invalid\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment