#!/bin/bash

# WildlifeSystems - onboard sensors
#
# Script to read DS18B20 1-Wire temperature sensors.
#
# This script is part of the WildlifeSystems project. For further information
# please refer to https://docs.wildlife.systems, or for more information on
# the project itself, please refer to https://wildlife.systems.

if [[ "$#" -eq 1 ]]; then
  if [[ "$1"  = "identify" ]]; then
    exit 60;
  fi
  if [[ "$1" == "list" ]]; then
    echo "temperature"
    exit 0
  fi
fi


OUTPUT_COUNT=0
PI_SERIAL=$(awk '/Serial/ {print $NF}' /proc/cpuinfo)

echo -n "["

for folder in /sys/bus/w1/devices/28-*/; do
  if [[ ! -d "$folder" ]]; then
    # Not a directory
    break
  fi

  # Extract sensor ID from folder name
  SENSOR_ID=$(basename "$folder")

  # Read temperature value from w1_slave file
  if [[ -f "$folder/w1_slave" ]]; then
    TEMP=$(awk -F"=" '/t=/ {print $2/1000}' "$folder/w1_slave")
    if [[ -z "$TEMP" || ! "$TEMP" =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
      echo "Error: Invalid temperature value in $folder/w1_slave" >&2
      continue
    fi
  else
    echo "Error: Missing w1_slave file in $folder" >&2
    continue
  fi

 # Add a comma if this is not the first sensor
  if [[ $OUTPUT_COUNT -gt 0 ]]; then
    echo -n ","
  fi

  JSON=$(sc-prototype)
  SENSOR=$(echo $JSON | jq ".sensor |= \"ds18b20\" | .measures |= \"temperature\" | .unit |= \"Celsius\"| .value |= ${TEMP} | .sensor_id |= \"${SENSOR_ID}\"")
  echo -n $SENSOR
  OUTPUT_COUNT=$((OUTPUT_COUNT+1))
done

echo "]"
