sample code - “Request Operation”

usage:
   license
To exit, please enter 'q'.

This sample code is included in SimpleCli.

  1// RequestOperation sample
  2#include <chrono>
  3#include <cinttypes>
  4#include <cstdint>
  5#include <cstdlib>
  6#include <fstream>
  7#include <future>
  8#include <iostream>
  9#include <mutex>
 10#include <sstream>
 11#include <stdexcept>
 12#include <string>
 13#include <thread>
 14#include <vector>
 15
 16#if !defined(__APPLE__)
 17  #if defined(USE_EXPERIMENTAL_FS) // for jetson
 18    #include <experimental/filesystem>
 19    namespace fs = std::experimental::filesystem;
 20  #else
 21    #include <filesystem>
 22    namespace fs = std::filesystem;
 23  #endif
 24#endif
 25
 26#if defined(__APPLE__) || defined(__linux__)
 27  #include <unistd.h>
 28#endif
 29
 30// macro for multibyte character
 31#if defined(_WIN32) || defined(_WIN64)
 32  using CrString = std::wstring;
 33  #define CRSTR(s) L ## s
 34  #define CrCout std::wcout
 35#else
 36  using CrString = std::string;
 37  #define CRSTR(s) s
 38  #define CrCout std::cout
 39#endif
 40
 41
 42#include "CrDeviceProperty.h"
 43#include "CameraRemote_SDK.h"
 44#include "IDeviceCallback.h"
 45#include "CrDebugString.h"   // use CrDebugString.cpp
 46
 47#define PrintError(msg, err) { fprintf(stderr, "Error in %s(%d):" msg ",%s\n", __FUNCTION__, __LINE__, (err ? CrErrorString(err).c_str():"")); }
 48#define GotoError(msg, err) { PrintError(msg, err); goto Error; }
 49
 50bool  m_connected = false;
 51CrString m_modelId;
 52int64_t  m_device_handle = 0;
 53
 54std::mutex m_eventPromiseMutex;
 55std::promise<void>* m_eventPromise = nullptr;
 56void setEventPromise(std::promise<void>* dp)
 57{
 58    std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
 59    m_eventPromise = dp;
 60}
 61
 62class DeviceCallback : public SCRSDK::IDeviceCallback
 63{
 64public:
 65    DeviceCallback() {};
 66    ~DeviceCallback() {};
 67
 68    void OnConnected(SCRSDK::DeviceConnectionVersioin version)
 69    {
 70        CrCout << "Connected to " << m_modelId << "\n";
 71        m_connected = true;
 72        std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
 73        if(m_eventPromise) {
 74            m_eventPromise->set_value();
 75            m_eventPromise = nullptr;
 76        }
 77    }
 78
 79    void OnError(CrInt32u error)
 80    {
 81        printf("Connection error:%s\n", CrErrorString(error).c_str());
 82        std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
 83        if(m_eventPromise) {
 84            m_eventPromise->set_exception(std::make_exception_ptr(std::runtime_error("error")));
 85            m_eventPromise = nullptr;
 86        }
 87    }
 88
 89    void OnDisconnected(CrInt32u error)
 90    {
 91        CrCout << "Disconnected from " << m_modelId << "\n";
 92        m_connected = false;
 93        std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
 94        if(m_eventPromise) {
 95            m_eventPromise->set_value();
 96            m_eventPromise = nullptr;
 97        }
 98    }
 99
100    void OnCompleteDownload(CrChar* filename, CrInt32u type )
101    {
102        CrCout << "OnCompleteDownload:" << filename << "\n";
103    }
104
105    void OnNotifyContentsTransfer(CrInt32u notify, SCRSDK::CrContentHandle contentHandle, CrChar* filename)
106    {
107        std::cout << "OnNotifyContentsTransfer.\n";
108    }
109
110    void OnWarning(CrInt32u warning)
111    {
112        if (warning == SCRSDK::CrWarning_Connect_Reconnecting) {
113            CrCout << "Reconnecting to " << m_modelId << "\n";
114            return;
115        }
116        std::cout << "OnWarning:" << CrErrorString(warning) << "\n";
117    }
118
119    void OnWarningExt(CrInt32u warning, CrInt32 param1, CrInt32 param2, CrInt32 param3)
120    {
121        std::cout << "OnWarningExt:" << CrWarningExtString(warning, param1, param2, param3).c_str() << "\n";
122    }
123
124    void OnLvPropertyChanged() {}
125    void OnLvPropertyChangedCodes(CrInt32u num, CrInt32u* codes) {}
126    void OnPropertyChanged() {}
127    void OnPropertyChangedCodes(CrInt32u num, CrInt32u* codes)
128    {
129        std::cout << "OnPropertyChangedCodes:\n";
130    }
131
132    void OnCompleteOperation(CrInt32u code, SCRSDK::CrOperationResultData* resultData)
133    {
134        std::string ope_name = CrOperationCodeString((SCRSDK::CrOperationCode)code);
135        printf("OnCompleteOperation:%s\n", ope_name.c_str());
136
137        switch(code) {
138            case SCRSDK::CrOperationCode_GetLicenseInfoList: {
139                SCRSDK::CrLicenseInfoList* obj = (SCRSDK::CrLicenseInfoList*)resultData;
140                SCRSDK::CrLicenseInfo* info = (SCRSDK::CrLicenseInfo*)obj->GetLicenseInfo();
141                for(uint32_t i = 0; i < obj->GetListNum(); ++i) {
142                    uint64_t data = 0;
143                    switch(info[i].GetLicenseIdLength()) {
144                        case 4:
145                        {
146                            const CrInt32u* licenseId32 = (CrInt32u*)info[i].GetLicenseId();
147                            data = (uint64_t)*licenseId32;
148                            break;
149                        }
150                        case 8:
151                        {
152                            const CrInt64u* licenseId64 = (CrInt64u*)info[i].GetLicenseId();
153                            data = (uint64_t)*licenseId64;
154                            break;
155                        }
156                        default:
157                        {
158                            PrintError("", 0);
159                        }
160                    }
161                    uint32_t hours = info[i].GetRemainingHours();
162                    if(hours == SCRSDK::CrLicenseInfo::CrLicenseRemainingHours_Infinity) {
163                        printf("  id=%" PRId64 ",infinity\n", data);
164                    } else {
165                        printf("  id=%" PRId64 ",%dh\n", data, hours);
166                    }
167                } // loop
168                SCRSDK::ReleaseOperationResultObject(m_device_handle, resultData);
169                break;
170            }
171        }
172    }
173};
174
175CrString _getModelId(const SCRSDK::ICrCameraObjectInfo* objInfo)
176{
177    CrString id;
178    if (CrString(objInfo->GetConnectionTypeName()) == CRSTR("IP")) {
179        id = CrString(objInfo->GetMACAddressChar());
180    } else {
181        id = CrString((CrChar*)objInfo->GetId());
182    }
183    return CrString(objInfo->GetModel()).append(CRSTR(" (")).append(id).append(CRSTR(")"));
184}
185
186SCRSDK::CrError _getIdPassword(SCRSDK::ICrCameraObjectInfo* objInfo, std::string& fingerprint, std::string& userId, std::string& userPassword)
187{
188    char fpBuff[128] = {0};
189    CrInt32u fpLen = 0;
190    SCRSDK::CrError err = SCRSDK::GetFingerprint(objInfo, fpBuff, &fpLen);
191    if(err) GotoError("", err);
192    fingerprint = std::string(fpBuff, fpLen);
193
194    std::cout << "fingerprint: " << fingerprint.c_str() << "\n";
195    std::cout << "id:";       std::getline(std::cin, userId);
196    std::cout << "password:"; std::getline(std::cin, userPassword);
197    return 0;
198Error:
199    return err;
200}
201
202std::vector<std::string> _split(std::string inputLine, char delimiter)
203{
204    std::vector<std::string> strArray;
205    if (inputLine.empty()) return strArray;
206
207    std::string tmp;
208    std::stringstream ss{inputLine};
209    while (getline(ss, tmp, delimiter)) {
210        strArray.push_back(tmp);
211    }
212    return strArray;
213}
214
215int main(void)
216{
217    int result = -1;
218    SCRSDK::CrError err = SCRSDK::CrError_None;
219    SCRSDK::ICrEnumCameraObjectInfo* enumCameraObjectInfo = nullptr;
220    SCRSDK::ICrCameraObjectInfo* objInfo = nullptr;
221    DeviceCallback deviceCallback;
222
223  #if defined(__APPLE__)
224    #define MAC_MAX_PATH 255
225    char pathBuf[MAC_MAX_PATH] = {0};
226    if(NULL == getcwd(pathBuf, sizeof(pathBuf) - 1)) return 1;
227    CrString path = pathBuf;
228  #else
229    CrString path = fs::current_path().native();
230  #endif
231
232    bool boolRet = SCRSDK::Init();
233    if(!boolRet) GotoError("", 0);
234
235    // enumeration
236    {
237        uint32_t count = 0;
238        uint32_t index = 1;
239
240        err = SCRSDK::EnumCameraObjects(&enumCameraObjectInfo, 3/*timeInSec*/);
241        if(err || !enumCameraObjectInfo) GotoError("no camera", err);
242
243        count = enumCameraObjectInfo->GetCount();
244        if(count >= 2) {
245            for (uint32_t i = 0; i < count; ++i) {
246                auto* info = enumCameraObjectInfo->GetCameraObjectInfo(i);
247                CrCout << '[' << i + 1 << "] " << _getModelId(info) << "\n";
248            }
249
250            std::string inputLine;
251            std::cout << "select camera:"; std::getline(std::cin, inputLine);
252            try { index = stoi(inputLine); } catch(const std::exception&) { GotoError("", 0); }
253            if(index < 1 || index > count) GotoError("", 0);
254        }
255        objInfo = (SCRSDK::ICrCameraObjectInfo*)enumCameraObjectInfo->GetCameraObjectInfo(index - 1);
256        m_modelId = _getModelId(objInfo);
257    }
258
259    // connect
260    {
261        std::string  fingerprint = "";
262        std::string  userId = "";
263        std::string  userPassword = "";
264        std::promise<void> eventPromise;
265        std::future<void> eventFuture = eventPromise.get_future();
266
267        if (objInfo->GetSSHsupport() == SCRSDK::CrSSHsupport_ON) {
268            err = _getIdPassword(objInfo, fingerprint, userId, userPassword); if(err) goto Error;
269        }
270
271        setEventPromise(&eventPromise);
272        err = SCRSDK::Connect(objInfo, &deviceCallback, &m_device_handle,
273            SCRSDK::CrSdkControlMode_Remote,
274            SCRSDK::CrReconnecting_ON,
275            userId.c_str(), userPassword.c_str(), fingerprint.c_str(), (uint32_t)fingerprint.size());
276        if(err) GotoError("", err);
277
278    //  std::future_status status = eventFuture.wait_for(std::chrono::milliseconds(3000));
279    //  if(status != std::future_status::ready) GotoError("timeout",0);
280        try{
281            eventFuture.get();
282        } catch(const std::exception&) GotoError("", 0);
283    }
284
285    // set work directory
286    {
287        CrCout << "path=" << path.data() << "\n";
288        err = SCRSDK::SetSaveInfo(m_device_handle, const_cast<CrChar*>(path.data()), const_cast<CrChar*>(CRSTR("DSC")), -1/*startNo*/);
289        if(err) GotoError("", err);
290    }
291
292    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
293
294    std::cout << "usage:\n";
295    std::cout << "   license\n";
296    std::cout << "To exit, please enter 'q'.\n";
297
298    while(1) {
299        std::string inputLine;
300        std::getline(std::cin, inputLine);
301        std::vector<std::string> args = _split(inputLine, ' ');
302
303        if(args.size() == 0) {
304
305        } else if(args[0] == "license") {
306            err = RequestOperation(m_device_handle, SCRSDK::CrOperationCode_GetLicenseInfoList, 0,0,0,0,0, nullptr, 0);
307            if(err) GotoError("", err);
308        } else if(args[0] == "q" || args[0] == "Q") {
309            break;
310        } else {
311            std::cout << "unknown command\n";
312        }
313    }
314
315    result = 0;
316Error:
317    if(enumCameraObjectInfo) enumCameraObjectInfo->Release();
318
319    if(m_connected) {
320        std::promise<void> eventPromise;
321        std::future<void> eventFuture = eventPromise.get_future();
322        setEventPromise(&eventPromise);
323        SCRSDK::Disconnect(m_device_handle);
324        eventFuture.wait_for(std::chrono::milliseconds(3000));
325    }
326    if(m_device_handle) SCRSDK::ReleaseDevice(m_device_handle);
327    SCRSDK::Release();
328
329    return result;
330}