Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Report device status to AWS IoT (Reporter)
# 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