1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

openweather map(気象情報の提供サイト)から屋外の温度・湿度情報を5分おきに取得

Last updated at Posted at 2021-05-05

部屋の中の温度・湿度は取得できるようになったのですが、屋外のデータも取得したいなと思って外部の気象情報提供サイトを探したところ、無料で使えるopenweathermapというものを見つけました。
そのopenweathermapのデータを以下ページで実施した室内の温湿度データの横に記載しています。

前提

  • googleのアカウントを持っていること

openweathermapの準備

  • 基本的に以下のページを参照して実施しました

  • openweathermapのアカウント作成
    • 以下のページからSign in → Create an Accountで登録
    • Sign in → API keys で API keyが発行できます。複数も発行できます。
    • APIをたたけるようになるまで一晩かかった気がします

  • APIのテスト
    • 以下のURLにブラウザでアクセスして表示されることを確認
https://api.openweathermap.org/data/2.5/weather?lang=en&q=tokyo&appid={API key}&units=metric

google spread sheetの設定

  • google spread sheetで1個ファイルを作成

    • ファイル名は自由に設定、シート名は"test1"とします
  • ツール→スクリプトエディタからgoogle apps scriptを開き、以下を貼り付ける

var spreadsheetId = 'スプレッドシートのIDを入れる'

function getWeatherOfTokyo() {
 const response = UrlFetchApp.fetch('https://api.openweathermap.org/data/2.5/weather?lang=en&q=tokyo&appid={API key}&units=metric')
 const forecast = JSON.parse(response.getContentText())
 const date = new Date()
 const mySheet = SpreadsheetApp.getActiveSheet()
 const lastRow = mySheet.getLastRow()
 mySheet.getRange(lastRow, 15).setValue(Utilities.formatDate(date, 'Asia/Tokyo', 'yyyy/MM/dd HH:mm:ss'))

 mySheet.getRange(lastRow, 16).setValue(forecast.main.temp)
 mySheet.getRange(lastRow, 17).setValue(forecast.main.humidity)
 mySheet.getRange(lastRow, 18).setValue(forecast.main.pressure)
 mySheet.getRange(lastRow, 19).setValue(forecast.weather[0].main)
 mySheet.getRange(lastRow, 20).setValue(forecast.weather[0].description)
 mySheet.getRange(lastRow, 21).setValue(forecast.rain) 
}
  • ちなみに、私はraspberry piから取得している部屋の中の温湿度データに追記したいので、last rowの15列目以降に追記するやり方をしていますが、このスクリプトだけで動かすなら、lastrow+1にしないと上書きされてしまいます。
  • raspberry piから取得する方法はこちら↓を参照

トリガーの設定

  • 旧エディタなら時計マーク、新しいエディタなら左メニューからトリガーを選択 → トリガーを追加 →
    • 実行する関数:作った関数(getWeatherOfTokyo)
    • 実行するデプロイ:Head
    • イベントのソース:時間主導型
    • 時間ベースのトリガーのタイプ:分ベースのタイマー
    • 時間の間隔:5分おき
      • 1日1000リクエストの上限があるので(無料だと)、5分おきがいいと思います

データをGoogle Data Portalで表示できるようにしています

2021年3月から始めたスマートホーム化はこちらに一覧化しています(2021年5月時点)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?