/*
 * BACnetLight - Basic Device Example for Arduino UNO R4
 * 
 * Simplest BACnet MS/TP device: one Analog Value input and one binary output
 * Hardware: Arduino UNO R4 + Zihatec RS485 Shield
 */


#include <BACnetLight.h>

// --- definitions ---
#define RS485_DE   -1   // no DE pin needed - we use the auto transmit function of the shield 
#define MSTP_MAC   1    // Our MSTP address (0-127)
#define MSTP_BAUD  38400


BACnetMSTP bacnet;

void setup() {
    Serial.begin(115200);
    delay(1000);
    
    // Set device metadata
    bacnet.setDeviceInfo("Vendor", 0, "Model", "1.0.0", "1.0.0");
    
    Serial1.begin(MSTP_BAUD, SERIAL_8N1);
    if (!bacnet.beginMSTP(3000, "MSTP-Arduino", Serial1, RS485_DE, MSTP_MAC, MSTP_BAUD)) {
         Serial.println("ERROR: MSTP init failed!");
         while (1) delay(1000);
    }
    
    // Analog Input (read-only sensors) 
    bacnet.addAnalogValue(0, "Temperature", 22.5, BACNET_UNITS_DEGREES_CELSIUS);

    // Binary Output (commandable with priority array)
    bacnet.addBinaryOutput(0, "Relay", false, "Relay output"); 

    Serial.println("BACnet ready!");
}

void loop() {
    bacnet.loop();

    static unsigned long last = 0;
    if (millis() - last >= 5000) {
        last = millis();

        // generate random temperature value for fake temp sensor
        float temp = 20.0 + random(0, 50) / 10.0;
        bacnet.setValue(BACNET_OBJ_ANALOG_VALUE, 0, temp);
        Serial.print("Temp: "); Serial.print(temp); Serial.println("°C");

        // control led (binary output)
        int relay = bacnet.getValue(BACNET_OBJ_BINARY_OUTPUT, 0); 
        if (relay) {
            Serial.println("Relay: ON");
        } else {
            Serial.println("Relay: OFF");
        }
        

    }
}
