SAThread.cpp 8.2 KB
Newer Older
Jean-Luc Pons's avatar
Jean-Luc Pons committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
//+=============================================================================
//
// file :         SAThread.cpp
//
// description :  This class is used for reading SAStream
//
// project :      LiberaSparkSRBPM TANGO Device Server
//
// copyleft :     European Synchrotron Radiation Facility
//                BP 220, Grenoble 38043
//                FRANCE
//
//-=============================================================================
namespace LiberaSparkSRBPM_ns
{
class SAThread;
}

#include <SAThread.h>
#include "PosCalculation.h"
#include "LiberaSparkSRBPM.h"

#define SQUARE(x) ((x)*(x))

namespace LiberaSparkSRBPM_ns
{

// ----------------------------------------------------------------------------------------
// Constructor
// ----------------------------------------------------------------------------------------
SAThread::SAThread(LiberaSparkSRBPM *libera, PosCalculation *pc, omni_mutex &m):
        Tango::LogAdapter(libera), mutex(m), PC(pc), ds(libera)
{
  INFO_STREAM << "SAThread: Starting SA Thread." << endl;

  m_stream = std::dynamic_pointer_cast<RStream>(ds->saSignal);

  historyLength = 1800;
  average = false;
  avgLength  = 20;
  statLength = 0;
  currentPos.va = NAN;
  currentPos.vb = NAN;
  currentPos.vc = NAN;
  currentPos.vd = NAN;
  currentPos.sum = NAN;
47 48
  currentPos.h = NAN;
  currentPos.v = NAN;
Jean-Luc Pons's avatar
Jean-Luc Pons committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  currentPos.q = NAN;
  HStdDev = NAN;
  VStdDev = NAN;
  threadStatus = "SAThread: acquiring";
  start_undetached();

}

// ----------------------------------------------------------------------------------------
// Main loop
// ----------------------------------------------------------------------------------------
void *SAThread::run_undetached(void *arg) {

  string errorStr;

  exitThread = false;
  isConnected = false;

  cout << "SAThread: entering." << endl;

  while(!exitThread) {

    isConnected = OpenStream();
    if( isConnected ) {

      // Read data
      try {

        isig::SuccessCode_e res = m_streamClient->Read(*m_buf);
        if (res != isig::eSuccess) {
          cerr << "SAThread: Failed to read stream, Error:" << res << endl;
          mutex.lock();
          threadStatus = "Failed to read stream, Error code:" + std::to_string(res);
          mutex.unlock();
          m_streamClient->Close();
          std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        } else {

          // Two more samples
          // Reduce from 40Hz to 20Hz

          BP p;
          PC->ComputePosition(*m_buf, p);

          // Uupdate buffers and values
          mutex.lock();

          saValues.push_back(p);
          while ((int) saValues.size() > historyLength)
            saValues.erase(saValues.begin());

          currentPos = p;

          computeAveraging();
          computeStats();

          mutex.unlock();


        }

      } catch (istd::Exception &e) {
        mutex.lock();
        threadStatus = "Failed to read stream, Error :" + string(e.what());
        mutex.unlock();
        cerr << "SAThread: Failed to read stream, Error:" << e.what() << endl;
        m_streamClient->Close();
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      }

    } else {

      // Connection failure
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    }

  }

  cout << "SAThread: disconnecting." << endl;

  if (m_streamClient && m_streamClient->IsOpen())
    m_streamClient->Close();

  cout << "SAThread: exiting." << endl;

  return NULL;

}

// ----------------------------------------------------------------------------------------

bool SAThread::OpenStream() {

  if (m_streamClient && m_streamClient->IsOpen()) {
    // Already connected
    return true;
  }

  m_streamClient = std::make_shared<StreamClient>(m_stream.get(), "stream_client");
  m_buf =  std::make_shared<Int32Buffer>(m_streamClient->CreateBuffer(2));
  isig::SuccessCode_e res = m_streamClient->Open();
  if (res != isig::eSuccess) {
    mutex.lock();
    threadStatus = "Failed to read stream, Error :" + std::to_string(res);
    mutex.unlock();
    cerr << "SAThread::Failed to open SA stream" << endl;
    return false;
  }

  return true;

}

// ----------------------------------------------------------------------------------------

void SAThread::computeAveraging() {

  if(average) {

    int hSize = (int)saValues.size();
    int start = hSize - avgLength;
    int length = avgLength;
    if(start<0)
      length += start;

    double sumx = 0;
    double sumz = 0;
    for(int i=0;i<length;i++) {
178 179
      sumx += saValues[hSize-(i+1)].h;
      sumz += saValues[hSize-(i+1)].v;
Jean-Luc Pons's avatar
Jean-Luc Pons committed
180
    }
181 182
    currentPos.h = sumx / (double)length;
    currentPos.v = sumz / (double)length;
Jean-Luc Pons's avatar
Jean-Luc Pons committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  }

}

void SAThread::computeStats() {

  if(statLength>0) {

    int hSize = (int)saValues.size();
    int start = hSize - statLength;
    int length = statLength;
    if(start<0)
      length += start;

    double sumx = 0;
    double sumz = 0;
    double sumx2 = 0;
    double sumz2 = 0;
    for(int i=0;i<length;i++) {
203 204 205 206
      sumx += saValues[hSize-(i+1)].h;
      sumz += saValues[hSize-(i+1)].v;
      sumx2 += SQUARE(saValues[hSize-(i+1)].h);
      sumz2 += SQUARE(saValues[hSize-(i+1)].v);
Jean-Luc Pons's avatar
Jean-Luc Pons committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    }

    double avgx = sumx / (double)length;
    double avgz = sumz / (double)length;
    double avgx2 = sumx2 / (double)length;
    double avgz2 = sumz2 / (double)length;

    HStdDev = sqrt( avgx2 - SQUARE(avgx) );
    VStdDev = sqrt( avgz2 - SQUARE(avgz) );

  } else {

    HStdDev = NAN;
    VStdDev = NAN;

  }

}

// ----------------------------------------------------------------------------------------

void SAThread::wakeup() {

}

// ----------------------------------------------------------------------------------------
// Scalar values
// ----------------------------------------------------------------------------------------
#define GET_VAL(v)        \
omni_mutex_lock l(mutex); \
if(!isConnected)          \
  return NAN;             \
else                      \
  return v;

double SAThread::GetX() {

244
  GET_VAL(currentPos.h);
Jean-Luc Pons's avatar
Jean-Luc Pons committed
245 246 247 248 249

}

double SAThread::GetZ() {

250
  GET_VAL(currentPos.v);
Jean-Luc Pons's avatar
Jean-Luc Pons committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

}

double SAThread::GetQ() {

  GET_VAL(currentPos.q);

}

double SAThread::GetVa() {

  GET_VAL(currentPos.va);

}

double SAThread::GetVb() {

  GET_VAL(currentPos.vb);

}

double SAThread::GetVc() {

  GET_VAL(currentPos.vc);

}

double SAThread::GetVd() {

  GET_VAL(currentPos.vd);

}

double SAThread::GetSum() {

  GET_VAL(currentPos.sum);

}

double SAThread::GetXStdDev() {

  GET_VAL(HStdDev);

}

double SAThread::GetZStdDev() {

  GET_VAL(VStdDev);

}

// ----------------------------------------------------------------------------------------
// Config values
// ----------------------------------------------------------------------------------------

void SAThread::setHistoryLength(int length) {

  omni_mutex_lock l(mutex);
  historyLength = length;

}

int  SAThread::getHistoryLength() {

  return historyLength;

}

void SAThread::setStatLength(int length) {
  omni_mutex_lock l(mutex);
  statLength = length;
}

int SAThread::getStatLength() {
  return statLength;
}

void SAThread::setAveraging(bool avg) {

  average = avg;

}

bool SAThread::isAveraging() {

  return average;

}

void SAThread::setAvgLength(int length) {

  omni_mutex_lock l(mutex);
  avgLength = length;

}

int SAThread::getAvgLength() {

  return avgLength;

}

// ----------------------------------------------------------------------------------------
// History values
// ----------------------------------------------------------------------------------------

#define GET_HIST(field)                   \
  omni_mutex_lock l(mutex);               \
  for(int i=0;i<(int)saValues.size();i++) \
    hist[i]=saValues[i].field;            \
  *length = saValues.size();

void SAThread::getVaHistory(double *hist,int *length) {
  GET_HIST(va);
}

void SAThread::getVbHistory(double *hist,int *length) {
  GET_HIST(vb);
}

void SAThread::getVcHistory(double *hist,int *length) {
  GET_HIST(vc);
}

void SAThread::getVdHistory(double *hist,int *length) {
  GET_HIST(vd);
}

void SAThread::getSumHistory(double *hist,int *length) {
  GET_HIST(sum);
}

void SAThread::getXHistory(double *hist,int *length) {
384
  GET_HIST(h);
Jean-Luc Pons's avatar
Jean-Luc Pons committed
385 386 387
}

void SAThread::getZHistory(double *hist,int *length) {
388
  GET_HIST(v);
Jean-Luc Pons's avatar
Jean-Luc Pons committed
389 390 391 392 393 394 395
}

void SAThread::getQHistory(double *hist,int *length) {
  GET_HIST(q);
}

} // namespace LiberaBrilliance_ns