Module: OpenHAB::Core::Items::Item

Includes:
Persistence, Semantics, DSL::Items::Ensure::Item, DSL::Items::TimedCommand
Included in:
GenericItem
Defined in:
lib/openhab/core/items/item.rb

Overview

The core features of an openHAB item.

Constant Summary

Constants included from Semantics

Semantics::Equipment, Semantics::Location, Semantics::Point, Semantics::Property, Semantics::Tag

Constants included from Persistence

Persistence::HistoricState

Instance Attribute Summary collapse

Attributes included from Semantics

#equipment, #equipment_type, #location, #location_type, #point_type, #property_type, #semantic_type

Instance Method Summary collapse

Methods included from Semantics

add, #equipment?, #location?, lookup, #point?, #points, remove, #semantic?, tags

Methods included from DSL::Items::Ensure::Ensurable

#ensure

Methods included from Persistence

#all_states_between, #all_states_since, #all_states_until, #average_between, #average_since, #average_until, #changed_between?, #changed_since?, #changed_until?, #count_between, #count_since, #count_state_changes_between, #count_state_changes_since, #count_state_changes_until, #count_until, #delta_between, #delta_since, #delta_until, #deviation_between, #deviation_since, #deviation_until, #evolution_rate, #evolution_rate_between, #evolution_rate_since, #evolution_rate_until, #historic_state, #last_change, #last_update, #maximum_between, #maximum_since, #maximum_until, #median_between, #median_since, #median_until, #minimum_between, #minimum_since, #minimum_until, #next_change, #next_state, #next_update, #persist, #persisted_state, #previous_state, #remove_all_states_between, #remove_all_states_since, #remove_all_states_until, #riemann_sum_between, #riemann_sum_since, #riemann_sum_until, #sum_between, #sum_since, #sum_until, #updated_between?, #updated_since?, #updated_until?, #variance_between, #variance_since, #variance_until

Instance Attribute Details

#accepted_command_typesArray<Class> (readonly)

Returns An array of Commands that can be sent as commands to this item.

Returns:

  • (Array<Class>)

    An array of Commands that can be sent as commands to this item



# File 'lib/openhab/core/items/item.rb', line 64

#accepted_data_typesArray<Class> (readonly)

Returns An array of States that can be sent as commands to this item.

Returns:

  • (Array<Class>)

    An array of States that can be sent as commands to this item



# File 'lib/openhab/core/items/item.rb', line 67

#all_groupsArray<GroupItem> (readonly)

Returns all groups that this item is a part of, as well as those groups' groups, recursively

Returns:



281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/openhab/core/items/item.rb', line 281

def all_groups
  result = []
  new_groups = Set.new(groups)

  until new_groups.empty?
    result.concat(new_groups.to_a)
    new_groups.replace(new_groups.flat_map(&:groups))
    # remove any groups we already have in the result to avoid loops
    new_groups.subtract(result)
  end

  result
end

#channelThings::Channel? (readonly)

Return the channel this item is linked to. If an item is linked to more than one channel, this method only returns the first channel.

Returns:



481
482
483
# File 'lib/openhab/core/items/item.rb', line 481

def channel
  channel_uids.first&.channel
end

#channel_uidThings::ChannelUID? (readonly)

Return the UID of the channel this item is linked to. If an item is linked to more than one channel, this method only returns the first channel.

Returns:



464
465
466
# File 'lib/openhab/core/items/item.rb', line 464

def channel_uid
  channel_uids.first
end

#channel_uidsArray<Things::ChannelUID> (readonly)

Return the UIDs of all of the channels this item is linked to.



472
473
474
# File 'lib/openhab/core/items/item.rb', line 472

def channel_uids
  Things::Links::Provider.registry.get_bound_channels(name)
end

#channelsArray<Things::Channel> (readonly)

Return all of the channels this item is linked to.

Returns:



489
490
491
# File 'lib/openhab/core/items/item.rb', line 489

def channels
  channel_uids.map(&:channel)
end

#command_descriptionTypes::CommandDescription? (readonly)

Returns:



# File 'lib/openhab/core/items/item.rb', line 73

#display_stateString (readonly) Also known as: transformed_state, formatted_state

Note:

While this method is also aliased to #transformed_state to match the field available in the openHAB REST API, unlike the API it will always return a value even if the state description has no transformation.

Format the item's state according to its state description

This may include running a transformation, if one is defined in the state description's pattern, otherwise it will format according to the pattern. If no state description is defined, the state will simply be returned as a string.

Examples:

logger.info(Exterior_WindDirection.display_state) # => "NE (36°)"

Returns:

  • (String)

    The formatted state



116
117
118
# File 'lib/openhab/core/items/item.rb', line 116

def display_state
  Item.item_states_event_builder.get_display_state(self)
end

#groupsArray<GroupItem> (readonly)

Returns all groups that this item is part of

Returns:



254
255
256
# File 'lib/openhab/core/items/item.rb', line 254

def groups
  group_names.filter_map { |name| EntityLookup.lookup_item(name) }
end

#last_stateState (readonly)

Returns The previous state of the item.

Returns:

  • (State)

    The previous state of the item.

Since:

  • openHAB 5.0



# File 'lib/openhab/core/items/item.rb', line 76

#last_state_changeZonedDateTime (readonly)

Returns The time of the last state change.

Returns:

Since:

  • openHAB 5.0



# File 'lib/openhab/core/items/item.rb', line 80

#last_state_updateZonedDateTime (readonly)

Returns The time of the last state update.

Returns:

Since:

  • openHAB 5.0



# File 'lib/openhab/core/items/item.rb', line 84

Returns all of the item's links (channels and link configurations).

Examples:

Get the configuration of the first link

LivingRoom_Light_Power.links.first.configuration

Remove all managed links

LivingRoom_Light_Power.links.clear

Returns:

See Also:



508
509
510
# File 'lib/openhab/core/items/item.rb', line 508

def links
  ItemChannelLinks.new(name, Things::Links::Provider.registry.get_links(name))
end

#metadataMetadata::NamespaceHash (readonly)

Access to the item's metadata.

Both the return value of this method as well as the individual namespaces can be treated as Hashes.

Examples assume the following items:

Switch Item1 { namespace1="value" [ config1="foo", config2="bar" ] }
String StringItem1

Examples:

Check namespace's existence

Item1.metadata["namespace"].nil?
Item1.metadata.key?("namespace")

Access item's metadata value

Item1.metadata["namespace1"].value

Access namespace1's configuration

Item1.metadata["namespace1"]["config1"]

Safely search for the specified value - no errors are raised, only nil returned if a key in the chain doesn't exist

Item1.metadata.dig("namespace1", "config1") # => "foo"
Item1.metadata.dig("namespace2", "config1") # => nil

Set item's metadata value, preserving its config

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"].value = "new value"
# Item1's metadata after: {"namespace1"=>["new value", {"config1"=>"foo", "config2"=>"bar"]}}

Set item's metadata config, preserving its value

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"].replace({ "scooby"=>"doo" })
# Item1's metadata after: {"namespace1"=>["value", {scooby="doo"}]}

Set a namespace to a new value and config in one line

# Item1's metadata before: {"namespace1"=>"value", {"config1"=>"foo", "config2"=>"bar"}}
Item1.metadata["namespace1"] = "new value", { "scooby"=>"doo" }
# Item1's metadata after: {"namespace1"=>["new value", {scooby="doo"}]}

Set item's metadata value and clear its previous config

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"] = "new value"
# Item1's metadata after: {"namespace1"=>"value" }

Set item's metadata config, set its value to nil, and wiping out previous config

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"] = { "newconfig"=>"value" }
# Item1's metadata after: {"namespace1"=>{"config1"=>"foo", "config2"=>"bar"}}

Update namespace1's specific configuration, preserving its value and other config

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"]["config1"] = "doo"
# Item1's metadata will be: {"namespace1"=>["value", {"config1"=>"doo", "config2"=>"bar"}]}

Add a new configuration to namespace1

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"]["config3"] = "boo"
# Item1's metadata after: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar", config3="boo"}]}

Delete a config

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace1"].delete("config2")
# Item1's metadata after: {"namespace1"=>["value", {"config1"=>"foo"}]}

Add a namespace and set it to a value

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace2"] = "qx"
# Item1's metadata after: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}], "namespace2"=>"qx"}

Add a namespace and set it to a value and config

# Item1's metadata before: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace2"] = "qx", { "config1"=>"doo" }
# Item1's metadata after: {"namespace1"=>["value", {"config1"=>"foo", "config2"=>"bar"}], "namespace2"=>["qx", {"config1"=>"doo"}]}

Enumerate Item1's namespaces

Item1.metadata.each { |namespace, metadata| logger.info("Item1's namespace: #{namespace}=#{metadata}") }

Add metadata from a hash

Item1.metadata.merge!({"namespace1"=>{"foo", {"config1"=>"baz"} ], "namespace2"=>{"qux", {"config"=>"quu"} ]})

Merge Item2's metadata into Item1's metadata

Item1.metadata.merge!(Item2.metadata)

Delete a namespace

Item1.metadata.delete("namespace1")

Delete all metadata of the item

Item1.metadata.clear

Does this item have any metadata?

Item1.metadata.any?

Store another item's state

StringItem1.update "TEST"
Item1.metadata["other_state"] = StringItem1.state

Store event's state

rule "save event state" do
  changed StringItem1
  run { |event| Item1.metadata["last_event"] = event.was }
end

If the namespace already exists: Update the value of a namespace but preserve its config; otherwise create a new namespace with the given value and nil config.

Item1.metadata["namespace"] = "value", Item1.metadata["namespace"]

Copy another namespace

# Item1's metadata before: {"namespace2"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}
Item1.metadata["namespace"] = Item1.metadata["namespace2"]
# Item1's metadata after: {"namespace2"=>["value", {"config1"=>"foo", "config2"=>"bar"}], "namespace"=>["value", {"config1"=>"foo", "config2"=>"bar"}]}

Returns:



412
413
414
# File 'lib/openhab/core/items/item.rb', line 412

def metadata
  Metadata::NamespaceHash.new(name)
end

#nameString (readonly)

The item's name.

Returns:

  • (String)


# File 'lib/openhab/core/items/item.rb', line 60

#providerorg.openhab.core.common.registry.Provider? (readonly)

Returns the provider for this item.

Returns:



601
602
603
# File 'lib/openhab/core/items/item.rb', line 601

def provider
  Provider.registry.provider_for(self)
end

#state_descriptionTypes::StateDescription? (readonly)

Returns:



# File 'lib/openhab/core/items/item.rb', line 70

#thingThings::Thing? (readonly) Also known as: linked_thing

Return the item's thing if this item is linked with a thing. If an item is linked to more than one channel, this method only returns the first thing.

Returns:



445
446
447
# File 'lib/openhab/core/items/item.rb', line 445

def thing
  all_linked_things.first
end

#thingsArray<Things::Thing> (readonly) Also known as: all_linked_things

Returns all of the item's linked things.

Returns:



454
455
456
# File 'lib/openhab/core/items/item.rb', line 454

def things
  Things::Links::Provider.registry.get_bound_things(name).map { |thing| Things::Proxy.new(thing) }
end

Instance Method Details

#call_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a call item.

Check if the item is a call item.

Returns:

  • (true, false)


622
# File 'lib/openhab/core/items/item.rb', line 622

def_type_predicate(:call)

#color_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a color item.

Check if the item is a color item.

Returns:

  • (true, false)


623
# File 'lib/openhab/core/items/item.rb', line 623

def_type_predicate(:color)

#command(command, source: nil) ⇒ self? Also known as: command!, <<

Send a command to this item

When this method is chained after the ensure method, or issued inside an ensure_states block, or after ensure_states! have been called, the command will only be sent if the item is not already in the same state.

The similar method command!, however, will always send the command regardless of the item's state.

Examples:

Sending a Command to an item

MySwitch.command(ON) # The preferred method is `MySwitch.on`
Garage_Door.command(DOWN) # The preferred method is `Garage_Door.down`
SetTemperature.command 20 | "°C"

Sending a plain number to a NumberItem

SetTemperature.command(22.5) # if it accepts a DecimalType

Sending a string to a dimensioned NumberItem

SetTemperature.command("22.5 °C") # The string will be parsed and converted to a QuantityType

Parameters:

  • command (Command, #to_s)

    command to send to the item. When given a Command argument, it will be passed directly. Otherwise, the result of #to_s will be parsed into a Command.

  • source (String, nil) (defaults to: nil)

    Optional string to identify what sent the event.

Returns:

  • (self, nil)

    nil when ensure is in effect and the item was already in the same state, otherwise the item.

See Also:



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/openhab/core/items/item.rb', line 155

def command(command, source: nil)
  command = format_command(command)
  logger.trace { "Sending Command #{command} to #{name}" }
  source ||= infer_source if VERSION >= V5_1
  if source
    Events.publisher.post(Events::ItemEventFactory.create_command_event(name, command, source.to_s))
  else
    $events.send_command(self, command)
  end
  Proxy.new(self)
end

#contact_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a contact item.

Check if the item is a contact item.

Returns:

  • (true, false)


624
# File 'lib/openhab/core/items/item.rb', line 624

def_type_predicate(:contact)

#date_time_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a date_time item.

Check if the item is a date_time item.

Returns:

  • (true, false)


625
# File 'lib/openhab/core/items/item.rb', line 625

def_type_predicate(:date_time)

#dimmer_item?true, false

Note:

Color items are also considered dimmer items.

Note:

If the item is a group item, it will also return true if the base item is a dimmer item.

Check if the item is a dimmer item.

Returns:

  • (true, false)


627
# File 'lib/openhab/core/items/item.rb', line 627

def_type_predicate(:dimmer)

#group_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a group item.

Check if the item is a group item.

Returns:

  • (true, false)


628
# File 'lib/openhab/core/items/item.rb', line 628

def_type_predicate(:group)

#image_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a image item.

Check if the item is a image item.

Returns:

  • (true, false)


629
# File 'lib/openhab/core/items/item.rb', line 629

def_type_predicate(:image)

#inspectString

Returns:

  • (String)


583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/openhab/core/items/item.rb', line 583

def inspect
  s = "#<OpenHAB::Core::Items::#{type}Item#{type_details} #{name} #{label.inspect} state=#{raw_state.inspect}"
  # @deprecated OH 4.3 Remove if guard when dropping support for OH 4.3
  if respond_to?(:last_state)
    s += " last_state=#{last_state.inspect}" if last_state
    s += " last_state_update=#{last_state_update}" if last_state_update
    s += " last_state_change=#{last_state_change}" if last_state_change
  end
  s += " category=#{category.inspect}" if category
  s += " tags=#{tags.to_a.inspect}" unless tags.empty?
  s += " groups=#{group_names}" unless group_names.empty?
  meta = metadata.to_h
  s += " metadata=#{meta.inspect}" unless meta.empty?
  "#{s}>"
end

Overloads:

  • #linkThings::ItemChannelLink?

    Returns the item's link. If an item is linked to more than one channel, this method only returns the first link.

    Returns:

  • #link(channel, config = {}) ⇒ Things::ItemChannelLink

    Links the item to a channel.

    Examples:

    Link an item to a channel

    LivingRoom_Light_Power.link("mqtt:topic:livingroom-light:power")

    Link to a Thing's channel

    LivingRoom_Light_Power.link(things["mqtt:topic:livingroom-light"].channels["power"])

    Specify a link configuration

    High_Temperature_Alert.link(
      "mqtt:topic:outdoor-thermometer:temperature",
      profile: "system:hysteresis",
      lower: "29 °C",
      upper: "30 °C")

    Parameters:

    Returns:

    See Also:

Returns:



546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/openhab/core/items/item.rb', line 546

def link(channel = nil, config = nil)
  return Things::Links::Provider.registry.get_links(name).first if channel.nil? && config.nil?

  config ||= {}
  Core::Things::Links::Provider.create_link(self, channel, config).tap do |new_link|
    provider = Core::Things::Links::Provider.current
    if !(current_link = provider.get(new_link.uid))
      provider.add(new_link)
    elsif current_link.configuration != config
      provider.update(new_link)
    end
  end
end

#location_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a location item.

Check if the item is a location item.

Returns:

  • (true, false)


630
# File 'lib/openhab/core/items/item.rb', line 630

def_type_predicate(:location)

#member_of?(*groups) ⇒ true, false

Checks if this item is a member of at least one of the given groups.

Examples:

event.item.member_of?(gFullOn)

Parameters:

  • groups (String, GroupItem)

    the group to check membership in

Returns:

  • (true, false)


267
268
269
270
271
272
# File 'lib/openhab/core/items/item.rb', line 267

def member_of?(*groups)
  groups.map! do |group|
    group.is_a?(GroupItem) ? group.name : group
  end
  !!group_names.intersect?(groups)
end

#number_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a number item.

Check if the item is a number item.

Returns:

  • (true, false)


631
# File 'lib/openhab/core/items/item.rb', line 631

def_type_predicate(:number)

#player_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a player item.

Check if the item is a player item.

Returns:

  • (true, false)


632
# File 'lib/openhab/core/items/item.rb', line 632

def_type_predicate(:player)

#refreshItem

Send the REFRESH command to the item

Returns:



# File 'lib/openhab/core/items/item.rb', line 175

#rollershutter_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a rollershutter item.

Check if the item is a rollershutter item.

Returns:

  • (true, false)


633
# File 'lib/openhab/core/items/item.rb', line 633

def_type_predicate(:rollershutter)

#string_item?true, false

Note:

If the item is a group item, it will also return true if the base item is a string item.

Check if the item is a string item.

Returns:

  • (true, false)


634
# File 'lib/openhab/core/items/item.rb', line 634

def_type_predicate(:string)

#switch_item?true, false

Note:

Color and dimmer items are also considered switch items.

Note:

If the item is a group item, it will also return true if the base item is a switch item.

Check if the item is a switch item.

Returns:

  • (true, false)


636
# File 'lib/openhab/core/items/item.rb', line 636

def_type_predicate(:switch)

#tagged?(*tags) ⇒ true, false

Checks if this item has at least one of the given tags.

Examples:

event.item.tagged?("Setpoint")
event.item.tagged?(Semantics::Switch)

Parameters:

  • tags (String, Module)

    the tag(s) to check

Returns:

  • (true, false)


429
430
431
432
433
434
435
436
437
438
# File 'lib/openhab/core/items/item.rb', line 429

def tagged?(*tags)
  tags.map! do |tag|
    if tag.is_a?(Semantics::SemanticTag)
      tag.name
    else
      tag
    end
  end
  !!self.tags.to_a.intersect?(tags)
end

#to_sString

The item's label if one is defined, otherwise its #name.

Returns:

  • (String)


93
94
95
# File 'lib/openhab/core/items/item.rb', line 93

def to_s
  label || name
end

Removes a link to a channel from managed link providers.

Parameters:

Returns:

Raises:

  • (FrozenError)

    if the link is not managed by a managed link provider.

See Also:



571
572
573
574
575
576
577
578
579
580
# File 'lib/openhab/core/items/item.rb', line 571

def unlink(channel)
  link_to_delete = Things::Links::Provider.create_link(self, channel, {})
  provider = Things::Links::Provider.registry.provider_for(link_to_delete.uid)
  unless provider.is_a?(ManagedProvider)
    raise FrozenError,
          "Cannot remove the link #{link_to_delete.uid} from non-managed provider #{provider.inspect}"
  end

  provider.remove(link_to_delete.uid)
end

#update(state, source: nil) ⇒ self? Also known as: update!

Send an update to this item

Examples:

Updating to a State

DoorStatus.update(OPEN)
InsideTemperature.update 20 | "°C"

Updating to NULL, the two following are equivalent:

DoorStatus.update(nil)
DoorStatus.update(NULL)

Updating with a plain number

PeopleCount.update(5) # A plain NumberItem

Updating with a string to a dimensioned NumberItem

InsideTemperature.update("22.5 °C") # The string will be parsed and converted to a QuantityType

Parameters:

  • state (State, #to_s, nil)

    the state to update the item. When given a State argument, it will be passed directly. Otherwise, the result of #to_s will be parsed into a State first. If nil is passed, the item will be updated to NULL.

  • source (String, nil) (defaults to: nil)

    Optional string to identify what sent the event.

Returns:

  • (self, nil)

    nil when ensure is in effect and the item was already in the same state, otherwise the item.



204
205
206
207
208
209
210
211
212
213
214
# File 'lib/openhab/core/items/item.rb', line 204

def update(state, source: nil)
  state = format_update(state)
  logger.trace { "Sending Update #{state} to #{name}" }
  source ||= infer_source if VERSION >= V5_1
  if source
    Events.publisher.post(Events::ItemEventFactory.create_state_event(name, state, source.to_s))
  else
    $events.post_update(self, state)
  end
  Proxy.new(self)
end