Skip to content

Instantly share code, notes, and snippets.

@qoobaa qoobaa/sds011.rb
Created Apr 9, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.