質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

Raspberry Pi

Raspberry Piは、ラズベリーパイ財団が開発した、名刺サイズのLinuxコンピュータです。 学校で基本的なコンピュータ科学の教育を促進することを意図しています。

Q&A

解決済

1回答

716閲覧

Raspberry PIにて計測した温度,気圧データをGoogleスプレッドシートに書き込み

yasegata

総合スコア10

Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

Raspberry Pi

Raspberry Piは、ラズベリーパイ財団が開発した、名刺サイズのLinuxコンピュータです。 学校で基本的なコンピュータ科学の教育を促進することを意図しています。

0グッド

1クリップ

投稿2018/07/29 04:21

ラズパイにて測定した温度気圧データをGoogleスプレッドシートに上げたいのですが,コードを起動すると,書き込みエラーが出てしまいました.

Python

1python google_spreadsheet.py 2Logging sensor measurements to t,h every 30 seconds. 3Press Ctrl-C to quit. 4Temperature: 25.5 C 5Humidity: 51.2 % 6Append error, logging in again

こちらのサイトを参考にしております.
リンク内容

こちらに従ってAPIを有効化,サービスアカウントキーも取得しております.
取得したアカウントキーの内容もコードに記述いたしました.

Python

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

どこが間違っているのか,ご指摘いただけると助かります.

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

回答がつかないようなので、直接的な解決策ではないかと思いますが、IFTTTを使ってGoogleSpreadSheetに書き込んでみてはどうでしょうか?

私はこんな感じでやっています。
https://qiita.com/masa328/items/8d1749bb24e41fada6d4

ここも参考に
http://www.daipanman.com/entry/2017/07/07/071949

投稿2018/08/20 09:31

Masa_328

総合スコア65

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yasegata

2018/08/21 00:58

Masa_328様 ご回答いただき誠にありがとうございます。 教えていただいたIFTTTの方法を一度試してみました。 リンクに従い作業の方進めました。 ただ、リンクにある”Maker Webhooks”が見つからなかったため代わりに”Webhooks”を使用いたしました。 その後"test it"からのGoogle sheetへの書き込みを試しましたがGoogle sheetに反映されませんでした。 引き続き何が原因なのかを探ってみたいと思います。
yasegata

2018/08/30 02:03

Masa_328様 あれから教えていただいたやり方を何度か試し、無事にIFTTTを通してGoogleスプレッドシートに1時間毎の温度湿度を書き込むことができました。 余裕があるときにあらためてGoogleAPIを用いてスプレッドシートにデータを書き込むコードを書いてみたいと思います。
Masa_328

2018/08/30 02:24

お疲れ様でした。出来てしまうと何だぁという感じですよね。これからもよろしくお願い致します。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問