Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created April 9, 2016 12:33
Show Gist options
  • Save qoobaa/076745e63319783cd9e6db93a9b01e6b to your computer and use it in GitHub Desktop.
Save qoobaa/076745e63319783cd9e6db93a9b01e6b to your computer and use it in GitHub Desktop.
require "optparse"
require "json"
require "net/http"
options = {}
OptionParser.new do |parser|
parser.banner = "Usage: sds011.rb [options]"
parser.on("-dDEVICE", "--device DEVICE", "SDS011 serial port path") do |device|
options[:device] = device
end
parser.on("-fFIREBASE", "--firebase FIREBASE", "Firebase host") do |firebase|
options[:firebase] = firebase
end
parser.on("-tTOKEN", "--token TOKEN", "Firebase authentication token") do |token|
options[:token] = token
end
end.parse!
SDS011_DEV = options.fetch(:device) { raise OptionParser::MissingArgument, "device" }
FIREBASE_HOST = options.fetch(:firebase) { raise OptionParser::MissingArgument, "firebase" }
AUTH_TOKEN = options.fetch(:token, "")
header, command, pm25l, pm25h, pm10l, pm10h, id1, id2, sum, tail = IO.read(SDS011_DEV, 10).unpack("CCCCCCCCCC")
if header == 0xAA && command == 0xC0 && (pm25l + pm25h + pm10l + pm10h + id1 + id2) % 256 == sum && tail == 0xAB
pm25 = (pm25h * 256 + pm25l) / 10.0
pm10 = (pm10h * 256 + pm10l) / 10.0
data = JSON.generate({pm10: pm10, pm25: pm25, timestamp: {".sv": "timestamp"}})
Net::HTTP.start(FIREBASE_HOST, 443, use_ssl: true) do |http|
response = http.post("/measurements.json?auth=#{AUTH_TOKEN}", data)
raise "Firebase communication error #{response.code}" if response.code != "200"
end
else
raise "SDS011 communication error"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment