#include <Wire.h>
#include <RTClib.h>

#include <NeoSWSerial.h>
#include <ModbusMaster.h>
#include "PM8000_Modbus_Map_ad.h"

//#include <SD.h>

#include <SPI.h>
#include <SdFat.h>
#define SD_CS_PIN 10 // Chip Select for SD Card
//RS485 pins
#define DE_RE_PIN 4
#define RX_PIN 8     // SoftwareSerial RX pin
#define TX_PIN 7     // SoftwareSerial TX pin
#define SLAVE_ID 101
#define SERIAL_BAUDRATE 9600

// Try to select the best SD card configuration.
#define SPI_CLOCK SD_SCK_MHZ(50)
#if HAS_SDIO_CLASS
#define SD_CONFIG SdioConfig(FIFO_SDIO)
#elif ENABLE_DEDICATED_SPI
#define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SPI_CLOCK)
#else  // HAS_SDIO_CLASS
#define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SPI_CLOCK)
#endif  // HAS_SDIO_CLASS

RTC_DS3231 rtc; // Create an RTC object
SdFat32 sd;
//SdExFat sd;
File dataFile;
NeoSWSerial modbusSerial(RX_PIN, TX_PIN); // Create a software serial instance
ModbusMaster node;

void setup()
{
    Serial.begin(SERIAL_BAUDRATE); // For debugging
    Serial.println(F("Startup \n"));
    
    // Initialize RTC
    if (!rtc.begin())
    {
        Serial.println(F("Couldn't find RTC\n"));
    }

    if (rtc.lostPower())
    {
        Serial.println(F("RTC lost power, let's set the time!\n"));
        // Comment out the following line once the time is set to avoid resetting on every start
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }
    
    Serial.print(F("Time: "));
    Serial.print(rtc.now().timestamp());
    Serial.println(F("\n"));

    // Initialize SD card
    Serial.println(F("SD card initializing..."));
    pinMode(SD_CS_PIN, OUTPUT);
    
    // if (!SD.begin(SPI_HALF_SPEED, SD_CS_PIN ))
    // {
    //     Serial.println(F("SD card initialization failed!\n"));
    //     return;
    // }
      // Initialize the SD.
    if (!sd.begin(SD_CONFIG)) {
      sd.initErrorHalt(&Serial);
      return;
    }
    Serial.println(F("SD card initialized.\n"));

    Serial.println(F("Initialize RS485 module / Modbus \n"));
    

    pinMode(DE_RE_PIN, OUTPUT);
    digitalWrite(DE_RE_PIN, LOW); // Set to LOW for receiving mode initially
    modbusSerial.begin(SERIAL_BAUDRATE);
 
    node.begin(SLAVE_ID, modbusSerial); 
    node.preTransmission(preTransmission);
    node.postTransmission(postTransmission);
}

void preTransmission()
{
  digitalWrite(DE_RE_PIN, HIGH); // Enable RS485 transmit
}

void postTransmission()
{
  digitalWrite(DE_RE_PIN, LOW); // Disable RS485 transmit
}


void writeFile(char *str)
{
    if (!dataFile)
    {
        Serial.println(F("Error opening file"));
        return;
    }
    DateTime now = rtc.now();
    // Log the current date and time
    dataFile.print(now.year(), DEC);
    dataFile.print('-');
    dataFile.print(now.month(), DEC);
    dataFile.print('-');
    dataFile.print(now.day(), DEC);
    dataFile.print(" ");
    dataFile.print(now.hour(), DEC);
    dataFile.print(':');
    dataFile.print(now.minute(), DEC);
    dataFile.print(':');
    dataFile.print(now.second(), DEC);
    dataFile.print(F(","));
    dataFile.print(str);

    dataFile.println();
}

String getFilename()
{
    DateTime now = rtc.now();
    String mb = F("");
    mb += now.year();
    mb += now.month();
    mb += now.day();
    mb += F(".csv");

    return mb;
}
unsigned long lastRefreshTime = 0;
void loop()
{
  delay(100);


    if(millis() - lastRefreshTime >= 1000)
    {
      lastRefreshTime += 1000;

      Serial.print(F("\nTime: "));
      Serial.print(rtc.now().timestamp());
      //   Serial.print("\nHeep:");
      //  Serial.print(ESP.getFreeHeap());
      Serial.print("\n");
  
      // Open file for writing
      String filename = getFilename();
      dataFile.open(filename.c_str(), FILE_WRITE);
      Serial.print(F("Open Card "));
      Serial.print(filename.c_str());
      Serial.print("\n");

      String mb = "modbus,";
      writeFile(mb.c_str());
  
      if (dataFile)
      {
          dataFile.close(); // Close the file
          Serial.print(F("Data written to SD card: "));
          Serial.print(filename.c_str());
          Serial.print(F("\n"));
      }
  
      Serial.print(F("\n\n"));
      
    }



    for (int i  = 0; i < 10; i++) {

        Serial.print(F("\naddress: "));
        Serial.print(registers[i].regaddr);
        Serial.print(F("\ntype: "));
        Serial.print(registers[i].regtype);
        Serial.print(F("\n "));
        if (registers[i].regaddr > 0) {
          uint8_t result  = node.readHoldingRegisters(registers[i].regaddr , 2);
          
          if (result == node.ku8MBSuccess)
          {
            Serial.print(F("Modbus Read successful:"));
            
          } else {
            Serial.print(F("Modbus Read error: "));
            Serial.println(result, HEX);
          }
        }
    }
    
         // // Check if the read was successful
    
    delay(100);
}
