Hi,
I want to use a barcode scanner to quickly add items I put in the trash can to the HASS Shopping List.
So far I have the scanner connected (using this great repository: Barcode Server) that sends the barcode over mqtt to a sensor in Home assistant. This works perfectly.
mqtt:
sensor:
- name: Barcode Reader
state_topic: "scanner/barcode"
value_template: '{{ value_json.barcode | string }}'
Next I want to make a data lookup to put the corresponding generic product name to the shopping list. This is where I have been stuck all weekend…
My idea is to keep the value pairs in a single line JSON file and then loop through the data to populate a template sensor with the product name that can then be added to the shopping list. To test, I have created a file, barcodes.json, that looks like this:
[{"barcode":"5099765037067","product":"milk"},{"barcode":"075992561419","product":"coffee"}]
I have created this sensor:
sensor:
- platform: file
name: barcode_product
file_path: /config/barcodes/barcodes.json
value_template: >-
{% set ns = namespace(found=false) %}
{% for i in value_json %}
{%- if i.barcode == states.sensor.barcode_reader.state %}
{% set ns.found = true %}
"{{ i.product }}"
{% endif -%}
{% endfor %}
{% if not ns.found %} "unknown" {% endif %}
But I can’t get the sensor to work. I get the below error and the value of the sensor is “unknown” no matter what value the barcode reader
sensor has.
Template variable warning: 'value_json' is undefined when rendering '{% set ns = namespace(found=false) %} {% for i in value_json %} {%- if i.barcode == states.sensor.barcode_reader.state %} {% set ns.found = true %} "{{ i.product }}" {% endif -%} {% endfor %} {% if not ns.found %} "unknown" {% endif %}'
- The json file is available and the full line loads into the sensor when I remove the
value_template
variable - The above value template works in the Template editor. The JSON string is pasted directly from the
barcodes.json
file
What am I doing wrong? Or is there another way to achieve this? I first tried with the SQL
integration but I learned the integration does not accept variables in SQL statements yet.