#include <ecm.h>
#include <stdio.h>
#include <string.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 *pCw = NULL; //control word
static uint32_t *pTv = NULL; //target velocity
static uint8_t *pMop = NULL; //mode of operation

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;
        
        case ECM_EVENT_SLV:
            printf("ECM_EVENT_SLV: Slave address %d state change to ", pEvent->ulArg2 & 0x0000FFFF);
            switch(pEvent->ulArg1)
            {
            case ECM_ESC_AL_STATUS_INIT:
                printf("INIT\n");
                break;
            case ECM_ESC_AL_STATUS_PREOP:
                printf("PREOP\n");
                break;
            case ECM_ESC_AL_STATUS_BOOTSTRAP:
                printf("BOOTSTRAP\n");
                break;
            case ECM_ESC_AL_STATUS_SAFEOP:
                printf("SAFEOP\n");
                break;
            case ECM_ESC_AL_STATUS_OP:
                printf("OP\n");
                break;
            default:
                printf("???\n");
                break;
            }
            break;
    }
    return(0);
}

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_HANDLE hndSlave =NULL;
    ECM_VAR_DESC VarDesc;
    ECM_PROC_CTRL ProcCtrl;
    ECM_COPY_VECTOR *pCopyVectorOutput;
    uint32_t ulEntries;
    ECM_COPY_VECTOR *pCopyVectorInput;

    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_pv_ms-mini3e.xml";
    cfgInitData.ulFlags = ECM_FLAG_CFG_KEEP_PROCVARS;
    result = ecmReadConfiguration(&cfgInitData, &hndDevice, &hndMaster);
    if (result != ECM_SUCCESS) {
        printf("Reading configuration failed with %s\n", ecmResultToString(result));
        ecmInitLibrary(NULL);
        return(result);
    }

    result = ecmGetCopyVector(hndMaster, NULL, &ulEntries, ECM_OUTPUT_DATA);
    if (ECM_SUCCESS == result) {
        pCopyVectorOutput = calloc((size_t)ulEntries, sizeof(ECM_COPY_VECTOR));
        if (pCopyVectorOutput != NULL) {
            result = ecmGetCopyVector(hndMaster, pCopyVectorOutput, &ulEntries, ECM_OUTPUT_DATA);
            if (ECM_SUCCESS == result) {
                printf("Output process image:\n");
                printf("---------------------\n");
                for (int i = 0; i < ulEntries; i++) {
                    printf("Offset = %08lu Size: %08lu\n",
                            (unsigned long)pCopyVectorOutput[i].ulOffset,
                            (unsigned long)pCopyVectorOutput[i].ulSize);
                }
            }
        }
    }

    printf("\n");

    result = ecmGetCopyVector(hndMaster, NULL, &ulEntries, ECM_INPUT_DATA);
    if (ECM_SUCCESS == result) {
        pCopyVectorInput = calloc((size_t)ulEntries, sizeof(ECM_COPY_VECTOR));
        if (pCopyVectorInput != NULL) {
            result = ecmGetCopyVector(hndMaster, pCopyVectorInput, &ulEntries, ECM_INPUT_DATA);
            if (ECM_SUCCESS == result) {
                printf("Input process image:\n");
                printf("---------------------\n");
                for (int i = 0; i < ulEntries; i++) {
                    printf("Offset = %08lu Size: %08lu\n",
                            (unsigned long)pCopyVectorInput[i].ulOffset,
                            (unsigned long)pCopyVectorInput[i].ulSize);
                }
            }
        }
    }

    printf("\n");

    result = ecmGetDataReference(hndMaster, ECM_OUTPUT_DATA, pCopyVectorOutput->ulOffset, 2, (void **)&pCw);
    if (result != ECM_SUCCESS) {
        printf("Failed to get reference to virtual variable Output\n");
    }    

    result = ecmGetDataReference(hndMaster, ECM_OUTPUT_DATA, pCopyVectorOutput->ulOffset+2, 4, (void **)&pTv);
    if (result != ECM_SUCCESS) {
        printf("Failed to get reference to virtual variable Output\n");
    }    

    result = ecmGetDataReference(hndMaster, ECM_OUTPUT_DATA, pCopyVectorOutput->ulOffset+6, 1, (void **)&pMop);
    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);
    }

    result = ecmGetSlaveHandle(hndMaster, &hndSlave);
    if (result != ECM_SUCCESS) {
        printf("Failed with %s to get slave handle!\n", ecmResultToString(result));
        ecmDetachMaster(hndMaster);
        ecmDeleteMaster(hndMaster);
        ecmDeleteDevice(hndDevice);
        ecmInitLibrary(NULL);
        return(-1);
    }
    

    *pMop = 3;
    *pCw = 0x000f;

    *pTv = 0x00010000; //clockwise rotate
    for (int i=0;i<3;i++)
    {
        ecmSleep(3000);
        *pTv+= 0x00001000; //increase speed
    }
    ecmSleep(3000);

    *pTv = 0xFFFF0000; //counter-clockwise rotate
    for (int i=0;i<3;i++)
    {
        ecmSleep(3000);
        *pTv-= 0x00001000; //increase speed
    }
    ecmSleep(3000);

    *pCw = 0;
    ecmSleep(1000);

    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);

    free(pCopyVectorOutput);
    free(pCopyVectorInput);

    return 0;

}


