const int MC9_CH[] = {1000, 1008, 1016, 1024, 1100, 1108, 1116, 1124};

#define MC9_10_PV "10DRS,08,0001CB"
#define MC9_10_SV "10DRS,08,0011CC"

// 10DWR,02,0302,0001,0501,0001
// Auto Tune. 0302(Ch Sel) 0001(Ch.1) 0501(AT) 0001(On, Off=0000)

int saveMC9(String message){
  int addr;
  String mode;
  int data[8];
  int crc;

  if (parseMC9(message, addr, mode, data, crc)) {
    if(latest_sent_msg == MC9_10_PV){
      rcv_10_PV = true;
      for(int i = 0 ; i < Size_PV ; i++){
        Values_10_PV[i] = data[i];
      }
    }
    if(latest_sent_msg == MC9_10_SV){
      rcv_10_SV = true;
      for(int i = 0 ; i < Size_SV ; i++){
        Values_10_SV[i] = data[i];
      }
    }
    return 1;
  } else {
      Serial.println("error 485 read");
      return 0;
  }
}

int timeoutMC9(){
  int addr;
  String mode;
  int data[8];
  int crc;
  if(latest_sent_msg == MC9_10_PV){
    rcv_10_PV = false;
  }
  if(latest_sent_msg == MC9_10_SV){
    rcv_10_SV = false;

  }else {
      Serial.println("error 485 read");
      return 0;
  }

  return 1;
}

int parseMC9(const String& message, int& addr, String& mode, int data[8], int& crc) {
    char addrC[3], modeC[4], statusC[3];
    int dataC[8], crcC;

    if (message[0] == '\x02') {
      message = message.substring(1);
    }

    int ret = sscanf(message.c_str(), "%2s%3s,%2s,%4x,%4x,%4x,%4x,%4x,%4x,%4x,%4x%2x", 
        addrC, modeC, statusC, &dataC[0], &dataC[1], &dataC[2], &dataC[3], &dataC[4], &dataC[5], &dataC[6], &dataC[7], &crcC);

    if (strcmp(statusC, "OK") != 0 || ret != 12) {
        return 0;
    }
    
    // copy data
    addr = atoi(addrC);
    mode = String(modeC);
    for (int i = 0; i < 8; i++) {
        data[i] = dataC[i];
    }
    crc = crcC;

    return 1;
}

String sumMC9(String input) {
    int sum = 0;
    for (char c : input) {
        sum += c;
    }
    sum = sum & 0xFF;  // Make sure we only keep the least significant byte
    String hexSum = String(sum, HEX);  // Convert the sum to hexadecimal
    hexSum.toUpperCase();  // Make it upper-case
    return hexSum;
}
