#!/bin/bash
#
# Publish tfrec datagram as MQTT message
#
# Arguments: tfrec datagram, e.g.
#  id    temp  hum seq lowbat rssi flags time
#  5158  +23.8 59  10  0      79   0     1496588364
#

MQTT_TOPIC_PREFIX="devices/tfa/30.3180.it"
MQTT_BROKER_HOSTNAME=localhost
# Hinweis: folgender Eintrag verhindert "Warning:unable to locate configuration directory" im Log-File!
export HOME="${HOME:-/dev/null}"

# read arguments into variables
read sensor_id temperature humidity seq lowbat rssi flags timestamp <<< "$*"

echo "$sensor_id $temperature $humidity $seq $lowbat $rssi $flags $timestamp"

# convert values to JSON types
temperature="${temperature/#+/}"
# conversion of 'lowbat' is only possible as soon as expandJSON support the JSON 'boolean' type; see htpps://gitupc.com/ddtlabs/expandJSON/issues/1 for details
#[ "$lowbat" = "0" ] && lowbat="false" || lowbat="true"

tx22_id="33000"

if [[ "${sensor_id:0:5}" == $tx22_id ]];
then
    sensor_id=tx22_${sensor_id:7:1}
fi



# build message string
# message="{ \"sensor_id\":\"$sensor_id\", \"temperature\":$temperature, \"humidity\":$humidity, \"lowbat\":$lowbat, \"rssi\":$rssi }"
message="{ \"sensor_id\":\"$sensor_id\", \"temperature\":$temperature, \"humidity\":$humidity, \"rssi\":$rssi }"

mosquitto_pub -h "$MQTT_BROKER_HOSTNAME" -t "$MQTT_TOPIC_PREFIX/$sensor_id/json" -m "$message"

