lib/escalator/config.rb in escalator-0.2.1 vs lib/escalator/config.rb in escalator-0.2.2

- old
+ new

@@ -20,54 +20,77 @@ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'active_support/core_ext/string/inflections' -require "escalator/protocol/protocol" -require 'escalator/uploader' require 'yaml' +require 'json' +require 'protocol/protocol' include Escalator::Protocol::Mitsubishi +include Escalator::Protocol::Keyence +include Escalator::Protocol::Emulator module Escalator - class EscalatorConfig - def self.default - @config ||= begin - config_path = File.join "config", "plc.yml" - h = YAML.load(File.read(config_path)) if File.exist?(config_path) + class << self + + def default + @config ||= begin + load File.join("config", "plc.yml") + end + end + + def load path + h = {} + if File.exist?(path) + h = YAML.load(File.read(path)) + h = JSON.parse(h.to_json, symbolize_names: true) + end new h || {} end + end def initialize options={} - default = {input: "asm/main.asm", output: "build/main.hex"} - @config = options.merge default + default = { + input: "asm/main.asm", + output: "build/main.hex", + } + emulator_default = { + host: "localhost", + port: 5555, + protocol: "emu_protocol", + } + + @config = default.merge options + @config[:plc] ||= {} + @config[:plc][:emulator] = @config[:plc][:emulator] ? emulator_default.merge(@config[:plc][:emulator]) : emulator_default + + @config[:default] ||= {} + + @targets = {} end - def protocol - @protocol ||= begin - plc_info = @config[:plc] - p = eval("#{plc_info[:protocol].camelize}.new") - p.host = plc_info[:host] if plc_info[:host] - p.port = plc_info[:port] if plc_info[:port] - p.log_level = plc_info[:log_level] if plc_info[:log_level] - p - rescue - nil - end + def [] key + @config[key] end - def uploader - @uploader ||= begin - u = Uploader.new - u.protocol = self.protocol - u.program_area = u.protocol.device_by_name(@config[:plc][:program_area]) if @config[:plc] && @config[:plc][:program_area] - u.interaction_area = u.protocol.device_by_name(@config[:plc][:interaction_area]) if @config[:plc] && @config[:plc][:interaction_area] - u + def target name=nil + name ||= (@config[:default][:target] || :emulator) + name = name.to_sym if name.is_a? String + target = @targets[name] + unless target + h = @config[:plc][name] + unless h.nil? || h.empty? + h = {name:name}.merge h + target = EscalatorConfigTarget.new h + @targets[name] = target + end end + target end def method_missing(name, *args) name = name.to_s unless name.is_a? String case name.to_s