Skip to content

Commit 73a46c4

Browse files
author
brentru
committed
adding updated DHT speadsheet code, for use with CircuitPython
1 parent be21e26 commit 73a46c4

1 file changed

Lines changed: 125 additions & 0 deletions

File tree

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
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+
DHT_TYPE = adafruit_dht.DHT22
37+
38+
# Example of sensor connected to Raspberry Pi Pin 23
39+
DHT_PIN = board.D4
40+
# Example of sensor connected to Beaglebone Black Pin P8_11
41+
# DHT_PIN = 'P8_11'
42+
43+
# Initialize the dht device, with data pin connected to:
44+
dhtDevice = DHT_TYPE(DHT_PIN)
45+
46+
# Google Docs OAuth credential JSON file. Note that the process for authenticating
47+
# with Google docs has changed as of ~April 2015. You _must_ use OAuth2 to log
48+
# in and authenticate with the gspread library. Unfortunately this process is much
49+
# more complicated than the old process. You _must_ carefully follow the steps on
50+
# this page to create a new OAuth service in your Google developer console:
51+
# http://gspread.readthedocs.org/en/latest/oauth2.html
52+
#
53+
# Once you've followed the steps above you should have downloaded a .json file with
54+
# your OAuth2 credentials. This file has a name like SpreadsheetData-<gibberish>.json.
55+
# Place that file in the same directory as this python script.
56+
#
57+
# Now one last _very important_ step before updating the spreadsheet will work.
58+
# Go to your spreadsheet in Google Spreadsheet and share it to the email address
59+
# inside the 'client_email' setting in the SpreadsheetData-*.json file. For example
60+
# if the client_email setting inside the .json file has an email address like:
61+
# 149345334675-md0qff5f0kib41meu20f7d1habos3qcu@developer.gserviceaccount.com
62+
# Then use the File -> Share... command in the spreadsheet to share it with read
63+
# and write acess to the email address above. If you don't do this step then the
64+
# updates to the sheet will fail!
65+
GDOCS_OAUTH_JSON = 'spreadapi.json'
66+
67+
# Google Docs spreadsheet name.
68+
GDOCS_SPREADSHEET_NAME = 'DHT'
69+
70+
# How long to wait (in seconds) between measurements.
71+
FREQUENCY_SECONDS = 30
72+
73+
74+
def login_open_sheet(oauth_key_file, spreadsheet):
75+
"""Connect to Google Docs spreadsheet and return the first worksheet."""
76+
try:
77+
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
78+
credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)
79+
gc = gspread.authorize(credentials)
80+
worksheet = gc.open(spreadsheet).sheet1 # pylint: disable=redefined-outer-name
81+
return worksheet
82+
except Exception as ex: # pylint: disable=bare-except, broad-except
83+
print('Unable to login and get spreadsheet. Check OAuth credentials, spreadsheet name, \
84+
and make sure spreadsheet is shared to the client_email address in the OAuth .json file!')
85+
print('Google sheet login failed with error:', ex)
86+
sys.exit(1)
87+
88+
89+
print('Logging sensor measurements to \
90+
{0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS))
91+
print('Press Ctrl-C to quit.')
92+
worksheet = None
93+
while True:
94+
# Login if necessary.
95+
if worksheet is None:
96+
worksheet = login_open_sheet(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME)
97+
98+
# Attempt to get sensor reading.
99+
temp = dhtDevice.temperature
100+
humidity = dhtDevice.humidity
101+
102+
# Skip to the next reading if a valid measurement couldn't be taken.
103+
# This might happen if the CPU is under a lot of load and the sensor
104+
# can't be reliably read (timing is critical to read the sensor).
105+
if humidity is None or temp is None:
106+
time.sleep(2)
107+
continue
108+
109+
print('Temperature: {0:0.1f} C'.format(temp))
110+
print('Humidity: {0:0.1f} %'.format(humidity))
111+
112+
# Append the data in the spreadsheet, including a timestamp
113+
try:
114+
worksheet.append_row((datetime.datetime.now().isoformat(), temp, humidity))
115+
except: # pylint: disable=bare-except, broad-except
116+
# Error appending data, most likely because credentials are stale.
117+
# Null out the worksheet so a login is performed at the top of the loop.
118+
print('Append error, logging in again')
119+
worksheet = None
120+
time.sleep(FREQUENCY_SECONDS)
121+
continue
122+
123+
# Wait 30 seconds before continuing
124+
print('Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME))
125+
time.sleep(FREQUENCY_SECONDS)

0 commit comments

Comments
 (0)