/*
 * program Camcom("DEV=CAMC:LI21:CV01")
 */
program Camcom

option -c;
option -r;

%%#include "epicsTime.h"
%%#include "epicsThread.h"
%%#include "epicsPrint.h" /* epicsPrintf    */
%%#include "string.h"     /* memcpy, memset */
%%#include "stdio.h"      /* sprintf        */

%%static char* comp_date = __DATE__; /* 12 characters long */
%%static char* comp_comment = "Version 1.0"; 

%%#define CAMCOM_FREE 0
%%#define CAMCOM_TAKEN 1
%%#define CAMCOM_HOST_DONE 2
%%#define CAMCOM_BUSY 3
%%#define CAMCOM_DONE 4

/* required macro:
 * LCLS standard device name is CAMC:<loca>:CV01  
 * SPEAR standard device name is 116-IOCCAMAC
 */
char *device_c;    /* Device name */

/* Local Process variables */

short  last_active_token;
short  active_token;        assign active_token       to "${DEV}:ACTIVE_TOKEN";  string active_token_pv;  monitor active_token;
short  in_buff_len;         assign in_buff_len        to "${DEV):INBUFF_LEN";    string in_buff_len_pv;
char   real_buff[16348];    assign real_buff          to "${DEV}:REALBUFF";       string real_buff_pv;
char   in_buff[16348];      assign in_buff            to "${DEV}:INBUFF";        string in_buff_pv;
short  camcom_status;       assign camcom_status      to "${DEV}:STATUS";        string camcom_status_pv;  monitor camcom_status;
string camcom_reservation;  assign camcom_reservation to "${DEV}:NOTE";          string camcom_reservation_pv;
string camcom_seq_ver;      assign camcom_seq_ver     to "${DEV}:SEQ_VER";       string camcom_seq_ver_pv;


ss DOcamcom {
    state init {
	when (1) {
          strcpy(device_c,macValueGet("DEV"));
          printf("\nCamcom: SNL program started for %s\n",device_c);
          sprintf(camcom_seq_ver,"%s : %s",comp_date,comp_comment);
          pvPut(camcom_seq_ver);
          camcom_status=CAMCOM_FREE; pvPut(camcom_status);
          last_active_token = -1;
	} state process
    }

    state process {
        when (camcom_status==CAMCOM_TAKEN && last_active_token!=active_token) {
            last_active_token=active_token;
         } state process

        when (camcom_status==CAMCOM_FREE && last_active_token == active_token) {
            last_active_token--;
        } state process

        when (camcom_status==CAMCOM_HOST_DONE) {
            camcom_status=CAMCOM_BUSY; pvPut(camcom_status);
            pvGet(in_buff_len); pvGet(in_buff);
            pvGet(camcom_reservation);  /* Just for debug?? */
%%          memcpy((void *)&real_buff[0],(void *)&in_buff[0],2*in_buff_len);
            pvPut(real_buff, SYNC); /* Start Camac operation */
            pvGet(real_buff, SYNC); /* Get results */
%%          memcpy((void *)&in_buff[0],(void *)&real_buff[0],2*in_buff_len);
            pvPut(in_buff, SYNC);    /* Put results back to in_buff */
            camcom_status=CAMCOM_DONE; pvPut(camcom_status);
            last_active_token=-1;
        } state process
    }

}




