JeVois  1.5
JeVois Smart Embedded Machine Vision Toolkit
Share this page:
Engine.C
Go to the documentation of this file.
1 // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 //
3 // JeVois Smart Embedded Machine Vision Toolkit - Copyright (C) 2016 by Laurent Itti, the University of Southern
4 // California (USC), and iLab at USC. See http://iLab.usc.edu and http://jevois.org for information about this project.
5 //
6 // This file is part of the JeVois Smart Embedded Machine Vision Toolkit. This program is free software; you can
7 // redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
8 // Foundation, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
10 // License for more details. You should have received a copy of the GNU General Public License along with this program;
11 // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
12 //
13 // Contact information: Laurent Itti - 3641 Watt Way, HNB-07A - Los Angeles, CA 90089-2520 - USA.
14 // Tel: +1 213 740 3527 - itti@pollux.usc.edu - http://iLab.usc.edu - http://jevois.org
15 // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
16 /*! \file */
17 
18 #include <jevois/Core/Engine.H>
19 
20 #include <jevois/Core/Camera.H>
21 #include <jevois/Core/MovieInput.H>
22 
23 #include <jevois/Core/Gadget.H>
27 
28 #include <jevois/Core/Serial.H>
30 
31 #include <jevois/Core/Module.H>
35 
36 #include <jevois/Debug/Log.H>
37 #include <jevois/Util/Utils.H>
38 #include <jevois/Debug/SysInfo.H>
39 
40 #include <cmath> // for fabs
41 #include <fstream>
42 #include <algorithm>
43 #include <cstdlib> // for std::system()
44 #include <cstdio> // for std::remove()
45 
46 // On the older platform kernel, detect class is not defined:
47 #ifndef V4L2_CTRL_CLASS_DETECT
48 #define V4L2_CTRL_CLASS_DETECT 0x00a30000
49 #endif
50 
51 namespace
52 {
53  // Assign a short name to every V4L2 control, for use by getcam and setcam commands
54  struct shortcontrol { int id; char const * const shortname; };
55 
56  // All V4L2 controls
57  // From this: grep V4L2_CID v4l2-controls.h | awk '{ print " { " $2 ", \"\" }," }'
58  // then fill-in the short names.
59  static shortcontrol camcontrols[] = {
60  // In V4L2_CID_BASE class:
61  { V4L2_CID_BRIGHTNESS, "brightness" },
62  { V4L2_CID_CONTRAST, "contrast" },
63  { V4L2_CID_SATURATION, "saturation" },
64  { V4L2_CID_HUE, "hue" },
65  { V4L2_CID_AUDIO_VOLUME, "audiovol" },
66  { V4L2_CID_AUDIO_BALANCE, "audiobal" },
67  { V4L2_CID_AUDIO_BASS, "audiobass" },
68  { V4L2_CID_AUDIO_TREBLE, "audiotreble" },
69  { V4L2_CID_AUDIO_MUTE, "audiomute" },
70  { V4L2_CID_AUDIO_LOUDNESS, "audioloudness" },
71  { V4L2_CID_BLACK_LEVEL, "blacklevel" },
72  { V4L2_CID_AUTO_WHITE_BALANCE, "autowb" },
73  { V4L2_CID_DO_WHITE_BALANCE, "dowb" },
74  { V4L2_CID_RED_BALANCE, "redbal" },
75  { V4L2_CID_BLUE_BALANCE, "bluebal" },
76  { V4L2_CID_GAMMA, "gamma" },
77  { V4L2_CID_WHITENESS, "whiteness" },
78  { V4L2_CID_EXPOSURE, "exposure" },
79  { V4L2_CID_AUTOGAIN, "autogain" },
80  { V4L2_CID_GAIN, "gain" },
81  { V4L2_CID_HFLIP, "hflip" },
82  { V4L2_CID_VFLIP, "vflip" },
83  { V4L2_CID_POWER_LINE_FREQUENCY, "powerfreq" },
84  { V4L2_CID_HUE_AUTO, "autohue" },
85  { V4L2_CID_WHITE_BALANCE_TEMPERATURE, "wbtemp" },
86  { V4L2_CID_SHARPNESS, "sharpness" },
87  { V4L2_CID_BACKLIGHT_COMPENSATION, "backlight" },
88  { V4L2_CID_CHROMA_AGC, "chromaagc" },
89  { V4L2_CID_COLOR_KILLER, "colorkiller" },
90  { V4L2_CID_COLORFX, "colorfx" },
91  { V4L2_CID_AUTOBRIGHTNESS, "autobrightness" },
92  { V4L2_CID_BAND_STOP_FILTER, "bandfilter" },
93  { V4L2_CID_ROTATE, "rotate" },
94  { V4L2_CID_BG_COLOR, "bgcolor" },
95  { V4L2_CID_CHROMA_GAIN, "chromagain" },
96  { V4L2_CID_ILLUMINATORS_1, "illum1" },
97  { V4L2_CID_ILLUMINATORS_2, "illum2" },
98  { V4L2_CID_MIN_BUFFERS_FOR_CAPTURE, "mincapbuf" },
99  { V4L2_CID_MIN_BUFFERS_FOR_OUTPUT, "minoutbuf" },
100  { V4L2_CID_ALPHA_COMPONENT, "alphacompo" },
101  // This one is not defined in our older platform kernel:
102  //{ V4L2_CID_COLORFX_CBCR, "colorfxcbcr" },
103 
104  // In V4L2_CID_CAMERA_CLASS_BASE class
105  { V4L2_CID_EXPOSURE_AUTO, "autoexp" },
106  { V4L2_CID_EXPOSURE_ABSOLUTE, "absexp" },
107  { V4L2_CID_EXPOSURE_AUTO_PRIORITY, "exppri" },
108  { V4L2_CID_PAN_RELATIVE, "panrel" },
109  { V4L2_CID_TILT_RELATIVE, "tiltrel" },
110  { V4L2_CID_PAN_RESET, "panreset" },
111  { V4L2_CID_TILT_RESET, "tiltreset" },
112  { V4L2_CID_PAN_ABSOLUTE, "panabs" },
113  { V4L2_CID_TILT_ABSOLUTE, "tiltabs" },
114  { V4L2_CID_FOCUS_ABSOLUTE, "focusabs" },
115  { V4L2_CID_FOCUS_RELATIVE, "focusrel" },
116  { V4L2_CID_FOCUS_AUTO, "focusauto" },
117  { V4L2_CID_ZOOM_ABSOLUTE, "zoomabs" },
118  { V4L2_CID_ZOOM_RELATIVE, "zoomrel" },
119  { V4L2_CID_ZOOM_CONTINUOUS, "zoomcontinuous" },
120  { V4L2_CID_PRIVACY, "privacy" },
121  { V4L2_CID_IRIS_ABSOLUTE, "irisabs" },
122  { V4L2_CID_IRIS_RELATIVE, "irisrel" },
123 
124  // definition for this one seems to be in the kernel but missing somehow here:
125 #ifndef V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE
126 #define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE (V4L2_CID_CAMERA_CLASS_BASE+20)
127 #endif
128  { V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE, "presetwb" },
129 
130  // Those are not defined in our older platform kernel:
131  //{ V4L2_CID_AUTO_EXPOSURE_BIAS, "expbias" },
132  //{ V4L2_CID_WIDE_DYNAMIC_RANGE, "wdr" },
133  //{ V4L2_CID_IMAGE_STABILIZATION, "stabilization" },
134  //{ V4L2_CID_ISO_SENSITIVITY, "isosens" },
135  //{ V4L2_CID_ISO_SENSITIVITY_AUTO, "isosensauto" },
136  //{ V4L2_CID_EXPOSURE_METERING, "expmetering" },
137  //{ V4L2_CID_SCENE_MODE, "scene" },
138  //{ V4L2_CID_3A_LOCK, "3alock" },
139  //{ V4L2_CID_AUTO_FOCUS_START, "autofocusstart" },
140  //{ V4L2_CID_AUTO_FOCUS_STOP, "autofocusstop" },
141  //{ V4L2_CID_AUTO_FOCUS_STATUS, "autofocusstatus" },
142  //{ V4L2_CID_AUTO_FOCUS_RANGE, "autofocusrange" },
143  //{ V4L2_CID_PAN_SPEED, "panspeed" },
144  //{ V4L2_CID_TILT_SPEED, "tiltspeed" },
145 
146  // In V4L2_CID_FLASH_CLASS_BASE:
147  { V4L2_CID_FLASH_LED_MODE, "flashled" },
148  { V4L2_CID_FLASH_STROBE_SOURCE, "flashstrobesrc" },
149  { V4L2_CID_FLASH_STROBE, "flashstrobe" },
150  { V4L2_CID_FLASH_STROBE_STOP, "flashstrobestop" },
151  { V4L2_CID_FLASH_STROBE_STATUS, "flashstrovestat" },
152  { V4L2_CID_FLASH_TIMEOUT, "flashtimeout" },
153  { V4L2_CID_FLASH_INTENSITY, "flashintens" },
154  { V4L2_CID_FLASH_TORCH_INTENSITY, "flashtorch" },
155  { V4L2_CID_FLASH_INDICATOR_INTENSITY, "flashindintens" },
156  { V4L2_CID_FLASH_FAULT, "flashfault" },
157  { V4L2_CID_FLASH_CHARGE, "flashcharge" },
158  { V4L2_CID_FLASH_READY, "flashready" },
159 
160  // In V4L2_CID_JPEG_CLASS_BASE:
161  { V4L2_CID_JPEG_CHROMA_SUBSAMPLING, "jpegchroma" },
162  { V4L2_CID_JPEG_RESTART_INTERVAL, "jpegrestartint" },
163  { V4L2_CID_JPEG_COMPRESSION_QUALITY, "jpegcompression" },
164  { V4L2_CID_JPEG_ACTIVE_MARKER, "jpegmarker" },
165 
166  // In V4L2_CID_IMAGE_SOURCE_CLASS_BASE:
167  // Those are not defined in our older platform kernel:
168  //{ V4L2_CID_VBLANK, "vblank" },
169  //{ V4L2_CID_HBLANK, "hblank" },
170  //{ V4L2_CID_ANALOGUE_GAIN, "again" },
171  //{ V4L2_CID_TEST_PATTERN_RED, "testpatred" },
172  //{ V4L2_CID_TEST_PATTERN_GREENR, "testpatgreenr" },
173  //{ V4L2_CID_TEST_PATTERN_BLUE, "testpatblue" },
174  //{ V4L2_CID_TEST_PATTERN_GREENB, "testpatbreenb" },
175 
176  // In V4L2_CID_IMAGE_PROC_CLASS_BASE:
177  //{ V4L2_CID_LINK_FREQ, "linkfreq" },
178  //{ V4L2_CID_PIXEL_RATE, "pixrate" },
179  //{ V4L2_CID_TEST_PATTERN, "testpat" },
180 
181  // In V4L2_CID_DETECT_CLASS_BASE:
182  //{ V4L2_CID_DETECT_MD_MODE, "detectmode" },
183  //{ V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD, "detectthresh" },
184  //{ V4L2_CID_DETECT_MD_THRESHOLD_GRID, "detectthreshgrid" },
185  //{ V4L2_CID_DETECT_MD_REGION_GRID, "detectregiongrid" },
186  };
187 
188  // Convert a long name to a short name:
189  std::string abbreviate(std::string const & longname)
190  {
191  std::string name(longname);
192  std::transform(name.begin(), name.end(), name.begin(), ::tolower);
193  name.erase(std::remove_if(name.begin(), name.end(), [](int c) { return !std::isalnum(c); }), name.end());
194  return name;
195  }
196 } // anonymous namespace
197 
198 
199 // ####################################################################################################
200 jevois::Engine::Engine(std::string const & instance) :
201  jevois::Manager(instance), itsMappings(jevois::loadVideoMappings(itsDefaultMappingIdx)),
202  itsRunning(false), itsStreaming(false), itsStopMainLoop(false), itsTurbo(false),
203  itsManualStreamon(false), itsVideoErrors(false)
204 {
205  JEVOIS_TRACE(1);
206 
207  LINFO("Loaded " << itsMappings.size() << " vision processing modes.");
208 
209 #ifdef JEVOIS_PLATFORM
210  // Start mass storage thread:
211  itsCheckingMassStorage.store(false); itsMassStorageMode.store(false);
212  itsCheckMassStorageFut = std::async(std::launch::async, &jevois::Engine::checkMassStorage, this);
213  while (itsCheckingMassStorage.load() == false) std::this_thread::sleep_for(std::chrono::milliseconds(5));
214 #endif
215 }
216 
217 // ####################################################################################################
218 jevois::Engine::Engine(int argc, char const* argv[], std::string const & instance) :
219  jevois::Manager(argc, argv, instance), itsMappings(jevois::loadVideoMappings(itsDefaultMappingIdx)),
220  itsRunning(false), itsStreaming(false), itsStopMainLoop(false), itsTurbo(false),
221  itsManualStreamon(false), itsVideoErrors(false)
222 {
223  JEVOIS_TRACE(1);
224 
225  LINFO("Loaded " << itsMappings.size() << " vision processing modes.");
226 
227 #ifdef JEVOIS_PLATFORM
228  // Start mass storage thread:
229  itsCheckingMassStorage.store(false); itsMassStorageMode.store(false);
230  itsCheckMassStorageFut = std::async(std::launch::async, &jevois::Engine::checkMassStorage, this);
231  while (itsCheckingMassStorage.load() == false) std::this_thread::sleep_for(std::chrono::milliseconds(5));
232 #endif
233 }
234 
235 // ####################################################################################################
236 void jevois::Engine::onParamChange(jevois::engine::serialdev const & JEVOIS_UNUSED_PARAM(param),
237  std::string const & newval)
238 {
240 
241  // If we have a serial already, nuke it:
242  for (std::list<std::shared_ptr<UserInterface> >::iterator itr = itsSerials.begin(); itr != itsSerials.end(); ++itr)
243  if ((*itr)->instanceName() == "serial") itr = itsSerials.erase(itr);
244  removeComponent("serial", false);
245 
246  // Open the usb hardware (4-pin connector) serial port, if any:
247  if (newval.empty() == false)
248  try
249  {
250  std::shared_ptr<jevois::UserInterface> s;
251  if (newval == "stdio")
252  s = addComponent<jevois::StdioInterface>("serial");
253  else
254  {
255  s = addComponent<jevois::Serial>("serial", jevois::UserInterface::Type::Hard);
256  s->setParamVal("devname", newval);
257  }
258 
259  itsSerials.push_back(s);
260  LINFO("Using [" << newval << "] hardware (4-pin connector) serial port");
261  }
262  catch (...) { jevois::warnAndIgnoreException(); LERROR("Could not start hardware (4-pin connector) serial port"); }
263  else LINFO("No hardware (4-pin connector) serial port used");
264 }
265 
266 // ####################################################################################################
267 void jevois::Engine::onParamChange(jevois::engine::usbserialdev const & JEVOIS_UNUSED_PARAM(param),
268  std::string const & newval)
269 {
271 
272  // If we have a usbserial already, nuke it:
273  for (std::list<std::shared_ptr<UserInterface> >::iterator itr = itsSerials.begin(); itr != itsSerials.end(); ++itr)
274  if ((*itr)->instanceName() == "usbserial") itr = itsSerials.erase(itr);
275  removeComponent("usbserial", false);
276 
277  // Open the USB serial port, if any:
278  if (newval.empty() == false)
279  try
280  {
281  std::shared_ptr<jevois::UserInterface> s =
282  addComponent<jevois::Serial>("usbserial", jevois::UserInterface::Type::USB);
283  s->setParamVal("devname", newval);
284  itsSerials.push_back(s);
285  LINFO("Using [" << newval << "] USB serial port");
286  }
287  catch (...) { jevois::warnAndIgnoreException(); LERROR("Could not start USB serial port"); }
288  else LINFO("No USB serial port used");
289 }
290 
291 // ####################################################################################################
292 void jevois::Engine::onParamChange(jevois::engine::cpumode const & JEVOIS_UNUSED_PARAM(param),
293  jevois::engine::CPUmode const & newval)
294 {
295  std::ofstream ofs("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor");
296  if (ofs.is_open() == false)
297  {
298 #ifdef JEVOIS_PLATFORM
299  LERROR("Cannot set cpu frequency governor mode -- IGNORED");
300 #endif
301  return;
302  }
303 
304  switch (newval)
305  {
306  case engine::CPUmode::PowerSave: ofs << "powersave" << std::endl; break;
307  case engine::CPUmode::Conservative: ofs << "conservative" << std::endl; break;
308  case engine::CPUmode::OnDemand: ofs << "ondemand" << std::endl; break;
309  case engine::CPUmode::Interactive: ofs << "interactive" << std::endl; break;
310  case engine::CPUmode::Performance: ofs << "performance" << std::endl; break;
311  }
312 }
313 
314 // ####################################################################################################
315 void jevois::Engine::onParamChange(jevois::engine::cpumax const & JEVOIS_UNUSED_PARAM(param),
316  unsigned int const & newval)
317 {
318  std::ofstream ofs("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq");
319  if (ofs.is_open() == false)
320  {
321 #ifdef JEVOIS_PLATFORM
322  LERROR("Cannot set cpu max frequency -- IGNORED");
323 #endif
324  return;
325  }
326 
327  ofs << newval * 1000U << std::endl;
328 }
329 
330 // ####################################################################################################
331 void jevois::Engine::onParamChange(jevois::engine::videoerrors const & JEVOIS_UNUSED_PARAM(param),
332  bool const & newval)
333 {
334  itsVideoErrors.store(newval);
335 }
336 
337 // ####################################################################################################
339 {
340  // Set any initial parameters from global config file:
341  std::string const paramcfg = std::string(JEVOIS_CONFIG_PATH) + '/' + JEVOIS_MODULE_PARAMS_FILENAME;
342  std::ifstream ifs(paramcfg); if (ifs.is_open()) setParamsFromStream(ifs, paramcfg);
343 
344  // Run the Manager version. This parses the command line:
346 }
347 
348 // ####################################################################################################
350 {
351  // First make sure the manager gets to run this:
353 
354  // Freeze the serial port device names, their params, and camera and gadget too:
355  serialdev::freeze();
356  usbserialdev::freeze();
357  for (auto & s : itsSerials) s->freezeAllParams();
358  cameradev::freeze();
359  cameranbuf::freeze();
360  camturbo::freeze();
361  gadgetdev::freeze();
362  gadgetnbuf::freeze();
363  itsTurbo = camturbo::get();
364 
365  // Grab the log messages, itsSerials is not going to change anymore now that the serial params are frozen:
366  jevois::logSetEngine(this);
367 
368  // Get python going, we need to do this here to avoid segfaults on platform when instantiating our first python
369  // module. This likely has to do with the fact that the python core is not very thread-safe, and setFormatInternal()
370  // in Engine, which instantiates python modules, will indeed be invoked from a different thread (the one that receives
371  // USB UVC events). Have a look at Python Thread State, Python Gobal Interpreter Lock, etc if interested:
372  LINFO("Initalizing Python...");
373  jevois::pythonModuleSetEngine(this);
374 
375  // Instantiate a camera: If device names starts with "/dev/v", assume a hardware camera, otherwise a movie file:
376  std::string const camdev = cameradev::get();
377  if (jevois::stringStartsWith(camdev, "/dev/v"))
378  {
379  LINFO("Starting camera device " << camdev);
380 
381 #ifdef JEVOIS_PLATFORM
382  // Set turbo mode or not:
383  std::ofstream ofs("/sys/module/vfe_v4l2/parameters/turbo");
384  if (ofs.is_open())
385  {
386  if (itsTurbo) ofs << "1" << std::endl; else ofs << "0" << std::endl;
387  ofs.close();
388  }
389  else LERROR("Could not access VFE turbo parameter -- IGNORED");
390 #endif
391 
392  // Now instantiate the camera:
393  itsCamera.reset(new jevois::Camera(camdev, cameranbuf::get()));
394 
395 #ifndef JEVOIS_PLATFORM
396  // No need to confuse people with a non-working camreg param:
397  camreg::set(false);
398  camreg::freeze();
399 #endif
400  }
401  else
402  {
403  LINFO("Using movie input " << camdev << " -- issue a 'streamon' to start processing.");
404  itsCamera.reset(new jevois::MovieInput(camdev, cameranbuf::get()));
405 
406  // No need to confuse people with a non-working camreg param:
407  camreg::set(false);
408  camreg::freeze();
409  }
410 
411  // Instantiate a USB gadget: Note: it will want to access the mappings. If the user-selected video mapping has no usb
412  // out, do not instantiate a gadget:
413  int midx = videomapping::get();
414 
415  // The videomapping parameter is now disabled, users should use the 'setmapping' command once running:
416  videomapping::freeze();
417 
418  if (midx >= int(itsMappings.size()))
419  { LERROR("Mapping index " << midx << " out of range -- USING DEFAULT"); midx = -1; }
420 
421  if (midx < 0) midx = itsDefaultMappingIdx;
422 
423  // Always instantiate a gadget even if not used right now, may be used later:
424  std::string const gd = gadgetdev::get();
425  if (gd == "None")
426  {
427  LINFO("Using no USB video output.");
428  // No USB output and no display, useful for benchmarking only:
429  itsGadget.reset(new jevois::VideoOutputNone());
430  itsManualStreamon = true;
431  }
432  else if (jevois::stringStartsWith(gd, "/dev/"))
433  {
434  LINFO("Loading USB video driver " << gd);
435  // USB gadget driver:
436  itsGadget.reset(new jevois::Gadget(gd, itsCamera.get(), this, gadgetnbuf::get()));
437  }
438  else if (gd.empty() == false)
439  {
440  LINFO("Saving output video to file " << gd);
441  // Non-empty filename, save to file:
442  itsGadget.reset(new jevois::MovieOutput(gd));
443  itsManualStreamon = true;
444  }
445  else
446  {
447  LINFO("Using display for video output");
448  // Local video display, for use on a host desktop:
449  itsGadget.reset(new jevois::VideoDisplay("jevois", gadgetnbuf::get()));
450  itsManualStreamon = true;
451  }
452 
453  // We are ready to run:
454  itsRunning.store(true);
455 
456  // Set initial format:
457  try { setFormat(midx); } catch (...) { jevois::warnAndIgnoreException(); }
458 
459  // Run init script:
461  runScriptFromFile(JEVOIS_ENGINE_INIT_SCRIPT, nullptr, false);
462 }
463 
464 // ####################################################################################################
466 {
467  JEVOIS_TRACE(1);
468 
469  // Turn off stream if it is on:
470  streamOff();
471 
472  // Tell our run() thread to finish up:
473  itsRunning.store(false);
474 
475 #ifdef JEVOIS_PLATFORM
476  // Tell checkMassStorage() thread to finish up:
477  itsCheckingMassStorage.store(false);
478 #endif
479 
480  // Nuke our module as soon as we can, hopefully soon now that we turned off streaming and running:
481  {
484  itsModule.reset();
485 
486  // Gone, nuke the loader now:
487  itsLoader.reset();
488  }
489 
490  // Because we passed the camera as a raw pointer to the gadget, nuke the gadget first and then the camera:
491  itsGadget.reset();
492  itsCamera.reset();
493 
494 #ifdef JEVOIS_PLATFORM
495  // Will block until the checkMassStorage() thread completes:
496  if (itsCheckMassStorageFut.valid())
497  try { itsCheckMassStorageFut.get(); } catch (...) { jevois::warnAndIgnoreException(); }
498 #endif
499 
500  // Things should be quiet now, unhook from the logger (this call is not strictly thread safe):
501  jevois::logSetEngine(nullptr);
502 }
503 
504 // ####################################################################################################
505 #ifdef JEVOIS_PLATFORM
506 void jevois::Engine::checkMassStorage()
507 {
508  itsCheckingMassStorage.store(true);
509 
510  while (itsCheckingMassStorage.load())
511  {
512  // Check from the mass storage gadget (with JeVois extension) whether the virtual USB drive is mounted by the
513  // host. If currently in mass storage mode and the host just ejected the virtual flash drive, resume normal
514  // operation. If not in mass-storage mode and the host mounted it, enter mass-storage mode (may happen if
515  // /boot/usbsdauto was selected):
516  std::ifstream ifs("/sys/devices/platform/sunxi_usb_udc/gadget/lun0/mass_storage_in_use");
517  if (ifs.is_open())
518  {
519  int inuse; ifs >> inuse;
520  if (itsMassStorageMode.load())
521  {
522  if (inuse == 0) stopMassStorageMode();
523  }
524  else
525  {
526  if (inuse) { JEVOIS_TIMED_LOCK(itsMtx); startMassStorageMode(); }
527  }
528  }
529  std::this_thread::sleep_for(std::chrono::milliseconds(500));
530  }
531 }
532 #endif
533 
534 // ####################################################################################################
536 {
537  JEVOIS_TRACE(2);
538 
540  itsCamera->streamOn();
541  itsGadget->streamOn();
542  itsStreaming.store(true);
543 }
544 
545 // ####################################################################################################
547 {
548  JEVOIS_TRACE(2);
549 
550  // First, tell both ethe camera and gadget to abort streaming, this will make get()/done()/send() to throw:
551  itsGadget->abortStream();
552  itsCamera->abortStream();
553 
554  // Stop the main loop, which will flip itsStreaming to false and will make it easier for us to lock itsMtx:
555  LDEBUG("Stopping main loop...");
556  itsStopMainLoop.store(true);
557  while (itsStopMainLoop.load() && itsRunning.load()) std::this_thread::sleep_for(std::chrono::milliseconds(10));
558  LDEBUG("Main loop stopped.");
559 
560  // Lock up and stream off:
562  itsGadget->streamOff();
563  itsCamera->streamOff();
564 }
565 
566 // ####################################################################################################
568 {
569  JEVOIS_TRACE(2);
570 
571  LDEBUG("Set format number " << idx << " start...");
572 
573  if (idx >= itsMappings.size())
574  LFATAL("Requested mapping index " << idx << " out of range [0 .. " << itsMappings.size()-1 << ']');
575 
577  setFormatInternal(idx);
578  LDEBUG("Set format number " << idx << " done");
579 }
580 
581 // ####################################################################################################
582 void jevois::Engine::setFormatInternal(size_t idx)
583 {
584  // itsMtx should be locked by caller, idx should be valid:
585  JEVOIS_TRACE(2);
586 
587  jevois::VideoMapping const & m = itsMappings[idx];
588  setFormatInternal(m);
589 }
590 
591 // ####################################################################################################
592 void jevois::Engine::setFormatInternal(jevois::VideoMapping const & m)
593 {
594  // itsMtx should be locked by caller, idx should be valid:
595  JEVOIS_TRACE(2);
596 
597  LINFO(m.str());
598 
599 #ifdef JEVOIS_PLATFORM
600  if (itsMassStorageMode.load())
601  LFATAL("Cannot setup video streaming while in mass-storage mode. Eject the USB drive on your host computer first.");
602 #endif
603 
604  // Now that the module is nuked, we won't have any get()/done()/send() requests on the camera or gadget, thus it is
605  // safe to change the formats on both:
606  itsCamera->setFormat(m);
607  if (m.ofmt) itsGadget->setFormat(m);
608 
609  // Keep track of our current mapping:
610  itsCurrentMapping = m;
611 
612  // Nuke the processing module, if any, so we can also safely nuke the loader. We always nuke the module instance so we
613  // won't have any issues with latent state even if we re-use the same module but possibly with different input
614  // image resolution, etc:
615  if (itsModule) { removeComponent(itsModule); itsModule.reset(); }
616 
617 
618  // Instantiate the module. If the constructor throws, code is bogus, for example some syntax error in a python module
619  // that is detected at load time. We get the exception's error message for later display into video frames in the main
620  // loop, and mark itsModuleConstructionError:
621  try
622  {
623  // For python modules, we do not need a loader, we just instantiate our special python wrapper module instead:
624  std::string const sopath = m.sopath();
625  if (m.ispython)
626  {
627  // Instantiate the python wrapper.
628  itsModule.reset(new jevois::PythonModule(m));
629  }
630  else
631  {
632  // C++ compiled module. We can re-use the same loader and avoid closing the .so if we will use the same module:
633  if (itsLoader.get() == nullptr || itsLoader->sopath() != sopath)
634  {
635  // Nuke our previous loader and free its resources if needed, then start a new loader:
636  LINFO("Instantiating dynamic loader for " << sopath);
637  itsLoader.reset(new jevois::DynamicLoader(sopath, true));
638  }
639 
640  // Check version match:
641  auto version_major = itsLoader->load<int()>(m.modulename + "_version_major");
642  auto version_minor = itsLoader->load<int()>(m.modulename + "_version_minor");
643  if (version_major() != JEVOIS_VERSION_MAJOR || version_minor() != JEVOIS_VERSION_MINOR)
644  LERROR("Module " << m.modulename << " in file " << sopath << " was build for JeVois v" << version_major() << '.'
645  << version_minor() << ", but running framework is v" << JEVOIS_VERSION_STRING << " -- TRYING ANYWAY");
646 
647  // Instantiate the new module:
648  auto create = itsLoader->load<std::shared_ptr<jevois::Module>(std::string const &)>(m.modulename + "_create");
649  itsModule = create(m.modulename); // Here we just use the class name as instance name
650  }
651 
652  // Add the module as a component to us. Keep this code in sync with Manager::addComponent():
653  {
654  // Lock up so we guarantee the instance name does not get robbed as we add the sub:
655  boost::unique_lock<boost::shared_mutex> ulck(itsSubMtx);
656 
657  // Then add it as a sub-component to us:
658  itsSubComponents.push_back(itsModule);
659  itsModule->itsParent = this;
660  itsModule->setPath(sopath.substr(0, sopath.rfind('/')));
661  }
662 
663  // Bring it to our runstate and load any extra params. NOTE: Keep this in sync with Component::init():
664  if (itsInitialized) itsModule->runPreInit();
665 
666  std::string const paramcfg = itsModule->absolutePath(JEVOIS_MODULE_PARAMS_FILENAME);
667  std::ifstream ifs(paramcfg); if (ifs.is_open()) itsModule->setParamsFromStream(ifs, paramcfg);
668 
669  if (itsInitialized) { itsModule->setInitialized(); itsModule->runPostInit(); }
670 
671  // And finally run any config script:
672  runScriptFromFile(itsModule->absolutePath(JEVOIS_MODULE_SCRIPT_FILENAME), nullptr, false);
673 
674  LINFO("Module [" << m.modulename << "] loaded, initialized, and ready.");
675  itsModuleConstructionError.clear();
676  }
677  catch (...)
678  {
679  itsModuleConstructionError = jevois::warnAndIgnoreException();
680  if (itsModule) { removeComponent(itsModule); itsModule.reset(); }
681  LERROR("Module [" << m.modulename << "] startup error and not operational.");
682  }
683 }
684 
685 // ####################################################################################################
687 {
688  JEVOIS_TRACE(2);
689 
690  // Announce that we are ready to the hardware serial port, if any. Do not use sendSerial() here so we always issue
691  // this message irrespectively of the user serial preferences:
692  for (auto & s : itsSerials)
693  if (s->instanceName() == "serial")
694  try { s->writeString("INF READY JEVOIS " JEVOIS_VERSION_STRING); }
695  catch (...) { jevois::warnAndIgnoreException(); }
696 
697  while (itsRunning.load())
698  {
699  bool dosleep = true;
700 
701  if (itsStreaming.load())
702  {
704 
705  if (itsModule)
706  {
707  try
708  {
709  if (itsCurrentMapping.ofmt) // Process with USB outputs:
710  itsModule->process(jevois::InputFrame(itsCamera, itsTurbo),
711  jevois::OutputFrame(itsGadget, itsVideoErrors.load() ? &itsVideoErrorImage : nullptr));
712  else // Process with no USB outputs:
713  itsModule->process(jevois::InputFrame(itsCamera, itsTurbo));
714  dosleep = false;
715  }
716  catch (...)
717  {
718  // Report exceptions to video if desired: We have to be extra careful here because the exception might have
719  // been called by the input frame (camera not streaming) or the output frame (gadget not streaming), in
720  // addition to exceptions thrown by the module:
721  if (itsVideoErrors.load())
722  {
723  try
724  {
725  // If the module threw before get() or after send() on the output frame, get a buffer from the gadget:
726  if (itsVideoErrorImage.valid() == false) itsGadget->get(itsVideoErrorImage); // could throw when streamoff
727 
728  // Report module exception to serlog and get it back as a string:
729  std::string errstr = jevois::warnAndIgnoreException();
730 
731  // Draw the error message into our video frame:
732  jevois::drawErrorImage(errstr, itsVideoErrorImage);
733  }
734  catch (...) { jevois::warnAndIgnoreException(); }
735 
736  try
737  {
738  // Send the error image over USB:
739  if (itsVideoErrorImage.valid()) itsGadget->send(itsVideoErrorImage); // could throw if gadget stream off
740  }
741  catch (...) { jevois::warnAndIgnoreException(); }
742 
743  // Invalidate the error image so it is clean for the next frame:
744  itsVideoErrorImage.invalidate();
745  }
746  else
747  {
748  // Report module exception to serlog, and ignore:
750  }
751  }
752  }
753  else
754  {
755  // No module. If we have a module construction error, render it to an image and stream it over USB now (if we
756  // are doing USB and we want to see errors in the video stream):
757  if (itsCurrentMapping.ofmt && itsVideoErrors.load())
758  try
759  {
760  // Get an output image, draw error message, and send to host:
761  itsGadget->get(itsVideoErrorImage);
762  jevois::drawErrorImage(itsModuleConstructionError, itsVideoErrorImage);
763  itsGadget->send(itsVideoErrorImage);
764 
765  // Also get one camera frame to avoid accumulation of stale buffers:
766  (void)jevois::InputFrame(itsCamera, itsTurbo).get();
767  }
768  catch (...) { jevois::warnAndIgnoreException(); }
769  }
770  }
771 
772  if (itsStopMainLoop.load())
773  {
774  itsStreaming.store(false);
775  LDEBUG("-- Main loop stopped --");
776  itsStopMainLoop.store(false);
777  }
778 
779  if (dosleep)
780  {
781  LDEBUG("No processing module loaded or not streaming... Sleeping...");
782  std::this_thread::sleep_for(std::chrono::milliseconds(50));
783  }
784 
785  // Serial input handling. Note that readSome() and writeString() on the serial could throw. The code below is
786  // organized to catch all other exceptions, except for those, which are caught here at the first try level:
787  for (auto & s : itsSerials)
788  {
789  try
790  {
791  std::string str; bool parsed = false; bool success = false;
792 
793  if (s->readSome(str))
794  {
796 
797  // Try to execute this command. If the command is for us (e.g., set a parameter) and is correct,
798  // parseCommand() will return true; if it is for us but buggy, it will throw. If it is not recognized by us,
799  // it will return false and we should try sending it to the Module:
800  try { parsed = parseCommand(str, s); success = parsed; }
801  catch (std::exception const & e) { s->writeString(std::string("ERR ") + e.what()); parsed = true; }
802  catch (...) { s->writeString("ERR Unknown error"); parsed = true; }
803 
804  if (parsed == false)
805  {
806  if (itsModule)
807  {
808  try { itsModule->parseSerial(str, s); success = true; }
809  catch (std::exception const & me) { s->writeString(std::string("ERR ") + me.what()); }
810  catch (...) { s->writeString("ERR Command [" + str + "] not recognized by Engine or Module"); }
811  }
812  else s->writeString("ERR Unsupported command [" + str + "] and no module");
813  }
814 
815  // If success, let user know:
816  if (success) s->writeString("OK");
817  }
818  }
819  catch (...) { jevois::warnAndIgnoreException(); }
820  }
821  }
822 }
823 
824 // ####################################################################################################
825 void jevois::Engine::sendSerial(std::string const & str, bool islog)
826 {
827  // Decide where to send this message based on the value of islog:
828  jevois::engine::SerPort p = islog ? serlog::get() : serout::get();
829 
830  switch (p)
831  {
832  case jevois::engine::SerPort::None:
833  break; // Nothing to send
834 
835  case jevois::engine::SerPort::All:
836  for (auto & s : itsSerials)
837  try { s->writeString(str); } catch (...) { jevois::warnAndIgnoreException(); }
838  break;
839 
840  case jevois::engine::SerPort::Hard:
841  for (auto & s : itsSerials)
842  if (s->type() == jevois::UserInterface::Type::Hard)
843  try { s->writeString(str); } catch (...) { jevois::warnAndIgnoreException(); }
844  break;
845 
846  case jevois::engine::SerPort::USB:
847  for (auto & s : itsSerials)
848  if (s->type() == jevois::UserInterface::Type::USB)
849  try { s->writeString(str); } catch (...) { jevois::warnAndIgnoreException(); }
850  break;
851  }
852 }
853 
854 // ####################################################################################################
856 {
857  return itsCurrentMapping;
858 }
859 
860 // ####################################################################################################
862 {
863  return itsMappings.size();
864 }
865 
866 // ####################################################################################################
868 {
869  if (idx >= itsMappings.size())
870  LFATAL("Index " << idx << " out of range [0 .. " << itsMappings.size()-1 << ']');
871 
872  return itsMappings[idx];
873 }
874 
875 // ####################################################################################################
876 size_t jevois::Engine::getVideoMappingIdx(unsigned int iformat, unsigned int iframe, unsigned int interval) const
877 {
878  // If the iformat or iframe is zero, that's probably a probe for the default mode, so return it:
879  if (iformat == 0 || iframe == 0) return itsDefaultMappingIdx;
880 
881  // If interval is zero, probably a driver trying to probe for our default interval, so return the first available one;
882  // otherwise try to find the desired interval and return the corresponding mapping:
883  if (interval)
884  {
885  float const fps = jevois::VideoMapping::uvcToFps(interval);
886  size_t idx = 0;
887 
888  for (jevois::VideoMapping const & m : itsMappings)
889  if (m.uvcformat == iformat && m.uvcframe == iframe && std::fabs(m.ofps - fps) < 0.1F) return idx;
890  else ++idx;
891 
892  LFATAL("No video mapping for iformat=" << iformat <<", iframe=" << iframe << ", interval=" << interval);
893  }
894  else
895  {
896  size_t idx = 0;
897 
898  for (jevois::VideoMapping const & m : itsMappings)
899  if (m.uvcformat == iformat && m.uvcframe == iframe) return idx;
900  else ++idx;
901 
902  LFATAL("No video mapping for iformat=" << iformat <<", iframe=" << iframe << ", interval=" << interval);
903  }
904 }
905 
906 // ####################################################################################################
909 
910 // ####################################################################################################
912 { return itsDefaultMappingIdx; }
913 
914 // ####################################################################################################
915 jevois::VideoMapping const &
916 jevois::Engine::findVideoMapping(unsigned int oformat, unsigned int owidth, unsigned int oheight,
917  float oframespersec) const
918 {
919  for (jevois::VideoMapping const & m : itsMappings)
920  if (m.match(oformat, owidth, oheight, oframespersec)) return m;
921 
922  LFATAL("Could not find mapping for output format " << jevois::fccstr(oformat) << ' ' <<
923  owidth << 'x' << oheight << " @ " << oframespersec << " fps");
924 }
925 
926 // ####################################################################################################
927 std::string jevois::Engine::camctrlname(int id, char const * longname) const
928 {
929  for (size_t i = 0; i < sizeof camcontrols / sizeof camcontrols[0]; ++i)
930  if (camcontrols[i].id == id) return camcontrols[i].shortname;
931 
932  // Darn, this control is not in our list, probably something exotic. Compute a name from the control's long name:
933  return abbreviate(longname);
934 }
935 
936 // ####################################################################################################
937 int jevois::Engine::camctrlid(std::string const & shortname)
938 {
939  for (size_t i = 0; i < sizeof camcontrols / sizeof camcontrols[0]; ++i)
940  if (shortname.compare(camcontrols[i].shortname) == 0) return camcontrols[i].id;
941 
942  // Not in our list, all right, let's find it then in the camera:
943  struct v4l2_queryctrl qc = { };
944  for (int cls = V4L2_CTRL_CLASS_USER; cls <= V4L2_CTRL_CLASS_DETECT; cls += 0x10000)
945  {
946  // Enumerate all controls in this class. Looks like there is some spillover between V4L2 classes in the V4L2
947  // enumeration process, we end up with duplicate controls if we try to enumerate all the classes. Hence the
948  // doneids set to keep track of the ones already reported:
949  qc.id = cls | 0x900;
950  while (true)
951  {
952  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL; unsigned int old_id = qc.id; bool failed = false;
953  try
954  {
955  itsCamera->queryControl(qc);
956  if (abbreviate(reinterpret_cast<char const *>(qc.name)) == shortname) return qc.id;
957  }
958  catch (...) { failed = true; }
959 
960  // With V4L2_CTRL_FLAG_NEXT_CTRL, the camera kernel driver is supposed to pass down the next valid control if
961  // the requested one is not found, but some drivers do not honor that, so let's move on to the next control
962  // manually if needed:
963  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
964  if (qc.id == old_id) { ++qc.id; if (qc.id > 100 + (cls | 0x900 | V4L2_CTRL_FLAG_NEXT_CTRL)) break; }
965  else if (failed) break;
966  }
967  }
968 
969  LFATAL("Could not find control [" << shortname << "] in the camera");
970 }
971 
972 // ####################################################################################################
973 std::string jevois::Engine::camCtrlHelp(struct v4l2_queryctrl & qc, std::set<int> & doneids)
974 {
975  // See if we have this control:
976  itsCamera->queryControl(qc);
977  qc.id &= ~V4L2_CTRL_FLAG_NEXT_CTRL;
978 
979  // If we have already done this control, just return an empty string:
980  if (doneids.find(qc.id) != doneids.end()) return std::string(); else doneids.insert(qc.id);
981 
982  // Control exists, let's also get its current value:
983  struct v4l2_control ctrl = { }; ctrl.id = qc.id;
984  itsCamera->getControl(ctrl);
985 
986  // Print out some description depending on control type:
987  std::ostringstream ss;
988  ss << "- " << camctrlname(qc.id, reinterpret_cast<char const *>(qc.name));
989 
990  switch (qc.type)
991  {
992  case V4L2_CTRL_TYPE_INTEGER:
993  ss << " [int] min=" << qc.minimum << " max=" << qc.maximum << " step=" << qc.step
994  << " def=" << qc.default_value << " curr=" << ctrl.value;
995  break;
996 
997  //case V4L2_CTRL_TYPE_INTEGER64:
998  //ss << " [int64] value=" << ctrl.value64;
999  //break;
1000 
1001  //case V4L2_CTRL_TYPE_STRING:
1002  //ss << " [str] min=" << qc.minimum << " max=" << qc.maximum << " step=" << qc.step
1003  // << " curr=" << ctrl.string;
1004  //break;
1005 
1006  case V4L2_CTRL_TYPE_BOOLEAN:
1007  ss << " [bool] default=" << qc.default_value << " curr=" << ctrl.value;
1008  break;
1009 
1010  // This one is not supported by the older kernel on platform:
1011  //case V4L2_CTRL_TYPE_INTEGER_MENU:
1012  //ss << " [intmenu] min=" << qc.minimum << " max=" << qc.maximum
1013  // << " def=" << qc.default_value << " curr=" << ctrl.value;
1014  //break;
1015 
1016  case V4L2_CTRL_TYPE_BUTTON:
1017  ss << " [button]";
1018  break;
1019 
1020  case V4L2_CTRL_TYPE_BITMASK:
1021  ss << " [bitmask] max=" << qc.maximum << " def=" << qc.default_value << " curr=" << ctrl.value;
1022  break;
1023 
1024  case V4L2_CTRL_TYPE_MENU:
1025  {
1026  struct v4l2_querymenu querymenu = { };
1027  querymenu.id = qc.id;
1028  ss << " [menu] values ";
1029  for (querymenu.index = qc.minimum; querymenu.index <= (unsigned int)qc.maximum; ++querymenu.index)
1030  {
1031  try { itsCamera->queryMenu(querymenu); } catch (...) { strcpy((char *)(querymenu.name), "fixme"); }
1032  ss << querymenu.index << ':' << querymenu.name << ' ';
1033  }
1034  ss << "curr=" << ctrl.value;
1035  }
1036  break;
1037 
1038  default:
1039  ss << "[unknown type]";
1040  }
1041 
1042  if (qc.flags & V4L2_CTRL_FLAG_DISABLED) ss << " [DISABLED]";
1043 
1044  return ss.str();
1045 }
1046 
1047 #ifdef JEVOIS_PLATFORM
1048 // ####################################################################################################
1049 void jevois::Engine::startMassStorageMode()
1050 {
1051  // itsMtx must be locked by caller
1052 
1053  if (itsMassStorageMode.load()) { LERROR("Already in mass-storage mode -- IGNORED"); return; }
1054 
1055  // Nuke any module and loader so we have nothing loaded that uses /jevois:
1056  if (itsModule) { removeComponent(itsModule); itsModule.reset(); }
1057  if (itsLoader) itsLoader.reset();
1058 
1059  // Unmount /jevois:
1060  if (std::system("sync")) LERROR("Disk sync failed -- IGNORED");
1061  if (std::system("mount -o remount,ro /jevois")) LERROR("Failed to remount /jevois read-only -- IGNORED");
1062 
1063  // Now set the backing partition in mass-storage gadget:
1064  std::ofstream ofs(JEVOIS_USBSD_SYS);
1065  if (ofs.is_open() == false) LFATAL("Cannot setup mass-storage backing file to " << JEVOIS_USBSD_SYS);
1066  ofs << JEVOIS_USBSD_FILE << std::endl;
1067 
1068  LINFO("Exported JEVOIS partition of microSD to host computer as virtual flash drive.");
1069  itsMassStorageMode.store(true);
1070 }
1071 
1072 // ####################################################################################################
1073 void jevois::Engine::stopMassStorageMode()
1074 {
1075  //itsMassStorageMode.store(false);
1076  LINFO("JeVois virtual USB drive ejected by host -- REBOOTING");
1077  reboot();
1078 }
1079 
1080 // ####################################################################################################
1081 void jevois::Engine::reboot()
1082 {
1083  if (std::system("sync")) LERROR("Disk sync failed -- IGNORED");
1084  itsCheckingMassStorage.store(false);
1085  itsRunning.store(false);
1086 
1087  // Hard reset to avoid possible hanging during module unload, etc:
1088  if ( ! std::ofstream("/proc/sys/kernel/sysrq").put('1')) LERROR("Cannot trigger hard reset -- please unplug me!");
1089  if ( ! std::ofstream("/proc/sysrq-trigger").put('s')) LERROR("Cannot trigger hard reset -- please unplug me!");
1090  if ( ! std::ofstream("/proc/sysrq-trigger").put('b')) LERROR("Cannot trigger hard reset -- please unplug me!");
1091  std::terminate();
1092 }
1093 #endif
1094 
1095 // ####################################################################################################
1096 bool jevois::Engine::parseCommand(std::string const & str, std::shared_ptr<UserInterface> s)
1097 {
1098  // itsMtx should be locked by caller
1099 
1100  std::string errmsg;
1101 
1102  // Note: ModemManager on Ubuntu sends this on startup, kill ModemManager to avoid:
1103  // 41 54 5e 53 51 50 4f 52 54 3f 0d 41 54 0d 41 54 0d 41 54 0d 7e 00 78 f0 7e 7e 00 78 f0 7e
1104  //
1105  // AT^SQPORT?
1106  // AT
1107  // AT
1108  // AT
1109  // ~
1110  //
1111  // then later on it insists on trying to mess with us, issuing things like AT, AT+CGMI, AT+GMI, AT+CGMM, AT+GMM,
1112  // AT%IPSYS?, ATE0, ATV1, etc etc
1113 
1114  switch (str.length())
1115  {
1116  case 0:
1117  LDEBUG("Ignoring empty string"); return true;
1118  break;
1119 
1120  case 1:
1121  if (str[0] == '~') { LDEBUG("Ignoring modem config command [~]"); return true; }
1122 
1123  // If the string starts with "#", then just print it out on the serlog port(s). We use this to allow debug messages
1124  // from the arduino to be printed out to the user:
1125  if (str[0] == '#') { sendSerial(str, true); return true; }
1126  break;
1127 
1128  default: // length is 2 or more:
1129 
1130  // Ignore any command that starts with a '~':
1131  if (str[0] == '~') { LDEBUG("Ignoring modem config command [" << str << ']'); return true; }
1132 
1133  // Ignore any command that starts with "AT":
1134  if (str[0] == 'A' && str[1] == 'T') { LDEBUG("Ignoring AT command [" << str <<']'); return true; }
1135 
1136  // If the string starts with "#", then just print it out on the serlog port(s). We use this to allow debug messages
1137  // in the arduino to be printed out to the user:
1138  if (str[0] == '#') { sendSerial(str, true); return true; }
1139 
1140  // Get the first word, i.e., the command:
1141  size_t const idx = str.find(' '); std::string cmd, rem;
1142  if (idx == str.npos) cmd = str; else { cmd = str.substr(0, idx); if (idx < str.length()) rem = str.substr(idx+1); }
1143 
1144  // ----------------------------------------------------------------------------------------------------
1145  if (cmd == "help")
1146  {
1147  // Show all commands, first ours, as supported below:
1148  s->writeString("GENERAL COMMANDS:");
1149  s->writeString("");
1150  s->writeString("help - print this help message");
1151  s->writeString("help2 - print compact help message about current vision module only");
1152  s->writeString("info - show system information including CPU speed, load and temperature");
1153  s->writeString("setpar <name> <value> - set a parameter value");
1154  s->writeString("getpar <name> - get a parameter value(s)");
1155  s->writeString("runscript <filename> - run script commands in specified file");
1156  s->writeString("setcam <ctrl> <val> - set camera control <ctrl> to value <val>");
1157  s->writeString("getcam <ctrl> - get value of camera control <ctrl>");
1158  if (camreg::get())
1159  {
1160  s->writeString("setcamreg <reg> <val> - set raw camera register <reg> to value <val>");
1161  s->writeString("getcamreg <reg> - get value of raw camera register <reg>");
1162  }
1163  s->writeString("listmappings - list all available video mappings");
1164  s->writeString("setmapping <num> - select video mapping <num>, only possible while not streaming");
1165  s->writeString("setmapping2 <CAMmode> <CAMwidth> <CAMheight> <CAMfps> <Vendor> <Module> - set no-USB-out "
1166  "video mapping defined on the fly, while not streaming");
1167  if (itsCurrentMapping.ofmt == 0 || itsManualStreamon)
1168  {
1169  s->writeString("streamon - start camera video streaming");
1170  s->writeString("streamoff - stop camera video streaming");
1171  }
1172  s->writeString("ping - returns 'ALIVE'");
1173  s->writeString("serlog <string> - forward string to the serial port(s) specified by the serlog parameter");
1174  s->writeString("serout <string> - forward string to the serial port(s) specified by the serout parameter");
1175 
1176 #ifdef JEVOIS_PLATFORM
1177  s->writeString("usbsd - export the JEVOIS partition of the microSD card as a virtual USB drive");
1178 #endif
1179  s->writeString("sync - commit any pending data write to microSD");
1180  s->writeString("date [date and time] - get or set the system date and time");
1181 
1182 #ifdef JEVOIS_PLATFORM
1183  s->writeString("restart - restart the JeVois smart camera");
1184 #else
1185  s->writeString("quit - quit this program");
1186 #endif
1187  s->writeString("");
1188 
1189  // Then the module's custom commands, if any:
1190  if (itsModule)
1191  {
1192  std::stringstream css; itsModule->supportedCommands(css);
1193  s->writeString("MODULE-SPECIFIC COMMANDS:");
1194  s->writeString("");
1195  for (std::string line; std::getline(css, line); /* */) s->writeString(line);
1196  s->writeString("");
1197  }
1198 
1199  // Get the help message for our parameters and write it out line by line so the serial fixes the line endings:
1200  std::stringstream pss; constructHelpMessage(pss);
1201  for (std::string line; std::getline(pss, line); /* */) s->writeString(line);
1202 
1203  // Show all camera controls
1204  s->writeString("AVAILABLE CAMERA CONTROLS:");
1205  s->writeString("");
1206 
1207  struct v4l2_queryctrl qc = { }; std::set<int> doneids;
1208  for (int cls = V4L2_CTRL_CLASS_USER; cls <= V4L2_CTRL_CLASS_DETECT; cls += 0x10000)
1209  {
1210  // Enumerate all controls in this class. Looks like there is some spillover between V4L2 classes in the V4L2
1211  // enumeration process, we end up with duplicate controls if we try to enumerate all the classes. Hence the
1212  // doneids set to keep track of the ones already reported:
1213  qc.id = cls | 0x900; unsigned int old_id;
1214  while (true)
1215  {
1216  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL; old_id = qc.id; bool failed = false;
1217  try { std::string hlp = camCtrlHelp(qc, doneids); if (hlp.empty() == false) s->writeString(hlp); }
1218  catch (...) { failed = true; }
1219 
1220  // The camera kernel driver is supposed to pass down the next valid control if the requested one is not
1221  // found, but some drivers do not honor that, so let's move on to the next control manually if needed:
1222  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
1223  if (qc.id == old_id) { ++qc.id; if (qc.id > 100 + (cls | 0x900 | V4L2_CTRL_FLAG_NEXT_CTRL)) break; }
1224  else if (failed) break;
1225  }
1226  }
1227 
1228  return true;
1229  }
1230 
1231  // ----------------------------------------------------------------------------------------------------
1232  if (cmd == "help2")
1233  {
1234  if (itsModule)
1235  {
1236  // Start with the module's commands:
1237  std::stringstream css; itsModule->supportedCommands(css);
1238  s->writeString("MODULE-SPECIFIC COMMANDS:");
1239  s->writeString("");
1240  for (std::string line; std::getline(css, line); /* */) s->writeString(line);
1241  s->writeString("");
1242 
1243  // Now the parameters for that module (and its subs) only:
1244  s->writeString("MODULE PARAMETERS:");
1245  s->writeString("");
1246 
1247  // Keep this in sync with Manager::constructHelpMessage():
1248  std::unordered_map<std::string, // category:description
1249  std::unordered_map<std::string, // --name (type) default=[def]
1250  std::vector<std::pair<std::string, // component name
1251  std::string // current param value
1252  > > > > helplist;
1253  itsModule->populateHelpMessage("", helplist);
1254 
1255  if (helplist.empty())
1256  s->writeString("None.");
1257  else
1258  {
1259  for (auto const & c : helplist)
1260  {
1261  // Print out the category name and description
1262  s->writeString(c.first);
1263 
1264  // Print out the parameter details
1265  for (auto const & n : c.second)
1266  {
1267  std::vector tok = jevois::split(n.first, "[\\r\\n]+");
1268  bool first = true;
1269  for (auto const & t : tok)
1270  {
1271  // Add current value info to the first thing we write (which is name, default, etc)
1272  if (first)
1273  {
1274  auto const & v = n.second;
1275  if (v.size() == 1) // only one component using this param
1276  {
1277  if (v[0].second.empty())
1278  s->writeString(t); // only one comp, and using default val
1279  else
1280  s->writeString(t + " current=[" + v[0].second + ']'); // using non-default val
1281  }
1282  else if (v.size() > 1) // several components using this param with possibly different values
1283  {
1284  std::string sss = t + " current=";
1285  for (auto const & pp : v)
1286  if (pp.second.empty() == false) sss += '[' + pp.first + ':' + pp.second + "] ";
1287  s->writeString(sss);
1288  }
1289  else s->writeString(t); // no non-default value(s) to report
1290 
1291  first = false;
1292  }
1293 
1294  else // just write out the other lines (param description)
1295  s->writeString(t);
1296  }
1297  }
1298  s->writeString("");
1299  }
1300  }
1301  }
1302  else
1303  s->writeString("No module loaded.");
1304 
1305  return true;
1306  }
1307 
1308  // ----------------------------------------------------------------------------------------------------
1309  if (cmd == "info")
1310  {
1311  s->writeString("INFO: JeVois " JEVOIS_VERSION_STRING);
1312  s->writeString("INFO: " + jevois::getSysInfoVersion());
1313  s->writeString("INFO: " + jevois::getSysInfoCPU());
1314  s->writeString("INFO: " + jevois::getSysInfoMem());
1315  if (itsModule) s->writeString("INFO: " + itsCurrentMapping.str());
1316  else s->writeString("INFO: " + jevois::VideoMapping().str());
1317  return true;
1318  }
1319 
1320  // ----------------------------------------------------------------------------------------------------
1321  if (cmd == "setpar")
1322  {
1323  size_t const remidx = rem.find(' ');
1324  if (remidx != rem.npos)
1325  {
1326  std::string const desc = rem.substr(0, remidx);
1327  if (remidx < rem.length())
1328  {
1329  std::string const val = rem.substr(remidx+1);
1330  setParamString(desc, val);
1331  return true;
1332  }
1333  }
1334  errmsg = "Need to provide a parameter name and a parameter value in setpar";
1335  }
1336 
1337  // ----------------------------------------------------------------------------------------------------
1338  if (cmd == "getpar")
1339  {
1340  auto vec = getParamString(rem);
1341  for (auto const & p : vec) s->writeString(p.first + ' ' + p.second);
1342  return true;
1343  }
1344 
1345  // ----------------------------------------------------------------------------------------------------
1346  if (cmd == "setcam")
1347  {
1348  std::istringstream ss(rem); std::string ctrl; int val; ss >> ctrl >> val;
1349  struct v4l2_control c = { }; c.id = camctrlid(ctrl); c.value = val;
1350  itsCamera->setControl(c);
1351  return true;
1352  }
1353 
1354  // ----------------------------------------------------------------------------------------------------
1355  if (cmd == "getcam")
1356  {
1357  struct v4l2_control c = { }; c.id = camctrlid(rem);
1358  itsCamera->getControl(c);
1359  s->writeString(rem + ' ' + std::to_string(c.value));
1360  return true;
1361  }
1362 
1363  // ----------------------------------------------------------------------------------------------------
1364  if (cmd == "setcamreg")
1365  {
1366  if (camreg::get())
1367  {
1368  // Read register and value as strings, then std::stoi to convert to int, supports 0x (and 0 for octal, caution)
1369  std::istringstream ss(rem); std::string reg, val; ss >> reg >> val;
1370  itsCamera->writeRegister(std::stoi(reg, nullptr, 0), std::stoi(val, nullptr, 0));
1371  return true;
1372  }
1373  errmsg = "Access to camera registers is disabled, enable with: setpar camreg true";
1374  }
1375 
1376  // ----------------------------------------------------------------------------------------------------
1377  if (cmd == "getcamreg")
1378  {
1379  if (camreg::get())
1380  {
1381  unsigned int val = itsCamera->readRegister(std::stoi(rem, nullptr, 0));
1382  std::ostringstream os; os << std::hex << val;
1383  s->writeString(os.str());
1384  return true;
1385  }
1386  errmsg = "Access to camera registers is disabled, enable with: setpar camreg true";
1387  }
1388 
1389  // ----------------------------------------------------------------------------------------------------
1390  if (cmd == "listmappings")
1391  {
1392  s->writeString("AVAILABLE VIDEO MAPPINGS:");
1393  s->writeString("");
1394  for (size_t idx = 0; idx < itsMappings.size(); ++idx)
1395  {
1396  std::string idxstr = std::to_string(idx);
1397  if (idxstr.length() < 5) idxstr = std::string(5 - idxstr.length(), ' ') + idxstr; // pad to 5-char long
1398  s->writeString(idxstr + " - " + itsMappings[idx].str());
1399  }
1400  return true;
1401  }
1402 
1403  // ----------------------------------------------------------------------------------------------------
1404  if (cmd == "setmapping")
1405  {
1406  size_t const idx = std::stoi(rem);
1407  bool was_streaming = itsStreaming.load();
1408 
1409  if (was_streaming)
1410  {
1411  errmsg = "Cannot set mapping while streaming: ";
1412  if (itsCurrentMapping.ofmt) errmsg += "Stop your webcam program on the host computer first.";
1413  else errmsg += "Issue a 'streamoff' command first.";
1414  }
1415  else if (idx >= itsMappings.size())
1416  errmsg = "Requested mapping index " + std::to_string(idx) + " out of range [0 .. " +
1417  std::to_string(itsMappings.size()-1) + ']';
1418  else
1419  {
1420  try
1421  {
1422  setFormatInternal(idx);
1423  return true;
1424  }
1425  catch (std::exception const & e) { errmsg = "Error parsing or setting mapping [" + rem + "]: " + e.what(); }
1426  catch (...) { errmsg = "Error parsing or setting mapping [" + rem + ']'; }
1427  }
1428  }
1429 
1430  // ----------------------------------------------------------------------------------------------------
1431  if (cmd == "setmapping2")
1432  {
1433  bool was_streaming = itsStreaming.load();
1434 
1435  if (was_streaming)
1436  {
1437  errmsg = "Cannot set mapping while streaming: ";
1438  if (itsCurrentMapping.ofmt) errmsg += "Stop your webcam program on the host computer first.";
1439  else errmsg += "Issue a 'streamoff' command first.";
1440  }
1441  else
1442  {
1443  try
1444  {
1445  jevois::VideoMapping m; std::istringstream full("NONE 0 0 0.0 " + rem); full >> m;
1446  setFormatInternal(m);
1447  return true;
1448  }
1449  catch (std::exception const & e) { errmsg = "Error parsing or setting mapping [" + rem + "]: " + e.what(); }
1450  catch (...) { errmsg = "Error parsing or setting mapping [" + rem + ']'; }
1451  }
1452  }
1453 
1454  // ----------------------------------------------------------------------------------------------------
1455  if (itsCurrentMapping.ofmt == 0 || itsManualStreamon)
1456  {
1457  if (cmd == "streamon")
1458  {
1459  // keep this in sync with streamOn(), modulo the fact that here we are already locked:
1460  itsCamera->streamOn();
1461  itsGadget->streamOn();
1462  itsStreaming.store(true);
1463  return true;
1464  }
1465 
1466  if (cmd == "streamoff")
1467  {
1468  // keep this in sync with streamOff(), modulo the fact that here we are already locked:
1469  itsGadget->abortStream();
1470  itsCamera->abortStream();
1471 
1472  itsStreaming.store(false);
1473 
1474  itsGadget->streamOff();
1475  itsCamera->streamOff();
1476  return true;
1477  }
1478  }
1479 
1480  // ----------------------------------------------------------------------------------------------------
1481  if (cmd == "ping")
1482  {
1483  s->writeString("ALIVE");
1484  return true;
1485  }
1486 
1487  // ----------------------------------------------------------------------------------------------------
1488  if (cmd == "serlog")
1489  {
1490  sendSerial(rem, true);
1491  return true;
1492  }
1493 
1494  // ----------------------------------------------------------------------------------------------------
1495  if (cmd == "serout")
1496  {
1497  sendSerial(rem, false);
1498  return true;
1499  }
1500 
1501  // ----------------------------------------------------------------------------------------------------
1502 #ifdef JEVOIS_PLATFORM
1503  if (cmd == "usbsd")
1504  {
1505  if (itsStreaming.load())
1506  {
1507  errmsg = "Cannot export microSD over USB while streaming: ";
1508  if (itsCurrentMapping.ofmt) errmsg += "Stop your webcam program on the host computer first.";
1509  else errmsg += "Issue a 'streamoff' command first.";
1510  }
1511  else
1512  {
1513  startMassStorageMode();
1514  return true;
1515  }
1516  }
1517 #endif
1518 
1519  // ----------------------------------------------------------------------------------------------------
1520  if (cmd == "sync")
1521  {
1522  if (std::system("sync")) errmsg = "Disk sync failed";
1523  else return true;
1524  }
1525 
1526  // ----------------------------------------------------------------------------------------------------
1527  if (cmd == "date")
1528  {
1529  std::string dat = jevois::system("/bin/date " + rem);
1530  s->writeString("date now " + dat.substr(0, dat.size()-1)); // skip trailing newline
1531  return true;
1532  }
1533 
1534  // ----------------------------------------------------------------------------------------------------
1535  if (cmd == "runscript")
1536  {
1537  std::string fname;
1538  if (itsModule) fname = itsModule->absolutePath(rem); else fname = rem;
1539 
1540  try { runScriptFromFile(fname, s, true); return true; }
1541  catch (...) { errmsg = "Script execution failed"; }
1542  }
1543 
1544 #ifdef JEVOIS_PLATFORM
1545  // ----------------------------------------------------------------------------------------------------
1546  if (cmd == "restart")
1547  {
1548  s->writeString("Restart command received - bye-bye!");
1549 
1550  if (itsStreaming.load())
1551  s->writeString("ERR Video streaming is on - you should quit your video viewer before rebooting");
1552 
1553  // Turn off the SD storage if it is there:
1554  std::ofstream(JEVOIS_USBSD_SYS).put('\n'); // ignore errors
1555  if (std::system("sync")) s->writeString("ERR Disk sync failed -- IGNORED");
1556 
1557  // Hard reboot:
1558  this->reboot();
1559  return true;
1560  }
1561  // ----------------------------------------------------------------------------------------------------
1562 #else
1563  // ----------------------------------------------------------------------------------------------------
1564  if (cmd == "quit")
1565  {
1566  s->writeString("Quit command received - bye-bye!");
1567  itsGadget->abortStream();
1568  itsCamera->abortStream();
1569  itsStreaming.store(false);
1570  itsGadget->streamOff();
1571  itsCamera->streamOff();
1572  itsRunning.store(false);
1573  return true;
1574  }
1575  // ----------------------------------------------------------------------------------------------------
1576 #endif
1577  }
1578 
1579  // If we make it here, we did not parse the command. If we have an error message, that means we had started parsing
1580  // the command but it was buggy, so let's throw. Otherwise, we just return false to indicate that we did not parse
1581  // this command and maybe it is for the Module:
1582  if (errmsg.size()) throw std::runtime_error("Command error [" + str + "]: " + errmsg);
1583  return false;
1584 }
1585 
1586 // ####################################################################################################
1587 void jevois::Engine::runScriptFromFile(std::string const & filename, std::shared_ptr<jevois::UserInterface> ser,
1588  bool throw_no_file)
1589 {
1590  // itsMtx should be locked by caller
1591 
1592  // Try to find the file:
1593  std::ifstream ifs(filename);
1594  if (!ifs) { if (throw_no_file) LFATAL("Could not open file " << filename); else return; }
1595 
1596  // We need to identify a serial to send any errors to, if none was given to us. Let's use the one in serlog, or, if
1597  // none is specified there, the first available serial:
1598  if (!ser)
1599  {
1600  if (itsSerials.empty()) LFATAL("Need at least one active serial to run script");
1601  switch (serlog::get())
1602  {
1603  case jevois::engine::SerPort::Hard:
1604  for (auto & s : itsSerials) if (s->type() == jevois::UserInterface::Type::Hard) { ser = s; break; }
1605  break;
1606 
1607  case jevois::engine::SerPort::USB:
1608  for (auto & s : itsSerials) if (s->type() == jevois::UserInterface::Type::USB) { ser = s; break; }
1609  break;
1610 
1611  default: break;
1612  }
1613  if (!ser) ser = itsSerials.front();
1614  }
1615 
1616  // Ok, run the script, plowing through any errors:
1617  size_t linenum = 1;
1618  for (std::string line; std::getline(ifs, line); /* */)
1619  {
1620  // Skip comments and empty lines:
1621  if (line.length() == 0 || line[0] == '#') continue;
1622 
1623  // Go and parse that line:
1624  try
1625  {
1626  bool parsed = false;
1627  try { parsed = parseCommand(line, ser); }
1628  catch (std::exception const & e)
1629  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum) + ": " + e.what()); }
1630  catch (...)
1631  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum) + ": Bogus command ["+line+"] ignored"); }
1632 
1633  if (parsed == false)
1634  {
1635  if (itsModule)
1636  {
1637  try { itsModule->parseSerial(line, ser); }
1638  catch (std::exception const & me)
1639  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum) + ": " + me.what()); }
1640  catch (...)
1641  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum)+": Bogus command ["+line+"] ignored"); }
1642  }
1643  else ser->writeString("ERR Unsupported command [" + line + "] and no module");
1644  }
1645  }
1646  catch (...) { jevois::warnAndIgnoreException(); }
1647 
1648  ++linenum;
1649  }
1650 }
#define LDEBUG(msg)
Convenience macro for users to print out console or syslog messages, DEBUG level. ...
Definition: Log.H:155
std::string warnAndIgnoreException()
Convenience function to catch an exception, issue some LERROR (depending on type), and ignore it.
Definition: Log.C:211
float ofps
output frame rate in frames/sec
Definition: VideoMapping.H:46
size_t getVideoMappingIdx(unsigned int iformat, unsigned int iframe, unsigned int interval) const
Get the video mapping index for a given UVC iformat, iframe and interval.
Definition: Engine.C:876
size_t numVideoMappings() const
Return the number of video mappings.
Definition: Engine.C:861
unsigned int uvcformat
USB-UVC format number (1-based)
Definition: VideoMapping.H:53
void drawErrorImage(std::string const &errmsg, RawImage &videoerrimg)
Display an error message into a RawImage.
Definition: Log.C:244
Class to open shared object (.so) files and load functions contained in them.
Definition: DynamicLoader.H:69
Exception-safe wrapper around a raw camera input frame.
Definition: Module.H:56
size_t itsDefaultMappingIdx
Index of default mapping.
Definition: Engine.H:317
std::vector< std::string > setParamString(std::string const &paramdescriptor, std::string const &val)
Set a parameter value, by string.
Definition: Component.C:346
void postInit() override
Override of Manager::postInit()
Definition: Engine.C:349
std::shared_ptr< VideoInput > itsCamera
Our camera.
Definition: Engine.H:321
#define V4L2_CTRL_CLASS_DETECT
Definition: Engine.C:48
void streamOff()
Stop streaming on video from camera, processing, and USB.
Definition: Engine.C:546
void preInit() override
Calls parseCommandLine()
Definition: Manager.C:49
void preInit() override
Override of Manager::preInit()
Definition: Engine.C:338
bool parseCommand(std::string const &str, std::shared_ptr< UserInterface > s)
Parse a user command received over serial port.
Definition: Engine.C:1096
std::unique_ptr< DynamicLoader > itsLoader
Our module loader.
Definition: Engine.H:324
std::atomic< bool > itsStreaming
True when we are streaming video.
Definition: Engine.H:328
Manager of a hierarchy of Component objects.
Definition: Manager.H:73
void streamOn()
Start streaming on video from camera, processing, and USB.
Definition: Engine.C:535
unsigned int ofmt
output pixel format, or 0 for no output over USB
Definition: VideoMapping.H:43
VideoMapping const & findVideoMapping(unsigned int oformat, unsigned int owidth, unsigned int oheight, float oframespersec) const
Find the VideoMapping that has the given output specs, or throw if not found.
Definition: Engine.C:916
#define JEVOIS_TIMED_LOCK(mtx)
Helper macro to create a timed_lock_guard object.
Definition: Log.H:299
#define success()
void invalidate()
Invalidate the image by zero&#39;ing out the pointer to pixel buffer and the dims and format...
Definition: RawImage.C:42
RawImage const & get(bool casync=false) const
Get the next captured camera image.
Definition: Module.C:51
void mainLoop()
Main loop: grab, process, send over USB. Should be called by main application thread.
Definition: Engine.C:686
#define JEVOIS_TRACE(level)
Trace object.
Definition: Log.H:267
std::string modulename
Name of the Module that will process this mapping.
Definition: VideoMapping.H:58
Video output to a movie file, using OpenCV video encoding.
Definition: MovieOutput.H:33
std::string getSysInfoVersion()
Get O.S. version info.
Definition: SysInfo.C:72
void sendSerial(std::string const &str, bool islog=false)
Send a string to all serial ports.
Definition: Engine.C:825
std::string str() const
Convenience function to print out the whole mapping in a human-friendly way.
Definition: VideoMapping.C:87
bool valid() const
Check whether the image has a valid pixel buffer.
Definition: RawImage.C:46
void removeComponent(std::shared_ptr< Comp > &component)
Remove a top-level Component from the Manager, by shared_ptr.
Definition: ManagerImpl.H:100
std::shared_ptr< VideoOutput > itsGadget
Our gadget.
Definition: Engine.H:322
void constructHelpMessage(std::ostream &out) const
Constructs a help message from all parameters in the model, and outputs it to &#39;out&#39;.
Definition: Manager.C:82
#define LERROR(msg)
Convenience macro for users to print out console or syslog messages, ERROR level. ...
Definition: Log.H:193
std::string sopath() const
Return the full absolute path and file name of the module&#39;s .so or .py file.
Definition: VideoMapping.C:30
VideoMapping itsCurrentMapping
Current video mapping, may not match any in itsMappings if setmapping2 used.
Definition: Engine.H:319
static float uvcToFps(unsigned int interval)
Convert from USB/UVC interval to fps.
Definition: VideoMapping.C:45
VideoMapping const & getVideoMapping(size_t idx) const
Allow access to our video mappings which are parsed from file at construction.
Definition: Engine.C:867
~Engine()
Destructor.
Definition: Engine.C:465
std::string getSysInfoCPU()
Get CPU info: frequency, thermal, load.
Definition: SysInfo.C:38
JeVois camera driver class - grabs frames from a Video4Linux camera sensor.
Definition: Camera.H:64
void logSetEngine(Engine *e)
Set an Engine so that all log messages will be forwarded to its serial ports.
Definition: Log.C:114
Simple struct to hold video mapping definitions for the processing Engine.
Definition: VideoMapping.H:41
VideoMapping const & getCurrentVideoMapping() const
Get the current video mapping.
Definition: Engine.C:855
std::atomic< bool > itsStopMainLoop
Flag used to stop the main loop.
Definition: Engine.H:329
void onParamChange(engine::cameradev const &param, std::string const &newval)
Parameter callback.
bool stringStartsWith(std::string const &str, std::string const &prefix)
Return true if str starts with prefix (including if both strings are equal)
Definition: Utils.C:137
std::string fccstr(unsigned int fcc)
Convert a V4L2 four-cc code (V4L2_PIX_FMT_...) to a 4-char string.
Definition: Utils.C:37
unsigned int uvcframe
USB UVC frame number (1-based)
Definition: VideoMapping.H:54
std::vector< VideoMapping > const itsMappings
All our mappings from videomappings.cfg.
Definition: Engine.H:318
JeVois gadget driver - exposes a uvcvideo interface to host computer connected over USB...
Definition: Gadget.H:65
#define LFATAL(msg)
Convenience macro for users to print out console or syslog messages, FATAL level. ...
Definition: Log.H:212
Movie input, can be used as a replacement for Camera to debug algorithms using a fixed video sequence...
Definition: MovieInput.H:35
size_t getDefaultVideoMappingIdx() const
Allow access to the default video mapping index.
Definition: Engine.C:911
std::istream & setParamsFromStream(std::istream &is, std::string const &absfile)
Set some parameters from an open stream.
Definition: Component.C:449
Video output to local screen.
Definition: VideoDisplay.H:34
Wrapper module to allow users to develop new modules written in Python.
Definition: PythonModule.H:143
std::vector< std::pair< std::string, std::string > > getParamString(std::string const &paramdescriptor) const
Get a parameter value, by string.
Definition: Component.C:373
void runScriptFromFile(std::string const &filename, std::shared_ptr< UserInterface > ser, bool throw_no_file)
Run a script from file.
Definition: Engine.C:1587
std::string to_string(T const &val)
Convert from type to string.
Definition: UtilsImpl.H:51
bool match(unsigned int oformat, unsigned int owidth, unsigned int oheight, float oframespersec) const
Return true if this VideoMapping&#39;s output format is a match to the given output parameters.
Definition: VideoMapping.C:302
std::timed_mutex itsMtx
Mutex to protect our internals.
Definition: Engine.H:331
Exception-safe wrapper around a raw image to be sent over USB.
Definition: Module.H:144
VideoMapping const & getDefaultVideoMapping() const
Allow access to the default video mapping.
Definition: Engine.C:907
bool ispython
True if the module is written in Python; affects behavior of sopath() only.
Definition: VideoMapping.H:60
std::string system(std::string const &cmd)
Execute a command and grab stdout output to a string.
Definition: Utils.C:211
void postInit() override
Checks for the –help flag.
Definition: Manager.C:58
std::string getSysInfoMem()
Get memory info.
Definition: SysInfo.C:64
void setFormat(size_t idx)
Callback for when the user selects a new output video format.
Definition: Engine.C:567
#define LINFO(msg)
Convenience macro for users to print out console or syslog messages, INFO level.
Definition: Log.H:176
std::atomic< bool > itsRunning
True when we are running.
Definition: Engine.H:327
std::shared_ptr< Module > itsModule
Our current module.
Definition: Engine.H:325
No-op VideoOutput derivative for when there is no video output.
Engine(std::string const &instance)
Constructor.
Definition: Engine.C:200
std::vector< std::string > split(std::string const &input, std::string const &regex="\+")
Split string into vector of tokens using a regex to specify what to split on; default regex splits by...
Definition: Utils.C:113
#define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE