lib/artoo/robot.rb in artoo-1.4.1 vs lib/artoo/robot.rb in artoo-1.5.0

- old
+ new

@@ -1,10 +1,11 @@ require 'celluloid/autostart' require 'celluloid/io' require 'multi_json' - +require 'artoo/ext/timers' require 'artoo/ext/actor' + require 'artoo/robot_class_methods' require 'artoo/basic' require 'artoo/connection' require 'artoo/adaptors/adaptor' require 'artoo/device' @@ -27,21 +28,22 @@ extend Artoo::Basic extend Artoo::Robot::ClassMethods include Artoo::Utility include Artoo::Events - attr_reader :connections, :devices, :name + attr_reader :connections, :devices, :name, :commands exclusive :execute_startup # Create new robot # @param [Hash] params # @option params [String] :name # @option params [Collection] :connections # @option params [Collection] :devices def initialize(params={}) @name = params[:name] || "Robot #{random_string}" + @commands = params[:commands] || [] initialize_connections(params[:connections] || {}) initialize_devices(params[:devices] || {}) end # @return [String] Name without spaces and downcased @@ -115,11 +117,12 @@ # @return [Hash] robot def to_hash { :name => name, :connections => connections.each_value.collect {|c|c.to_hash}, - :devices => devices.each_value.collect {|d|d.to_hash} + :devices => devices.each_value.collect {|d|d.to_hash}, + :commands => commands } end # @return [JSON] robot def as_json @@ -129,12 +132,35 @@ # @return [String] robot def inspect "#<Robot #{object_id}>" end + def command(method_name, *arguments) + if known_command?(method_name) + if arguments.first + self.send(method_name, *arguments) + else + self.send(method_name) + end + else + "Unknown Command" + end + rescue Exception => e + Logger.error e.message + Logger.error e.backtrace.inspect + return nil + end + + # @return [Boolean] True if command exists + def known_command?(method_name) + return commands.include?(method_name.intern) + end + + private + def initialize_connections(params={}) @connections = {} connection_types.each {|ct| Logger.info "Initializing connection #{ct[:name].to_s}..." cp = params[ct[:name]] || {} @@ -145,10 +171,11 @@ def initialize_devices(params={}) @devices = {} device_types.each {|d| Logger.info "Initializing device #{d[:name].to_s}..." - d = Device.new(d.merge(:parent => current_instance)) + dp = params[d[:name]] || {} + d = Device.new(d.merge(dp).merge(:parent => current_instance)) instance_eval("def #{d.name}; return devices[:#{d.name}]; end") @devices[d.name.intern] = d } end