commit e3ab44e7b598d16cfe5c105206ba8d8b0a58b4e1 Author: Alexander Soederqvist Date: Tue Sep 22 13:20:58 2026 +0200 Import uwave driver and frontend from LEM diff --git a/device/uWave.cxx b/device/uWave.cxx new file mode 100644 index 0000000..93f6426 --- /dev/null +++ b/device/uWave.cxx @@ -0,0 +1,690 @@ +/********************************************************************\ + + Name: uWave.cxx + Created by: Zaher Salman 05/03/2021 + + Contents: Device driver for the RPi uWave controller. + TCP/IP calls sent to the RPi. + + TCPIP: IEEE-448 + termination: \n "new line" + +\********************************************************************/ + +#include +#include +#include +#include +#include + +#include "midas.h" +#include "mfe.h" +#include "msystem.h" + +#include "uWave.h" + +//----- globals ----------------------------------------------------- + +#define UWAVE_MAX_ERROR 10 //!< maximum number of error messages + +//! timeout in (ms) for the communication between pc and uWave +#define UWAVE_TIME_OUT 20000 +#define UWAVE_TIME_OUT_SLOW 100000 + +//! timeout in (sec) between logout terminal server an reconnection trial +#define UWAVE_RECONNECTION_TIMEOUT 5 +//! maximum number of readback failures before a reconnect will take place +#define UWAVE_MAX_READBACK_FAILURE 5 +//! maximum number of reconnections before bailing off +#define UWAVE_MAX_RECONNECTION_FAILURE 5 + +//--------- to handle error messages ------------------------------- + +#define UWAVE_SUCCESS 1 +#define UWAVE_STANDBY 0 //!< uWave standby tag +#define UWAVE_CMD_ERROR -3 //!< invalid command error +#define UWAVE_INIT_ERROR -2 //!< initialize error tag +#define UWAVE_READ_ERROR -1 //!< read error tag + +#define UWAVE_DELTA_TIME_ERROR 3600 //!< reset error counter after _DELTA_TIME_ERROR seconds + +//---------- channel definition tags -------------------------------- +#define UWAVE_IN_PH1_RB 0 +#define UWAVE_IN_PH2_RB 1 +#define UWAVE_IN_AMPL_RB 2 +#define UWAVE_IN_FREQ_RB 3 +#define UWAVE_IN_ONOFF_RB 4 + +#define UWAVE_OUT_PH1 0 +#define UWAVE_OUT_PH2 1 +#define UWAVE_OUT_AMPL 2 +#define UWAVE_OUT_FREQ 3 +#define UWAVE_OUT_ONOFF 4 + +//------------------------------------------------------------------- + +/*! + *

Generally it stores internal informations within the DD. In this + * case these are the names for the ODB describing the in-channels. + */ +typedef struct { + INT detailed_msg; //!< flag 0: no add. msg, 1: some add. msg, 2: debug + char name[5][NAME_LENGTH]; //!< input channel names +} UWAVE_IN_SETTINGS; + +/*! + *

Generally it stores internal informations within the DD. In this + * case this are the names for the ODB describing the out-channels. + */ +typedef struct { + char name[5][NAME_LENGTH]; //!< output channel names +} UWAVE_OUT_SETTINGS; + +//! Initializing string for the UWAVE_IN_SETTINGS structure. +const char *uWave_in_settings_str = +"Detailed Messages = FLOAT : 0\n\ +Input = STRING[5]:\n\ +[32] Phase 1 (deg)\n\ +[32] Phase 2 (deg)\n\ +[32] Amplitude (dBm)\n\ +[32] Frequency (GHz)\n\ +[32] On/Off (1/0)\n\ +"; + +//! initializing string for the UWAVE_OUT_SETTINGS structure. +const char *uWave_out_settings_str = +"Output = STRING[5] :\n\ +[32] Phase 1 (deg)\n\ +[32] Phase 2 (deg)\n\ +[32] Amplitude (dBm)\n\ +[32] Frequency (GHz)\n\ +[32] On/Off (1/0)\n\ +"; + +/*! + *

This structure contains private variables for the device driver. + */ +typedef struct { + UWAVE_IN_SETTINGS uWave_in_settings; //!< internal DD settings for the in-channels + UWAVE_OUT_SETTINGS uWave_out_settings; //!< internal DD settings for the out-channels + HNDLE hkey; //!< ODB key for bus driver info + INT (*bd)(INT cmd, ...); //!< bus driver entry function + void *bd_info; //!< private info of bus driver + INT bd_connected; //!< flag showing if bus driver is connected + INT first_bd_error; //!< flag showing if the bus driver error message is already given + INT errorcount; //!< error coutner + INT startup_error; //!< startup error tag; if set, the get and bh_set and bh_get routines wont do anything + DWORD lasterrtime; //!< timer for error handling + INT readback_failure; //!< counts the number of readback failures + DWORD last_reconnect; //!< timer for bus driver reconnect error handling + INT reconnection_failures; //!< how often reconnection failed + INT ph1; //!< Phase1 in degrees + INT ph2; //!< Phase2 in degrees + INT ampl; //!< Amplitude in dBm + INT freq; //!< Frequency in GHz + INT onoff; //!< On/Off state (1/0) + INT ph1_sp; //!< keep Phase1 in degrees + INT ph2_sp; //!< keep Phase2 in degrees + INT ampl_sp; //!< keep Amplitude in dBm + INT freq_sp; //!< keep Frequency in GHz + INT onoff_sp; //!< keep On/Off state (1/0) +} UWAVE_INFO; + +UWAVE_INFO *uWave_info; //!< global info structure since port can only be initialized once. + +typedef INT(func_t) (INT cmd, ...); + +/*---- device driver routines ---------------------------------------------------------*/ +/*! + *

Initializes the uWave device driver, i.e. generates all the necessary + * structures in the ODB if necessary, initializes the bus driver and the uWave.

+ *

Return: + * - FE_SUCCESS if everything went smooth + * - FE_ERR_ODB otherwise + * \param hKey is the device driver handle given from the class driver + * \param pinfo is needed to store the internal info structure + * \param channels is the number of channels of the device (from the class driver) + * \param bd is a pointer to the bus driver + */ +INT uWave_in_init(HNDLE hKey, UWAVE_INFO **pinfo, INT channels, func_t *bd) +{ + INT status, size; + HNDLE hDB, hKeyLocal; + char cmd[1024], rcv[128]; + float fval; + + cm_get_experiment_database(&hDB, NULL); + + // allocate info structure + UWAVE_INFO *info = (UWAVE_INFO*)calloc(1, sizeof(UWAVE_INFO)); + uWave_info = info; + *pinfo = info; + + // create uWave settings record + status = db_create_record(hDB, hKey, "DD/uWave", uWave_in_settings_str); + if (status != DB_SUCCESS) + return FE_ERR_ODB; + + // copy DD entries into the info structure + db_find_key(hDB, hKey, "DD/uWave", &hKeyLocal); + db_open_record(hDB, hKeyLocal, &info->uWave_in_settings, sizeof(info->uWave_in_settings), MODE_READ, NULL, NULL); + + // initialize driver + info->hkey = hKey; + info->bd = bd; + info->errorcount = 0; + info->lasterrtime = ss_time(); + info->startup_error = 0; + info->readback_failure = 0; + info->last_reconnect = ss_time(); + info->reconnection_failures = 0; + + if (!bd) + return FE_ERR_ODB; + + // initialize bus driver + status = info->bd(CMD_INIT, info->hkey, &info->bd_info); + if (status != SUCCESS) { + info->startup_error = 1; + info->bd_connected = FALSE; + cm_msg(MINFO, "uWave_in_init", "Bus driver failed to initialize! status=%d",status); + return status; + } + cm_msg(MINFO, "uWave_in_init", "Bus driver initialized!"); + info->bd_connected = TRUE; + + // read back from ODB + status = db_find_key(hDB, 0, "/Equipment/uWave/Variables/Output", &hKeyLocal); + if (status != DB_SUCCESS) { + cm_msg(MERROR, "uWave_in_init", "uWave_in_init: couldn't obtain readback ..."); + cm_yield(0); + info->startup_error = UWAVE_INIT_ERROR; + return FE_SUCCESS; + } + // read back from ODB Phase 1 + size = sizeof(fval); + db_get_data_index(hDB, hKeyLocal, &fval, &size, UWAVE_OUT_PH1, TID_FLOAT); + info->ph1 = fval; + + // read back from ODB Phase 2 + size = sizeof(fval); + db_get_data_index(hDB, hKeyLocal, &fval, &size, UWAVE_OUT_PH2, TID_FLOAT); + info->ph2 = fval; + + // read back from ODB Amplitude + size = sizeof(fval); + db_get_data_index(hDB, hKeyLocal, &fval, &size, UWAVE_OUT_AMPL, TID_FLOAT); + info->ampl = fval; + + // read back from ODB Frequency + size = sizeof(fval); + db_get_data_index(hDB, hKeyLocal, &fval, &size, UWAVE_OUT_FREQ, TID_FLOAT); + info->freq = fval; + + if (info->uWave_in_settings.detailed_msg == 2) { + cm_msg(MINFO, "uWave_in_init", "uWave_in_init: phase 1 = %f", info->ph1); + cm_yield(0); + } + + // read back from ODB On/Off + size = sizeof(fval); + db_get_data_index(hDB, hKeyLocal, &fval, &size, UWAVE_OUT_ONOFF, TID_FLOAT); + info->onoff = (int)fval; + + // How to check that the device is responding + strcpy(cmd, "OUTP?\n"); + BD_PUTS(cmd); + status = BD_GETS(rcv, sizeof(rcv), "\n", UWAVE_TIME_OUT); + if (status) { + sscanf(rcv, "%f", &fval); + cm_msg(MINFO, "uWave_in_init", "uWave initialized ..."); + cm_yield(0); + } else { + info->startup_error = UWAVE_INIT_ERROR; + cm_msg(MINFO, "uWave_in_init", "uWave driver failed to initialize ..."); + cm_yield(0); + } + + return FE_SUCCESS; +} + +/*----------------------------------------------------------------------------------*/ +/*! + *

Initializes the uWave device driver, i.e. generates all the necessary + * structures in the ODB if necessary, no initialization of the bus driver etc. + * is done, since this is part of uWave_in_init.

+ *

Return: + * - FE_SUCCESS if everything went smooth + * - FE_ERR_ODB otherwise + * \param hKey is the device driver handle given from the class driver + * \param pinfo is needed to store the internal info structure + * \param channels is the number of channels of the device (from the class driver) + * \param bd is a pointer to the bus driver + */ +INT uWave_out_init(HNDLE hKey, UWAVE_INFO **pinfo, INT channels, func_t *bd) +{ + INT status; + HNDLE hDB, hKeyLocal; + + cm_get_experiment_database(&hDB, NULL); + + UWAVE_INFO *info = uWave_info; + *pinfo = info; + + /* create uWave settings record */ + status = db_create_record(hDB, hKey, "DD", uWave_out_settings_str); + if (status != DB_SUCCESS) + return FE_ERR_ODB; + + // copy DD entries into the info structure + db_find_key(hDB, hKey, "DD", &hKeyLocal); + db_open_record(hDB, hKeyLocal, &info->uWave_out_settings, + sizeof(info->uWave_out_settings), MODE_READ, NULL, NULL); + + return FE_SUCCESS; +} + +/*----------------------------------------------------------------------------------*/ +/*! + *

terminates the bus driver and free's the memory allocated for the info structure + * UWAVE_INFO.

+ *

Return: FE_SUCCESS

+ * \param info is a pointer to the DD specific info structure + */ +INT uWave_exit(UWAVE_INFO *info) +{ + if (info->startup_error) + return FE_SUCCESS; + + // call EXIT function of bus driver, usually closes device + info->bd(CMD_EXIT, info->bd_info); + + free(info); + + return FE_SUCCESS; +} + +/*----------------------------------------------------------------------------------*/ +/*! + *

set a value of the uWave.

+ *

Return: FE_SUCCESS

+ * \param info is a pointer to the DD specific info structure. + * \param channel is the channel number + * \param value to be set + */ +INT uWave_set(UWAVE_INFO *info, INT channel, float value) +{ + char cmd[128]; + + // Debug message + // cm_msg(MINFO, "uWave_set", "uWave_set: %d, set cmd: %f", channel, value); + + if (info->startup_error) + return FE_SUCCESS; + + if (!info->bd_connected) { + if (info->first_bd_error) { + info->first_bd_error = 0; + cm_msg(MINFO, "uWave_set", + "uWave_set: set values not possible at the moment, since the bus driver is not available!"); + } + ss_sleep(10); + return FE_SUCCESS; + } + + // set command should go here + switch (channel) { + // Phase 1 + case UWAVE_OUT_PH1: // set Phase 1 in degrees + sprintf(cmd, "PH1 %f\n",value); + if (info->uWave_in_settings.detailed_msg == 2) // debug only + cm_msg(MINFO, "uWave_set", "uWave_set: cmd: %s", cmd); + BD_PUTS(cmd); + info->ph1_sp = value; + return FE_SUCCESS; + break; + + // Phase 2 + case UWAVE_OUT_PH2: // set Phase 2 in degrees + sprintf(cmd, "PH2 %f\n",value); + if (info->uWave_in_settings.detailed_msg == 2) // debug only + cm_msg(MINFO, "uWave_set", "uWave_set: cmd: %s", cmd); + BD_PUTS(cmd); + info->ph2_sp = value; + return FE_SUCCESS; + break; + + // Amplitude + case UWAVE_OUT_AMPL: // set Amplitude in dBm + sprintf(cmd, "AMPL %f\n",value); + if (info->uWave_in_settings.detailed_msg == 2) // debug only + cm_msg(MINFO, "uWave_set", "uWave_set: cmd: %s", cmd); + BD_PUTS(cmd); + info->ampl_sp = value; + return FE_SUCCESS; + break; + + // Frequency + case UWAVE_OUT_FREQ: // set Frequency in GHz + sprintf(cmd, "FREQ %f\n",value); + if (info->uWave_in_settings.detailed_msg == 2) // debug only + cm_msg(MINFO, "uWave_set", "uWave_set: cmd: %s", cmd); + BD_PUTS(cmd); + info->freq_sp = value; + return FE_SUCCESS; + break; + + // Toggle on/off + case UWAVE_OUT_ONOFF: // output on=1, off=0 + sprintf(cmd, "OUTP %d\n",(int)value); + if (info->uWave_in_settings.detailed_msg == 2) // debug only + cm_msg(MINFO, "uWave_set", "uWave_set: cmd: %s", cmd); + BD_PUTS(cmd); + info->onoff_sp = (int)value; + return FE_SUCCESS; + break; + + default: + return FE_SUCCESS; + break; + } + + if (info->uWave_in_settings.detailed_msg > 0) + cm_msg(MINFO, "uWave_set", "uWave_set: cmd: %s", cmd); + + ss_sleep(100); + return FE_SUCCESS; +} + +/*----------------------------------------------------------------------------------*/ +/*! + *

get a value from the uWave.

+ *

Return: FE_SUCCESS

+ * \param info is a pointer to the DD specific info structure. + * \param channel is the channel number + * \param pvalue read + */ +INT uWave_get(UWAVE_INFO *info, INT channel, float *pvalue) +{ + int status; + int chan; + char cmd[128], rcv[128]; + DWORD nowtime, difftime; + // float fval, fval1; + + // error timeout facility + nowtime = ss_time(); + difftime = nowtime - info->lasterrtime; + if ( difftime > UWAVE_DELTA_TIME_ERROR ) { + info->errorcount = 0; + info->lasterrtime = ss_time(); + } + + // check if there was a startup error + if ( info->startup_error ) { + *pvalue = (float) UWAVE_INIT_ERROR; + ss_sleep(10); // to keep CPU load low when Run active + return FE_SUCCESS; + } + + // check if there where too many reconnection failures + if (info->reconnection_failures > UWAVE_MAX_RECONNECTION_FAILURE) { + *pvalue = (float) UWAVE_READ_ERROR; + if (info->reconnection_failures == UWAVE_MAX_RECONNECTION_FAILURE+1) { + cm_msg(MERROR, "uWave_get", "too many reconnection failures, bailing out :-("); + info->reconnection_failures++; + } + return FE_SUCCESS; + } + + // if disconnected, try to reconnect after a timeout of a timeout + if (!info->bd_connected) { + if (ss_time()-info->last_reconnect > UWAVE_RECONNECTION_TIMEOUT) { // timeout expired + if (info->uWave_in_settings.detailed_msg > 0) + cm_msg(MINFO, "uWave_get", "uWave: reconnection trial ..."); + status = info->bd(CMD_INIT, info->hkey, &info->bd_info); + if (status != FE_SUCCESS) { + info->reconnection_failures++; + *pvalue = (float) UWAVE_READ_ERROR; + if (info->uWave_in_settings.detailed_msg > 0) + cm_msg(MINFO, "uWave_get", "uWave: reconnection attempted failed"); + return FE_ERR_HW; + } else { + info->bd_connected = 1; // bus driver is connected again + info->last_reconnect = ss_time(); + info->reconnection_failures = 0; + info->first_bd_error = 1; + if (info->uWave_in_settings.detailed_msg > 0) + cm_msg(MINFO, "uWave_get", "uWave: successfully reconnected"); + } + } else { // timeout still running + ss_sleep(10); + return FE_SUCCESS; + } + } + + // set the read command + switch (channel) { + case UWAVE_IN_PH1_RB: // check what is Phase 1 + sprintf(cmd, "PH1?\n"); + break; + case UWAVE_IN_PH2_RB: // check what is Phase 2 + sprintf(cmd, "PH2?\n"); + break; + case UWAVE_IN_AMPL_RB: // check what is the Amplitude + sprintf(cmd, "AMPL?\n"); + break; + case UWAVE_IN_FREQ_RB: // check what is the Frequency + sprintf(cmd, "FREQ?\n"); + break; + case UWAVE_IN_ONOFF_RB: // check what is the trigger level + sprintf(cmd, "OUTP?\n"); + break; + default: + return FE_SUCCESS; + } + + // The above commands return relative channel, value + // these need to be processed. + + // send the command and read the response + BD_PUTS(cmd); + status = BD_GETS(rcv, sizeof(rcv), "\n", UWAVE_TIME_OUT); + + if (info->uWave_in_settings.detailed_msg == 2) {// debug only + cm_msg(MINFO, "uWave_get", "uWave_get: cmd:\"%s\", %d, %s, status=%d", cmd, channel, rcv, status); + cm_msg(MINFO, "uWave_get", "uWave_get: cmd: %s", cmd); + cm_msg(MINFO, "uWave_get", "uWave_get: rdb: %s", rcv); + } + + // check for any error + if (!status) { // error occured + *pvalue = (float) UWAVE_READ_ERROR; + status = UWAVE_READ_ERROR; + } else { // no error -> decode data + status = UWAVE_SUCCESS; + + // interpret the response + switch (channel) { + case UWAVE_IN_PH1_RB: // read Phase 1 + sscanf(rcv, "%f", pvalue); + break; + case UWAVE_IN_PH2_RB: // read Phase 2 + sscanf(rcv, "%f", pvalue); + break; + case UWAVE_IN_AMPL_RB: // read Amplitude + sscanf(rcv, "%f", pvalue); + break; + case UWAVE_IN_FREQ_RB: // read Frequency + sscanf(rcv, "%f", pvalue); + break; + case UWAVE_IN_ONOFF_RB: // read On/Off state + sscanf(rcv, "%f", pvalue); + break; + default: + return FE_SUCCESS; + } + } + + if (status != UWAVE_SUCCESS) { + if ( info->errorcount < UWAVE_MAX_ERROR ) { + if (info->uWave_in_settings.detailed_msg > 0) + cm_msg(MERROR, "uWave_get", "uWave communication or command error. Status = %d", status); + info->errorcount++; + } + info->readback_failure++; + + if (info->readback_failure == UWAVE_MAX_READBACK_FAILURE) { + info->readback_failure = 0; + // try to disconnect and reconnect the bus driver + if ((ss_time()-info->last_reconnect > UWAVE_RECONNECTION_TIMEOUT) && info->bd_connected) { + info->bd(CMD_EXIT, info->bd_info); // disconnect bus driver + if (info->uWave_in_settings.detailed_msg > 0) + cm_msg(MINFO, "uWave_get", "uWave: try to disconnect and reconnect the bus driver"); + info->last_reconnect = ss_time(); + info->bd_connected = 0; + } + } + return FE_SUCCESS; + } + + ss_sleep(1000); + return FE_SUCCESS; +} + +/*----------------------------------------------------------------------------------*/ +/*! + *

at startup, after initialization of the DD, this routine allows to write + * default names of the in-channels into the ODB.

+ *

Return: FE_SUCCESS + * \param info is a pointer to the DD specific info structure + * \param channel of the name to be set + * \param name pointer to the ODB name + */ +INT uWave_in_get_label(UWAVE_INFO *info, INT channel, char *name) +{ + strcpy(name, info->uWave_in_settings.name[channel]); + return FE_SUCCESS; +} + +/*----------------------------------------------------------------------------------*/ +/*! + *

at startup, after initialization of the DD, this routine allows to write + * default names of the out-channels into the ODB.

+ *

Return: FE_SUCCESS + * \param info is a pointer to the DD specific info structure + * \param channel of the name to be set + * \param name pointer to the ODB name + */ +INT uWave_out_get_label(UWAVE_INFO *info, INT channel, char *name) +{ + strcpy(name, info->uWave_out_settings.name[channel]); + return FE_SUCCESS; +} + +/*---- device driver entry point ---------------------------------------------------*/ +/*! + *

The device driver for the uWave is setup such that it can send TCP/IP commands + * to an RPi to control uWave properties. + */ +INT uWave_in(INT cmd, ...) +{ + va_list argptr; + HNDLE hKey; + INT channel, status; + float *pvalue; + UWAVE_INFO *info; + char *name; + + va_start(argptr, cmd); + status = FE_SUCCESS; + + switch (cmd) { + case CMD_INIT: + { + hKey = va_arg(argptr, HNDLE); + UWAVE_INFO **pinfo = va_arg(argptr, UWAVE_INFO**); + channel = va_arg(argptr, INT); + va_arg(argptr, DWORD); // flags - currently not used + func_t *bd = va_arg(argptr, func_t*); + status = uWave_in_init(hKey, pinfo, channel, bd); + } + break; + + case CMD_EXIT: + info = va_arg(argptr, UWAVE_INFO*); + status = uWave_exit(info); + break; + + case CMD_GET: + info = va_arg(argptr, UWAVE_INFO*); + channel = va_arg(argptr, INT); + pvalue = va_arg(argptr, float*); + status = uWave_get(info, channel, pvalue); + break; + + case CMD_GET_LABEL: + info = va_arg(argptr, UWAVE_INFO*); + channel = va_arg(argptr, INT); + name = va_arg(argptr, char *); + status = uWave_in_get_label(info, channel, name); + break; + + default: + break; + } + + va_end(argptr); + return status; +} + +/************************************************************************/ + +INT uWave_out(INT cmd, ...) +{ + va_list argptr; + HNDLE hKey; + INT channel, status; + float value; + UWAVE_INFO *info; + char *name; + + va_start(argptr, cmd); + status = FE_SUCCESS; + + switch (cmd) { + case CMD_INIT: + { + hKey = va_arg(argptr, HNDLE); + UWAVE_INFO **pinfo = va_arg(argptr, UWAVE_INFO**); + channel = va_arg(argptr, INT); + va_arg(argptr, DWORD); // flags - currently not used + func_t *bd = va_arg(argptr, func_t*); + status = uWave_out_init(hKey, pinfo, channel, bd); + } + break; + + case CMD_SET: + info = va_arg(argptr, UWAVE_INFO*); + channel = va_arg(argptr, INT); + value = (float) va_arg(argptr, double); + status = uWave_set(info, channel, value); + break; + + case CMD_GET_LABEL: + info = va_arg(argptr, UWAVE_INFO*); + channel = va_arg(argptr, INT); + name = va_arg(argptr, char *); + status = uWave_out_get_label(info, channel, name); + break; + + default: + break; + } + + va_end(argptr); + + return status; +} + +/*------------------------------------------------------------------*/ diff --git a/device/uWave.h b/device/uWave.h new file mode 100644 index 0000000..332d549 --- /dev/null +++ b/device/uWave.h @@ -0,0 +1,22 @@ +/********************************************************************\ + + Name: uWave.h + Created by: Zaher Salman 05/03/2021 + + Contents: Device driver for the RPi uWave controller. + TCP/IP calls sent to the RPi. + +\********************************************************************/ + +/*---- device driver declaration -----------------------------------*/ +/*! + *

UWAVE device driver (DD) for reading. + * Handling the communication between the uWave and midas. + */ +INT uWave_in(INT cmd, ...); + +/*! + *

UWAVE device driver (DD) for setting values. + * Handling communication between the uWave and midas. + */ +INT uWave_out(INT cmd, ...); diff --git a/frontend/CMakeLists.txt b/frontend/CMakeLists.txt new file mode 100644 index 0000000..7b9a8ed --- /dev/null +++ b/frontend/CMakeLists.txt @@ -0,0 +1,60 @@ +# Build uWave SCFE +cmake_minimum_required(VERSION 3.03) + +project(uWave_scfe VERSION 1.0) + +find_package(Midas PATHS $ENV{MIDASSYS} REQUIRED) + +#--- make sure the MIDAS_PREFIX system variable is present -------------------- +if (NOT DEFINED ENV{MIDAS_PREFIX}) + message(FATAL_ERROR "The system variable MIDAS_PREFIX is not defined.") +endif (NOT DEFINED ENV{MIDAS_PREFIX}) + +#--- check if the user want to install NOT under MIDAS_PREFIX ----------------- +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(install_path "$ENV{MIDAS_PREFIX}/bin") +else (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(install_path "${CMAKE_INSTALL_PREFIX}/bin") +endif (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) +message(STATUS "The install dir is: ${install_path}") + +#--- set default install prefix ----------------------------------------------- +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/SetDefaultInstallPath.cmake) + +set (DRIVERS + $ENV{MIDASSYS}/drivers/bus/tcpip.cxx + $ENV{MIDASSYS}/drivers/class/multi.cxx + $ENV{MIDAS_WORK}/drivers/device/uWave.cxx +) + +add_executable(uWave_scfe + uWave_scfe.cxx + ${DRIVERS} +) + +set_property( + TARGET + uWave_scfe + PROPERTY + CXX_STANDARD 17 +) + +target_include_directories(uWave_scfe + PRIVATE + $ENV{MIDASSYS}/drivers + $ENV{MIDASSYS}/include + $ENV{MIDAS_WORK}/drivers/device +) + +target_link_libraries(uWave_scfe + midas::mfe + midas::midas +) + +install( + TARGETS + uWave_scfe + RUNTIME DESTINATION + ${install_path} +) + diff --git a/frontend/RPisock_thread_gpioera/RPisock.py b/frontend/RPisock_thread_gpioera/RPisock.py new file mode 100644 index 0000000..4526b3f --- /dev/null +++ b/frontend/RPisock_thread_gpioera/RPisock.py @@ -0,0 +1,283 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Feb 11 09:30:36 2021 + +@author: doll_a +""" +# sketch of socket server running on RPi to listen to commands +# main purpose: Parsing of commands sent by MIDAS + +import socket +import numpy as np +#import era_test +import era_test_thread +import gpio_test_thread +import time + + +class RPisock: + + + # initialization function + def __init__(self): + + + # command list + # it is specified as follows + # [command, argument type, number of arguments, execution function] + self.commands = [] + # Phase functions: ---> GPIO + self.commands.append(['PH1 ', float , 1, self.set_phase1]) + self.commands.append(['PH2 ', float , 1, self.set_phase2]) + self.commands.append(['PH1?', float , 0, self.get_phase1]) + self.commands.append(['PH2?', float , 0, self.get_phase2]) + + # synth functions + self.commands.append(['AMPL ', float , 1, self.set_ampl]) + self.commands.append(['FREQ ', float , 1, self.set_freq]) + self.commands.append(['OUTP ', int , 1, self.set_outp]) + self.commands.append(['AMPL?', float , 0, self.get_ampl]) + self.commands.append(['FREQ?', float , 0, self.get_freq]) + self.commands.append(['OUTP?', int , 0, self.get_outp]) +# self.commands.append(['OUTP?', int , 0, self.reply_1]) +# self.commands.append(['OUTPUT?', int , 0, self.get_outp]) + self.commands.append(['OUTPUT?', int , 0, self.reply_1]) + + self.commands.append(['STAT?', int , 0, self.get_stat]) + + + + # open the socket + HOST = 'lempi.psi.ch' # Server IP or Hostname + HOST = 'localhost' # Server IP or Hostname + HOST = 'uwavepi.psi.ch' # Server IP or Hostname + PORT = 5025 # Pick an open Port (1000+ recommended), must match the client sport + # make the connection ready + try: + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.s.bind((HOST, PORT)) + print('Socket created and bound') + except socket.error: + print('Problem setting up the socket') + + + self.s.listen(5) + print('Socket lsitening') + + # verbose: + # TRUE: send user-understandeable response + # FALSE: just send a short response about the status (for reporting back to MIDAS) + # idea: a python client for debugging will make live easier in verbose mode + # This sitll needs to be implemented + self.verbose = False + + # MIDAS specific: In non-verbose mode, it is a good idea to define the maxlen of the message. + # at Zaher: you need to hardcode this into your driver. + # I will then make sure that a response in non-verbose mode will not be longer than midas_bytelen + self.midas_bytelen = 1024 + + # initialize hardware + # phase setting + self.pha1 = 0 + self.pha2 = 0 + self.gpio = gpio_test_thread.myDriver() + self.gpio.write('Phase 1', self.pha1) + self.gpio.write('Phase 2', self.pha2) + # TODO: HW command to set GPIO bits + # using the python library RPi.GPIO, i.e. + # import RPi.GPIO as GPIO + # requires: sudo apt-get -y install python3-rpi.gpio + + # uwave synth + self.era = era_test_thread.myDriver() + self.era_frq = 3.8 + self.era_amp = 0 + self.era_state = 0 + self.era.write('LOFreq', self.era_frq) + self.era.write('LOAmp', self.era_amp) + self.era.write('Power', self.era_state) + # TODO: HW commands to set the erasynth via USB-serial + # this is via the serial library, as already in use at XTreme + # dev = "/dev/ttyACM0" + # self.eras = serial.Serial(port=dev,baudrate=9600,timeout=1) + + + # this can be extended to add other hardware.. + # implemented and tested for signal averaging is the DSOX2014 oscilloscope + # --> we could use this to look at the High power monitor signals + # control of this one is via the usbtmc library and uses the instruments ascii commands + # instr = usbtmc.Instrument(vid, did) + # print(instr.ask('*IDN?')) + + # time stamps to time requests from midas + self.tstamp = time.time() + self.tstamp0 = 0 + self.n_calls = 0 + + # stuff to close the connection + def close(self): + self.s.close() # Close connections + + # class destructor: close connection + def __del__(self): + self.close() + + # server that processes data + # for the moment highly quick-and-dirty. needs to be put in a seperate thread that is started by an event + # also needs to be safe to receive more than one connection. + # This is all documented and can be done + def run(self): + + # listen to client + (self.client, addr) = self.s.accept() + + # awaiting for message + while True: + try: + data = self.client.recv(self.midas_bytelen).decode() + print('Reacting to: ' + data) + + # debug stuff: time it + self.n_calls += 1 + acttim = time.time() + # give it some offset to start the time measurement + call_offset = 30 + if self.n_calls == call_offset: + self.tstamp0 = acttim + if self.n_calls > call_offset: + print('time delay {:.02f}, avg {:.03f}'.format(acttim - self.tstamp, (acttim - self.tstamp0)/(self.n_calls-call_offset))) + self.tstamp = time.time() + + + # when the client terminates, a zero length packet is received + # --> make it ready for a repeated connection + if len(data) == 0: + self.client.close() + (self.client, addr) = self.s.accept() + self.n_calls = 0 # reset the number of calls (to remeasure timing) + continue + + + # if more than one command has been sent + data_l = data.split('\n') + for data in data_l: + + # parse command + for ii_c, cmd in enumerate(self.commands): + # simplistic for the moment + if data.startswith(cmd[0]): + # check arguments + # direct call for calls without argument + if cmd[2] == 0: + cmd[3]() + else: + # isolate the arguments + argstr = data[len(cmd[0]):] + # comma separate + argstr_split = argstr.split(',') + if len(argstr_split) != cmd[2]: + # The response below is obviously verbose mode + reply = 'Problem with arguments of command {}, expected {} arguments'.format(data, cmd[2]) + print(reply) + self.client.send(reply.encode()) + + # parsed arguments + args = np.zeros((cmd[2],1), dtype = cmd[1]) + for ii in range(len(args)): + args[ii] = argstr_split[ii] + + # here we go, forward the arguments + cmd[3](args) + + + except socket.error as e: + self.client.close() + print(e) + + + # _____________________________ + # functions related to commands + # _____________________________ + def set_phase1(self, args): + self.pha1 = args[0,0] + self.gpio.write_thread('Phase 1', self.pha1) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def set_phase2(self, args): + self.pha2 = args[0,0] + self.gpio.write_thread('Phase 2', self.pha2) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def get_phase1(self): + reply = self.gpio.get_vars(['dec_1'])[0] + self.pha1 = reply + reply = '{:.3f}\n'.format(reply) + self.client.send(reply.encode()) + + def get_phase2(self): + reply = self.gpio.get_vars(['dec_2'])[0] + self.pha2 = reply + reply = '{:.3f}\n'.format(reply) + self.client.send(reply.encode()) + + + def set_ampl(self, args): + self.era_amp = args[0,0] + self.era.write_thread('LOAmp', self.era_amp) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def set_freq(self, args): + self.era_frq = args[0,0] + self.era.write_thread('LOFreq', self.era_frq) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def set_outp(self, args): + self.era_state = args[0,0] + self.era.write_thread('Power', self.era_state) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def get_ampl(self): + reply = self.era.get_vars(['amplitude'])[0] + self.era_amp = float(reply) + reply = reply + '\n' + self.client.send(reply.encode()) + + def get_freq(self): + reply = self.era.get_vars(['frequency'])[0] + self.era_frq = float(reply)*1e-9 + reply = '{:.3f}\n'.format(self.era_frq) + self.client.send(reply.encode()) + + + def get_outp(self): + reply = self.era.get_vars(['rfoutput'])[0] + self.era_state = int(reply) + reply = reply + '\n' + self.client.send(reply.encode()) + + + def get_stat(self): + reply = self.era.get_all() + reply = 'Printed\n' + self.client.send(reply.encode()) + + + def reply_1(self): + reply = '1\n' + self.client.send(reply.encode()) + + + +# the main program being run when runnig the RPisock.py script +if __name__ == '__main__': + sock = RPisock() + sock.run() + # it will never stop runnig at the momment... + sock.close() + + diff --git a/frontend/RPisock_thread_gpioera/era_test_thread.py b/frontend/RPisock_thread_gpioera/era_test_thread.py new file mode 100644 index 0000000..7c878cd --- /dev/null +++ b/frontend/RPisock_thread_gpioera/era_test_thread.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python +import numpy as np +import serial +import time +from time import sleep +import json +import glob +import threading + +#function that check for active serial port device ttyACM (the erasynth sits behind an arduino, thus it is a ttyACM device) +def find_ports(): + ports = glob.glob('/dev/ttyACM[0-9]*') + + res = [] + for port in ports: + try: + s = serial.Serial(port) + s.close() + res.append(port) + except: + pass + return res + + +class myDriver: + def __init__(self): + + + # mutexes to control threads + self.comm_mutex = threading.Lock() # this is to avoid that more than one thread talks to the era + self.var_mutex = threading.Lock() # this is to avoid that more than one thread accesses self.rback + + # get the ttyACM port that is valid + ACMs = find_ports() + # if nothing was found, use pts/1 for testing without the synth + if len(ACMs) == 0: + dev = "/dev/pts/1" + else: + dev = ACMs[0] + + self.eras = serial.Serial(port=dev,baudrate=115200,timeout=1) +# self.eras.close() + sleep(0.1) + self.write('Power', 0) + sleep(0.1) + self.write('LOFreq', 5.0) + sleep(0.1) + self.write('LOMod', 0) + sleep(0.1) + self.write('LOAmp', 0.0) + sleep(2.0) + + print(self.eras.readall().decode()) + + + # check lock status + self.eras.write('>RD\r\n'.encode()) + try: + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + except: + pass + +# rset = False +# while (rback['lock_lmx1'] != '1') or (rback['lock_lmx2'] != '1'): +# print('re-setting PLL mode to achieve lock!') +# self.write('PNmode', 0) +# sleep(15.0) +# rback_r = self.eras.readall().decode() +# self.eras.write('>RD\r\n'.encode()) +# rback_r = self.eras.readall().decode() +# rback = json.loads(rback_r) +# rset = True +# +# if rset: +# print('... PLLs locked!') + + self.rback_interval = 5 # readback interval in seconds + self.rback_interval = 1 # readback interval in seconds + self.update_pars() + + # start update thread + self.updater = readback_thread(self,self.rback_interval) + + def write(self, reason, value): + status = True + try: + self.comm_mutex.acquire() + + # take proper actions + if reason == 'Power': + self.eras.write('>P0{}\r\n'.format(value).encode()) + sleep(0.05) + if reason == 'LOMod': + self.eras.write('>MS{}\r\n'.format(value).encode()) + sleep(0.05) + elif reason == 'LOFreq': + frq = int(value*1e9) + self.eras.write('>F{}\r\n'.format(frq).encode()) + sleep(0.05) + elif reason == 'LOAmp': + amp = float(value) + self.eras.write('>A{:.1f}\r\n'.format(amp).encode()) + sleep(0.05) + elif reason == 'PNmode': + self.eras.write('>P9{}\r\n'.format(int(value)).encode()) + sleep(0.05) + + except: + status = False + finally: + self.comm_mutex.release() + print('Written data') + + return status + + # also write data with threads to avoid that many write operations hang the system + def write_thread(self, reason, value): + t = threading.Thread(target=myDriver.write, args=(self, reason, value)) + t.start() + + def get_all(self): + + + rback_ok = True + try: + self.comm_mutex.acquire() + + + rback_r = self.eras.readall().decode() + + # get all values + self.eras.write('>RA\r\n'.encode()) + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + print(rback) + + + # get status + self.eras.write('>RD\r\n'.encode()) + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + print(rback) + + except: + rback_ok = False + finally: + self.comm_mutex.release() + + return rback_ok + + + + def get_vars(self, var_list): + + + try: + self.var_mutex.acquire() + + ret_vals = [] + for var in var_list: + if var in self.rback.keys(): + ret_vals.append(self.rback[var]) + else: + ret_vals.append('ERR') + + + + t_act = time.time() + elapsed = t_act - self.rback_ts + if (elapsed) > self.rback_interval*2: + print('Parameters not up-to-date. {:.01} secs since last update, thus {:.01} secs above interval'.format(elapsed, elapsed - self.rback_interval )) + + # in case this fails, just assign all to zero + except: + ret_vals = [None]*len(var_list) + for ii in range(len(ret_vals)): + ret_vals[ii] = '0' + + finally: + self.var_mutex.release() + + + return ret_vals + + # retrieve all parameteres and store in class + def update_pars(self): + + rback_ok = True + try: + self.comm_mutex.acquire() + + rback_r = self.eras.readall().decode() + self.eras.write('>RA\r\n'.encode()) + sleep(0.2) + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + except: + rback_ok = False + finally: + self.comm_mutex.release() + + # store in self.readback if it went fine + if rback_ok: + + ts = time.time() + + try: + self.var_mutex.acquire() + + self.rback = rback + self.rback_ts = ts + finally: + self.var_mutex.release() + + + +class readback_thread(): + """ Thread reading back the device state in the background + """ + + def __init__(self, driver, interval=1): + """ Constructor + :type interval: int + :param interval: Check interval, in seconds + """ + self.driver = driver + self.interval = interval + + self.thread = threading.Thread(target=self.run, args=()) + self.thread.daemon = True # Daemonize thread + self.thread.start() # Start the execution + + def run(self): + """ Method that runs forever """ + while True: + # Do something + print('Update parameters (erasynth)') + self.driver.update_pars() + + time.sleep(self.interval) + + +if __name__ == '__main__': + driver = myDriver() + + diff --git a/frontend/RPisock_thread_gpioera/gpio_test_thread.py b/frontend/RPisock_thread_gpioera/gpio_test_thread.py new file mode 100644 index 0000000..fad7a2d --- /dev/null +++ b/frontend/RPisock_thread_gpioera/gpio_test_thread.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python +import numpy as np +import RPi.GPIO as GPIO +import time +from time import sleep +import json +from os import path +import threading + + +class myDriver: + def __init__(self): + + + # mutexes to control threads + self.comm_mutex = threading.Lock() # this is to avoid that more than one thread talks to the GPIO pins + self.var_mutex = threading.Lock() # this is to avoid that more than one thread accesses the read back GPIO state + + # the 6 bits used for the first phase controller + self.pin_array_1 = [3, 5, 7, 11, 13, 15] + self.state_1 = np.array([0, 0, 0, 0, 0, 0], dtype = int) + self.mult_1 = 360/64.0 # multiplier between binary (state_) and decimal (dec_) representation + self.dec_1 = 0.0 + + # the 6 bits used for the second phase controller + self.pin_array_2 = [8, 10, 12, 16, 18, 22] + self.state_2 = np.array([0, 0, 0, 0, 0, 0], dtype = int) + self.mult_2 = 360/64.0 + self.dec_2 = 0.0 + + # avoid the annoying and unimportant warning about channel in use (its just because there is no cleanup in this ever-running script) + GPIO.setwarnings(False) + + # set GPIO mode to board + GPIO.setmode(GPIO.BOARD) + + # setup and initialize all the ports accordingly + for ii, port in enumerate(self.pin_array_1): + GPIO.setup(port, GPIO.OUT) + GPIO.output(port, int(self.state_1[ii])) + for port in self.pin_array_2: + GPIO.setup(port, GPIO.OUT) + GPIO.output(port, int(self.state_2[ii])) + + self.rback_interval = 5 # readback interval in seconds + self.update_pars() + + # start update thread + self.updater = readback_thread(self,self.rback_interval) + + # in principle, one should clean up afterwareds with GPIO.cleanup() + + # convert binary to decimal + def bin2dec(self, bin_arr, mult = 1.0): + decval = 0 + for digit in bin_arr: + decval = (decval << 1) | digit + + return decval * mult + + # convert decimal to binary array + def dec2bin(self, decval, mult = 1.0, bitlen = 6): + + # get binary string representation + deceqv = int(np.round(decval/mult)) + bin_arr0 = np.array(list(bin((deceqv))[2:]),dtype=int) + + # case where we should not land + if bitlen < len(bin_arr0): + print('Weird state: {} is beyond the range of {} bits: {}'.format((deceqv),bitlen, bin(deceqv))) + bin_arr = bin_arr0[-bitlen:] + elif bitlen == len(bin_arr0): + bin_arr = bin_arr0 + elif bitlen > len(bin_arr0): + bin_arr = np.zeros((bitlen,),dtype=int) + bin_arr[-len(bin_arr0):] = bin_arr0 + + return bin_arr + + + def write(self, reason, value): + status = True + try: + self.comm_mutex.acquire() + + # take proper actions + if reason == 'Phase 1': + bin_arr = self.dec2bin(value, mult = self.mult_1, bitlen = len(self.pin_array_1)) + status = self.write_pins(bin_arr, self.pin_array_1) + sleep(0.05) + elif reason == 'Phase 2': + bin_arr = self.dec2bin(value, mult = self.mult_2, bitlen = len(self.pin_array_2)) + status = self.write_pins(bin_arr, self.pin_array_2) + sleep(0.05) + + except: + status = False + print('Exception!') + finally: + self.comm_mutex.release() + print('Written data') + + return status + + # function that writes the GPIO state + def write_pins(self, bit_array, pin_array): + + if len(bit_array) != len(pin_array): + print('Problem with bit array length!') + return False + + for ii in range(len(bit_array)): + GPIO.output(pin_array[ii], int(bit_array[ii])) + + + return True + + + + # function that reads the GPIO state + def read_pins(self, pin_array): + + bit_array = np.zeros((len(pin_array),),dtype=int) + + for ii in range(len(bit_array)): + bit_array[ii] = GPIO.input(pin_array[ii]) + + + return bit_array + + # also write data with threads to avoid that many write operations hang the system + def write_thread(self, reason, value): + t = threading.Thread(target=myDriver.write, args=(self, reason, value)) + t.start() + + + def get_vars(self, var_list): + + try: + self.var_mutex.acquire() + + ret_vals = [] + for var in var_list: + if var in dir(self): + ret_vals.append(getattr(self,var)) + else: + ret_vals.append('ERR') + + t_act = time.time() + elapsed = t_act - self.rback_ts + if (elapsed) > self.rback_interval*2: + print('Parameters not up-to-date. {:.01} secs since last update, thus {:.01} secs above interval'.format(elapsed, elapsed - self.rback_interval )) + finally: + self.var_mutex.release() + + + return ret_vals + + # retrieve all parameteres and store in class + def update_pars(self): + + rback_ok = True + try: + # get back all the GPIO values with GPIO.input() + self.comm_mutex.acquire() + + state_1 = self.read_pins(self.pin_array_1) + state_2 = self.read_pins(self.pin_array_2) + except: + rback_ok = False + finally: + self.comm_mutex.release() + + # store in self.readback if it went fine + if rback_ok: + + ts = time.time() + + try: + self.var_mutex.acquire() + + self.state_1 = state_1 + self.dec_1 = self.bin2dec(self.state_1, mult=self.mult_1) + + self.state_2 = state_2 + self.dec_2 = self.bin2dec(self.state_2, mult=self.mult_2) + + self.rback_ts = ts + + finally: + self.var_mutex.release() + + + +class readback_thread(): + """ Thread reading back the device state in the background + """ + + def __init__(self, driver, interval=1): + """ Constructor + :type interval: int + :param interval: Check interval, in seconds + """ + self.driver = driver + self.interval = interval + + self.thread = threading.Thread(target=self.run, args=()) + self.thread.daemon = True # Daemonize thread + self.thread.start() # Start the execution + + def run(self): + """ Method that runs forever """ + while True: + # Do something + print('Update parameters (GPIO)') + self.driver.update_pars() + + time.sleep(self.interval) + + +if __name__ == '__main__': + driver = myDriver() + + diff --git a/frontend/RPisock_thread_pts1/RPisock.py b/frontend/RPisock_thread_pts1/RPisock.py new file mode 100644 index 0000000..bce46d7 --- /dev/null +++ b/frontend/RPisock_thread_pts1/RPisock.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Feb 11 09:30:36 2021 + +@author: doll_a +""" +# sketch of socket server running on RPi to listen to commands +# main purpose: Parsing of commands sent by MIDAS + +import socket +import numpy as np +#import era_test +import era_test_thread +import time + + +class RPisock: + + + # initialization function + def __init__(self): + + + # command list + # it is specified as follows + # [command, argument type, number of arguments, execution function] + self.commands = [] + # Phase functions: ---> GPIO + self.commands.append(['PH1 ', float , 1, self.set_phase1]) + self.commands.append(['PH2 ', float , 1, self.set_phase2]) + self.commands.append(['PH1?', float , 0, self.get_phase1]) + self.commands.append(['PH2?', float , 0, self.get_phase2]) + + # synth functions + self.commands.append(['AMPL ', float , 1, self.set_ampl]) + self.commands.append(['FREQ ', float , 1, self.set_freq]) + self.commands.append(['OUTP ', int , 1, self.set_outp]) + self.commands.append(['AMPL?', float , 0, self.get_ampl]) + self.commands.append(['FREQ?', float , 0, self.get_freq]) + self.commands.append(['OUTP?', int , 0, self.get_outp]) +# self.commands.append(['OUTP?', int , 0, self.reply_1]) +# self.commands.append(['OUTPUT?', int , 0, self.get_outp]) + self.commands.append(['OUTPUT?', int , 0, self.reply_1]) + + self.commands.append(['STAT?', int , 0, self.get_stat]) + + + + # open the socket + HOST = 'lempi.psi.ch' # Server IP or Hostname + HOST = 'localhost' # Server IP or Hostname + HOST = 'uwavepi.psi.ch' # Server IP or Hostname + PORT = 5025 # Pick an open Port (1000+ recommended), must match the client sport + # make the connection ready + try: + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.s.bind((HOST, PORT)) + print('Socket created and bound') + except socket.error: + print('Problem setting up the socket') + + + self.s.listen(5) + print('Socket lsitening') + + # verbose: + # TRUE: send user-understandeable response + # FALSE: just send a short response about the status (for reporting back to MIDAS) + # idea: a python client for debugging will make live easier in verbose mode + # This sitll needs to be implemented + self.verbose = False + + # MIDAS specific: In non-verbose mode, it is a good idea to define the maxlen of the message. + # at Zaher: you need to hardcode this into your driver. + # I will then make sure that a response in non-verbose mode will not be longer than midas_bytelen + self.midas_bytelen = 1024 + + # initialize hardware + # phase setting + self.pha1 = 0 + self.pha2 = 0 + # TODO: HW command to set GPIO bits + # using the python library RPi.GPIO, i.e. + # import RPi.GPIO as GPIO + # requires: sudo apt-get -y install python3-rpi.gpio + + # uwave synth + self.era = era_test_thread.myDriver() + self.era_frq = 3.8 + self.era_amp = 0 + self.era_state = 0 + self.era.write('LOFreq', self.era_frq) + self.era.write('LOAmp', self.era_amp) + self.era.write('Power', self.era_state) + # TODO: HW commands to set the erasynth via USB-serial + # this is via the serial library, as already in use at XTreme + # dev = "/dev/ttyACM0" + # self.eras = serial.Serial(port=dev,baudrate=9600,timeout=1) + + + # this can be extended to add other hardware.. + # implemented and tested for signal averaging is the DSOX2014 oscilloscope + # --> we could use this to look at the High power monitor signals + # control of this one is via the usbtmc library and uses the instruments ascii commands + # instr = usbtmc.Instrument(vid, did) + # print(instr.ask('*IDN?')) + + # time stamps to time requests from midas + self.tstamp = time.time() + self.tstamp0 = 0 + self.n_calls = 0 + + # stuff to close the connection + def close(self): + self.s.close() # Close connections + + # class destructor: close connection + def __del__(self): + self.close() + + # server that processes data + # for the moment highly quick-and-dirty. needs to be put in a seperate thread that is started by an event + # also needs to be safe to receive more than one connection. + # This is all documented and can be done + def run(self): + + # listen to client + (self.client, addr) = self.s.accept() + + # awaiting for message + while True: + try: + data = self.client.recv(self.midas_bytelen).decode() + print('Reacting to: ' + data) + + # debug stuff: time it + self.n_calls += 1 + acttim = time.time() + # give it some offset to start the time measurement + call_offset = 30 + if self.n_calls == call_offset: + self.tstamp0 = acttim + if self.n_calls > call_offset: + print('time delay {:.02f}, avg {:.03f}'.format(acttim - self.tstamp, (acttim - self.tstamp0)/(self.n_calls-call_offset))) + self.tstamp = time.time() + + + # when the client terminates, a zero length packet is received + # --> make it ready for a repeated connection + if len(data) == 0: + self.client.close() + (self.client, addr) = self.s.accept() + self.n_calls = 0 # reset the number of calls (to remeasure timing) + continue + + + # if more than one command has been sent + data_l = data.split('\n') + for data in data_l: + + # parse command + for ii_c, cmd in enumerate(self.commands): + # simplistic for the moment + if data.startswith(cmd[0]): + # check arguments + # direct call for calls without argument + if cmd[2] == 0: + cmd[3]() + else: + # isolate the arguments + argstr = data[len(cmd[0]):] + # comma separate + argstr_split = argstr.split(',') + if len(argstr_split) != cmd[2]: + # The response below is obviously verbose mode + reply = 'Problem with arguments of command {}, expected {} arguments'.format(data, cmd[2]) + print(reply) + self.client.send(reply.encode()) + + # parsed arguments + args = np.zeros((cmd[2],1), dtype = cmd[1]) + for ii in range(len(args)): + args[ii] = argstr_split[ii] + + # here we go, forward the arguments + cmd[3](args) + + + except socket.error as e: + self.client.close() + print(e) + + + # _____________________________ + # functions related to commands + # _____________________________ + def set_phase1(self, args): + print('TODO: setting phase1 to {}'.format(args[0,0])) + self.pha1 = args[0,0] + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def set_phase2(self, args): + print('TODO: setting phase2 to {}'.format(args[0,0])) + self.pha2 = args[0,0] + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def get_phase1(self): + pha_str = '{}\n'.format(self.pha1) + self.client.send(pha_str.encode()) + + def get_phase2(self): + pha_str = '{}\n'.format(self.pha2) + self.client.send(pha_str.encode()) + + def set_ampl(self, args): + self.era_amp = args[0,0] + self.era.write_thread('LOAmp', self.era_amp) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def set_freq(self, args): + self.era_frq = args[0,0] + self.era.write_thread('LOFreq', self.era_frq) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def set_outp(self, args): + self.era_state = args[0,0] + self.era.write_thread('Power', self.era_state) + reply = '{}'.format(args[0,0]) +# self.client.send(reply.encode()) + + def get_ampl(self): + reply = self.era.get_vars(['amplitude'])[0] + self.era_amp = float(reply) + reply = reply + '\n' + self.client.send(reply.encode()) + + def get_freq(self): + reply = self.era.get_vars(['frequency'])[0] + self.era_frq = float(reply)*1e-9 + reply = '{:.3f}\n'.format(self.era_frq) + self.client.send(reply.encode()) + + + def get_outp(self): + reply = self.era.get_vars(['rfoutput'])[0] + self.era_state = int(reply) + reply = reply + '\n' + self.client.send(reply.encode()) + + + def get_stat(self): + reply = self.era.get_all() + reply = 'Printed\n' + self.client.send(reply.encode()) + + + def reply_1(self): + reply = '1\n' + self.client.send(reply.encode()) + + + +# the main program being run when runnig the RPisock.py script +if __name__ == '__main__': + sock = RPisock() + sock.run() + # it will never stop runnig at the momment... + sock.close() + + diff --git a/frontend/RPisock_thread_pts1/client_py3.py b/frontend/RPisock_thread_pts1/client_py3.py new file mode 100644 index 0000000..d696aae --- /dev/null +++ b/frontend/RPisock_thread_pts1/client_py3.py @@ -0,0 +1,65 @@ +import socket +from time import sleep + +HOST = 'lempi.psi.ch' # Enter IP or Hostname of your server +HOST = 'localhost' # Enter IP or Hostname of your server +PORT = 5025 # Pick an open Port (1000+ recommended), must match the server port +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +s.connect((HOST,PORT)) + +# Lets loop awaiting for your input +# while True: +# command = input('Enter your command: ') +# s.send(command.encode()) +# reply = s.recv(1024).decode() +# if reply == 'Terminate': +# break +# print(reply) + + + +command = u"Hello" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + +command = u"This is important" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + + +command = u":Phase1 0" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + +command = u":Phase2 90" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + +command = u":Phase1?" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + +command = u":Phase2?" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + +# and a wrong command, which will here give a long response (later that will be short or long, controlled by the verbose mode) +command = u":Phase1 0, 90" +s.send(command.encode()) +reply = s.recv(1024).decode() +print(reply) +sleep(0.1) + +s.close() diff --git a/frontend/RPisock_thread_pts1/era_test_thread.py b/frontend/RPisock_thread_pts1/era_test_thread.py new file mode 100644 index 0000000..37dd71a --- /dev/null +++ b/frontend/RPisock_thread_pts1/era_test_thread.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python +import numpy as np +import serial +import time +from time import sleep +import json +from os import path +import threading + + +class myDriver: + def __init__(self): + + + # mutexes to control threads + self.comm_mutex = threading.Lock() # this is to avoid that more than one thread talks to the era + self.var_mutex = threading.Lock() # this is to avoid that more than one thread accesses self.rback + + + dev = "/dev/ttyACM0" # todo: check for ttyACM, as it toggles between 0 and 1 + dev = "/dev/pts/1" # todo: check for ttyACM, as it toggles between 0 and 1 + + self.eras = serial.Serial(port=dev,baudrate=115200,timeout=1) +# self.eras.close() + sleep(0.1) + self.write('Power', 0) + sleep(0.1) + self.write('LOFreq', 5.0) + sleep(0.1) + self.write('LOMod', 0) + sleep(0.1) + self.write('LOAmp', 0.0) + sleep(2.0) + + print(self.eras.readall().decode()) + + + # check lock status + self.eras.write('>RD\r\n'.encode()) + try: + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + except: + pass + +# rset = False +# while (rback['lock_lmx1'] != '1') or (rback['lock_lmx2'] != '1'): +# print('re-setting PLL mode to achieve lock!') +# self.write('PNmode', 0) +# sleep(15.0) +# rback_r = self.eras.readall().decode() +# self.eras.write('>RD\r\n'.encode()) +# rback_r = self.eras.readall().decode() +# rback = json.loads(rback_r) +# rset = True +# +# if rset: +# print('... PLLs locked!') + + self.rback_interval = 5 # readback interval in seconds + self.rback_interval = 1 # readback interval in seconds + self.update_pars() + + # start update thread + self.updater = readback_thread(self,self.rback_interval) + + def write(self, reason, value): + status = True + try: + self.comm_mutex.acquire() + + # take proper actions + if reason == 'Power': + self.eras.write('>P0{}\r\n'.format(value).encode()) + sleep(0.05) + if reason == 'LOMod': + self.eras.write('>MS{}\r\n'.format(value).encode()) + sleep(0.05) + elif reason == 'LOFreq': + frq = int(value*1e9) + self.eras.write('>F{}\r\n'.format(frq).encode()) + sleep(0.05) + elif reason == 'LOAmp': + amp = float(value) + self.eras.write('>A{:.1f}\r\n'.format(amp).encode()) + sleep(0.05) + elif reason == 'PNmode': + self.eras.write('>P9{}\r\n'.format(int(value)).encode()) + sleep(0.05) + + except: + status = False + finally: + self.comm_mutex.release() + print('Written data') + + return status + + # also write data with threads to avoid that many write operations hang the system + def write_thread(self, reason, value): + t = threading.Thread(target=myDriver.write, args=(self, reason, value)) + t.start() + + def get_all(self): + + + rback_ok = True + try: + self.comm_mutex.acquire() + + + rback_r = self.eras.readall().decode() + + # get all values + self.eras.write('>RA\r\n'.encode()) + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + print(rback) + + + # get status + self.eras.write('>RD\r\n'.encode()) + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + print(rback) + + except: + rback_ok = False + finally: + self.comm_mutex.release() + + return rback_ok + + + + def get_vars(self, var_list): + + + try: + self.var_mutex.acquire() + + ret_vals = [] + for var in var_list: + if var in self.rback.keys(): + ret_vals.append(self.rback[var]) + else: + ret_vals.append('ERR') + + + + t_act = time.time() + elapsed = t_act - self.rback_ts + if (elapsed) > self.rback_interval*2: + print('Parameters not up-to-date. {:.01} secs since last update, thus {:.01} secs above interval'.format(elapsed, elapsed - self.rback_interval )) + + # in case this fails, just assign all to zero + except: + ret_vals = [None]*len(var_list) + for ii in range(len(ret_vals)): + ret_vals[ii] = '0' + + finally: + self.var_mutex.release() + + + return ret_vals + + # retrieve all parameteres and store in class + def update_pars(self): + + rback_ok = True + try: + self.comm_mutex.acquire() + + rback_r = self.eras.readall().decode() + self.eras.write('>RA\r\n'.encode()) + sleep(0.2) + rback_r = self.eras.readall().decode() + rback = json.loads(rback_r) + except: + rback_ok = False + finally: + self.comm_mutex.release() + + # store in self.readback if it went fine + if rback_ok: + + ts = time.time() + + try: + self.var_mutex.acquire() + + self.rback = rback + self.rback_ts = ts + finally: + self.var_mutex.release() + + + +class readback_thread(): + """ Thread reading back the device state in the background + """ + + def __init__(self, driver, interval=1): + """ Constructor + :type interval: int + :param interval: Check interval, in seconds + """ + self.driver = driver + self.interval = interval + + self.thread = threading.Thread(target=self.run, args=()) + self.thread.daemon = True # Daemonize thread + self.thread.start() # Start the execution + + def run(self): + """ Method that runs forever """ + while True: + # Do something + print('Update parameters') + self.driver.update_pars() + + time.sleep(self.interval) + + +if __name__ == '__main__': + driver = myDriver() + + diff --git a/frontend/RPisock_thread_pts1/server_py3.py b/frontend/RPisock_thread_pts1/server_py3.py new file mode 100644 index 0000000..23a1425 --- /dev/null +++ b/frontend/RPisock_thread_pts1/server_py3.py @@ -0,0 +1,44 @@ +import socket + +HOST = 'lempi.psi.ch' # Server IP or Hostname +HOST = 'localhost' # Server IP or Hostname +PORT = 5025 # Pick an open Port (1000+ recommended), must match the client sport +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +print('Socket created') + +#managing error exception +try: + s.bind((HOST, PORT)) +except socket.error: + print('Bind failed ') + +s.listen(5) +print('Socket awaiting messages') +(conn, addr) = s.accept() +print('Connected') + +# awaiting for message +while True: + data = conn.recv(1024) + print(data) + data = data.decode() + print('I sent a message back in response to: ' + data) + reply = '' + + + # process your message + if data == 'Hello': + reply = 'Hi, back!' + elif data == 'This is important': + reply = 'OK, I have done the important thing you have asked me!' + + #and so on and on until... + elif data == 'quit': + conn.send('Terminating'.encode()) + break + else: + reply = 'Unknown command' + + # Sending reply + conn.send(reply.encode()) +conn.close() # Close connections diff --git a/frontend/uWave.h b/frontend/uWave.h new file mode 100644 index 0000000..f774f64 --- /dev/null +++ b/frontend/uWave.h @@ -0,0 +1,23 @@ +/********************************************************************\ + + Name: uWave.h + Created by: Zaher Salman 05/03/2021 + + Contents: Device driver for the RPi uWave controller. + TCP/IP calls sent to the RPi. + +\********************************************************************/ + +/*---- device driver declaration -----------------------------------*/ +/*! + *

UWAVE device driver (DD) for reading. + * Handling the communication between the uWave and midas. + */ +INT uWave_in(INT cmd, ...); + +/*! + *

UWAVE device driver (DD) for setting values. + * Handling communication between the uWave and midas. + */ +INT uWave_out(INT cmd, ...); + diff --git a/frontend/uWave_scfe.cxx b/frontend/uWave_scfe.cxx new file mode 100644 index 0000000..63ef4d5 --- /dev/null +++ b/frontend/uWave_scfe.cxx @@ -0,0 +1,175 @@ +/********************************************************************\ + + Name: uWave_scfe.cxx + Created by: Zaher Salman + + Contents: Midas Slow control frontend for controlling the uWave + RPi. This is a dummy FE that sends TCP/IP calls + +\********************************************************************/ + +#include +#include +#include +#include + +#include "midas.h" +#include "mfe.h" + +#include "class/multi.h" +#include "bus/tcpip.h" +#include "uWave.h" + +//-- Globals ------------------------------------------------------- + +//! The frontend name (client name) as seen by other MIDAS clients +const char *frontend_name = "uWave SC"; +//! The frontend file name, don't change it +const char *frontend_file_name = __FILE__; + +//! frontend_loop is called periodically if this variable is TRUE +BOOL frontend_call_loop = TRUE; + +//! a frontend status page is displayed with this frequency in ms +INT display_period = 10000; + +//! maximum event size produced by this frontend +INT max_event_size = 10000; + +//! maximum event size for fragmented events (EQ_FRAGMENTED) +INT max_event_size_frag = 5*1024*1024; + +//! buffer size to hold events +INT event_buffer_size = 10*10000; + +//-- Equipment list ------------------------------------------------ + +/*! + *

+ */ +DEVICE_DRIVER UWAVE_driver[] = { + { "UWAVE_in", uWave_in, 5, tcpip, DF_INPUT }, + { "UWAVE_out", uWave_out, 5, tcpip, DF_OUTPUT }, + { "" } +}; + +/*! + * equipment_common_overwrite: + * + * - If that flag is TRUE, then the contents of the "equipment" structure is copied to + * the ODB on each start of the front-end. + * + * - If the flag is FALSE, then the ODB values are kept on the start of the front-end + */ +BOOL equipment_common_overwrite = FALSE; + +//! equipment structure for the mfe.c +EQUIPMENT equipment[] = { + + { "uWave", // equipment name + {195, 0, // event ID, trigger mask + "SYSTEM", // event buffer + EQ_SLOW, // equipment type + 0, // event source + "FIXED", // format + TRUE, // enabled + RO_RUNNING | + RO_TRANSITIONS, // read when running and on transitions + 30000, // read every 30 sec + 0, // stop run after this event limit + 0, // number of sub events + 1, // log history every event + "", "", "",}, + cd_multi_read, // readout routine + cd_multi, // class driver main routine + UWAVE_driver, // device driver list + NULL, // init string + }, + + { "" } +}; + + + +//-- Dummy routines ------------------------------------------------ + +INT poll_event(INT source, INT count, BOOL test) {return 1;}; +INT interrupt_configure(INT cmd, INT source, POINTER_T adr) {return 1;}; + +//-- Frontend Init ------------------------------------------------- +/*! + *

Called by the master frontend (mfe) at initializing stage. + * Here it is only a dummy. + */ +INT frontend_init() +{ + // de-register run-transition notifications + cm_deregister_transition(TR_START); + cm_deregister_transition(TR_STOP); + cm_deregister_transition(TR_PAUSE); + cm_deregister_transition(TR_RESUME); + + return CM_SUCCESS; +} + +//-- Frontend Exit ------------------------------------------------- +/*! + *

Called by the mfe at exiting stage. + * Here it is only a dummy. + */ +INT frontend_exit() +{ + return CM_SUCCESS; +} + +//-- Frontend Loop ------------------------------------------------- +/*! + *

Called by the mfe in the main loop. + * Here it is only a dummy. + */ +INT frontend_loop() +{ + return CM_SUCCESS; +} + +//-- Begin of Run -------------------------------------------------- +/*! + *

Called by the mfe at the begin of the run. + * Here it is only a dummy. + */ +INT begin_of_run(INT run_number, char *error) +{ + return CM_SUCCESS; +} + +//-- End of Run ---------------------------------------------------- +/*! + *

Called by the mfe at the end of the run. + * Here it is only a dummy. + */ +INT end_of_run(INT run_number, char *error) +{ + return CM_SUCCESS; +} + +//-- Pause Run ----------------------------------------------------- +/*! + *

Called by the mfe when the run is paused. + * Here it is only a dummy. + */ +INT pause_run(INT run_number, char *error) +{ + return CM_SUCCESS; +} + +//-- Resume Run ---------------------------------------------------- +/*! + *

Called by the mfe when the run is resumed. + * Here it is only a dummy. + */ +INT resume_run(INT run_number, char *error) +{ + return CM_SUCCESS; +} + +//------------------------------------------------------------------