#!/bin/bash
#
# MHT mSense ID Change + Reboot Script v1.1.0
# Created by Enrico Buttignol (ebuttignol@messana.tech)
# Copyright by Messana Hydronic Technologies
#
# NOTE:
#   mbpoll uses 1-based addressing.
#   This means that when specifying a register with the -r option,
#   you must add +1 to the real register address.
#   Example:
#     Real register: 200  ->  mbpoll: -r 201
#     Real register: 231  ->  mbpoll: -r 232
#

# Serial configuration
SERIAL_PORT="/dev/ttyS0"
BAUDRATE=9600
PARITY="none"
STOPBITS=1

echo "---------------------------------------------"
echo "      MHT mSense - Change ID + Reboot"
echo "---------------------------------------------"

# Ask for the current device ID
read -p "Enter the current device ID: " CURRENT_ID

# Read the value from register 200
echo "Reading ID from register 200 (slave $CURRENT_ID)..."
READ_VALUE=$(mbpoll -m rtu -b $BAUDRATE -P $PARITY -s $STOPBITS \
    -a $CURRENT_ID -t 4 -r 201 -1 $SERIAL_PORT 2>/dev/null \
    | grep '\[' | tail -n1 | awk -F ']:' '{print $2}' | xargs)

echo "Current value in register 200: $READ_VALUE"

# Ask for the new device ID
read -p "Enter the NEW device ID to assign: " NEW_ID

# Write the new ID into register 200
echo "Writing new ID $NEW_ID into register 200..."
mbpoll -m rtu -b $BAUDRATE -P $PARITY -s $STOPBITS \
     -a $CURRENT_ID -t 4 -r 201 -1 $SERIAL_PORT $NEW_ID

# Verify the written value
VERIFY_VALUE=$(mbpoll -m rtu -b $BAUDRATE -P $PARITY -s $STOPBITS \
    -a $NEW_ID -t 4 -r 201 -1 $SERIAL_PORT 2>/dev/null \
    | grep '\[' | tail -n1 | awk -F ']:' '{print $2}' | xargs)

echo "Verification read: $VERIFY_VALUE"

if [ "$VERIFY_VALUE" == "$NEW_ID" ]; then
    echo "✅ ID successfully updated to $NEW_ID"
    echo "Proceeding with reboot..."

    # Reboot sequence (still with the old ID)
    mbpoll -m rtu -b $BAUDRATE -P $PARITY -s $STOPBITS \
        -a $CURRENT_ID -t 4:hex -r 231 -1 $SERIAL_PORT 0x0055

    sleep 0.3

    mbpoll -m rtu -b $BAUDRATE -P $PARITY -s $STOPBITS \
        -a $CURRENT_ID -t 4:hex -r 232 -1 $SERIAL_PORT 0x00AA

    echo "Reboot completed. The new device ID is now $NEW_ID"
else
    echo "❌ ERROR: Verification failed!"
    echo "Expected $NEW_ID but read back $VERIFY_VALUE"
    echo "Reboot aborted."
fi