Showing posts with label Raspberry Pi. Show all posts
Showing posts with label Raspberry Pi. Show all posts

Feb 1, 2015

Mail DS18B20 temperature sensor alert

If you have working DS18B20 temperature sensors configured from here and want to receive mail when temperature is high or low next script is for you.

CODE:

 #!/usr/bin/python  
 # -*- coding: utf-8 -*-  
 #  
 # read 1-wire sensor  
 # in case of value exceeding alarm limit  
 # send email via smtp  
 # 2013-06-06 V0.2 by Thomas Hoeser  
 # 2015-02-01 Edited by Aleksandar Stoichkov  
 #  
 import sys  
 import smtplib  
 from email.mime.multipart import MIMEMultipart  
 from email.mime.text import MIMEText  
 mail_server  = 'smtp.gmail.com:587'      # Mail Server  
 mail_account = 'sendersmail@gmail.com'  # name of mail account  
 mail_password = 'senderspassword'      # password  
 addr_sender  = 'sendersmail@gmail.com'  # sender email  
 addr_receiver = 'receiversmail@gmail.com'  # receiver email  
 verbose_level = 2  
 debug_level  = 0  
 error_temp = -999  
 # dictionary with for 1-wire sensors: [sensor name] [1-Wire device]  
 sensor_dict = {  "IN": "28-000004d05fbe",  
         "OUT"  : "28-000004d05fbe",  
         "Office" : "28-00000534eec5"  
         }  
 #-------------------------------------------------------------------------------------------  
 def read_sensor(Sensor):  
   if verbose_level > 2:   
     print "1++++ read_sensor()"    
     print "sensor:" , Sensor  
   if debug_level == 0:  
     # get 1-Wire id from dictionary  
     sensor_slave = str(sensor_dict.get(Sensor))  
     # Open 1-wire slave file  
     sensor_device = '/sys/bus/w1/devices/' + str(sensor_slave) + '/w1_slave'  
     if verbose_level > 2:   
       print "open: ", sensor_device  
     try:  
       file = open(sensor_device)  
       filecontent = file.read()             # Read content from 1-wire slave file  
       file.close()                      # Close 1-wire slave file  
       stringvalue = filecontent.split("\n")[1].split(" ")[9] # Extract temperature string  
       if stringvalue[0].find("YES") > 0:  
         temp = error_temp  
       else:  
         temp = float(stringvalue[2:]) / 1000      # Convert temperature value  
       # temp=str(temp)  
     except IOError:  
       print "PANIC read_sensor - Cannot find file >" + sensor_slave + "< in /sys/bus/w1/devices/"  
       print "No sensor attached"  
       print "check with > cat /sys/devices/w1_bus_master1/w1_master_slaves"  
       temp=("Sensor not attached")  
   else:  
     # this is dummy function generating a random number  
     # ony used for testing purposes  
     temp = random.randrange(-10, 30, 2) + 0.3  
     # temp = Sensor + " " + str(temp)  
   return(temp) # exit function read_sensor  
 # --------------------------------------------------------------------------------  
 def send_mail(title,message):  
      debug_level = 0 # set to 1 to get more messages  
      # Create message container - the correct MIME type is multipart/alternative.  
      msg = MIMEMultipart('alternative')  
      msg['Subject'] = title  
      msg['From'] = addr_sender  
      msg['To'] = addr_receiver  
      # Create the body of the message (a plain-text and an HTML version).  
      text = message  
      html = """\  
 """  
      html += message  
      html += """\  
 This is a service provided by raspberry  
 """  
      # print html  
      # Record the MIME types of both parts - text/plain and text/html.  
      part1 = MIMEText(text, 'plain')  
      part2 = MIMEText(html, 'html')  
      # Attach parts into message container.  
      msg.attach(part1)  
      msg.attach(part2)  
      mailsrv = smtplib.SMTP('smtp.gmail.com' , 587)  
     mailsrv.starttls()  
      mailsrv.login("sendesrsmail@gmail.com", "senderspassword")  
      mailsrv.sendmail("sendersmail@gmail.com", "receiversmail@gmail.com", msg.as_string())  
      mailsrv.quit()  
      return()  
      try:  
           if debug_level > 0: print "smtplib.SMTP:", mail_server  
           mailsrv = smtplib.SMTP(mail_server) # Send the message via local SMTP server.  
      except:  
           print "Error: unable to send email - smtp server"  
           print "Server on ", mail_server, " cannot be reached or service is down"  
           return()  
      try:  
           if debug_level > 0: print "mailsrv.login:", mail_account, mail_password  
           mailsrv.login(mail_account,mail_password)  
      except:  
           print "Error: unable to send email - login failed"  
           print "login is not valid - check name and password:",mail_account,mail_password  
           return()  
      try:  
           # sendmail function takes 3 arguments: sender's address, recipient's address and message to send - here it is sent as one string.  
           if debug_level > 0: print "mailsrv.sendmail:", addr_sender, addr_receiver  
           mailsrv.sendmail(addr_sender, addr_receiver, msg.as_string())  
           mailsrv.quit()  
           print "Successfully sent email"  
      except:  
           print "Error: unable to send email - wrong address"  
           print "mail address for sender or receiver invalid:",addr_sender,addr_receiver  
 #---------------------------------------------------------------------------------------------    
 if __name__ == "__main__":  
   alarm_hi = 70.5    # upper alarm level  
   alarm_lo = 12.5    # lowe alarm level  
   cur_temp = read_sensor("OUT")  
   print cur_temp, alarm_hi, alarm_lo  
   if cur_temp == error_temp:  
    print "read error - CRC = NO"  
   else:  
    if (cur_temp > alarm_hi) or (cur_temp < alarm_lo):  
      subject = "Critical Warning Alert"  
      message = "Temperature is: " + str(cur_temp)  
      print subject, message  
      send_mail(subject,message)  
    else:  
      print "o.k."  
   sys.exit(0)  
Add script to crontab:
 su -  #to become root  
 crontab -e  #to edit crontab lines  
 Add this:  
 *30 * * * * python /home/pi/python_test/mailsendDS18b20alert1.py #this will check temp every 30min.  
Also you can download script from DROPBOX
Save and exit and you are done! Enjoy!
You can buy sensors from HERE

Jan 25, 2015

High CPU temperature Raspberry Pi warning by mail

Prevent to bake your Raspberry Pi with this script. It alerts you by mail when CPU temperature is too high. Let's start.... Create your script file:
 cd to /path/you/prefered/   
 sudo nano nameofscript.py #this wiil create blank file and paste code   
CODE:
 #!/usr/bin/env python  
 # coding=utf-8  
 import os  
 import smtplib  
 from email.mime.text import MIMEText  
 # At First we have to get the current CPU-Temperature with this defined function  
 def getCPUtemperature():  
  res = os.popen('vcgencmd measure_temp').readline()  
  return(res.replace("temp=","").replace("'C\n",""))  
 # Now we convert our value into a float number  
 temp = float(getCPUtemperature())  
 # Check if the temperature is abouve 60°C (you can change this value, but it shouldn't be above 70)  
 if (temp >50):  
  # Enter your smtp Server-Connection  
  server = smtplib.SMTP('smtp.gmail.com' , 587)  
  #if your using gmail: smtp.gmail.com  
  server.ehlo()  
  server.starttls()  
  server.ehlo  
  # Login  
  server.login("yourmail@gmail.com" , "yourpassword")  
  # Now comes the Text we want to send:  
  value = "Warning! Too high CPU Temperature is: " + getCPUtemperature()  
  msg = MIMEText(value)  
  # The Subject of your E-Mail  
  msg['Subject'] = "Warning! Too high CPU Temperature:" + getCPUtemperature()  
  # Consigner of your E-Mail  
  msg['From'] = "Raspberry Pi"  
  # recipient of your E-Mail  
  msg['To'] = "receivermail@gmail.com"  
  # Finally send the mail  
  server.sendmail("yourmail@gmail.com", "receivermail@gmail.com", msg.as_string())  
  server.quit()  
Fill your data and save file (CTRL+O-> Enter) and exit (CTRL+X). To test it just make temperature lower than actual. If you receive mail everything is correct. One more thing add script to crontab:
 su - # to become root  
 crontab -e # to edit   
Then add:
 */5 * * * * python /path/to/yourscript/yourscript.py 2>&1 # this will check your temp every 5 minutes  
And again save file (CTRL+O-> Enter) and exit (CTRL+X). That's it! You are done!

You can buy sensors from HERE

Jan 24, 2015

Daily CPU and harddisk status updates on Raspberry PI by mail

Very useful script to daily status updates of CPU temperature and attached HDD on your Raspberry Pi.
To create a script copy the code and make a file with command:
 cd to /path/you/prefered/  
 sudo nano nameofscript.py #this wiil create blank file and paste code   

CODE:
 # coding=utf-8  
 import os  
 import smtplib  
 import statvfs  
 from datetime import timedelta  
 from email.mime.text import MIMEText  
 #Read the systems uptime:  
 with open('/proc/uptime', 'r') as f:  
   uptime_seconds = float(f.readline().split()[0])  
 # At First we have to get the current CPU-Temperature with this defined function  
 def getCPUtemperature():  
  res = os.popen('vcgencmd measure_temp').readline()  
  return(res.replace("temp=","").replace("'C\n",""))  
 # Now we convert our value into a float number  
  temp = float(getCPUtemperature())  
 #Read the statistics of the drives in bytes and convert to Gigabytes (using the mount points)  
 GB = (1024 * 1024) * 1024  
 HDD = os.statvfs ("/media/SERVICE")  # in my case is mounted to /media/ , name is SERVICE  
 HDD = (HDD.f_frsize * HDD.f_bfree)/GB  
 #HDD1 = os.statvfs ("/media/HDD2")  
 #HDD1 = (HDD1.f_frsize * HDD1.f_bfree) / GB  
 # Enter your smtp Server-Connection  
 server = smtplib.SMTP('smtp.gmail.com' , 587)  
  #if your using gmail: smtp.gmail.com  
 server.ehlo()  
 server.starttls()  
 server.ehlo  
  # Login  
 server.login("yourmail@gmail.com" , "yourpassword")  
 # Now comes the Text we want to send. It will send the System Uptime, the CPU Temperature and the free space of your hard drives:  
 value = "System Uptime (hh:mm:ss) is: " + str(timedelta(seconds = uptime_seconds)) + "\n" + "CPU Temperature is: " + getCPUtemperature() + "C " + "\n" + "HDD Free Space: " + str(HDD) + " GB"  
 msg = MIMEText(value)  
 # The Subject of your E-Mail  
 msg['Subject'] = "Daily Raspberry Pi Status" #you can wtite everyting you prefer   
 # Consigner of your E-Mail  
 msg['From'] = "Raspberry Pi"  
 # recipient of your E-Mail  
 msg['To'] = "receivermail@gmail.com"  
 # Finally send the mail  
 server.sendmail("sendermail@gmail.com", "receivermail@gmail.com", msg.as_string())  
 server.quit()  
You have to change this lines according where your HDD is mounted and name of it:
 HDD = os.statvfs ("/media/SERVICE")      # in my case is mounted to media and name is SERVICE  
 HDD = (HDD.f_frsize * HDD.f_bfree)/GB  
Check where is maunted and what's the name of HHD with this command:
 df -h   
You will see it of the bottom of output. When you are ready with edited code test it with this command: cd /path/to/script sudo python nameofscript.py and wait to receive mail :) If everything is OK add script to crontab:
 su - #to become a root  
 crontab – e # to edit cron jobs  
and add this line:
 */*10* * * * python /path/to/yourscript/temp_usbHDD_status.py 2>&1   
 # with this you will receive mail every day at 10 am.  
To save it -> CTRL+O-> Enter To exit -> CTRL+X Final result: That's it! You are done!
Source

You can buy sensors from HERE

Jan 8, 2014

Monitor fireplace water temperature using Raspberry Pi + DS18B20 sensors + Alarm

Before you start make sure that you have configured cacti installation.
To complete the project, you will need the following parts :
  • Raspberry Pi
  • DS18B20 Digital temperature sensor(s)
  • 4 .7K or 10K ohm resistor
  • Jumper wire
I used waterproof version of the DS18B20 the device has three leads: red(VCC), black(GND) and yellow(DATA). Every seller may have different variation of colors!
How to connect sensor to your Raspberry Pi.


As you can see sensor is NOT waterproof, but this is only for example!
Now login in Raspberry Pi and open terminal. You can use ssh to operate with Pi.
Type these commands into a terminal window:
 sudo modprobe w1-gpio 
 sudo modprobe w1-therm 
 cd /sys/bus/w1/devices 
 ls 
 cd 28-xxxx (change this to match what serial number pops up) 
 cat w1_slave 

If everything is OK, you will see current temperature.

I have two sensors with unique serial numbers for my fireplace in/out water.
I use this perl script,because reading the sensors on the command line with cat isn't very useful.

Script is for ONLY ONE SENSOR!
 #!/usr/bin/perl
 $mods = `cat /proc/modules`;
 if ($mods =~ /w1_gpio/ && $mods =~ /w1_therm/)
 {
  print "w1 modules already loaded \n";
 }
 else 
 {
 print "loading w1 modules \n";
 $mod_gpio = `sudo modprobe w1-gpio`;
 $mod_them = `sudo modprobe w1-therm`;
 }
 $sensor_temp = `cat /sys/bus/w1/devices/10-*/w1_slave 2>&1`;
 if ($sensor_temp !~ /No such file or directory/)
 {
 if ($sensor_temp !~ /NO/)
 {
     $sensor_temp =~ /t=(\d+)/i;
     $tempreature = (($1/1000)-0); #You can fix your temp value.In this case is0
     print "fireplace temp = $tempreature\n"; #Print fireplace temp as result
     exit;
 }
 die "Error locating sensor file or sensor CRC was invalid";
 }

Now you need to install RRDtool archiving and graphing temperature readings.
This command will install it.
 sudo apt-get install rrdtool

Then create database to store readings.
 pi@raspberrypi:~/rrdtool create fireplace.rrd --step 300 \ 
 DS:temp:GAUGE:600:0:100 \ 
 RRA:AVERAGE:0.5:1:12 \ 
 RRA:AVERAGE:0.5:1:288 \ 
 RRA:AVERAGE:0.5:12:168 \ 
 RRA:AVERAGE:0.5:12:720 \ 
 RRA:AVERAGE:0.5:288:365 

A shell script produces graphs.
 
 #!/bin/bash 
 RRDPATH="/home/pi/temperature/" 
 RAWCOLOUR="#FF0000" 
 TRENDCOLOUR="#0000FF" 
 # Edited 2012/12/9 to add running averages to hourly and daily graphs 
 #hour 
 rrdtool graph $RRDPATH/hour.png --start -6h \ 
 DEF:temp=$RRDPATH/fireplace.rrd:temp:AVERAGE \ 
 CDEF:trend=temp,1800,TREND \ 
 LINE2:temp$RAWCOLOUR:"Hourly Raspberry PI temperature" \ 
 LINE1:trend$TRENDCOLOUR:"30 min average" 
 #day 
 rrdtool graph $RRDPATH/day.png --start -1d \ 
 DEF:temp=$RRDPATH/fireplace.rrd:temp:AVERAGE \ 
 CDEF:trend=temp,21600,TREND \ 
 LINE2:temp$RAWCOLOUR:"Daily Raspberry PI temperature" \ 
 LINE1:trend$TRENDCOLOUR:"6h average" 
 #week 
 rrdtool graph $RRDPATH/week.png --start -1w \ 
 DEF:temp=$RRDPATH/fireplace.rrd:temp:AVERAGE \ 
 LINE2:temp$RAWCOLOUR:"Weekly Raspberry PI temperature" \ 
 #month 
 rrdtool graph $RRDPATH/month.png --start -1m \ 
 DEF:temp=$RRDPATH/fireplace.rrd:temp:AVERAGE \ 
 LINE1:temp$RAWCOLOUR:"Monthly Raspberry PI temperature" \ 
 #year 
 rrdtool graph $RRDPATH/year.png --start -1y \ 
 DEF:temp=$RRDPATH/fireplace.rrd:temp:AVERAGE \ 
 LINE1:temp$RAWCOLOUR:"Yearly Raspberry PI temperature" \ 

To run the perl sensor reading code and the graph generating script every five minutes from a cron job.
 # m h dom mon dow command 
 */5 * * * * /home/pi/temperature/get_temp_one.pl 
 */5 * * * * /home/pi/temperature/graph_temp_one.sh  

Where get_temp_one.pl is the perl sensor code, and graph_temp.sh plots the graphs.



Cacti can use external rrd files. I found very good tutorial to make it happen.
TUTORIAL: external rrd files in cacti

Aaand final result in cacti!





You can download all need files from DROPBOX
 get_temp_one.pl - script for ONE sensor 
 get_temp_multiple.pl – script for MULTIPLE sensors 
 graph_temp_one.sh – graph ONE sensor 
 graph_temp_multiple.sh – graph MULTIPLE sensor 
 create_rrd.sh – creates rrd file 
 createrrd_multi.sh - creates rrd file for multiple sensors 

If you want mail alert when temperature is high or low check here.
 

 Hope you like it! Enjoy!

You can buy  DS18B20 sensors from HERE


Apr 9, 2013

SELL Raspberry Pi Starter Kit

Raspberry Pi Starter Kit
Items Condition: Brand New / Factory Sealed In Box
Raspberry Pi 512MB - Model B 2.0 System Board
Specifications
  • SoC Broadcom BCM2835 (CPU, GPU, DSP, and SDRAM)
  • CPU: 700 MHz ARM1176JZF-S core (ARM11 family)
  • GPU: Broadcom VideoCore IV, OpenGL ES 2.0, 1080p30 h.264/MPEG-4 AVC high-profile decoder
  • Memory (SDRAM): 512 Megabytes (MB)
  • Video outputs: Composite RCA, HDMI
  • Audio outputs: 3.5 mm jack, HDMI
  • Onboard storage: SD, MMC, SDIO card slot
  • 10/100 Ethernet RJ45 onboard network
  • Storage via SD/ MMC/ SDIO card slot
  • Package Includes
    • 1x Raspberry Pi 512MB - Model B 2.0 System Board
    • 1x Transparent Case (Require Assembly) Please remove the plastic membrane before use!!! 
    • 1x Wi Fi adapter
    • 1x AC adapter ( EU UK USA ) plug
    • 1x HDMI cable 1m 
    • 1x 8GB SD Card SanDisk 
Orders before 5.00pm shipped same day Monday to Friday!!!Any duty charges are to be paid by buyer.

Location Sofia, Bulgaria
 
 

NOT AVAILABLE!!!Please let me know if you have any further questions.
actrules at gmail.com

Thanks!!!

Mar 5, 2013

SELL New Aluminium Raspberry Pi cases

























Brand new aluminium cases for Raspberry Pi model B



Boxes will be delivered disassembled. They will need to be assembled with your Raspberry Pi.

Masking will be left on to prevent scratches during shipping. This is to be removed by the buyer. It peals off like sticker backing.

Any duty charges are to be paid by buyer.

Large quantities available. Just send me a note for a custom quote.



Click together design
    With easy access to all ports



Orders before 5.00pm shipped same day Monday to Friday!!!

Location Sofia, Bulgaria
 

NOT AVAILABLE!Please let me know if you have any further questions.Thanks!!!

Feb 5, 2013

SELL Brand new acrylic cases for Raspberry Pi model B











Boxes will be delivered disassembled. They will need to be assembled with your Raspberry Pi.

Masking will be left on to prevent scratches during shipping. This is to be removed by the buyer. It peals off like sticker backing.

Any duty charges are to be paid by buyer.

Large quantities available. Just send me a note for a custom quote.



Click together design
    With easy access to all ports

Orders before 5.00pm shipped same day Monday to Friday!!!


Location Sofia, Bulgaria
 NOT AVAILABLE!
Please let me know if you have any further questions.Thanks!!!