lynxeyedの電音鍵盤

MBDとFPGAと車載で使うデバイスの備忘録

FlashAirからTwitterに天気をポストする

前回のFlashAirネタの続きです

CJSONが使える

FlashAir W-03シリーズはLuaスクリプトが使えるわけですが、スクリプト中でCJSONも使えることが公式ページに書いてありました。へぇ、すごいじゃん。

JSON形式でデータが取り扱えると何かと便利です。
たとえばFlashAirならGPIO機能使って指定した時間にブザーを鳴らしたいとき
LuaでGPIO制御命令を記述し、時刻情報はJSON形式で
{”beep_date”:"20150510","beep_time":"06:30:00 JST"}
みたいなデータをupload.cgiでアップさせれば良いわけです。

天気情報の取得

今回は、CJSONのお勉強もかねて、天気予報をTwitterにポストさせてみました。使用した天気情報はOpenWeatherMap current weather and forecastのサービスです。

東京のお天気情報は
http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp
からJSON形式で取得できます。

データは以下のような構造になっています。

{
	"coord":{
		"lon":139.69,
		"lat":35.69
		},
	"sys":{
		"message":0.0325,
		"country":"JP",
		"sunrise":1431027729,
		"sunset":1431077599
	},
	"weather":[
		{
			"id":802,
			"main":"Clouds",
			"description":"scattered clouds",
			"icon":"03n"
		}
	],
	"base":"stations",
	"main":{
		"temp":288.78,
		"temp_min":288.78,
		"temp_max":288.78,
		"pressure":1021.85,
		"sea_level":1026.83,
		"grnd_level":1021.85,
		"humidity":99
	},
	"wind":{
		"speed":3.39,
		"deg":195.501
	},
	"clouds":{
		"all":44
	},
	"dt":1431092484,
	"id":1850147,
	"name":"Tokyo",
	"cod":200
}

Luaスクリプト

今回は

  • 天気情報(weather[0].description)
  • 最高気温(main.temp_max)
  • 最低気温(main.temp_min)

を取得してTwitterにポストしました。なお、Luaはデフォルトでは配列は[1]から始まるようなので天気情報はweather[1].descriptionとなります。なんだかMATLABみたい。

ポストには相変わらずStewgate-Uを使っています。

組み込み関数はローカルの参照を持ったほうが高速に動作するので、冒頭部分で宣言しています。

print("HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=utf-8\r\n")

local s_find = string.find
local s_len = string.len
local fa_req = fa.request
local i_cloz = io.close
local i_open = io.open
local cjson = require "cjson"

contenttype = "application/json;charset=utf-8"			
bb,cc,hh = fa_req{url = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp",
		method = "GET", 
		headers = {["Content-Type"] = contenttype
			}
		}
bb = cjson.decode(bb)
print(bb.weather[1].description)

temp_min = tonumber(bb.main.temp_min) - 273.15 -- 絶対温度から摂氏に変換
temp_max = tonumber(bb.main.temp_max) - 273.15
weathe = bb.weather[1].description
			
bb,cc,hh = fa_req{url = "https://ntp-a1.nict.go.jp/cgi-bin/time",
			method = "GET"
		}

mes = "_t=(ここにStewgate-Uのトークンを書く)&msg=東京の最高気温: "..tostring(temp_max).."℃ 最低気温:"..tostring(temp_min).."℃ 天気: "..weathe..". posted at "..bb
blen = s_len(mes)
			
contenttype = "application/x-www-form-urlencoded"
b,c,h = fa_req{url = "http://stewgate-u.appspot.com/api/post/",
		 method = "POST",
		 headers = {["Content-Length"] = tostring(blen),
		 ["Content-Type"] = contenttype},
		body = mes
	}
print(tostring(b))

ブラウザから上記luaスクリプトを呼び出し、成功すると、
f:id:Lynx-EyED:20150508235102p:plain

なんか、最高気温=最低気温になっちゃってるね…。なんでだろ。

おしまい。

参考リンク

  • qiita.com
  • database-tearoom.seesaa.net