/*
 * IKW1281Connection.h
 *
 *  Created on: Apr 9, 2025
 *      Author: herli
 */

#ifndef INC_IKW1281CONNECTION_H_
#define INC_IKW1281CONNECTION_H_

#include <string.h>
#include "stdint.h"

extern uint8_t RxData[];
extern volatile uint8_t rx_done_flag;
extern uint8_t connectionAlive;

#define KLINE_BUFFER_SIZE 20

#define PACKET_END_EXPECTED 0x03




//typedef uint8_t PacketCommand;
#define MAX_PACKET_SIZE 512  // if too big it will crash 128<max<256 //funcionando en 256
 	 //si es menor, no funciona????
#define EEPROM_RESPONSE_BODY_MAX 64  // Adjust as needed

#define MAX_CONTROLLER_PACKETS 8
#define MAX_PACKET_BODY_LENGTH 64


typedef struct {
    char client_ident[13];   // 12 + null
    char unk_ident1[11];
    char soft_info[11];
    char unk_ident2[11];
    char unk_ident3[11];
} ControllerInfo;

typedef struct {
    uint8_t data[EEPROM_RESPONSE_BODY_MAX];
    uint8_t length;
    uint8_t valid;
} EepromResult;

typedef enum {
    PACKET_CMD_ReadIdent = 0x00,
    PACKET_CMD_ReadRomEeprom = 0x03,
    PACKET_CMD_ActuatorTest = 0x04,
    PACKET_CMD_FaultCodesDelete = 0x05,
    PACKET_CMD_End = 0x06,
    PACKET_CMD_FaultCodesRead = 0x07,
    PACKET_CMD_ACK = 0x09,
    PACKET_CMD_NAK = 0x0A,
    PACKET_CMD_SoftwareCoding = 0x10,
    PACKET_CMD_ReadEeprom = 0x19,
    PACKET_CMD_WriteEeprom = 0x1A,
    PACKET_CMD_Custom = 0x1B,
    PACKET_CMD_GroupReading = 0x29,
    PACKET_CMD_Login = 0x2B,
    PACKET_CMD_GroupReadingResponse = 0xE7,
    PACKET_CMD_ReadEepromResponse = 0xEF,
    PACKET_CMD_ActuatorTestResponse = 0xF5,
    PACKET_CMD_AsciiData = 0xF6,
    PACKET_CMD_WriteEepromResponse = 0xF9,
    PACKET_CMD_FaultCodesResponse = 0xFC,
    PACKET_CMD_ReadRomEepromResponse = 0xFD
} PacketCommand;

typedef enum {
    PACKET_TYPE_UNKNOWN = 0,
    PACKET_TYPE_ACK,
    PACKET_TYPE_NAK,
    PACKET_TYPE_ASCII_DATA,
    PACKET_TYPE_CODING_WSC,
    PACKET_TYPE_READ_EEPROM_RESPONSE,
    PACKET_TYPE_READ_ROM_EEPROM_RESPONSE
} PacketType;

typedef struct {
    PacketType type;
    uint8_t title;
    uint8_t length;
    uint8_t raw[MAX_PACKET_SIZE];  // raw bytes
    uint8_t isAckNak;
} ParsedPacket;

extern void ResetPacketCounter(void);
extern uint8_t ReadPacketCounter(void);
extern ParsedPacket ReceivePacket(void);
extern uint8_t ReadByte();
extern uint8_t ReadAndAckByte(void);
extern uint8_t KeepAlive(void);

void SendPacket(uint8_t* payload, uint8_t length);
ParsedPacket* SendCustom(const uint8_t* data, int len, int *out_count);
ParsedPacket* ReceivePackets(int *out_count);

#endif /* INC_IKW1281CONNECTION_H_ */
