sample code - “upload CustomGridLine”

usage:
   set <1~4> <filename>    - set custom grid line
To exit, please enter 'q'.

This sample code is included in SimpleCli.

  1// "custom grid line" sample
  2#include <chrono>
  3#include <codecvt>
  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  #define DELIMITER CRSTR("\\")
 36  #define Utf8ToCr(a) wstring_convert.from_bytes(a)
 37  static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> wstring_convert;
 38#else
 39  using CrString = std::string;
 40  #define CRSTR(s) s
 41  #define CrCout std::cout
 42  #define DELIMITER CRSTR("/")
 43  #define Utf8ToCr(a) (a)
 44#endif
 45
 46#include "CrDeviceProperty.h"
 47#include "CameraRemote_SDK.h"
 48#include "IDeviceCallback.h"
 49#include "CrDebugString.h"   // use CrDebugString.cpp
 50
 51#define PrintError(msg, err) { fprintf(stderr, "Error in %s(%d):" msg ",%s\n", __FUNCTION__, __LINE__, (err ? CrErrorString(err).c_str():"")); }
 52#define GotoError(msg, err) { PrintError(msg, err); goto Error; }
 53
 54bool  m_connected = false;
 55CrString m_modelId;
 56
 57std::mutex m_eventPromiseMutex;
 58std::promise<void>* m_eventPromise = nullptr;
 59void setEventPromise(std::promise<void>* dp)
 60{
 61    std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
 62    m_eventPromise = dp;
 63}
 64
 65SCRSDK::CrError _getDeviceProperty(int64_t device_handle, uint32_t code, SCRSDK::CrDeviceProperty* devProp)
 66{
 67    std::int32_t nprop = 0;
 68    SCRSDK::CrDeviceProperty* prop_list = nullptr;
 69    SCRSDK::CrError err = SCRSDK::GetSelectDeviceProperties(device_handle, 1, &code, &prop_list, &nprop);
 70    if(err) GotoError("", err);
 71    if(prop_list && nprop >= 1) {
 72        *devProp = prop_list[0];
 73    }
 74Error:
 75    if(prop_list) SCRSDK::ReleaseDeviceProperties(device_handle, prop_list);
 76    return err;
 77}
 78
 79class DeviceCallback : public SCRSDK::IDeviceCallback
 80{
 81public:
 82    DeviceCallback() {};
 83    ~DeviceCallback() {};
 84
 85    void OnConnected(SCRSDK::DeviceConnectionVersioin version)
 86    {
 87        CrCout << "Connected to " << m_modelId << "\n";
 88        m_connected = true;
 89        std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
 90        if(m_eventPromise) {
 91            m_eventPromise->set_value();
 92            m_eventPromise = nullptr;
 93        }
 94    }
 95
 96    void OnError(CrInt32u error)
 97    {
 98        printf("Connection error:%s\n", CrErrorString(error).c_str());
 99        std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
100        if(m_eventPromise) {
101            m_eventPromise->set_exception(std::make_exception_ptr(std::runtime_error("error")));
102            m_eventPromise = nullptr;
103        }
104    }
105
106    void OnDisconnected(CrInt32u error)
107    {
108        CrCout << "Disconnected from " << m_modelId << "\n";
109        m_connected = false;
110        std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
111        if(m_eventPromise) {
112            m_eventPromise->set_value();
113            m_eventPromise = nullptr;
114        }
115    }
116
117    void OnCompleteDownload(CrChar* filename, CrInt32u type )
118    {
119        CrCout << "OnCompleteDownload:" << filename << "\n";
120    }
121
122    void OnNotifyContentsTransfer(CrInt32u notify, SCRSDK::CrContentHandle contentHandle, CrChar* filename)
123    {
124        std::cout << "OnNotifyContentsTransfer.\n";
125    }
126
127    void OnWarning(CrInt32u warning)
128    {
129        if (warning == SCRSDK::CrWarning_Connect_Reconnecting) {
130            CrCout << "Reconnecting to " << m_modelId << "\n";
131            return;
132        }
133    }
134
135    void OnWarningExt(CrInt32u warning, CrInt32 param1, CrInt32 param2, CrInt32 param3)
136    {
137        std::cout << "OnWarningExt:" << CrWarningExtString(warning, param1, param2, param3).c_str() << "\n";
138        if(warning == SCRSDK::CrWarningExt_UploadCustomGridLineFile) {
139            std::lock_guard<std::mutex> lock(m_eventPromiseMutex);
140            switch((uint32_t)param1) {
141            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_OK:
142                if(m_eventPromise) {
143                    m_eventPromise->set_value();
144                    m_eventPromise = nullptr;
145                }
146                break;
147            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_Invalid:
148            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_StatusError:
149            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_InvalidFileName:
150            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_MediaError:
151            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_ReadError:
152            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_OverFileSize:
153            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_OverImageSize:
154            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_DecodeError:
155            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_InvalidParameter:
156            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_File_CantOpen:
157            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_File_CantRead:
158            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_DeviceBusy:
159            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_FeatureVersionInvalidValue:
160            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_TemporaryStorageFull:
161            case SCRSDK::CrWarningExtParam_UploadCustomGridLineFile_CameraStatusError:
162            default:
163                if(m_eventPromise) {
164                    m_eventPromise->set_exception(std::make_exception_ptr(std::runtime_error("error")));
165                    m_eventPromise = nullptr;
166                }
167                break;
168            }
169        }
170    }
171
172    void OnLvPropertyChanged() {}
173    void OnLvPropertyChangedCodes(CrInt32u num, CrInt32u* codes) {}
174    void OnPropertyChanged() {}
175    void OnPropertyChangedCodes(CrInt32u num, CrInt32u* codes)
176    {
177        //std::cout << "OnPropertyChangedCodes:\n";
178    }
179};
180
181CrString _getModelId(const SCRSDK::ICrCameraObjectInfo* objInfo)
182{
183    CrString id;
184    if (CrString(objInfo->GetConnectionTypeName()) == CRSTR("IP")) {
185        id = CrString(objInfo->GetMACAddressChar());
186    } else {
187        id = CrString((CrChar*)objInfo->GetId());
188    }
189    return CrString(objInfo->GetModel()).append(CRSTR(" (")).append(id).append(CRSTR(")"));
190}
191
192SCRSDK::CrError _getIdPassword(SCRSDK::ICrCameraObjectInfo* objInfo, std::string& fingerprint, std::string& userId, std::string& userPassword)
193{
194    char fpBuff[128] = {0};
195    CrInt32u fpLen = 0;
196    SCRSDK::CrError err = SCRSDK::GetFingerprint(objInfo, fpBuff, &fpLen);
197    if(err) GotoError("", err);
198    fingerprint = std::string(fpBuff, fpLen);
199
200    std::cout << "fingerprint: " << fingerprint.c_str() << "\n";
201    std::cout << "id:";       std::getline(std::cin, userId);
202    std::cout << "password:"; std::getline(std::cin, userPassword);
203    return 0;
204Error:
205    return err;
206}
207
208std::vector<std::string> _split(std::string inputLine, char delimiter)
209{
210    std::vector<std::string> strArray;
211    if (inputLine.empty()) return strArray;
212
213    std::string tmp;
214    std::stringstream ss{inputLine};
215    while (getline(ss, tmp, delimiter)) {
216        strArray.push_back(tmp);
217    }
218    return strArray;
219}
220
221SCRSDK::CrError _uploadCustomGridLineFile(/*in*/ SCRSDK::CrDeviceHandle deviceHandle, /*in*/ SCRSDK::CrGridLineType gridLineType, /*in*/ CrChar* filePath, /*in*/ CrChar* displayName)
222{
223    int result = SCRSDK::CrError_Generic_Unknown;
224    SCRSDK::CrError err = SCRSDK::CrError_None;
225    std::promise<void> eventPromise;
226    std::future<void> eventFuture = eventPromise.get_future();
227
228    setEventPromise(&eventPromise);
229    err = SCRSDK::UploadCustomGridLineFile(deviceHandle, gridLineType, filePath, displayName);
230    if(err) GotoError("", err);
231
232    try{
233        eventFuture.get();
234    } catch(const std::exception&) GotoError("", 0);
235
236    result = 0;
237Error:
238    setEventPromise(nullptr);
239    return result;
240}
241
242int main(void)
243{
244    int result = -1;
245    SCRSDK::CrError err = SCRSDK::CrError_None;
246    int64_t  m_device_handle = 0;
247    SCRSDK::ICrEnumCameraObjectInfo* enumCameraObjectInfo = nullptr;
248    SCRSDK::ICrCameraObjectInfo* objInfo = nullptr;
249    DeviceCallback deviceCallback;
250
251  #if defined(__APPLE__)
252    #define MAC_MAX_PATH 255
253    char pathBuf[MAC_MAX_PATH] = {0};
254    if(NULL == getcwd(pathBuf, sizeof(pathBuf) - 1)) return 1;
255    CrString path = pathBuf;
256  #else
257    CrString path = fs::current_path().native();
258  #endif
259
260    bool boolRet = SCRSDK::Init();
261    if(!boolRet) GotoError("", 0);
262
263    // enumeration
264    {
265        uint32_t count = 0;
266        uint32_t index = 1;
267
268        err = SCRSDK::EnumCameraObjects(&enumCameraObjectInfo, 3/*timeInSec*/);
269        if(err || !enumCameraObjectInfo) GotoError("no camera", err);
270
271        count = enumCameraObjectInfo->GetCount();
272        if(count >= 2) {
273            for (uint32_t i = 0; i < count; ++i) {
274                auto* info = enumCameraObjectInfo->GetCameraObjectInfo(i);
275                CrCout << '[' << i + 1 << "] " << _getModelId(info) << "\n";
276            }
277
278            std::string inputLine;
279            std::cout << "select camera:"; std::getline(std::cin, inputLine);
280            try { index = stoi(inputLine); } catch(const std::exception&) { GotoError("", 0); }
281            if(index < 1 || index > count) GotoError("", 0);
282        }
283        objInfo = (SCRSDK::ICrCameraObjectInfo*)enumCameraObjectInfo->GetCameraObjectInfo(index - 1);
284        m_modelId = _getModelId(objInfo);
285    }
286
287    // connect
288    {
289        std::string  fingerprint = "";
290        std::string  userId = "";
291        std::string  userPassword = "";
292        std::promise<void> eventPromise;
293        std::future<void> eventFuture = eventPromise.get_future();
294
295        if (objInfo->GetSSHsupport() == SCRSDK::CrSSHsupport_ON) {
296            err = _getIdPassword(objInfo, fingerprint, userId, userPassword); if(err) goto Error;
297        }
298
299        setEventPromise(&eventPromise);
300        err = SCRSDK::Connect(objInfo, &deviceCallback, &m_device_handle,
301            SCRSDK::CrSdkControlMode_Remote,
302            SCRSDK::CrReconnecting_ON,
303            userId.c_str(), userPassword.c_str(), fingerprint.c_str(), (uint32_t)fingerprint.size());
304        if(err) GotoError("", err);
305
306    //  std::future_status status = eventFuture.wait_for(std::chrono::milliseconds(3000));
307    //  if(status != std::future_status::ready) GotoError("timeout",0);
308        try{
309            eventFuture.get();
310        } catch(const std::exception&) GotoError("", 0);
311    }
312
313    // set work directory
314    {
315        CrCout << "path=" << path.data() << "\n";
316        err = SCRSDK::SetSaveInfo(m_device_handle, const_cast<CrChar*>(path.data()), const_cast<CrChar*>(CRSTR("DSC")), -1/*startNo*/);
317        if(err) GotoError("", err);
318    }
319
320    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
321
322    std::cout << "usage:\n";
323    std::cout << "   set <1~4> <filename>    - set custom grid line\n";
324    std::cout << "To exit, please enter 'q'.\n";
325
326    while(1) {
327        std::string inputLine;
328        std::getline(std::cin, inputLine);
329        std::vector<std::string> args = _split(inputLine, ' ');
330
331        if(args.size() == 0) {
332
333        } else if(args[0] == "set" && args.size() >=3) {
334            uint32_t val;
335            CrString pathCgl = path;
336            try { val = stoi(args[1]); } catch(const std::exception&) { GotoError("", 0); }
337            pathCgl.append(DELIMITER).append(Utf8ToCr(args[2]));
338            CrCout << pathCgl.data() << "\n";
339
340            err = _uploadCustomGridLineFile(m_device_handle, (SCRSDK::CrGridLineType)(val + 0x10), const_cast<CrChar*>(pathCgl.data()), const_cast<CrChar*>(CRSTR("tmp.png")));
341            //if(err) goto Error;
342            std::cout << "OK\n";
343
344        } else if(args[0] == "q" || args[0] == "Q") {
345            break;
346        } else {
347            std::cout << "unknown command\n";
348        }
349    }
350
351    result = 0;
352Error:
353    if(enumCameraObjectInfo) enumCameraObjectInfo->Release();
354
355    if(m_connected) {
356        std::promise<void> eventPromise;
357        std::future<void> eventFuture = eventPromise.get_future();
358        setEventPromise(&eventPromise);
359        SCRSDK::Disconnect(m_device_handle);
360        eventFuture.wait_for(std::chrono::milliseconds(3000));
361    }
362    if(m_device_handle) SCRSDK::ReleaseDevice(m_device_handle);
363    SCRSDK::Release();
364
365    return result;
366}