/********************************************************************************/
/*                   Demo source for esd EtherCAT Master stack                  */
/*                                                                              */
/*              Copyright by Shanghai ESD Electric Technology Co., Ltd.         */
/*------------------------------------------------------------------------------*/
/*          Filename:       ecmC2EReadCANMsg.c                                  */
/*          Date:           2023-06-09                                          */
/*          Language:       ANSI C                                              */
/*          Targetsystem:   Linux                                               */
/*          Purpose:        Demostrate how to read CAN messages with 11 bit CAN */
/*                          ID, and decode its ID,LEN,rtr.                      */
/*          Author:         Bob Tu                                              */
/*------------------------------------------------------------------------------*/ 
/* Revision history:                                                            */
/*------------------------------------------------------------------------------*/
/* v1.0     Birth of module                                                     */
/********************************************************************************/

#include <ecm.h>
#include <stdio.h>

#define ECM2_EVENT_MASK     (ECM_EVENT_LOCAL | ECM_EVENT_CFG          |   \
                            ECM_EVENT_WCNT   | ECM_EVENT_STATE_CHANGE |   \
                            ECM_EVENT_SLV)

/* Reference to process variables */
static uint16_t *pucRxCountGateway = NULL;
static uint16_t *pucRxCountApp = NULL;
static uint16_t *pucNumOfRxMsgs = NULL;
static uint8_t *pucRxMsg = NULL;

static int ecmEventHandler(ECM_EVENT *pEvent)
{
    switch(pEvent->ulEvent)
    {
        case ECM_EVENT_STATE_CHANGE:
            printf("ECM_EVENT_STATE_CHANGE: Master state change to ");
            switch(pEvent->ulArg1)
            {
            case ECM_DEVICE_STATE_UNKNOWN:
                printf("UNKNOWN\n");
                break;
            case ECM_DEVICE_STATE_INIT:
                printf("INIT\n");
                break;
            case ECM_DEVICE_STATE_PREOP:
                printf("PREOP\n");
                break;
            case ECM_DEVICE_STATE_SAFEOP:
                printf("SAFEOP\n");
                break;
            case ECM_DEVICE_STATE_OP:
                printf("OP\n");
                break;
            default:
                printf("???\n");
                break;
            }
            break;
    }
    return(0);
}

static int CycleHandler(){
    uint8_t * pTemp = pucRxMsg;
    uint16_t numOfRxMsgs = *pucNumOfRxMsgs;
    uint8_t byteStream[10];
    uint16_t id;
    uint8_t rtr;
    uint8_t len;

    if(*pucRxCountGateway == *pucRxCountApp) 
        return 0;
    printf("----------------------------------\n");
    printf("Rx Count App: %d \n", *pucRxCountApp);
    printf("Rx Count Gateway: %d \n", *pucRxCountGateway);
    printf("Number of Rx Msg: %d \n\n", numOfRxMsgs);
    for(int i=0;i<numOfRxMsgs;){
        printf("Rx Msg No.%d octets (HEX): ", ++i);
        for(int j=0;j<10;j++){
            byteStream[j] = *pTemp++;
            printf("%02x ",  byteStream[j]);
        }
        printf("\n");

        id = 0;
        id |= (byteStream[1]<<3);
        id |= (byteStream[0]&0xf0)>>5;
        printf("CAN ID (HEX): %03x \n",id);
        
        len = byteStream[0]&0xf;
        printf("CAN Msg Len: %d \n",len);

        rtr = (byteStream[0]>>4)&0x1;
        printf("RTR: %d \n",rtr);
        
        if(!rtr){
            printf("CAN Msg Content: ");
            for(int k=0;k<len;k++)
                printf("%02x ", byteStream[k+2]);
        }

        printf("\n\n");
    }
    printf("\n");
    *pucRxCountApp = *pucRxCountApp + 1;
}

int main(int argc, char *argv[])
{
    int result;
    ECM_LIB_INIT libInitData;
    ECM_CFG_INIT cfgInitData;
    ECM_HANDLE hndDevice =NULL;
    ECM_HANDLE hndMaster =NULL;
    ECM_VAR_DESC VarDesc;
    ECM_PROC_CTRL ProcCtrl;

    ECM_INIT(libInitData);
    libInitData.ulEventMask = ECM2_EVENT_MASK;
    libInitData.pfnEventHandler = ecmEventHandler;
    result = ecmInitLibrary(&libInitData);
    if (result != 0) {
      printf("ecmInitLibrary() returned with %d\n", result);
      return(-1);
    }

    ECM_INIT(cfgInitData);
    cfgInitData.Config.File.pszEniFile = "./eni_only_can-ethercat_11bit_1mbps.xml";
    cfgInitData.ulFlags = ECM_FLAG_CFG_KEEP_PROCVARS | ECM_FLAG_CFG_VIRTUAL_VARS;
    result = ecmReadConfiguration(&cfgInitData, &hndDevice, &hndMaster);
    if (result != ECM_SUCCESS) {
        printf("Reading configuration failed with %s\n", ecmResultToString(result));
        ecmInitLibrary(NULL);
        return(result);
    }

    result = ecmLookupVariable(hndMaster, "CAN TxPDO-Map.RX Counter", &VarDesc, ECM_FLAG_GET_FIRST);
    if (ECM_SUCCESS == result) {
        result = ecmGetDataReference(hndMaster, ECM_INPUT_DATA, VarDesc.ulBitOffs / 8, VarDesc.usBitSize / 8 , (void **)&pucRxCountGateway);
        if (result != ECM_SUCCESS) {
            printf("Failed to get reference to virtual variable Output\n");
        }
    }

    result = ecmLookupVariable(hndMaster, "CAN RxPDO-Map.RX Counter", &VarDesc, ECM_FLAG_GET_FIRST);
    if (ECM_SUCCESS == result) {
        result = ecmGetDataReference(hndMaster, ECM_OUTPUT_DATA, VarDesc.ulBitOffs / 8, VarDesc.usBitSize / 8 , (void **)&pucRxCountApp);
        if (result != ECM_SUCCESS) {
            printf("Failed to get reference to virtual variable Output\n");
        }
    }

    result = ecmLookupVariable(hndMaster, "CAN TxPDO-Map.Number of RX Messages", &VarDesc, ECM_FLAG_GET_FIRST);
    if (ECM_SUCCESS == result) {
        result = ecmGetDataReference(hndMaster, ECM_INPUT_DATA, VarDesc.ulBitOffs / 8, VarDesc.usBitSize / 8 , (void **)&pucNumOfRxMsgs);
        if (result != ECM_SUCCESS) {
            printf("Failed to get reference to virtual variable Output\n");
        }
    }

    result = ecmLookupVariable(hndMaster, "CAN TxPDO-Map.RX Message 1", &VarDesc, ECM_FLAG_GET_FIRST);
    if (ECM_SUCCESS == result) {
        result = ecmGetDataReference(hndMaster, ECM_INPUT_DATA, VarDesc.ulBitOffs / 8, VarDesc.usBitSize / 8 , (void **)&pucRxMsg);
        if (result != ECM_SUCCESS) {
            printf("Failed to get reference to virtual variable Output\n");
        }
    }
    
    result = ecmAttachMaster(hndMaster);
    if (result != ECM_SUCCESS) {
        printf("Attaching master failed with %s\n", ecmResultToString(result));
        ecmDeleteMaster(hndMaster);
        ecmDeleteDevice(hndDevice);
        ecmInitLibrary(NULL);
        return(-1);
    }

    ecmSleep(1000);

    ECM_INIT(ProcCtrl);
    ProcCtrl.ulAcyclicPeriod = 1000;
    ProcCtrl.ulAcyclicPrio   = ECM_PRIO_DEFAULT;
    ProcCtrl.ulCyclicPeriod = cfgInitData.cfgDataDevice.ulCycleTime;
    ProcCtrl.ulCyclicPrio   = ECM_PRIO_DEFAULT;
    ProcCtrl.pfnHandler     = CycleHandler;
    // ProcCtrl.pfnBeginCycle  = CycleStartHandler;
    // ProcCtrl.pfnEndCycle    = CycleEndHandler;
    result = ecmProcessControl(hndDevice, &ProcCtrl);
    if (result != ECM_SUCCESS) {
        printf("Creating background worker threads failed with %s\n", ecmResultToString(result));
        ecmDetachMaster(hndMaster);
        ecmDeleteMaster(hndMaster);
        ecmDeleteDevice(hndDevice);
        ecmInitLibrary(NULL);
        return(-1);
    } else {
        printf("Worker thread cycle times (microseconds) (Cyclic: %d)\n", ProcCtrl.ulCyclicPeriod);
    }

    result = ecmRequestState(hndMaster, ECM_DEVICE_STATE_OP, 60000);
    if (result != ECM_SUCCESS) {
        printf("Failed with %s to change network state into state %d !\n", ecmResultToString(result), ECM_DEVICE_STATE_OP);
        ecmDetachMaster(hndMaster);
        ecmDeleteMaster(hndMaster);
        ecmDeleteDevice(hndDevice);
        ecmInitLibrary(NULL);
        return(-1);
    }

ecmSleep(600000); //runtime 10 mins

    printf("Detaching master...\n");
    result = ecmDetachMaster(hndMaster);
    if (result != ECM_SUCCESS) {
        printf("Failed with %s\n", ecmResultToString(result));
    }

    printf("Deleting master...\n");
    result = ecmDeleteMaster(hndMaster);
    if (result != ECM_SUCCESS) {
        printf("Failed with %s\n", ecmResultToString(result));
    }

    printf("Deleting device...\n");
    result = ecmDeleteDevice(hndDevice);
    if (result != ECM_SUCCESS) {
        printf("Failed with %s\n", ecmResultToString(result));
    }

    ecmInitLibrary(NULL);

    return 0;

}


