Skip to content

Instantly share code, notes, and snippets.

@ma2shita
Created May 7, 2016 14:38
Show Gist options
  • Save ma2shita/197bc9b328bd21b20083dbc6fe14ff9b to your computer and use it in GitHub Desktop.
Save ma2shita/197bc9b328bd21b20083dbc6fe14ff9b to your computer and use it in GitHub Desktop.
Receive desire from AWS IoT and send command to real-device (Commander)
# Receive desire from AWS IoT and send command to real-device (Commander)
#
# POINT:
# * Listen on /update/delta
# <when Received a delta...>
# 1. Parse the delta
# 2. Execute command according to content
# 3. Erase on 'desired'
# => Should be removed "desired" ASAP after parsing delta
# Remains "desired" is cause of trouble (e.g. Out of sync)
# But, erasing is necessary to consider. In case of failure the delta may be needed
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"
}
MQTT::Client.connect(CONNECT_PARAMS) do |c|
c.get("$aws/things/#{thing_name}/shadow/update/delta") do |_, message| # Flow: Listen on /update/delta
JSON.parse(message).tap{|d|logger.debug(d)}["state"].each do |target, state| # Flow: Parsing delta
begin
Patlite.new(target.downcase.to_sym).send(state.downcase.to_sym) # Flow: Execute command to real-device # NOTE: e.g.) Patlite.new(:red).send(:on)
rescue NameError # NOTE: Ignore if unknown 'target and/or 'state'
logger.info($!.to_s)
logger.info("payload: #{m}")
end
end
MQTT::Client.connect(CONNECT_PARAMS) do |k| # Flow: Erase on 'desired'
k.publish("$aws/things/#{thing_name}/shadow/update", {state:{desired:nil}}.to_json)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment