Tag Data Sensor

I’ve seen some asking about getting tag scanned data. Here is what I did in order to map the tag_id to the name of the tag. I use linux with python venv, so modifications may be needed.

Create a python script…

tags.py

#! /srv/homeassistant/bin/python3

import json

new_tags = {}
new_tags['data'] = {}
with open('.storage/tag', 'r') as f:
  tags = json.load(f)

tag_data = tags['data']['items']

for tag in tag_data:
  t = tag.pop('tag_id')
  d = tag
  new_tags['data'][t] = d

print(json.dumps(new_tags))

Create a command_line sensor…

- sensor:
    name: "tags"
    command: "python3 /home/homeassistant/.homeassistant/./tags.py"
    scan_interval: 10
    json_attributes:
      - data
    value_template: '-'

What you get…

sensor.tags

data: 
501404bf-fa3c-4d9c-b217-1178dbd46a1d:
  id: 501404bf-fa3c-4d9c-b217-1178dbd46a1d
  name: Lock
  last_scanned: '2023-10-24T21:05:14.416925+00:00'
04-C0-38-73-CF-61-80:
  id: 04-C0-38-73-CF-61-80
  last_scanned: '2023-10-24T21:07:20.009623+00:00'
  name: Trash
c94a7b32-7e92-4eeb-a27d-e0dcd4e7494a:
  id: c94a7b32-7e92-4eeb-a27d-e0dcd4e7494a
  last_scanned: '2023-10-24T21:06:09.166335+00:00'
  name: Climate

Now in an automation…

trigger:
  platform: event
  event_type: tag_scanned
variables:
  # get the tag_id of the scanned tag
  id: "{{ trigger.event.data.tag_id }}"
  # use the id to look up the name by id in sensor.tags
  tag_name: "{{ state_attr('sensor.tags', 'data')[ id ][  'name' ] }}"  
  # need the device_id of the device that scanned the card?
  dev_id: "{{ trigger.event.data.device_id }}"
action:
  - service: script.tags
    data:
      tag_name: "{{ tag_name }}"  
      dev_id: "{{ dev_id }}"

Hope this helps someone out! If someone thinks of a way to improve this or a better way… please share!

You are genius man. This is exactly what i looked for.
But my HA is installed on raspberry pie how can i add the python component there?

Just add the command_line sensor. See here…https://www.home-assistant.io/integrations/command_line/