Created
May 29, 2012 21:08
-
-
Save eggie5/2830720 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'eventmachine' | |
| class String | |
| #literal_hex_string | |
| def lhs | |
| self.unpack('C*').map {|e| "0x#{e.to_s(16)} "}.join | |
| end | |
| end | |
| module InsteonNetwork | |
| class Client | |
| attr_accessor :connection | |
| def connect | |
| @connection = EM.connect "192.168.1.102", 9761, Listener, self | |
| end | |
| def on_connect(&block) | |
| if block_given? | |
| @on_connect=block | |
| start() | |
| else | |
| @on_connect | |
| end | |
| end | |
| def on_message(&block) | |
| if block_given? | |
| @on_message=block | |
| start() | |
| else | |
| @on_message | |
| end | |
| end | |
| def on_disconnect(&block) | |
| if block_given? | |
| @on_disconnect=block | |
| start() | |
| else | |
| @on_disconnect | |
| end | |
| end | |
| def do_callback(callback, data) | |
| proc = callback | |
| proc.call(data) | |
| end | |
| def start | |
| if EventMachine.reactor_running? | |
| connect() | |
| else | |
| EventMachine.epoll | |
| EventMachine.kqueue | |
| EventMachine::run do | |
| connect() | |
| end | |
| end | |
| end | |
| end | |
| class Listener < EM::Connection | |
| attr_accessor :client | |
| def initialize(client) | |
| @client=client | |
| end | |
| def parse(msg) | |
| msg.unpack('C*') | |
| end | |
| def post_init | |
| @client.do_callback(@client.on_connect, {msg: "connected"}) | |
| end | |
| def receive_data(data) | |
| msg=parse data | |
| @client.do_callback(@client.on_message, {msg: data}) | |
| end | |
| def unbind | |
| @client.do_callback(@client.on_disconnect, {msg: "disconnected"}) | |
| end | |
| end | |
| end | |
| client=InsteonNetwork::Client.new | |
| #event handler for when insteon device broadcasts | |
| client.on_connect do | |
| puts "connected" | |
| end | |
| p "connect handler" | |
| client.on_message do |msg| | |
| puts "msg: #{msg}" | |
| end | |
| p "message handler" | |
| p "listening..." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment