Anthonyfromtheuk
Posts: 17
Joined: Sat Mar 29, 2014 3:28 pm
Location: UK

tweeting DS18B20 sensor data

Thu Apr 17, 2014 9:18 pm

SOLVED DOWN BELOW :lol:

Hello, I am trying to get my raspberry pi to tweet sensor data.
I have searched for this but all i get is tweet your raspberries temperature nothing about using sensors.
I came across this code from http://www.averagemanvsraspberrypi.com/ ... t-its.html

Code: Select all

 #!/usr/bin/env python  
   
 import smtplib  
 from email.mime.text import MIMEText  
   
 temp1 = ""   
 f=os.popen("/opt/vc/bin/vcgencmd measure_temp")   
  for i in f.readlines():   
  temp1 += i   
  USERNAME = "[email protected]"   
  PASSWORD = "YourGmailPassword"   
  MAILTO = "[email protected]"   
  msg = MIMEText(temp1)   
  msg['Subject'] = 'My RPi temperature is '   
  msg['From'] = USERNAME   
  msg['To'] = MAILTO   
  server = smtplib.SMTP('smtp.gmail.com:587')   
  server.ehlo_or_helo_if_needed()   
  server.starttls()   
  server.ehlo_or_helo_if_needed()   
  server.login(USERNAME,PASSWORD)   
  server.sendmail(USERNAME, MAILTO, msg.as_string())   
  server.quit()   
unfortunately i cannot get that fully working yet i get indentation errors but the basic idea of that is perfect. my question would be how to adapt that to get the DS18B20 sensor data tweeted. I am guessing there is a way to run the required commands to get the data out (

Code: Select all

sudo modprobe w1-gpio
,

Code: Select all

sudo modprobe w1-therm
, then change to sensors directory and run

Code: Select all

cat w1_slave
but i am lost at how to do this in python. can anybody assist me please?
Last edited by Anthonyfromtheuk on Fri Apr 18, 2014 4:13 pm, edited 1 time in total.

User avatar
DougieLawson
Posts: 36578
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: tweeting DS18B20 sensor data

Thu Apr 17, 2014 10:31 pm

Use tweepy it's trivial to get that working with python.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

User avatar
rpdom
Posts: 15601
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: tweeting DS18B20 sensor data

Fri Apr 18, 2014 5:19 am

I use ttytter for tweeting. It can either run in an interactive terminal mode, or can post tweets from the command line. Once configured it should be easy to use from python (or any other language).

User avatar
DougieLawson
Posts: 36578
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: tweeting DS18B20 sensor data

Fri Apr 18, 2014 8:51 am

Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

Anthonyfromtheuk
Posts: 17
Joined: Sat Mar 29, 2014 3:28 pm
Location: UK

Re: tweeting DS18B20 sensor data

Fri Apr 18, 2014 11:32 am

I got the original twitter thing I was using "fixed" sorted the indentation and added import os, just unfortunately Googles not liking my username and password. I ripped some code from a different source which is not fully working in the manner I want but I think it shows more what I am trying to do here.

Code: Select all

import time
import RPi.GPIO as GPIO
import subprocess 
subprocess.call(['echo', "Working"])       
subprocess.call(['modprobe', 'w1-gpio'])
subprocess.call(['modprobe', 'w1-therm'])
                filename = "/sys/bus/w1/devices/"+globals.DallasSensorDirectory[no]+"/w1_slave"
                if (fileexists(filename)):
                        tfile = open(filename)
                else:
                        return 0
                # Read all of the text in the file.
                text = tfile.read()
                # Close the file now that the text has been read.
                tfile.close()
                #Perform a CRC Check
                firstline  = text.split("\n")[0]
                crc_check = text.split("crc=")[1]
                crc_check = crc_check.split(" ")[1]
                if crc_check.find("YES")>=0:
                        break
        secondline = text.split("\n")[1]
        temperaturedata = secondline.split(" ")[9]
        temperature = float(temperaturedata[2:])
        temperature = temperature / 1000
        temp = float(temperature)
        temp = round(temp,2)
        return(temp)
                
What I am after is something like that so I can then so I can send the chopped down temperature reading. I can incorporate a working version in to any working twitter thing, but most preferably the fixed original code I was using. ifttt.com that code is using to tweet is so simple and allows so many options.
Last edited by Anthonyfromtheuk on Fri Apr 18, 2014 2:20 pm, edited 1 time in total.

Anthonyfromtheuk
Posts: 17
Joined: Sat Mar 29, 2014 3:28 pm
Location: UK

Re: tweeting DS18B20 sensor data

Fri Apr 18, 2014 2:16 pm

Got the raspberry pi to tweet its own temperature now i am trying to use this code to tweet the sensor data

Code: Select all

#!/usr/bin/env python
import os, glob, time, sys, datetime, smtplib  
from email.mime.text import MIMEText
#initiate the temperature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

#set up the location of the sensor in the system
device_folder = glob.glob('/sys/bus/w1/devices/28*')
device_file = [device_folder[0] + '/w1_slave']


def read_temp_raw(): #a function that grabs the raw temperature data from the sensor
    f_1 = open(device_file[0], 'r')
    lines_1 = f_1.readlines()
    f_1.close()
    return lines_1


def read_temp(): #a function that checks that the connection was good and strips out the temperature
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES' or lines[2].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t='), lines[3].find('t=')
    temp = float(lines[1][equals_pos[0]+2:])/1000
    return temp
USERNAME = "[email protected]"
PASSWORD = "MYPASSWORD"
MAILTO = "[email protected]"
msg = MIMEText(temp)
msg['Subject'] = 'Current sensor temperature is '
msg['From'] = USERNAME
msg['To'] = MAILTO
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(USERNAME,PASSWORD)
server.sendmail(USERNAME, MAILTO, msg.as_string())
print "Email sent"
server.quit()
but i get an error from the line "msg = MIMEText(temp)" temp is not defined it says, what am i doing wrong here?

User avatar
DougieLawson
Posts: 36578
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: tweeting DS18B20 sensor data

Fri Apr 18, 2014 2:19 pm

If we start with a copy of the code from your linked thread we can hack it to get the data into an email

Code: Select all

def main():

#### delete all the Google spreadsheet stuff here ...

   temptosheet=(read_temp())
   temp1=str(temptosheet[0])
   temp2=str(temptosheet[1])

   dict = {} #the headers in this dictionary need to match the headers in the spreadsheet exactly
   dict['date'] = time.strftime('%d/%m/%Y')
   dict['time'] = time.strftime('%H:%M:%S')
   dict['temp1'] = temp1
   dict['temp2'] = temp2
   
   print dict #print for debugging 

### NEW CODE STARTS HERE 

   toaddr = '[email protected]'    # redacted
   me = '[email protected]' # redacted
   subject = 'Temp ' + dict['time'] + " " + dict['date']

   msg = MIMEMultipart()
   msg['Subject'] = subject
   msg['From'] = me
   msg['To'] = toaddr
   msg.preamble = subject
   
   text = "Temp1: " + dict['temp1'] + "\r\nTemp2: " + dict['temp2'] + "\r\n"
   part1 = MIMEtext(text,'plain')
   msg.attach(part1)

   try:
      s = smtplib.SMTP('localhost')
      s.send_message(msg)
      s.quit()
   except:
      print ("Error: unable to send email")

#### NEW CODE ENDS HERE
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

Anthonyfromtheuk
Posts: 17
Joined: Sat Mar 29, 2014 3:28 pm
Location: UK

Re: tweeting DS18B20 sensor data

Fri Apr 18, 2014 4:12 pm

Got it working! Thanks for all the replies, especially DougieLawson. even though you didnt answer my question directly you did make me realise what I was doing wrong. I didn't realise MIME didn't read variables. Also previously posted code wasn't giving out the output I even wanted. I had to chop the output up to get it to show the way I want. This was interesting for me besides the standard "hello world" I have never really used python, just going off my limited scripting knowledge from sqf coding for the game arma 3 :geek:

Anyway heres the working code:

Code: Select all

#!/usr/bin/env python
import os, glob, time, sys, datetime, smtplib  
from email.mime.text import MIMEText
#initiate the temperature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

device_folder = glob.glob('/sys/bus/w1/devices/28*')
device_file = [device_folder[0] + '/w1_slave']


def read_temp_raw(): 
    f_1 = open(device_file[0], 'r')
    lines_1 = f_1.readlines()
    f_1.close()
    return lines_1


def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES' or lines[2].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t='), lines[3].find('t=')
    temp = float(lines[1][equals_pos[0]+2:])/1000
    return temp

foremail= ""
temp = read_temp_raw() 
outputmain= temp[1][-6:-4]
outputdecimel= temp[1][-3]
finaloutput= outputmain+"."+outputdecimel+"C"
print finaloutput

f= (finaloutput)
for line in f:
    foremail= f
    

USERNAME = "[email protected]"
PASSWORD = "MYPASSWORD"
MAILTO = "[email protected]"
msg = MIMEText(foremail)
msg['Subject'] = 'Current sensor temperature is '
msg['From'] = USERNAME
msg['To'] = MAILTO
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(USERNAME,PASSWORD)
server.sendmail(USERNAME, MAILTO, msg.as_string())
print "Email sent"
server.quit()
Could be cleaned up a bit and only seems to work when i am logged in as root user, but I am well chuffed! :D

Return to “Python”