File: apgHelper.cpp

package info (click to toggle)
libapogee3 3.2%2B20221221183454-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 9,284 kB
  • sloc: cpp: 26,737; sh: 8; makefile: 3
file content (422 lines) | stat: -rw-r--r-- 11,850 bytes parent folder | download | duplicates (2)
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
47
48
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
244
245
246
247
248
249
250
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*! 
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright(c) 2010 Apogee Instruments, Inc. 
* \brief namespace helper for the apg library 
* 
*/ 

#include "apgHelper.h" 
#include <sstream>
#include <fstream>
#include <algorithm>
#include <stdexcept>
#include <iomanip>
 #include <cmath> 
#include <stdio.h>
#include "ApgLogger.h" 
#include "helpers.h"
#include "config.h"
#include "indimacros.h"


//CROSS-PLATFORM SLEEP
#ifdef WIN_OS
    #include <windows.h> // needed for Sleep
#else
    #include <unistd.h>
    #define Sleep(x) usleep((x)*1000)
#endif 

#ifdef DEBUGGING_CAMERA
namespace
{
    int32_t NumDebugMsgTries = 0;
    const int32_t MAX_NUM_DEBUG_TRIES = 3;
}
#endif

using namespace std;

//////////////////////////// 
//      DEBUG       MSG 
void apgHelper::DebugMsg( const char *fmt, ... )
{
#ifdef DEBUGGING_CAMERA
    // from http://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf
    va_list ap;
    va_start( ap, fmt );
    apgHelper::LogDebugMsg( 1024, fmt, ap );
    va_end( ap );
#else
    INDI_UNUSED(fmt);
#endif
}

//----------------------------------------------
//  LOG      DEBUG      MSG
 void apgHelper::LogDebugMsg(const int size, const char *fmt, va_list ap)
 {
#ifdef DEBUGGING_CAMERA
     // from http://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf
    std::vector<char> buf(size);
    
    // TODO - detemerine if I need to save a copy of va_list
    // to use later, ie is vsnprintf destructive???
    char *cbufPtr = &buf[0];
    int needed = vsnprintf(cbufPtr, size, fmt, ap);

    //handle the vsnprintf  -1 return case on microsoft compilers
    if(needed < 0) 
    {
        if( NumDebugMsgTries < MAX_NUM_DEBUG_TRIES)
        {
            //double the buffer size and try again
            ++NumDebugMsgTries;
            apgHelper::LogDebugMsg( size*2, fmt, ap );
        }
        else
        {
             NumDebugMsgTries = 0;

            //bailing don't want inifitely recuring loop
            apgHelper::throwRuntimeException( __FILE__, 
                "in infinite loop trying to log debug message", __LINE__,
                Apg::ErrorType_Critical );
        }
    }

    //handle the case where the number of chars are actually returned
    //by vsnprintf
    if (needed > size ) 
    {
        buf.resize( needed+1 );
        needed = vsnprintf( &buf[0], needed, fmt, ap); 
    }

    //we made it - log this message
    NumDebugMsgTries = 0;
    std::string msg( &buf[0] );
    ApgLogger::Instance().Write(ApgLogger::LEVEL_DEBUG, "debug", msg);
#else
    INDI_UNUSED(size);
    INDI_UNUSED(fmt);
    INDI_UNUSED(ap);
#endif
 }

//----------------------------------------------
//  LOG      VERBOSE       MSG
 void apgHelper::LogVerboseMsg(const std::string & fileName, 
        const std::string & msg, const int32_t lineNum, const std::string & type)
 {
     if( ApgLogger::Instance().IsLevelVerbose() )
     {
        string msg2Log = mkMsg(fileName, msg, lineNum);
        ApgLogger::Instance().Write(ApgLogger::LEVEL_VERBOSE,type, msg2Log);
     }
 }

 //----------------------------------------------
 //  LOG      ERROR       MSG
  void apgHelper::LogErrorMsg(const std::string & fileName,
         const std::string & msg, const int32_t lineNum)
  {
	 string msg2Log = mkMsg(fileName, msg, lineNum);
	 ApgLogger::Instance().Write(ApgLogger::LEVEL_RELEASE,"error", msg2Log);
  }

 //----------------------------------------------
 //  LOG      WARNING       MSG
  void apgHelper::LogWarningMsg(const std::string & fileName,
         const std::string & msg, const int32_t lineNum)
  {
	 string msg2Log = mkMsg(fileName, msg, lineNum);
	 ApgLogger::Instance().Write(ApgLogger::LEVEL_RELEASE,"warn", msg2Log);
  }
//----------------------------------------------
//  MK      MSG
string apgHelper::mkMsg( const string & fileName, 
                       const string & errStr, 
                       const int32_t lineNum)
{
    stringstream ss;
    ss << "libapogee:" << fileName << "("  << lineNum << "):" << errStr;
    return ss.str();
}

//----------------------------------------------
//  MK      MSG
string apgHelper::mkMsg( const string & fileName, 
                       const string & errStr, 
                       const int32_t lineNum, 
                       const Apg::ErrorType errType )
{
    string base = apgHelper::mkMsg( fileName, errStr, lineNum );
    
    stringstream ss;
    ss << ":" << errType;
    base.append( ss.str() );

    return base;
}

//----------------------------------------------
//  THROW       RUNTIME         EXCEPTION
void apgHelper::throwRuntimeException( const std::string & fileName, 
        const std::string & errStr, 
        const int32_t lineNum,
        const Apg::ErrorType errType )
{
    string whatStr = mkMsg(fileName, errStr, lineNum, errType);

    try
    {
        //log all exceptions
        ApgLogger::Instance().Write(ApgLogger::LEVEL_RELEASE, "error", whatStr);
    }
    catch(LoggerError & logException )
    {
        //add the logging failure information to the what that is thrown
        std::string logErrMsg("\nLogging Exception: ");
        logErrMsg.append( logException.what() );
        whatStr.append( logErrMsg );
    }

    runtime_error except( whatStr );
    throw except;
}


//----------------------------------------------
//  APOGEE    SLEEP
void apgHelper::ApogeeSleep( uint32_t TimeInMs )
{
    Sleep( TimeInMs );
}

//----------------------------------------------
//  CONVERT      USHORT    2   APNLEDSTATE
Apg::LedState apgHelper::ConvertUShort2ApnLedState( const uint16_t value )
{
    Apg::LedState result = Apg::LedState_Expose;
    switch( value )
    {
        case 0:
            result = Apg::LedState_Expose;
        break;

        case 1:
            result = Apg::LedState_ImageActive;
        break;

        case 2:
            result = Apg::LedState_Flushing;
        break;
        
        case 3:
            result = Apg::LedState_ExtTriggerWaiting;
        break;

        case 4:
            result = Apg::LedState_ExtTriggerReceived;
        break;

        case 5:
            result = Apg::LedState_ExtShutterInput;
        break;

        case 6:
            result = Apg::LedState_ExtStartReadout;
        break;

        case 7:
            result = Apg::LedState_AtTemp;
        break;

        default:
         {
            std::stringstream msg;
            msg << "Undefine led state: " << value;
            apgHelper::throwRuntimeException(__FILE__, msg.str(), __LINE__,
                Apg::ErrorType_InvalidUsage );
        }
        break;
    }

    return result;
}

//----------------------------------------------
//  APOGEE    SLEEP
bool apgHelper::IsEqual(const double x, const double y)
 {
    //from http://www.parashift.com/c++-faq-lite/newbie.html
    const double epsilon = 0.000001;
    return std::abs(x - y) <= epsilon * std::abs(x);
    // see Knuth section 4.2.2 pages 217-218
 }

//----------------------------------------------
//      SIZET      2      UINT32
uint32_t apgHelper::SizeT2Uint32( const size_t value )
{
    const uint32_t MAX_VALUE = 4294967295;

    if( value > MAX_VALUE  )
    {
        std::stringstream msg;
        msg << "SizeT2Uint32 conversion failed size = " << value;
        apgHelper::throwRuntimeException(__FILE__, msg.str(), __LINE__,
            Apg::ErrorType_InvalidUsage );
    }

    return static_cast<uint32_t>( value );
}

//----------------------------------------------
//      SIZET      2      INT32
int32_t apgHelper::SizeT2Int32( const size_t value )
{
    const int32_t MAX_VALUE =  2147483647;

    if( value > MAX_VALUE  )
    {
        std::stringstream msg;
        msg << "SizeT2Int32 conversion failed size = " << value;
        apgHelper::throwRuntimeException(__FILE__, msg.str(), __LINE__,
            Apg::ErrorType_InvalidUsage );
    }

    return static_cast<int32_t>( value );
}
 
//----------------------------------------------
//      SIZET      2      UINT16
uint16_t apgHelper::SizeT2Uint16( size_t value )
{
    const uint16_t MAX_VALUE =  65535;

    if( value > MAX_VALUE  )
    {
        std::stringstream msg;
        msg << "SizeT2Uint16 conversion failed size = " << value;
        apgHelper::throwRuntimeException(__FILE__, msg.str(), __LINE__,
            Apg::ErrorType_InvalidUsage );
    }

    return static_cast<uint16_t>( value );
}

//----------------------------------------------
//      SIZET      2      UINT8
uint8_t apgHelper::SizeT2Uint8( const size_t value )
{
    const uint8_t MAX_VALUE =  255;

    if( value > MAX_VALUE  )
    {
        std::stringstream msg;
        msg << "SizeT2Uint8 conversion failed size = " << value;
        apgHelper::throwRuntimeException(__FILE__, msg.str(), __LINE__,
            Apg::ErrorType_InvalidUsage );
    }

    return static_cast<uint8_t>( value );
}

//----------------------------------------------
//      OS   INT      2      INT32
int32_t apgHelper::OsInt2Int32( const int value )
{
    const int32_t MAX_VALUE =  2147483647;

    if( value > MAX_VALUE  )
    {
        std::stringstream msg;
        msg << "OsInt2Int32 conversion failed size = " << value;
        apgHelper::throwRuntimeException(__FILE__, msg.str(), __LINE__,
            Apg::ErrorType_InvalidUsage );
    }

    return static_cast<int32_t>( value );
}

//----------------------------------------------
//  GET    CFG     FILENAME
std::string apgHelper::GetCfgFileName()
{
    return std::string ( "apnmatrix.txt" );
}

//----------------------------------------------
//  GET    CAM        CFG    PATH
std::string apgHelper::GetCamCfgDir()
{
    std::string result = help::FixPath( apgHelper::GetCfgDir() );
    result.append( "camera/" );
    return result;

}
//CROSS-PLATFORM CFG DIR
#ifdef WIN32
#include <ShlObj.h>
#include <atlstr.h>
//----------------------------------------------
//  GET    CFG         DIR
std::string apgHelper::GetCfgDir()
{
    // http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx
    // MS has marked the SHGetFolderPath function depreciated, but there is 
    // no other option for XP.  Decide to go with the simpliest function here, instead doing
    // delayed dll load and such to get different behavoir for different Windoze OS's
    // need to switch this to SHGetKnownFolderPath when we drop windows XP support
    // or the function is removed from shell32.dll, which ever happens first....
    TCHAR szPath[MAX_PATH];
    if( FAILED( SHGetFolderPath(  nullptr, 
                        CSIDL_COMMON_APPDATA,
                        nullptr, 
                        0,
                        szPath ) ) )
    {
        apgHelper::throwRuntimeException(__FILE__, 
        "Failed fetching the configuration file directory", 
        __LINE__,
        Apg::ErrorType_Configuration );
    }

    USES_CONVERSION;
    std::string path;
    path.append( help::FixPath( T2A(szPath) ) );
    path.append( "Apogee/");
    return path;
}
#else

// SYSCONFDIR set by autotools on configuraiton
const char * sysconfdir = APOGEE_CONF_DIR;

//----------------------------------------------
//  GET    CFG         DIR
std::string apgHelper::GetCfgDir()
{
    std::string path;

    //On OS X, Prefer embedded App location if it exists
#if defined(__APPLE__)
	std::string driverSupportPath;
	if (getenv("INDIPREFIX") != nullptr)
		driverSupportPath = std::string(getenv("INDIPREFIX")).append("/Contents/Resources");
	else
		driverSupportPath = "/usr/local/lib/indi";
	path = help::FixPath( driverSupportPath );
#else
	path = help::FixPath( sysconfdir );
#endif
    path.append( "Apogee/" );
    return path;
}

#endif