Skip to content

Commit a115e24

Browse files
authored
Merge pull request #728 from brentru/add-dht-spreadsheet-code
Add CircuitPython-based DHT Google Sheets Code
2 parents be21e26 + ed2db8e commit a115e24

1 file changed

Lines changed: 126 additions & 0 deletions

File tree

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
"""
2+
Google Spreadsheet DHT Sensor Data-logging Example
3+
4+
Copyright (c) 2014 Adafruit Industries
5+
Author: Tony DiCola
6+
Modified by: Brent Rubell for Adafruit Industries
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
"""
26+
import sys
27+
import time
28+
import datetime
29+
30+
import board
31+
import adafruit_dht
32+
import gspread
33+
from oauth2client.service_account import ServiceAccountCredentials
34+
35+
# Type of sensor, can be `adafruit_dht.DHT11` or `adafruit_dht.DHT22`.
36+
# For the AM2302, use the `adafruit_dht.DHT22` class.
37+
DHT_TYPE = adafruit_dht.DHT22
38+
39+
# Example of sensor connected to Raspberry Pi Pin 23
40+
DHT_PIN = board.D4
41+
# Example of sensor connected to Beaglebone Black Pin P8_11
42+
# DHT_PIN = 'P8_11'
43+
44+
# Initialize the dht device, with data pin connected to:
45+
dhtDevice = DHT_TYPE(DHT_PIN)
46+
47+
# Google Docs OAuth credential JSON file. Note that the process for authenticating
48+
# with Google docs has changed as of ~April 2015. You _must_ use OAuth2 to log
49+
# in and authenticate with the gspread library. Unfortunately this process is much
50+
# more complicated than the old process. You _must_ carefully follow the steps on
51+
# this page to create a new OAuth service in your Google developer console:
52+
# http://gspread.readthedocs.org/en/latest/oauth2.html
53+
#
54+
# Once you've followed the steps above you should have downloaded a .json file with
55+
# your OAuth2 credentials. This file has a name like SpreadsheetData-<gibberish>.json.
56+
# Place that file in the same directory as this python script.
57+
#
58+
# Now one last _very important_ step before updating the spreadsheet will work.
59+
# Go to your spreadsheet in Google Spreadsheet and share it to the email address
60+
# inside the 'client_email' setting in the SpreadsheetData-*.json file. For example
61+
# if the client_email setting inside the .json file has an email address like:
62+
# 149345334675-md0qff5f0kib41meu20f7d1habos3qcu@developer.gserviceaccount.com
63+
# Then use the File -> Share... command in the spreadsheet to share it with read
64+
# and write acess to the email address above. If you don't do this step then the
65+
# updates to the sheet will fail!
66+
GDOCS_OAUTH_JSON = 'your SpreadsheetData-*.json file name'
67+
68+
# Google Docs spreadsheet name.
69+
GDOCS_SPREADSHEET_NAME = 'DHT'
70+
71+
# How long to wait (in seconds) between measurements.
72+
FREQUENCY_SECONDS = 30
73+
74+
75+
def login_open_sheet(oauth_key_file, spreadsheet):
76+
"""Connect to Google Docs spreadsheet and return the first worksheet."""
77+
try:
78+
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
79+
credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)
80+
gc = gspread.authorize(credentials)
81+
worksheet = gc.open(spreadsheet).sheet1 # pylint: disable=redefined-outer-name
82+
return worksheet
83+
except Exception as ex: # pylint: disable=bare-except, broad-except
84+
print('Unable to login and get spreadsheet. Check OAuth credentials, spreadsheet name, \
85+
and make sure spreadsheet is shared to the client_email address in the OAuth .json file!')
86+
print('Google sheet login failed with error:', ex)
87+
sys.exit(1)
88+
89+
90+
print('Logging sensor measurements to\
91+
{0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS))
92+
print('Press Ctrl-C to quit.')
93+
worksheet = None
94+
while True:
95+
# Login if necessary.
96+
if worksheet is None:
97+
worksheet = login_open_sheet(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME)
98+
99+
# Attempt to get sensor reading.
100+
temp = dhtDevice.temperature
101+
humidity = dhtDevice.humidity
102+
103+
# Skip to the next reading if a valid measurement couldn't be taken.
104+
# This might happen if the CPU is under a lot of load and the sensor
105+
# can't be reliably read (timing is critical to read the sensor).
106+
if humidity is None or temp is None:
107+
time.sleep(2)
108+
continue
109+
110+
print('Temperature: {0:0.1f} C'.format(temp))
111+
print('Humidity: {0:0.1f} %'.format(humidity))
112+
113+
# Append the data in the spreadsheet, including a timestamp
114+
try:
115+
worksheet.append_row((datetime.datetime.now().isoformat(), temp, humidity))
116+
except: # pylint: disable=bare-except, broad-except
117+
# Error appending data, most likely because credentials are stale.
118+
# Null out the worksheet so a login is performed at the top of the loop.
119+
print('Append error, logging in again')
120+
worksheet = None
121+
time.sleep(FREQUENCY_SECONDS)
122+
continue
123+
124+
# Wait 30 seconds before continuing
125+
print('Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME))
126+
time.sleep(FREQUENCY_SECONDS)

0 commit comments

Comments
 (0)