Skip to content

Instantly share code, notes, and snippets.

@henrik
Created March 16, 2025 23:02
Show Gist options
  • Save henrik/fd6252e0e9ee4fe06989844b67231772 to your computer and use it in GitHub Desktop.
Save henrik/fd6252e0e9ee4fe06989844b67231772 to your computer and use it in GitHub Desktop.
OnlyCat Ruby API client proof-of-concept.
# OnlyCat API Ruby proof-of-concept.
# By Henrik Nyh <https://henrik.nyh.se> 2025-03-16 under the MIT License.
#
# Based on https://community.home-assistant.io/t/home-assistant-integration-for-onlycat-catflap/814906.
require "bundler/inline"
require "json"
gemfile do
source "https://rubygems.org"
gem "websocket-eventmachine-client"
end
GATEWAY_URI = "wss://gateway.onlycat.com/socket.io/?platform=script&device=ruby-test-script&EIO=4&transport=websocket"
TOKEN_PATH = "~/.onlycat_token"
begin
TOKEN = File.read(File.expand_path(TOKEN_PATH)).chop
rescue Errno::ENOENT
abort "Error: Find your OnlyCat 'Device Token' on the Account tab of the app, and put it in `#{TOKEN_PATH}`."
end
EM.run do
ws = WebSocket::EventMachine::Client.connect(uri: GATEWAY_URI)
ws_send = ->(number, data = nil) {
msg = "#{number}#{data&.to_json}"
puts "-> #{msg}"
ws.send(msg)
}
stop = ->(_) {
puts "Terminating connection."
EventMachine.stop
}
trap("TERM", &stop)
trap("INT", &stop)
ws.onopen do
puts "Connected."
end
ws.onmessage do |msg, type|
puts "<- #{msg}"
case msg
when /\A0\D/
puts "(time to auth)"
ws_send.(40, token: TOKEN)
when /\A2\z/
puts "(ping)"
ws_send.(3)
puts "(pong)"
end
end
ws.onerror do |error|
puts "WS error: #{error}"
end
ws.onclose do |code, reason|
puts "Disconnected. Status code: #{code}; reason: #{reason.inspect}"
end
EventMachine.add_timer 5, -> {
puts "Getting devices."
ws_send.(420, [ "getDevices", { subscribe: false } ])
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment