Created
May 7, 2016 14:39
-
-
Save ma2shita/905a4d4a8a58377736154f79e769806f to your computer and use it in GitHub Desktop.
Report device status to AWS IoT (Reporter)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Report device status to AWS IoT (Reporter) | |
# | |
# POINT: | |
# 1. Delete exist shadow(status) for initialize [optional] | |
# 2. Fetch state of real-device | |
# 3. Formatting for submit to AWS IoT | |
# 4. Report to AWS IoT | |
# 2~4 <endless-loop> | |
require "timers" # NOTE: https://github.com/celluloid/timers | |
require "mqtt" # NOTE: https://github.com/njh/ruby-mqtt | |
require "./patlite" | |
require "logger" | |
require "json" | |
# TODO: parameter-fy | |
thing_name = "patlite0" | |
Patlite.host = "192.168.254.209" | |
logger = Logger.new(STDERR) | |
logger.level = Logger::DEBUG | |
CONNECT_PARAMS = { | |
host: "data.iot.ap-northeast-1.amazonaws.com", port: 8883, ssl: true, | |
cert_file: "awsiot_thing-certificate.pem.crt", key_file: "awsiot_thing-private.pem.key", | |
ca_file: "VeriSign-Class_3-Public-Primary-Certification-Authority-G5.pem" | |
} | |
interval = 10 # seconds | |
MQTT::Client.connect(CONNECT_PARAMS) do |c| # Flow: Delete exist shadow for initialize | |
c.publish("$aws/things/#{thing_name}/shadow/delete", nil) | |
end | |
timers = Timers::Group.new | |
fetch_and_report = timers.now_and_every(interval) do # NOTE: Loop using Celluloid/timers | |
status = [:red, :yellow, :green].inject(Hash.new) do |memo, i| # Flow: Fetch state from real-device | |
memo[i] = Patlite.new(i).state? | |
memo | |
end | |
payload_as_json = {state: {reported: status} }.to_json.tap{|d| logger.debug(d) } # Flow: Formatting for submit to AWS IoT | |
MQTT::Client.connect(CONNECT_PARAMS) do |c| # Flow: Report to AWS IoT | |
c.publish("$aws/things/#{thing_name}/shadow/update", payload_as_json) | |
end | |
end | |
trap(:INT) { | |
fetch_and_report.cancel | |
exit | |
} | |
loop { timers.wait } # NOTE: loop start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment