module MQTT::Homie::HomieAttribute::InstanceMethods
Public Instance Methods
homie_attr_init(data = {})
click to toggle source
initialize all homie attributes from the given hash
# File lib/mqtt/homie/homie_attribute.rb, line 44 def homie_attr_init(data = {}) self.class.homie_attr_list.each do |name, options| #puts "name: #{name}, default: #{options[:default]}, options: #{options.inspect}" value = data.include?(name) ? data[name] : options[:default] value = value.call(self) if value.kind_of?(Proc) homie_attr_set(name, value) end end
homie_attr_set(name, value)
click to toggle source
set attribute with validation
# File lib/mqtt/homie/homie_attribute.rb, line 59 def homie_attr_set(name, value) homie_attr_validate(name, value) homie_attr_set!(name, value) end
homie_attr_set!(name, value)
click to toggle source
set attribute without validation
# File lib/mqtt/homie/homie_attribute.rb, line 54 def homie_attr_set!(name, value) instance_variable_set("@#{name}", value) end
homie_attr_validate(name, value)
click to toggle source
attribute validation
# File lib/mqtt/homie/homie_attribute.rb, line 80 def homie_attr_validate(name, value) options = self.class.homie_attr_options(name) if value.nil? required = options[:required] required = required.call(self) if required.kind_of?(Proc) raise "#{name} is required for #{object_type} #{@id}" if required end datatype = options[:datatype] if datatype && !value.nil? && !datatype_match?(datatype, value) raise "expected #{name} to be a #{datatype} for #{object_type} #{@id}" end enum = options[:enum] if enum.kind_of?(Array) && !value.nil? && !enum.include?(value.to_sym) raise "expected #{name} (#{value}) to be one of #{enum.join(",")}" end end
homie_attributes()
click to toggle source
# File lib/mqtt/homie/homie_attribute.rb, line 64 def homie_attributes data = {} # if this object has an id, it needs a $ attribute prefix. # otherwise assume it is a hierarchical attribute like $stats/* or $fw/* attrib_prefix = self.class.homie_has_id? ? "$" : "" self.class.homie_attr_list.each do |name, options| next if options[:hidden] key = options[:topic] || (attrib_prefix + name.to_s) value = instance_variable_get("@#{name}") next if value == nil data[key] = value.kind_of?(Array) ? value.collect { |i| i.id }.join(",") : value end data end
Private Instance Methods
datatype_match?(datatype, value)
click to toggle source
# File lib/mqtt/homie/homie_attribute.rb, line 110 def datatype_match?(datatype, value) return value.kind_of?(datatype) if datatype.kind_of?(Class) case datatype when :boolean return value == true || value == false else raise "unhandled datatype '#{datatype}'" end false end
object_type()
click to toggle source
# File lib/mqtt/homie/homie_attribute.rb, line 102 def object_type self.class.name.split("::").last end
valid_id?(id)
click to toggle source
# File lib/mqtt/homie/homie_attribute.rb, line 106 def valid_id?(id) id && id.kind_of?(String) && id.match(/^[-a-z0-9]+$/) && !id.start_with?("-") end