Module: E3DCMqtt::ConfigLoader
- Defined in:
- lib/e3dc_mqtt/config.rb
Constant Summary collapse
- DURATION_UNITS =
{ "ns" => 1e-9, "us" => 1e-6, "µs" => 1e-6, "ms" => 1e-3, "s" => 1.0, "m" => 60.0, "h" => 3600.0 }.freeze
Class Method Summary collapse
Class Method Details
.build(raw) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/e3dc_mqtt/config.rb', line 49 def build(raw) e3dc_raw = raw["e3dc"] || {} mqtt_raw = raw["mqtt"] || {} e3dc = E3DCConfig.new( host: e3dc_raw["host"], port: e3dc_raw["port"] || 5033, username: e3dc_raw["username"], password: e3dc_raw["password"], key: e3dc_raw["key"], interval: parse_duration(e3dc_raw["interval"] || "5s"), statistic_update_interval: parse_duration(e3dc_raw["statistic_update_interval"] || "5m") ) mqtt = MQTTConfig.new( url: mqtt_raw["url"], root: mqtt_raw["root"], client_id: mqtt_raw["client_id"] || "e3dc-mqtt-ruby", username: mqtt_raw["username"] || "", password: mqtt_raw["password"] || "", tls_verify: mqtt_raw.fetch("tls_verify", true) ) cfg = Config.new( log_level: raw["log_level"] || "INFO", e3dc: e3dc, mqtt: mqtt ) validate!(cfg) cfg end |
.load(path) ⇒ Object
40 41 42 43 44 45 46 47 |
# File 'lib/e3dc_mqtt/config.rb', line 40 def load(path) raw = TomlRB.load_file(path) build(raw) rescue Errno::ENOENT raise ConfigError, "cannot read config file: #{path}" rescue TomlRB::ParseError => e raise ConfigError, "cannot parse config file: #{e.}" end |
.parse_duration(str) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/e3dc_mqtt/config.rb', line 25 def parse_duration(str) raise ConfigError, "duration must be a string, got #{str.inspect}" unless str.is_a?(String) total = 0.0 rest = str.dup until rest.empty? md = rest.match(/\A(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/) raise ConfigError, "invalid duration: #{str.inspect}" unless md total += md[1].to_f * DURATION_UNITS.fetch(md[2]) rest = rest[md[0].length..] end total end |
.validate!(cfg) ⇒ Object
82 83 84 85 86 87 88 89 90 91 |
# File 'lib/e3dc_mqtt/config.rb', line 82 def validate!(cfg) raise ConfigError, "e3dc.host is required" if cfg.e3dc.host.nil? || cfg.e3dc.host.empty? raise ConfigError, "e3dc.username is required" if cfg.e3dc.username.nil? || cfg.e3dc.username.empty? raise ConfigError, "e3dc.password is required" if cfg.e3dc.password.nil? || cfg.e3dc.password.empty? raise ConfigError, "e3dc.key is required" if cfg.e3dc.key.nil? || cfg.e3dc.key.empty? raise ConfigError, "e3dc.interval must be at least 5s" if cfg.e3dc.interval < 5.0 raise ConfigError, "e3dc.statistic_update_interval must be at least 5s" if cfg.e3dc.statistic_update_interval < 5.0 raise ConfigError, "mqtt.url is required" if cfg.mqtt.url.nil? || cfg.mqtt.url.empty? raise ConfigError, "mqtt.root is required" if cfg.mqtt.root.nil? || cfg.mqtt.root.empty? end |