//#include <SoftwareSerial.h>
#include <PostNeoSWSerial.h>
PostNeoSWSerial zt2Serial( 10, 11 );
    volatile uint32_t newlines = 0UL;
    
    static void handleRxChar( uint8_t c )
    {
      if (c == '\n')
        newlines++;
    }

// Define the buffer size and array to hold the data
const int bufferSize = 16;
uint8_t dataBuffer[bufferSize];
int dataIndex = 0;
bool dataStarted = false;  // Flag to indicate if we are in the middle of a valid packet

void setup() {
  Serial.begin(9600);
  zt2Serial.begin(9600);
}

void loop() {
  // Check if data is available on SoftwareSerial
  while (zt2Serial.available()) {
    // Read a byte from SoftwareSerial
    uint8_t byteRead = zt2Serial.read();

    // Check for the start of a new data packet
    if (!dataStarted) {
      // If the start of a new packet is detected
      if (byteRead == 0 && zt2Serial.available() >= 2) {
        // Read the next two bytes to confirm the start sequence
        uint8_t nextByte1 = zt2Serial.read();
        uint8_t nextByte2 = zt2Serial.read();
        
        // Check if the following bytes are 0x01 and 0x02
        if (nextByte1 == 0x01 && nextByte2 == 0x02) {
          // Start collecting data
          dataStarted = true;
          dataIndex = 0;
        }
      }
    }

    // If we're in a valid data packet, store the data
    if (dataStarted) {
      // Store the byte in the buffer
      if (dataIndex < bufferSize) {
        dataBuffer[dataIndex++] = byteRead;
      }

      // If buffer is full, process the data
      if (dataIndex >= bufferSize) {
        // Print out the collected data in hexadecimal format
        Serial.print("Received Data: ");
        for (int i = 0; i < bufferSize; i++) {
          Serial.print(dataBuffer[i]);
          Serial.print(" ");
        }
        Serial.println();

        // Reset flag and index to start collecting new data
        dataStarted = false;
        dataIndex = 0;
      }
    }
  }
}