Advertisement
Guest User

Untitled

a guest
Jul 4th, 2015
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.79 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Write some message on the display.
  4. # This project uses https://github.com/dbrgn/RPLCD.
  5. # sudo apt-get install python-matplotlib
  6.  
  7. from __future__ import print_function, division, absolute_import, unicode_literals
  8.  
  9. import sys
  10.  
  11. # Import LCD stuff from RPLCD, et. al.
  12. from RPLCD import CharLCD
  13. from RPLCD import Alignment, CursorMode, ShiftMode
  14. from RPLCD import cursor, cleared
  15.  
  16. from xml.dom.minidom import *
  17. import urllib
  18. import RPi.GPIO as GPIO
  19. import time
  20. import csv
  21.  
  22. # Imports for graph plotting
  23. import numpy as np
  24. import matplotlib.pyplot as plt
  25. import matplotlib.dates as mdates
  26.  
  27. import os
  28. import subprocess
  29. import shutil
  30.  
  31.  
  32. # some LCD magic happens here
  33. try:
  34. input = raw_input
  35. except NameError:
  36. pass
  37.  
  38. try:
  39. unichr = unichr
  40. except NameError:
  41. unichr = chr
  42.  
  43. # ###################################################################################
  44. # Configure stuff here:
  45. # Temp sensor ID is the folder name for ds18b20 1-wire sensors
  46. # found in /sys/bus/w1/devices/
  47. # Drivers are loaded with
  48. # sudo modprobe w1-gpio
  49. # sudo modprobe w1-therm
  50. # or put them in /etc/modules
  51. TempSensorInside = '28-000005ad1070'
  52. TempSensorOutside = '28-000005ad0691'
  53. # Yahoo location code. Get the right one for your location from Yahoo's weather page.
  54. LocationID = '700029'
  55. # ###################################################################################
  56.  
  57. # Disable useless GPIO warnings
  58. GPIO.setwarnings(False)
  59.  
  60. # Start Yahoo weather stuff
  61. # Weather array
  62. # Dimensions: 1 = today, 2 = tomorrow
  63. # Elements: 1 = day, 2 = date, 3 = low temp, 4 = high temp, 5 = weather text
  64. Weatherarray = [["", "", "", "", ""] , ["", "", "", "", ""]]
  65.  
  66. # Fetch weather XML for Trier, Germany
  67. Trier = urllib.urlopen('http://weather.yahooapis.com/forecastrss?w=' + LocationID + '&u=c').read()
  68.  
  69. # Parse the XML
  70. Trier = parseString(Trier)
  71.  
  72. # Get town
  73. Place = Trier.getElementsByTagName('yweather:location')[0]
  74. City = Place.attributes["city"].value
  75. Country = Place.attributes["country"].value
  76.  
  77. # Get date
  78. Date = Trier.getElementsByTagName('lastBuildDate')[0].firstChild.data
  79.  
  80. # Get coordinates
  81. Geo_Lat = Trier.getElementsByTagName('geo:lat')[0].firstChild.data
  82. Geo_Long = Trier.getElementsByTagName('geo:long')[0].firstChild.data
  83.  
  84. # Get today's weather
  85. Today = Trier.getElementsByTagName('yweather:condition')[0]
  86. Weathertext = Today.attributes["text"].value
  87. Temperature = float(Today.attributes["temp"].value)
  88. Conditioncode = Today.attributes["code"].value
  89.  
  90. # Put it all in a list
  91. for Counter in range(2):
  92.  
  93. # Weather data for two days
  94. # Get data
  95. Future = Trier.getElementsByTagName('yweather:forecast')[Counter]
  96.  
  97. # Process data
  98. Weatherarray[Counter][0] = Future.attributes["day"].value
  99. Weatherarray[Counter][1] = Future.attributes["date"].value
  100. Weatherarray[Counter][2] = float(Future.attributes["low"].value)
  101. Weatherarray[Counter][3] = float(Future.attributes["high"].value)
  102. Weatherarray[Counter][4] = Future.attributes["text"].value
  103. # End Yahoo weather stuff.
  104.  
  105. # Start sensor stuff
  106. # The inside sensor
  107. # Open, read, close the sensor files
  108. tempfilein = open("/sys/bus/w1/devices/" + TempSensorInside + "/w1_slave")
  109.  
  110. textin = tempfilein.read()
  111.  
  112. tempfilein.close()
  113.  
  114. # Jump to the right position in the sensor file, convert the string to a number, put the decimal point in
  115. secondlinein = textin.split("n")[1]
  116. temperaturedatain = secondlinein.split(" ")[9]
  117. temperaturein = float(temperaturedatain[2:])
  118. temperaturein = temperaturein / 1000
  119. # print temperaturein
  120.  
  121. # The outside sensor
  122. tempfileout = open("/sys/bus/w1/devices/" + TempSensorOutside + "/w1_slave")
  123.  
  124. textout = tempfileout.read()
  125.  
  126. tempfileout.close()
  127.  
  128. # Jump to the right position in the sensor file, convert the string to a number, put the decimal point in
  129. secondlineout = textout.split("n")[1]
  130. temperaturedataout = secondlineout.split(" ")[9]
  131. temperatureout = float(temperaturedataout[2:])
  132. temperatureout = temperatureout / 1000
  133. # print temperatureout
  134.  
  135. lcd = CharLCD()
  136.  
  137.  
  138. # Print the data onto the display.
  139. lcd.clear()
  140. lcd.write_string(time.strftime("%d.%m.%Y %H:%M"))
  141. lcd.cursor_pos = (1, 0)
  142. #lcd.write_string(str(City) + ' ')
  143. lcd.write_string('Innen: '+ str(temperaturein) + ' Grad')
  144. lcd.cursor_pos = (2, 0)
  145. lcd.write_string('Aussen: '+ str(temperatureout) + ' Grad')
  146. lcd.cursor_pos = (3, 0)
  147. lcd.write_string(Weathertext)
  148.  
  149. # Write the data to a webpage on the local server
  150. # Get some weather icons that are compliant with Yahoo condition codes. The ones by MerlinTheRed are nice and work well <http://merlinthered.deviantart.com/art/plain-weather-icons-157162192> CC-BY-NC-SA
  151. index = open('/var/www/aktuell.html','w')
  152. index.write('<style type="text/css">body {font-weight:lighter; font-family:Arial; font-size:100%; } h2 {margin:0 0 0 0;}''</style><h6>Updated: ' + time.strftime("%d.%m.%Y %H:%M:%S") + '</h6>' + Weathertext + '<img src="' + Conditioncode + '.png" align="right" alt="Wettericon"><br> Sensordaten: <br> Innen:<br><h2>' + str(temperaturein) + ' &deg;C</h2><br> Aussen:<br><h2>' + str(temperatureout) + '&deg;C</h2><br>')
  153. index.close()
  154.  
  155.  
  156. # Write data to a .csv file for graph creation
  157. weather_csv = open('/home/pi/YAWP/weather.csv', 'a')
  158. datawriter = csv.writer(weather_csv)
  159. datawriter.writerow([str(time.strftime('%Y-%m-%d %H:%M')),str(temperaturein),str(temperatureout)])
  160. weather_csv.close()
  161.  
  162. # From here, a gnuplot file will take over.
  163. p = subprocess.Popen("gnuplot plotter.gpi", shell = True)
  164. os.waitpid(p.pid, 0)
  165.  
  166. # Copy it over to the webserver
  167. shutil.copy2('/home/pi/YAWP/temps.png', '/var/www/')
  168.  
  169. class Elements():
  170. def __init__(self, day='', date='', low='', high='', weather=''):
  171. self.day = day
  172. self.date = date
  173. self.low = low
  174. self.high = high
  175. self.text= weather
  176.  
  177. # Creates `[Elements(), Elements()]`
  178. weather_array = [Elements()]*2
  179.  
  180. ...
  181.  
  182. for elem in weather_array:
  183. for prop in ['day', 'date', 'low', 'high', 'text']:
  184. val = Future.attributes[prop].value
  185.  
  186. if prop == 'low' or prop == 'high':
  187. val = float(val)
  188. setattr(elem, prop, val)
  189.  
  190. string = 'This is ' + foo + ' some string concatenation'
  191.  
  192. >>>'Hello {}!'.format('World')
  193. 'Hello World!'
  194.  
  195. with open('some_file.txt', 'r') as file:
  196. # Do something
  197.  
  198. # The file is closed at this point.
  199. foo = 'hello world!'
  200.  
  201. temp_data= ''
  202. temperatures = {temp_sensor_inside:0.0, temp_sensor_outside:0.0}
  203. for sensor in temperatures:
  204. with open('/sys/bus/w1/devices/{}/w1_slave'.format(sensor), 'r') as my_file:
  205. # Iterate line-by-line grabbing both the line number and its text
  206. for line, text in enumerate(my_file):
  207. if line == 2:
  208. temp_data = line.split(' ')[9]
  209.  
  210. # Assign the correct variable.
  211. temperatures[sensor] = float(temp_data[2:])/1000
  212.  
  213. break
  214.  
  215. >>>import os.path
  216. >>>file_path = os.path.join('~', 'Documents', 'my_file.txt')
  217. >>>file_path
  218. '~\Documents\my_file.txt'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement