/*
 * MertenBus.h
 *
 *  Created on: 28.07.2018
 *      Author: Probst
 */

#ifndef MERTENBUS_H_
#define MERTENBUS_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <xdc/std.h>
#include <stdint.h>
#include <stdbool.h>
#include <ti/drivers/UART.h>

#define MB_IDX_TYPE                     uint8_t
#define MB_SENT_STRING_MAX_LENGTH       100
#define MB_RECEIVE_STRING_MAX_LENGTH    100
#define MB_TELEGRAM_DELIMITER           254u

#define MB_QRY_INTERFACE_VERSION        0x00u
#define MB_QRY_MODULE_ADR               0x01u
#define MB_QRY_EVALUATED_SWITCHES       0x0Au
/* commands without data */
#define MB_CMD_SET_MODULE_ADR           0x01u
#define MB_CMD_SAVE_PARAMETERS          0x02u
#define MB_CMD_RESTORE_PARAMETERS       0x03u
#define MB_CMD_CLEAR_RESET_FLAG         0x04u
/* commands with 2 bytes of data 0..127 (green and red) */
#define MB_CMD_SET_LED_LEFT             0x11u
#define MB_CMD_SET_LED_RIGHT            0x12u

typedef enum MertenBusTransmissionStatus_en
{
    MBTS_na, // not applicable, no transmission started, yet
    MBTS_ongoing, // transmission is ongoing
    MBTS_ok, // transmission ended successfully
    MBTS_failure, // all trials failed
} MertenBusTransmissionStatus_t;

typedef struct MertenBus_s
{
    UART_Handle uartHdl;
    MertenBusTransmissionStatus_t transmissionStatus;
    uint8_t retryCnt;
    struct MertenBusTelegram_s *telegram;
} MertenBusObject;

typedef struct MertenBus_s *MertenBusHandle;

typedef struct MertenBusTelegram_s
{
    MB_IDX_TYPE idx; // index for consecutive writing or reading
    MB_IDX_TYPE sendSizeMax; //  maximum lenght of sendString
    UChar sendString[MB_SENT_STRING_MAX_LENGTH];
    MB_IDX_TYPE receiveSizeMax; //  maximum lenght of receivedString
    MB_IDX_TYPE receivedByteCount; // number of received bytes (without telegram delimiter)
    UChar receivedString[MB_RECEIVE_STRING_MAX_LENGTH];
} MertenBusTelegramObject;

MertenBusHandle mertenBusInitAndStart(uint8_t uartIdx, uint32_t txPortBase, uint8_t txPin);
void MertenBusConstructQueryTelegram(MertenBusTelegramObject *teleg, uint8_t moduleAdr, uint8_t qryId);
void MertenBusConstructCommandTelegram(MertenBusTelegramObject *teleg, uint8_t moduleAdr, uint8_t cmdId);
void MertenBusAddByteToTelegram(MertenBusTelegramObject *teleg, uint8_t data);
int_fast8_t MertenBusSendTelegram(MertenBusTelegramObject *teleg, MertenBusHandle objPtr);

#ifdef __cplusplus
}
#endif
#endif /* MERTENBUS_H_ */
