Skip to content

Instantly share code, notes, and snippets.

@abachman
Last active April 4, 2017 17:04
Show Gist options
  • Save abachman/b7fafbbc096843fce2e3f5e58a8967eb to your computer and use it in GitHub Desktop.
Save abachman/b7fafbbc096843fce2e3f5e58a8967eb to your computer and use it in GitHub Desktop.
Publish images to io.adafruit.com
source 'https://rubygems.org'
gem 'mqtt'
# mac only!
gem 'av_capture'
# If you have trouble installing, this is what worked for me:
#
# $ brew install imagemagick@6
# $ PKG_CONFIG_PATH='/usr/local/opt/imagemagick@6/lib/pkgconfig:$PKG_CONFIG_PATH' gem install rmagick
#
# The PKG_CONFIG_PATH I used came from the output of the brew install command.
#
# https://github.com/Homebrew/homebrew-core/pull/8756
gem 'rmagick'
require 'av_capture'
require 'RMagick'
require 'mqtt'
require 'json'
# MQTT Client
AIO_USER=ENV['AIO_USER']
AIO_KEY=ENV['AIO_KEY']
AIO_URL='io.adafruit.com'
AIO_PROTOCOL='mqtts'
AIO_PORT=8883
# connecting to IO
connect_uri = "#{AIO_PROTOCOL}://#{AIO_USER}:#{AIO_KEY}@#{AIO_URL}"
puts "CONNECT #{connect_uri}"
client = MQTT::Client.connect(connect_uri, AIO_PORT, ack_timeout: 10)
IMAGE_TOPIC = "#{AIO_USER}/f/image-stream"
SHUTTER_TOPIC = "#{AIO_USER}/f/click/json"
def post_image(client)
# Create a recording session
session = AVCapture::Session.new
dev = AVCapture.devices.select(&:video?).last
image = nil
# Connect the camera to the recording session
puts "[post_image] SNAP"
session.run_with(dev) do |connection|
# Capture an image and store as image
image = Magick::Image.from_blob(connection.capture)[0]
end
puts "[post_image] PREP"
# pull center chunk
image.crop!(Magick::CenterGravity, 700, 700)
# write to local file, reducing quality to make sure it fits
image.write('snapshot.jpg') do
self.format = 'jpeg'
self.quality = 75
end
# encode to base64 from command line
encoded = `cat snapshot.jpg | base64`.strip
puts "[post_image] size: #{ encoded.size } bytes"
puts "[post_image] PUBLISH"
client.publish(IMAGE_TOPIC, encoded, true, 0)
rescue => ex
puts "[post_image] failed to publish image: #{ex.message}"
puts ex.backtrace[0..5].join("\n")
end
client.get(SHUTTER_TOPIC) do |topic, message|
value = nil
begin
obj = JSON.parse(message)
value = obj['last_value'].to_i
rescue => ex
puts "failed to parse: #{message}"
puts "error: #{ex.message}"
end
if value === 1
puts 'click received'
post_image(client)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment