JeVois  1.8
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), itsFrame(0), itsNumSerialSent(0)
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), itsFrame(0), itsNumSerialSent(0)
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  multicam::freeze();
365  quietcmd::freeze();
366  python::freeze();
367 
368  // Grab the log messages, itsSerials is not going to change anymore now that the serial params are frozen:
369  jevois::logSetEngine(this);
370 
371  // Get python going, we need to do this here to avoid segfaults on platform when instantiating our first python
372  // module. This likely has to do with the fact that the python core is not very thread-safe, and setFormatInternal()
373  // in Engine, which instantiates python modules, will indeed be invoked from a different thread (the one that receives
374  // USB UVC events). Have a look at Python Thread State, Python Gobal Interpreter Lock, etc if interested:
375  if (python::get())
376  {
377  LINFO("Initalizing Python...");
378  jevois::pythonModuleSetEngine(this);
379  }
380 
381  // Instantiate a camera: If device names starts with "/dev/v", assume a hardware camera, otherwise a movie file:
382  std::string const camdev = cameradev::get();
383  if (jevois::stringStartsWith(camdev, "/dev/v"))
384  {
385  LINFO("Starting camera device " << camdev);
386 
387 #ifdef JEVOIS_PLATFORM
388  // Set turbo mode or not:
389  std::ofstream ofs("/sys/module/vfe_v4l2/parameters/turbo");
390  if (ofs.is_open())
391  {
392  if (itsTurbo) ofs << "1" << std::endl; else ofs << "0" << std::endl;
393  ofs.close();
394  }
395  else LERROR("Could not access VFE turbo parameter -- IGNORED");
396 #endif
397 
398  // Now instantiate the camera:
399  itsCamera.reset(new jevois::Camera(camdev, cameranbuf::get()));
400 
401 #ifndef JEVOIS_PLATFORM
402  // No need to confuse people with a non-working camreg param:
403  camreg::set(false);
404  camreg::freeze();
405 #endif
406  }
407  else
408  {
409  LINFO("Using movie input " << camdev << " -- issue a 'streamon' to start processing.");
410  itsCamera.reset(new jevois::MovieInput(camdev, cameranbuf::get()));
411 
412  // No need to confuse people with a non-working camreg param:
413  camreg::set(false);
414  camreg::freeze();
415  }
416 
417  // Instantiate a USB gadget: Note: it will want to access the mappings. If the user-selected video mapping has no usb
418  // out, do not instantiate a gadget:
419  int midx = videomapping::get();
420 
421  // The videomapping parameter is now disabled, users should use the 'setmapping' command once running:
422  videomapping::freeze();
423 
424  if (midx >= int(itsMappings.size()))
425  { LERROR("Mapping index " << midx << " out of range -- USING DEFAULT"); midx = -1; }
426 
427  if (midx < 0) midx = itsDefaultMappingIdx;
428 
429  // Always instantiate a gadget even if not used right now, may be used later:
430  std::string const gd = gadgetdev::get();
431  if (gd == "None")
432  {
433  LINFO("Using no USB video output.");
434  // No USB output and no display, useful for benchmarking only:
435  itsGadget.reset(new jevois::VideoOutputNone());
436  itsManualStreamon = true;
437  }
438  else if (jevois::stringStartsWith(gd, "/dev/"))
439  {
440  LINFO("Loading USB video driver " << gd);
441  // USB gadget driver:
442  itsGadget.reset(new jevois::Gadget(gd, itsCamera.get(), this, gadgetnbuf::get(), multicam::get()));
443  }
444  else if (gd.empty() == false)
445  {
446  LINFO("Saving output video to file " << gd);
447  // Non-empty filename, save to file:
448  itsGadget.reset(new jevois::MovieOutput(gd));
449  itsManualStreamon = true;
450  }
451  else
452  {
453  LINFO("Using display for video output");
454  // Local video display, for use on a host desktop:
455  itsGadget.reset(new jevois::VideoDisplay("jevois", gadgetnbuf::get()));
456  itsManualStreamon = true;
457  }
458 
459  // We are ready to run:
460  itsRunning.store(true);
461 
462  // Set initial format:
463  try { setFormat(midx); } catch (...) { jevois::warnAndIgnoreException(); }
464 
465  // Run init script:
467  runScriptFromFile(JEVOIS_ENGINE_INIT_SCRIPT, nullptr, false);
468 }
469 
470 // ####################################################################################################
472 {
473  JEVOIS_TRACE(1);
474 
475  // Turn off stream if it is on:
476  streamOff();
477 
478  // Tell our run() thread to finish up:
479  itsRunning.store(false);
480 
481 #ifdef JEVOIS_PLATFORM
482  // Tell checkMassStorage() thread to finish up:
483  itsCheckingMassStorage.store(false);
484 #endif
485 
486  // Nuke our module as soon as we can, hopefully soon now that we turned off streaming and running:
487  {
490  itsModule.reset();
491 
492  // Gone, nuke the loader now:
493  itsLoader.reset();
494  }
495 
496  // Because we passed the camera as a raw pointer to the gadget, nuke the gadget first and then the camera:
497  itsGadget.reset();
498  itsCamera.reset();
499 
500 #ifdef JEVOIS_PLATFORM
501  // Will block until the checkMassStorage() thread completes:
502  if (itsCheckMassStorageFut.valid())
503  try { itsCheckMassStorageFut.get(); } catch (...) { jevois::warnAndIgnoreException(); }
504 #endif
505 
506  // Things should be quiet now, unhook from the logger (this call is not strictly thread safe):
507  jevois::logSetEngine(nullptr);
508 }
509 
510 // ####################################################################################################
511 #ifdef JEVOIS_PLATFORM
512 void jevois::Engine::checkMassStorage()
513 {
514  itsCheckingMassStorage.store(true);
515 
516  while (itsCheckingMassStorage.load())
517  {
518  // Check from the mass storage gadget (with JeVois extension) whether the virtual USB drive is mounted by the
519  // host. If currently in mass storage mode and the host just ejected the virtual flash drive, resume normal
520  // operation. If not in mass-storage mode and the host mounted it, enter mass-storage mode (may happen if
521  // /boot/usbsdauto was selected):
522  std::ifstream ifs("/sys/devices/platform/sunxi_usb_udc/gadget/lun0/mass_storage_in_use");
523  if (ifs.is_open())
524  {
525  int inuse; ifs >> inuse;
526  if (itsMassStorageMode.load())
527  {
528  if (inuse == 0) stopMassStorageMode();
529  }
530  else
531  {
532  if (inuse) { JEVOIS_TIMED_LOCK(itsMtx); startMassStorageMode(); }
533  }
534  }
535  std::this_thread::sleep_for(std::chrono::milliseconds(500));
536  }
537 }
538 #endif
539 
540 // ####################################################################################################
542 {
543  JEVOIS_TRACE(2);
544 
546  itsCamera->streamOn();
547  itsGadget->streamOn();
548  itsStreaming.store(true);
549 }
550 
551 // ####################################################################################################
553 {
554  JEVOIS_TRACE(2);
555 
556  // First, tell both the camera and gadget to abort streaming, this will make get()/done()/send() throw:
557  itsGadget->abortStream();
558  itsCamera->abortStream();
559 
560  // Stop the main loop, which will flip itsStreaming to false and will make it easier for us to lock itsMtx:
561  LDEBUG("Stopping main loop...");
562  itsStopMainLoop.store(true);
563  while (itsStopMainLoop.load() && itsRunning.load()) std::this_thread::sleep_for(std::chrono::milliseconds(10));
564  LDEBUG("Main loop stopped.");
565 
566  // Lock up and stream off:
568  itsGadget->streamOff();
569  itsCamera->streamOff();
570 }
571 
572 // ####################################################################################################
574 {
575  JEVOIS_TRACE(2);
576 
577  LDEBUG("Set format number " << idx << " start...");
578 
579  if (idx >= itsMappings.size())
580  LFATAL("Requested mapping index " << idx << " out of range [0 .. " << itsMappings.size()-1 << ']');
581 
583  setFormatInternal(idx);
584  LDEBUG("Set format number " << idx << " done");
585 }
586 
587 // ####################################################################################################
588 void jevois::Engine::setFormatInternal(size_t idx)
589 {
590  // itsMtx should be locked by caller, idx should be valid:
591  JEVOIS_TRACE(2);
592 
593  jevois::VideoMapping const & m = itsMappings[idx];
594  setFormatInternal(m);
595 }
596 
597 // ####################################################################################################
598 void jevois::Engine::setFormatInternal(jevois::VideoMapping const & m, bool reload)
599 {
600  // itsMtx should be locked by caller, idx should be valid:
601  JEVOIS_TRACE(2);
602 
603  LINFO(m.str());
604 
605 #ifdef JEVOIS_PLATFORM
606  if (itsMassStorageMode.load())
607  LFATAL("Cannot setup video streaming while in mass-storage mode. Eject the USB drive on your host computer first.");
608 #endif
609 
610  // Set the format at the camera and gadget levels, unless we are just reloading:
611  if (reload == false)
612  {
613  itsCamera->setFormat(m);
614  if (m.ofmt) itsGadget->setFormat(m);
615  }
616 
617  // Keep track of our current mapping:
618  itsCurrentMapping = m;
619 
620  // Nuke the processing module, if any, so we can also safely nuke the loader. We always nuke the module instance so we
621  // won't have any issues with latent state even if we re-use the same module but possibly with different input
622  // image resolution, etc:
623  if (itsModule)
624  try { removeComponent(itsModule); itsModule.reset(); } catch (...) { jevois::warnAndIgnoreException(); }
625 
626  // Reset our master frame counter on each module load:
627  itsFrame.store(0);
628 
629  // Instantiate the module. If the constructor throws, code is bogus, for example some syntax error in a python module
630  // that is detected at load time. We get the exception's error message for later display into video frames in the main
631  // loop, and mark itsModuleConstructionError:
632  try
633  {
634  // For python modules, we do not need a loader, we just instantiate our special python wrapper module instead:
635  std::string const sopath = m.sopath();
636  if (m.ispython)
637  {
638  if (python::get() == false) LFATAL("Python disabled, delete BOOT:nopython and restart to enable python");
639 
640  // Instantiate the python wrapper:
641  itsLoader.reset();
642  itsModule.reset(new jevois::PythonModule(m));
643  }
644  else
645  {
646  // C++ compiled module. We can re-use the same loader and avoid closing the .so if we will use the same module:
647  if (itsLoader.get() == nullptr || itsLoader->sopath() != sopath)
648  {
649  // Nuke our previous loader and free its resources if needed, then start a new loader:
650  LINFO("Instantiating dynamic loader for " << sopath);
651  itsLoader.reset(new jevois::DynamicLoader(sopath, true));
652  }
653 
654  // Check version match:
655  auto version_major = itsLoader->load<int()>(m.modulename + "_version_major");
656  auto version_minor = itsLoader->load<int()>(m.modulename + "_version_minor");
657  if (version_major() != JEVOIS_VERSION_MAJOR || version_minor() != JEVOIS_VERSION_MINOR)
658  LERROR("Module " << m.modulename << " in file " << sopath << " was build for JeVois v" << version_major() << '.'
659  << version_minor() << ", but running framework is v" << JEVOIS_VERSION_STRING << " -- TRYING ANYWAY");
660 
661  // Instantiate the new module:
662  auto create = itsLoader->load<std::shared_ptr<jevois::Module>(std::string const &)>(m.modulename + "_create");
663  itsModule = create(m.modulename); // Here we just use the class name as instance name
664  }
665 
666  // Add the module as a component to us. Keep this code in sync with Manager::addComponent():
667  {
668  // Lock up so we guarantee the instance name does not get robbed as we add the sub:
669  boost::unique_lock<boost::shared_mutex> ulck(itsSubMtx);
670 
671  // Then add it as a sub-component to us:
672  itsSubComponents.push_back(itsModule);
673  itsModule->itsParent = this;
674  itsModule->setPath(sopath.substr(0, sopath.rfind('/')));
675  }
676 
677  // Bring it to our runstate and load any extra params. NOTE: Keep this in sync with Component::init():
678  if (itsInitialized) itsModule->runPreInit();
679 
680  std::string const paramcfg = itsModule->absolutePath(JEVOIS_MODULE_PARAMS_FILENAME);
681  std::ifstream ifs(paramcfg); if (ifs.is_open()) itsModule->setParamsFromStream(ifs, paramcfg);
682 
683  if (itsInitialized) { itsModule->setInitialized(); itsModule->runPostInit(); }
684 
685  // And finally run any config script:
686  runScriptFromFile(itsModule->absolutePath(JEVOIS_MODULE_SCRIPT_FILENAME), nullptr, false);
687 
688  LINFO("Module [" << m.modulename << "] loaded, initialized, and ready.");
689  itsModuleConstructionError.clear();
690  }
691  catch (...)
692  {
693  itsModuleConstructionError = jevois::warnAndIgnoreException();
694  if (itsModule) try { removeComponent(itsModule); itsModule.reset(); } catch (...) { }
695  LERROR("Module [" << m.modulename << "] startup error and not operational.");
696  }
697 }
698 
699 // ####################################################################################################
701 {
702  JEVOIS_TRACE(2);
703 
704  std::string pfx; // optional command prefix
705 
706  // Announce that we are ready to the hardware serial port, if any. Do not use sendSerial() here so we always issue
707  // this message irrespectively of the user serial preferences:
708  for (auto & s : itsSerials)
709  if (s->instanceName() == "serial")
710  try { s->writeString("INF READY JEVOIS " JEVOIS_VERSION_STRING); }
711  catch (...) { jevois::warnAndIgnoreException(); }
712 
713  while (itsRunning.load())
714  {
715  bool dosleep = true;
716 
717  if (itsStreaming.load())
718  {
719  // Lock up while we use the module:
721 
722  if (itsModule)
723  {
724  // We have a module ready for action. Call its process function and handle any exceptions:
725  try
726  {
727  if (itsCurrentMapping.ofmt) // Process with USB outputs:
728  itsModule->process(jevois::InputFrame(itsCamera, itsTurbo),
729  jevois::OutputFrame(itsGadget, itsVideoErrors.load() ? &itsVideoErrorImage : nullptr));
730  else // Process with no USB outputs:
731  itsModule->process(jevois::InputFrame(itsCamera, itsTurbo));
732  dosleep = false;
733  }
734  catch (...)
735  {
736  // Report exceptions to video if desired: We have to be extra careful here because the exception might have
737  // been called by the input frame (camera not streaming) or the output frame (gadget not streaming), in
738  // addition to exceptions thrown by the module:
739  if (itsCurrentMapping.ofmt && itsVideoErrors.load())
740  {
741  try
742  {
743  // If the module threw before get() or after send() on the output frame, get a buffer from the gadget:
744  if (itsVideoErrorImage.valid() == false)
745  itsGadget->get(itsVideoErrorImage); // could throw when streamoff
746 
747  // Report module exception to serlog and get it back as a string:
748  std::string errstr = jevois::warnAndIgnoreException();
749 
750  // Draw the error message into our video frame:
751  jevois::drawErrorImage(errstr, itsVideoErrorImage);
752  }
753  catch (...) { jevois::warnAndIgnoreException(); }
754 
755  try
756  {
757  // Send the error image over USB:
758  if (itsVideoErrorImage.valid()) itsGadget->send(itsVideoErrorImage); // could throw if gadget stream off
759  }
760  catch (...) { jevois::warnAndIgnoreException(); }
761 
762  // Invalidate the error image so it is clean for the next frame:
763  itsVideoErrorImage.invalidate();
764  }
765  else
766  {
767  // Report module exception to serlog, and ignore:
769  }
770  }
771  // Increment our master frame counter
772  ++ itsFrame;
773  itsNumSerialSent.store(0);
774  }
775  else
776  {
777  // No module. If we have a module construction error, render it to an image and stream it over USB now (if we
778  // are doing USB and we want to see errors in the video stream):
779  if (itsCurrentMapping.ofmt && itsVideoErrors.load())
780  try
781  {
782  // Get an output image, draw error message, and send to host:
783  itsGadget->get(itsVideoErrorImage);
784  jevois::drawErrorImage(itsModuleConstructionError, itsVideoErrorImage);
785  itsGadget->send(itsVideoErrorImage);
786 
787  // Also get one camera frame to avoid accumulation of stale buffers:
788  (void)jevois::InputFrame(itsCamera, itsTurbo).get();
789  }
790  catch (...) { jevois::warnAndIgnoreException(); }
791  }
792  }
793 
794  if (itsStopMainLoop.load())
795  {
796  itsStreaming.store(false);
797  LDEBUG("-- Main loop stopped --");
798  itsStopMainLoop.store(false);
799  }
800 
801  if (dosleep)
802  {
803  LDEBUG("No processing module loaded or not streaming... Sleeping...");
804  std::this_thread::sleep_for(std::chrono::milliseconds(50));
805  }
806 
807  // Serial input handling. Note that readSome() and writeString() on the serial could throw. The code below is
808  // organized to catch all other exceptions, except for those, which are caught here at the first try level:
809  for (auto & s : itsSerials)
810  {
811  try
812  {
813  std::string str; bool parsed = false; bool success = false;
814 
815  if (s->readSome(str))
816  {
818 
819 
820  // If the command starts with our hidden command prefix, set the prefix, otherwise clear it:
821  if (jevois::stringStartsWith(str, JEVOIS_JVINV_PREFIX))
822  {
823  pfx = JEVOIS_JVINV_PREFIX;
824  str = str.substr(pfx.length());
825  }
826  else pfx.clear();
827 
828  // Try to execute this command. If the command is for us (e.g., set a parameter) and is correct,
829  // parseCommand() will return true; if it is for us but buggy, it will throw. If it is not recognized by us,
830  // it will return false and we should try sending it to the Module:
831  try { parsed = parseCommand(str, s, pfx); success = parsed; }
832  catch (std::exception const & e)
833  { s->writeString(pfx, std::string("ERR ") + e.what()); parsed = true; }
834  catch (...)
835  { s->writeString(pfx, "ERR Unknown error"); parsed = true; }
836 
837  if (parsed == false)
838  {
839  if (itsModule)
840  {
841  // Note: prefixing is currently not supported for modules, it is for the Engine only
842  try { itsModule->parseSerial(str, s); success = true; }
843  catch (std::exception const & me) { s->writeString(pfx, std::string("ERR ") + me.what()); }
844  catch (...) { s->writeString(pfx, "ERR Command [" + str + "] not recognized by Engine or Module"); }
845  }
846  else s->writeString(pfx, "ERR Unsupported command [" + str + "] and no module");
847  }
848 
849  // If success, let user know:
850  if (success && quietcmd::get() == false) s->writeString(pfx, "OK");
851  }
852  }
853  catch (...) { jevois::warnAndIgnoreException(); }
854  }
855  }
856 }
857 
858 // ####################################################################################################
859 void jevois::Engine::sendSerial(std::string const & str, bool islog)
860 {
861  // If not a log message, we may want to limit the number of serout messages that a module sends on each frame:
862  size_t slim = serlimit::get();
863  if (islog == false && slim)
864  {
865  if (itsNumSerialSent.load() >= slim) return; // limit reached, message dropped
866  ++itsNumSerialSent; // increment number of messages sent. It is reset in the main loop on each new frame.
867  }
868 
869  // Decide where to send this message based on the value of islog:
870  jevois::engine::SerPort p = islog ? serlog::get() : serout::get();
871 
872  switch (p)
873  {
874  case jevois::engine::SerPort::None:
875  break; // Nothing to send
876 
877  case jevois::engine::SerPort::All:
878  for (auto & s : itsSerials)
879  try { s->writeString(str); } catch (...) { jevois::warnAndIgnoreException(); }
880  break;
881 
882  case jevois::engine::SerPort::Hard:
883  for (auto & s : itsSerials)
884  if (s->type() == jevois::UserInterface::Type::Hard)
885  try { s->writeString(str); } catch (...) { jevois::warnAndIgnoreException(); }
886  break;
887 
888  case jevois::engine::SerPort::USB:
889  for (auto & s : itsSerials)
890  if (s->type() == jevois::UserInterface::Type::USB)
891  try { s->writeString(str); } catch (...) { jevois::warnAndIgnoreException(); }
892  break;
893  }
894 }
895 
896 // ####################################################################################################
898 { return itsFrame; }
899 
900 // ####################################################################################################
902 {
903  return itsCurrentMapping;
904 }
905 
906 // ####################################################################################################
908 {
909  return itsMappings.size();
910 }
911 
912 // ####################################################################################################
914 {
915  if (idx >= itsMappings.size())
916  LFATAL("Index " << idx << " out of range [0 .. " << itsMappings.size()-1 << ']');
917 
918  return itsMappings[idx];
919 }
920 
921 // ####################################################################################################
922 size_t jevois::Engine::getVideoMappingIdx(unsigned int iformat, unsigned int iframe, unsigned int interval) const
923 {
924  // If the iformat or iframe is zero, that's probably a probe for the default mode, so return it:
925  if (iformat == 0 || iframe == 0) return itsDefaultMappingIdx;
926 
927  // If interval is zero, probably a driver trying to probe for our default interval, so return the first available one;
928  // otherwise try to find the desired interval and return the corresponding mapping:
929  if (interval)
930  {
931  float const fps = jevois::VideoMapping::uvcToFps(interval);
932  size_t idx = 0;
933 
934  for (jevois::VideoMapping const & m : itsMappings)
935  if (m.uvcformat == iformat && m.uvcframe == iframe && std::fabs(m.ofps - fps) < 0.1F) return idx;
936  else ++idx;
937 
938  LFATAL("No video mapping for iformat=" << iformat <<", iframe=" << iframe << ", interval=" << interval);
939  }
940  else
941  {
942  size_t idx = 0;
943 
944  for (jevois::VideoMapping const & m : itsMappings)
945  if (m.uvcformat == iformat && m.uvcframe == iframe) return idx;
946  else ++idx;
947 
948  LFATAL("No video mapping for iformat=" << iformat <<", iframe=" << iframe << ", interval=" << interval);
949  }
950 }
951 
952 // ####################################################################################################
955 
956 // ####################################################################################################
958 { return itsDefaultMappingIdx; }
959 
960 // ####################################################################################################
961 jevois::VideoMapping const &
962 jevois::Engine::findVideoMapping(unsigned int oformat, unsigned int owidth, unsigned int oheight,
963  float oframespersec) const
964 {
965  for (jevois::VideoMapping const & m : itsMappings)
966  if (m.match(oformat, owidth, oheight, oframespersec)) return m;
967 
968  LFATAL("Could not find mapping for output format " << jevois::fccstr(oformat) << ' ' <<
969  owidth << 'x' << oheight << " @ " << oframespersec << " fps");
970 }
971 
972 // ####################################################################################################
973 std::string jevois::Engine::camctrlname(int id, char const * longname) const
974 {
975  for (size_t i = 0; i < sizeof camcontrols / sizeof camcontrols[0]; ++i)
976  if (camcontrols[i].id == id) return camcontrols[i].shortname;
977 
978  // Darn, this control is not in our list, probably something exotic. Compute a name from the control's long name:
979  return abbreviate(longname);
980 }
981 
982 // ####################################################################################################
983 int jevois::Engine::camctrlid(std::string const & shortname)
984 {
985  for (size_t i = 0; i < sizeof camcontrols / sizeof camcontrols[0]; ++i)
986  if (shortname.compare(camcontrols[i].shortname) == 0) return camcontrols[i].id;
987 
988  // Not in our list, all right, let's find it then in the camera:
989  struct v4l2_queryctrl qc = { };
990  for (int cls = V4L2_CTRL_CLASS_USER; cls <= V4L2_CTRL_CLASS_DETECT; cls += 0x10000)
991  {
992  // Enumerate all controls in this class. Looks like there is some spillover between V4L2 classes in the V4L2
993  // enumeration process, we end up with duplicate controls if we try to enumerate all the classes. Hence the
994  // doneids set to keep track of the ones already reported:
995  qc.id = cls | 0x900;
996  while (true)
997  {
998  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL; unsigned int old_id = qc.id; bool failed = false;
999  try
1000  {
1001  itsCamera->queryControl(qc);
1002  if (abbreviate(reinterpret_cast<char const *>(qc.name)) == shortname) return qc.id;
1003  }
1004  catch (...) { failed = true; }
1005 
1006  // With V4L2_CTRL_FLAG_NEXT_CTRL, the camera kernel driver is supposed to pass down the next valid control if
1007  // the requested one is not found, but some drivers do not honor that, so let's move on to the next control
1008  // manually if needed:
1009  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
1010  if (qc.id == old_id) { ++qc.id; if (qc.id > 100 + (cls | 0x900 | V4L2_CTRL_FLAG_NEXT_CTRL)) break; }
1011  else if (failed) break;
1012  }
1013  }
1014 
1015  LFATAL("Could not find control [" << shortname << "] in the camera");
1016 }
1017 
1018 // ####################################################################################################
1019 std::string jevois::Engine::camCtrlHelp(struct v4l2_queryctrl & qc, std::set<int> & doneids)
1020 {
1021  // See if we have this control:
1022  itsCamera->queryControl(qc);
1023  qc.id &= ~V4L2_CTRL_FLAG_NEXT_CTRL;
1024 
1025  // If we have already done this control, just return an empty string:
1026  if (doneids.find(qc.id) != doneids.end()) return std::string(); else doneids.insert(qc.id);
1027 
1028  // Control exists, let's also get its current value:
1029  struct v4l2_control ctrl = { }; ctrl.id = qc.id;
1030  itsCamera->getControl(ctrl);
1031 
1032  // Print out some description depending on control type:
1033  std::ostringstream ss;
1034  ss << "- " << camctrlname(qc.id, reinterpret_cast<char const *>(qc.name));
1035 
1036  switch (qc.type)
1037  {
1038  case V4L2_CTRL_TYPE_INTEGER:
1039  ss << " [int] min=" << qc.minimum << " max=" << qc.maximum << " step=" << qc.step
1040  << " def=" << qc.default_value << " curr=" << ctrl.value;
1041  break;
1042 
1043  //case V4L2_CTRL_TYPE_INTEGER64:
1044  //ss << " [int64] value=" << ctrl.value64;
1045  //break;
1046 
1047  //case V4L2_CTRL_TYPE_STRING:
1048  //ss << " [str] min=" << qc.minimum << " max=" << qc.maximum << " step=" << qc.step
1049  // << " curr=" << ctrl.string;
1050  //break;
1051 
1052  case V4L2_CTRL_TYPE_BOOLEAN:
1053  ss << " [bool] default=" << qc.default_value << " curr=" << ctrl.value;
1054  break;
1055 
1056  // This one is not supported by the older kernel on platform:
1057  //case V4L2_CTRL_TYPE_INTEGER_MENU:
1058  //ss << " [intmenu] min=" << qc.minimum << " max=" << qc.maximum
1059  // << " def=" << qc.default_value << " curr=" << ctrl.value;
1060  //break;
1061 
1062  case V4L2_CTRL_TYPE_BUTTON:
1063  ss << " [button]";
1064  break;
1065 
1066  case V4L2_CTRL_TYPE_BITMASK:
1067  ss << " [bitmask] max=" << qc.maximum << " def=" << qc.default_value << " curr=" << ctrl.value;
1068  break;
1069 
1070  case V4L2_CTRL_TYPE_MENU:
1071  {
1072  struct v4l2_querymenu querymenu = { };
1073  querymenu.id = qc.id;
1074  ss << " [menu] values ";
1075  for (querymenu.index = qc.minimum; querymenu.index <= (unsigned int)qc.maximum; ++querymenu.index)
1076  {
1077  try { itsCamera->queryMenu(querymenu); } catch (...) { strcpy((char *)(querymenu.name), "fixme"); }
1078  ss << querymenu.index << ':' << querymenu.name << ' ';
1079  }
1080  ss << "curr=" << ctrl.value;
1081  }
1082  break;
1083 
1084  default:
1085  ss << "[unknown type]";
1086  }
1087 
1088  if (qc.flags & V4L2_CTRL_FLAG_DISABLED) ss << " [DISABLED]";
1089 
1090  return ss.str();
1091 }
1092 
1093 // ####################################################################################################
1094 std::string jevois::Engine::camCtrlInfo(struct v4l2_queryctrl & qc, std::set<int> & doneids)
1095 {
1096  // See if we have this control:
1097  itsCamera->queryControl(qc);
1098  qc.id &= ~V4L2_CTRL_FLAG_NEXT_CTRL;
1099 
1100  // If we have already done this control, just return an empty string:
1101  if (doneids.find(qc.id) != doneids.end()) return std::string(); else doneids.insert(qc.id);
1102 
1103  // Control exists, let's also get its current value:
1104  struct v4l2_control ctrl = { }; ctrl.id = qc.id;
1105  itsCamera->getControl(ctrl);
1106 
1107  // Print out some description depending on control type:
1108  std::ostringstream ss;
1109  ss << camctrlname(qc.id, reinterpret_cast<char const *>(qc.name));
1110 
1111  if (qc.flags & V4L2_CTRL_FLAG_DISABLED) ss << " D ";
1112 
1113  switch (qc.type)
1114  {
1115  case V4L2_CTRL_TYPE_INTEGER:
1116  ss << " I " << qc.minimum << ' ' << qc.maximum << ' ' << qc.step
1117  << ' ' << qc.default_value << ' ' << ctrl.value;
1118  break;
1119 
1120  //case V4L2_CTRL_TYPE_INTEGER64:
1121  //ss << " J " << ctrl.value64;
1122  //break;
1123 
1124  //case V4L2_CTRL_TYPE_STRING:
1125  //ss << " S " << qc.minimum << ' ' << qc.maximum << ' ' << qc.step << ' ' << ctrl.string;
1126  //break;
1127 
1128  case V4L2_CTRL_TYPE_BOOLEAN:
1129  ss << " B " << qc.default_value << ' ' << ctrl.value;
1130  break;
1131 
1132  // This one is not supported by the older kernel on platform:
1133  //case V4L2_CTRL_TYPE_INTEGER_MENU:
1134  //ss << " N " << qc.minimum << ' ' << qc.maximum << ' ' << qc.default_value << ' ' << ctrl.value;
1135  //break;
1136 
1137  case V4L2_CTRL_TYPE_BUTTON:
1138  ss << " U";
1139  break;
1140 
1141  case V4L2_CTRL_TYPE_BITMASK:
1142  ss << " K " << qc.maximum << ' ' << qc.default_value << ' ' << ctrl.value;
1143  break;
1144 
1145  case V4L2_CTRL_TYPE_MENU:
1146  {
1147  struct v4l2_querymenu querymenu = { };
1148  querymenu.id = qc.id;
1149  ss << " M " << qc.default_value << ' ' << ctrl.value;
1150  for (querymenu.index = qc.minimum; querymenu.index <= (unsigned int)qc.maximum; ++querymenu.index)
1151  {
1152  try { itsCamera->queryMenu(querymenu); } catch (...) { strcpy((char *)(querymenu.name), "fixme"); }
1153  ss << ' ' << querymenu.index << ':' << querymenu.name << ' ';
1154  }
1155  }
1156  break;
1157 
1158  default:
1159  ss << 'X';
1160  }
1161 
1162  return ss.str();
1163 }
1164 
1165 #ifdef JEVOIS_PLATFORM
1166 // ####################################################################################################
1167 void jevois::Engine::startMassStorageMode()
1168 {
1169  // itsMtx must be locked by caller
1170 
1171  if (itsMassStorageMode.load()) { LERROR("Already in mass-storage mode -- IGNORED"); return; }
1172 
1173  // Nuke any module and loader so we have nothing loaded that uses /jevois:
1174  if (itsModule) { removeComponent(itsModule); itsModule.reset(); }
1175  if (itsLoader) itsLoader.reset();
1176 
1177  // Unmount /jevois:
1178  if (std::system("sync")) LERROR("Disk sync failed -- IGNORED");
1179  if (std::system("mount -o remount,ro /jevois")) LERROR("Failed to remount /jevois read-only -- IGNORED");
1180 
1181  // Now set the backing partition in mass-storage gadget:
1182  std::ofstream ofs(JEVOIS_USBSD_SYS);
1183  if (ofs.is_open() == false) LFATAL("Cannot setup mass-storage backing file to " << JEVOIS_USBSD_SYS);
1184  ofs << JEVOIS_USBSD_FILE << std::endl;
1185 
1186  LINFO("Exported JEVOIS partition of microSD to host computer as virtual flash drive.");
1187  itsMassStorageMode.store(true);
1188 }
1189 
1190 // ####################################################################################################
1191 void jevois::Engine::stopMassStorageMode()
1192 {
1193  //itsMassStorageMode.store(false);
1194  LINFO("JeVois virtual USB drive ejected by host -- REBOOTING");
1195  reboot();
1196 }
1197 
1198 // ####################################################################################################
1199 void jevois::Engine::reboot()
1200 {
1201  if (std::system("sync")) LERROR("Disk sync failed -- IGNORED");
1202  itsCheckingMassStorage.store(false);
1203  itsRunning.store(false);
1204 
1205  // Hard reset to avoid possible hanging during module unload, etc:
1206  if ( ! std::ofstream("/proc/sys/kernel/sysrq").put('1')) LERROR("Cannot trigger hard reset -- please unplug me!");
1207  if ( ! std::ofstream("/proc/sysrq-trigger").put('s')) LERROR("Cannot trigger hard reset -- please unplug me!");
1208  if ( ! std::ofstream("/proc/sysrq-trigger").put('b')) LERROR("Cannot trigger hard reset -- please unplug me!");
1209  std::terminate();
1210 }
1211 #endif
1212 
1213 // ####################################################################################################
1214 void jevois::Engine::cmdInfo(std::shared_ptr<UserInterface> s, bool showAll, std::string const & pfx)
1215 {
1216  s->writeString(pfx, "help - print this help message");
1217  s->writeString(pfx, "help2 - print compact help message about current vision module only");
1218  s->writeString(pfx, "info - show system information including CPU speed, load and temperature");
1219  s->writeString(pfx, "setpar <name> <value> - set a parameter value");
1220  s->writeString(pfx, "getpar <name> - get a parameter value(s)");
1221  s->writeString(pfx, "runscript <filename> - run script commands in specified file");
1222  s->writeString(pfx, "setcam <ctrl> <val> - set camera control <ctrl> to value <val>");
1223  s->writeString(pfx, "getcam <ctrl> - get value of camera control <ctrl>");
1224 
1225  if (showAll || camreg::get())
1226  {
1227  s->writeString(pfx, "setcamreg <reg> <val> - set raw camera register <reg> to value <val>");
1228  s->writeString(pfx, "getcamreg <reg> - get value of raw camera register <reg>");
1229  }
1230 
1231  s->writeString(pfx, "listmappings - list all available video mappings");
1232  s->writeString(pfx, "setmapping <num> - select video mapping <num>, only possible while not streaming");
1233  s->writeString(pfx, "setmapping2 <CAMmode> <CAMwidth> <CAMheight> <CAMfps> <Vendor> <Module> - set no-USB-out "
1234  "video mapping defined on the fly, while not streaming");
1235  s->writeString(pfx, "reload - reload and reset the current module");
1236 
1237  if (showAll || itsCurrentMapping.ofmt == 0 || itsManualStreamon)
1238  {
1239  s->writeString(pfx, "streamon - start camera video streaming");
1240  s->writeString(pfx, "streamoff - stop camera video streaming");
1241  }
1242 
1243  s->writeString(pfx, "ping - returns 'ALIVE'");
1244  s->writeString(pfx, "serlog <string> - forward string to the serial port(s) specified by the serlog parameter");
1245  s->writeString(pfx, "serout <string> - forward string to the serial port(s) specified by the serout parameter");
1246 
1247  if (showAll)
1248  {
1249  // Hide machine-oriented commands by default
1250  s->writeString(pfx, "caminfo - returns machine-readable info about camera parameters");
1251  s->writeString(pfx, "cmdinfo [all] - returns machine-readable info about Engine commands");
1252  s->writeString(pfx, "modcmdinfo - returns machine-readable info about Module commands");
1253  s->writeString(pfx, "paraminfo [hot|mod|modhot] - returns machine-readable info about parameters");
1254  s->writeString(pfx, "serinfo - returns machine-readable info about serial settings (serout serlog serstyle serprec serstamp)");
1255  s->writeString(pfx, "fileget <filepath> - get a file from JeVois to the host. Use with caution!");
1256  s->writeString(pfx, "fileput <filepath> - put a file from the host to JeVois. Use with caution!");
1257  }
1258 
1259 #ifdef JEVOIS_PLATFORM
1260  s->writeString(pfx, "usbsd - export the JEVOIS partition of the microSD card as a virtual USB drive");
1261 #endif
1262  s->writeString(pfx, "sync - commit any pending data write to microSD");
1263  s->writeString(pfx, "date [date and time] - get or set the system date and time");
1264 
1265  s->writeString(pfx, "shell <string> - execute <string> as a shell command. Use with caution!");
1266 
1267 #ifdef JEVOIS_PLATFORM
1268  s->writeString(pfx, "restart - restart the JeVois smart camera");
1269 #else
1270  s->writeString(pfx, "quit - quit this program");
1271 #endif
1272 }
1273 
1274 // ####################################################################################################
1275 void jevois::Engine::modCmdInfo(std::shared_ptr<UserInterface> s, std::string const & pfx)
1276 {
1277  if (itsModule)
1278  {
1279  std::stringstream css; itsModule->supportedCommands(css);
1280  for (std::string line; std::getline(css, line); /* */) s->writeString(pfx, line);
1281  }
1282 }
1283 
1284 // ####################################################################################################
1285 bool jevois::Engine::parseCommand(std::string const & str, std::shared_ptr<UserInterface> s, std::string const & pfx)
1286 {
1287  // itsMtx should be locked by caller
1288 
1289  std::string errmsg;
1290 
1291  // Note: ModemManager on Ubuntu sends this on startup, kill ModemManager to avoid:
1292  // 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
1293  //
1294  // AT^SQPORT?
1295  // AT
1296  // AT
1297  // AT
1298  // ~
1299  //
1300  // then later on it insists on trying to mess with us, issuing things like AT, AT+CGMI, AT+GMI, AT+CGMM, AT+GMM,
1301  // AT%IPSYS?, ATE0, ATV1, etc etc
1302 
1303  switch (str.length())
1304  {
1305  case 0:
1306  LDEBUG("Ignoring empty string"); return true;
1307  break;
1308 
1309  case 1:
1310  if (str[0] == '~') { LDEBUG("Ignoring modem config command [~]"); return true; }
1311 
1312  // If the string starts with "#", then just print it out on the serlog port(s). We use this to allow debug messages
1313  // from the arduino to be printed out to the user:
1314  if (str[0] == '#') { sendSerial(str, true); return true; }
1315  break;
1316 
1317  default: // length is 2 or more:
1318 
1319  // Ignore any command that starts with a '~':
1320  if (str[0] == '~') { LDEBUG("Ignoring modem config command [" << str << ']'); return true; }
1321 
1322  // Ignore any command that starts with "AT":
1323  if (str[0] == 'A' && str[1] == 'T') { LDEBUG("Ignoring AT command [" << str <<']'); return true; }
1324 
1325  // If the string starts with "#", then just print it out on the serlog port(s). We use this to allow debug messages
1326  // in the arduino to be printed out to the user:
1327  if (str[0] == '#') { sendSerial(str, true); return true; }
1328 
1329  // Get the first word, i.e., the command:
1330  size_t const idx = str.find(' '); std::string cmd, rem;
1331  if (idx == str.npos) cmd = str; else { cmd = str.substr(0, idx); if (idx < str.length()) rem = str.substr(idx+1); }
1332 
1333  // ----------------------------------------------------------------------------------------------------
1334  if (cmd == "help")
1335  {
1336  // Show all commands, first ours, as supported below:
1337  s->writeString(pfx, "GENERAL COMMANDS:");
1338  s->writeString(pfx, "");
1339  cmdInfo(s, false, pfx);
1340  s->writeString(pfx, "");
1341 
1342  // Then the module's custom commands, if any:
1343  if (itsModule)
1344  {
1345  s->writeString(pfx, "MODULE-SPECIFIC COMMANDS:");
1346  s->writeString(pfx, "");
1347  modCmdInfo(s, pfx);
1348  s->writeString(pfx, "");
1349  }
1350 
1351  // Get the help message for our parameters and write it out line by line so the serial fixes the line endings:
1352  std::stringstream pss; constructHelpMessage(pss);
1353  for (std::string line; std::getline(pss, line); /* */) s->writeString(pfx, line);
1354 
1355  // Show all camera controls
1356  s->writeString(pfx, "AVAILABLE CAMERA CONTROLS:");
1357  s->writeString(pfx, "");
1358 
1359  struct v4l2_queryctrl qc = { }; std::set<int> doneids;
1360  for (int cls = V4L2_CTRL_CLASS_USER; cls <= V4L2_CTRL_CLASS_DETECT; cls += 0x10000)
1361  {
1362  // Enumerate all controls in this class. Looks like there is some spillover between V4L2 classes in the V4L2
1363  // enumeration process, we end up with duplicate controls if we try to enumerate all the classes. Hence the
1364  // doneids set to keep track of the ones already reported:
1365  qc.id = cls | 0x900; unsigned int old_id;
1366  while (true)
1367  {
1368  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL; old_id = qc.id; bool failed = false;
1369  try { std::string hlp = camCtrlHelp(qc, doneids); if (hlp.empty() == false) s->writeString(pfx, hlp); }
1370  catch (...) { failed = true; }
1371 
1372  // The camera kernel driver is supposed to pass down the next valid control if the requested one is not
1373  // found, but some drivers do not honor that, so let's move on to the next control manually if needed:
1374  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
1375  if (qc.id == old_id) { ++qc.id; if (qc.id > 100 + (cls | 0x900 | V4L2_CTRL_FLAG_NEXT_CTRL)) break; }
1376  else if (failed) break;
1377  }
1378  }
1379 
1380  return true;
1381  }
1382 
1383  // ----------------------------------------------------------------------------------------------------
1384  if (cmd == "caminfo")
1385  {
1386  // Machine-readable list of camera parameters:
1387  struct v4l2_queryctrl qc = { }; std::set<int> doneids;
1388  for (int cls = V4L2_CTRL_CLASS_USER; cls <= V4L2_CTRL_CLASS_DETECT; cls += 0x10000)
1389  {
1390  // Enumerate all controls in this class. Looks like there is some spillover between V4L2 classes in the V4L2
1391  // enumeration process, we end up with duplicate controls if we try to enumerate all the classes. Hence the
1392  // doneids set to keep track of the ones already reported:
1393  qc.id = cls | 0x900; unsigned int old_id;
1394  while (true)
1395  {
1396  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL; old_id = qc.id; bool failed = false;
1397  try { std::string hlp = camCtrlInfo(qc, doneids); if (hlp.empty() == false) s->writeString(pfx, hlp); }
1398  catch (...) { failed = true; }
1399 
1400  // The camera kernel driver is supposed to pass down the next valid control if the requested one is not
1401  // found, but some drivers do not honor that, so let's move on to the next control manually if needed:
1402  qc.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
1403  if (qc.id == old_id) { ++qc.id; if (qc.id > 100 + (cls | 0x900 | V4L2_CTRL_FLAG_NEXT_CTRL)) break; }
1404  else if (failed) break;
1405  }
1406  }
1407 
1408  return true;
1409  }
1410 
1411  // ----------------------------------------------------------------------------------------------------
1412  if (cmd == "cmdinfo")
1413  {
1414  bool showAll = (rem == "all") ? true : false;
1415  cmdInfo(s, showAll, pfx);
1416  return true;
1417  }
1418 
1419  // ----------------------------------------------------------------------------------------------------
1420  if (cmd == "modcmdinfo")
1421  {
1422  modCmdInfo(s, pfx);
1423  return true;
1424  }
1425 
1426  // ----------------------------------------------------------------------------------------------------
1427  if (cmd == "paraminfo")
1428  {
1429  std::map<std::string, std::string> categs;
1430  bool skipFrozen = (rem == "hot" || rem == "modhot") ? true : false;
1431 
1432  if (rem == "mod" || rem == "modhot")
1433  {
1434  // Report only on our module's parameter, if any:
1435  if (itsModule) itsModule->paramInfo(s, categs, skipFrozen, instanceName(), pfx);
1436  }
1437  else
1438  {
1439  // Report on all parameters:
1440  paramInfo(s, categs, skipFrozen, "", pfx);
1441  }
1442 
1443  return true;
1444  }
1445 
1446  // ----------------------------------------------------------------------------------------------------
1447  if (cmd == "serinfo")
1448  {
1449  std::string info = getParamStringUnique("serout") + ' ' + getParamStringUnique("serlog");
1450  if (auto mod = dynamic_cast<jevois::StdModule *>(itsModule.get()))
1451  info += ' ' + mod->getParamStringUnique("serstyle") + ' ' + mod->getParamStringUnique("serprec") +
1452  ' ' + mod->getParamStringUnique("serstamp");
1453  else info += " - - -";
1454 
1455  s->writeString(pfx, info);
1456 
1457  return true;
1458  }
1459 
1460  // ----------------------------------------------------------------------------------------------------
1461  if (cmd == "help2")
1462  {
1463  if (itsModule)
1464  {
1465  // Start with the module's commands:
1466  std::stringstream css; itsModule->supportedCommands(css);
1467  s->writeString(pfx, "MODULE-SPECIFIC COMMANDS:");
1468  s->writeString(pfx, "");
1469  for (std::string line; std::getline(css, line); /* */) s->writeString(pfx, line);
1470  s->writeString(pfx, "");
1471 
1472  // Now the parameters for that module (and its subs) only:
1473  s->writeString(pfx, "MODULE PARAMETERS:");
1474  s->writeString(pfx, "");
1475 
1476  // Keep this in sync with Manager::constructHelpMessage():
1477  std::unordered_map<std::string, // category:description
1478  std::unordered_map<std::string, // --name (type) default=[def]
1479  std::vector<std::pair<std::string, // component name
1480  std::string // current param value
1481  > > > > helplist;
1482  itsModule->populateHelpMessage("", helplist);
1483 
1484  if (helplist.empty())
1485  s->writeString(pfx, "None.");
1486  else
1487  {
1488  for (auto const & c : helplist)
1489  {
1490  // Print out the category name and description
1491  s->writeString(pfx, c.first);
1492 
1493  // Print out the parameter details
1494  for (auto const & n : c.second)
1495  {
1496  std::vector<std::string> tok = jevois::split(n.first, "[\\r\\n]+");
1497  bool first = true;
1498  for (auto const & t : tok)
1499  {
1500  // Add current value info to the first thing we write (which is name, default, etc)
1501  if (first)
1502  {
1503  auto const & v = n.second;
1504  if (v.size() == 1) // only one component using this param
1505  {
1506  if (v[0].second.empty())
1507  s->writeString(pfx, t); // only one comp, and using default val
1508  else
1509  s->writeString(pfx, t + " current=[" + v[0].second + ']'); // using non-default val
1510  }
1511  else if (v.size() > 1) // several components using this param with possibly different values
1512  {
1513  std::string sss = t + " current=";
1514  for (auto const & pp : v)
1515  if (pp.second.empty() == false) sss += '[' + pp.first + ':' + pp.second + "] ";
1516  s->writeString(pfx, sss);
1517  }
1518  else s->writeString(pfx, t); // no non-default value(s) to report
1519 
1520  first = false;
1521  }
1522 
1523  else // just write out the other lines (param description)
1524  s->writeString(pfx, t);
1525  }
1526  }
1527  s->writeString(pfx, "");
1528  }
1529  }
1530  }
1531  else
1532  s->writeString(pfx, "No module loaded.");
1533 
1534  return true;
1535  }
1536 
1537  // ----------------------------------------------------------------------------------------------------
1538  if (cmd == "info")
1539  {
1540  s->writeString(pfx, "INFO: JeVois " JEVOIS_VERSION_STRING);
1541  s->writeString(pfx, "INFO: " + jevois::getSysInfoVersion());
1542  s->writeString(pfx, "INFO: " + jevois::getSysInfoCPU());
1543  s->writeString(pfx, "INFO: " + jevois::getSysInfoMem());
1544  if (itsModule) s->writeString(pfx, "INFO: " + itsCurrentMapping.str());
1545  else s->writeString(pfx, "INFO: " + jevois::VideoMapping().str());
1546  return true;
1547  }
1548 
1549  // ----------------------------------------------------------------------------------------------------
1550  if (cmd == "setpar")
1551  {
1552  size_t const remidx = rem.find(' ');
1553  if (remidx != rem.npos)
1554  {
1555  std::string const desc = rem.substr(0, remidx);
1556  if (remidx < rem.length())
1557  {
1558  std::string const val = rem.substr(remidx+1);
1559  setParamString(desc, val);
1560  return true;
1561  }
1562  }
1563  errmsg = "Need to provide a parameter name and a parameter value in setpar";
1564  }
1565 
1566  // ----------------------------------------------------------------------------------------------------
1567  if (cmd == "getpar")
1568  {
1569  auto vec = getParamString(rem);
1570  for (auto const & p : vec) s->writeString(pfx, p.first + ' ' + p.second);
1571  return true;
1572  }
1573 
1574  // ----------------------------------------------------------------------------------------------------
1575  if (cmd == "setcam")
1576  {
1577  std::istringstream ss(rem); std::string ctrl; int val; ss >> ctrl >> val;
1578  struct v4l2_control c = { }; c.id = camctrlid(ctrl); c.value = val;
1579  itsCamera->setControl(c);
1580  return true;
1581  }
1582 
1583  // ----------------------------------------------------------------------------------------------------
1584  if (cmd == "getcam")
1585  {
1586  struct v4l2_control c = { }; c.id = camctrlid(rem);
1587  itsCamera->getControl(c);
1588  s->writeString(pfx, rem + ' ' + std::to_string(c.value));
1589  return true;
1590  }
1591 
1592  // ----------------------------------------------------------------------------------------------------
1593  if (cmd == "setcamreg")
1594  {
1595  if (camreg::get())
1596  {
1597  // Read register and value as strings, then std::stoi to convert to int, supports 0x (and 0 for octal, caution)
1598  std::istringstream ss(rem); std::string reg, val; ss >> reg >> val;
1599  itsCamera->writeRegister(std::stoi(reg, nullptr, 0), std::stoi(val, nullptr, 0));
1600  return true;
1601  }
1602  errmsg = "Access to camera registers is disabled, enable with: setpar camreg true";
1603  }
1604 
1605  // ----------------------------------------------------------------------------------------------------
1606  if (cmd == "getcamreg")
1607  {
1608  if (camreg::get())
1609  {
1610  unsigned int val = itsCamera->readRegister(std::stoi(rem, nullptr, 0));
1611  std::ostringstream os; os << std::hex << val;
1612  s->writeString(pfx, os.str());
1613  return true;
1614  }
1615  errmsg = "Access to camera registers is disabled, enable with: setpar camreg true";
1616  }
1617 
1618  // ----------------------------------------------------------------------------------------------------
1619  if (cmd == "listmappings")
1620  {
1621  s->writeString(pfx, "AVAILABLE VIDEO MAPPINGS:");
1622  s->writeString(pfx, "");
1623  for (size_t idx = 0; idx < itsMappings.size(); ++idx)
1624  {
1625  std::string idxstr = std::to_string(idx);
1626  if (idxstr.length() < 5) idxstr = std::string(5 - idxstr.length(), ' ') + idxstr; // pad to 5-char long
1627  s->writeString(pfx, idxstr + " - " + itsMappings[idx].str());
1628  }
1629  return true;
1630  }
1631 
1632  // ----------------------------------------------------------------------------------------------------
1633  if (cmd == "setmapping")
1634  {
1635  size_t const idx = std::stoi(rem);
1636  bool was_streaming = itsStreaming.load();
1637 
1638  if (was_streaming)
1639  {
1640  errmsg = "Cannot set mapping while streaming: ";
1641  if (itsCurrentMapping.ofmt) errmsg += "Stop your webcam program on the host computer first.";
1642  else errmsg += "Issue a 'streamoff' command first.";
1643  }
1644  else if (idx >= itsMappings.size())
1645  errmsg = "Requested mapping index " + std::to_string(idx) + " out of range [0 .. " +
1646  std::to_string(itsMappings.size()-1) + ']';
1647  else
1648  {
1649  try
1650  {
1651  setFormatInternal(idx);
1652  return true;
1653  }
1654  catch (std::exception const & e) { errmsg = "Error parsing or setting mapping [" + rem + "]: " + e.what(); }
1655  catch (...) { errmsg = "Error parsing or setting mapping [" + rem + ']'; }
1656  }
1657  }
1658 
1659  // ----------------------------------------------------------------------------------------------------
1660  if (cmd == "setmapping2")
1661  {
1662  bool was_streaming = itsStreaming.load();
1663 
1664  if (was_streaming)
1665  {
1666  errmsg = "Cannot set mapping while streaming: ";
1667  if (itsCurrentMapping.ofmt) errmsg += "Stop your webcam program on the host computer first.";
1668  else errmsg += "Issue a 'streamoff' command first.";
1669  }
1670  else
1671  {
1672  try
1673  {
1674  jevois::VideoMapping m; std::istringstream full("NONE 0 0 0.0 " + rem); full >> m;
1675  setFormatInternal(m);
1676  return true;
1677  }
1678  catch (std::exception const & e) { errmsg = "Error parsing or setting mapping [" + rem + "]: " + e.what(); }
1679  catch (...) { errmsg = "Error parsing or setting mapping [" + rem + ']'; }
1680  }
1681  }
1682 
1683  // ----------------------------------------------------------------------------------------------------
1684  if (cmd == "reload")
1685  {
1686  setFormatInternal(itsCurrentMapping, true);
1687  return true;
1688  }
1689 
1690  // ----------------------------------------------------------------------------------------------------
1691  if (itsCurrentMapping.ofmt == 0 || itsManualStreamon)
1692  {
1693  if (cmd == "streamon")
1694  {
1695  // keep this in sync with streamOn(), modulo the fact that here we are already locked:
1696  itsCamera->streamOn();
1697  itsGadget->streamOn();
1698  itsStreaming.store(true);
1699  return true;
1700  }
1701 
1702  if (cmd == "streamoff")
1703  {
1704  // keep this in sync with streamOff(), modulo the fact that here we are already locked:
1705  itsGadget->abortStream();
1706  itsCamera->abortStream();
1707 
1708  itsStreaming.store(false);
1709 
1710  itsGadget->streamOff();
1711  itsCamera->streamOff();
1712  return true;
1713  }
1714  }
1715 
1716  // ----------------------------------------------------------------------------------------------------
1717  if (cmd == "ping")
1718  {
1719  s->writeString(pfx, "ALIVE");
1720  return true;
1721  }
1722 
1723  // ----------------------------------------------------------------------------------------------------
1724  if (cmd == "serlog")
1725  {
1726  sendSerial(rem, true);
1727  return true;
1728  }
1729 
1730  // ----------------------------------------------------------------------------------------------------
1731  if (cmd == "serout")
1732  {
1733  sendSerial(rem, false);
1734  return true;
1735  }
1736 
1737  // ----------------------------------------------------------------------------------------------------
1738 #ifdef JEVOIS_PLATFORM
1739  if (cmd == "usbsd")
1740  {
1741  if (itsStreaming.load())
1742  {
1743  errmsg = "Cannot export microSD over USB while streaming: ";
1744  if (itsCurrentMapping.ofmt) errmsg += "Stop your webcam program on the host computer first.";
1745  else errmsg += "Issue a 'streamoff' command first.";
1746  }
1747  else
1748  {
1749  startMassStorageMode();
1750  return true;
1751  }
1752  }
1753 #endif
1754 
1755  // ----------------------------------------------------------------------------------------------------
1756  if (cmd == "sync")
1757  {
1758  if (std::system("sync")) errmsg = "Disk sync failed";
1759  else return true;
1760  }
1761 
1762  // ----------------------------------------------------------------------------------------------------
1763  if (cmd == "date")
1764  {
1765  std::string dat = jevois::system("/bin/date " + rem);
1766  s->writeString(pfx, "date now " + dat.substr(0, dat.size()-1)); // skip trailing newline
1767  return true;
1768  }
1769 
1770  // ----------------------------------------------------------------------------------------------------
1771  if (cmd == "runscript")
1772  {
1773  std::string const fname = itsModule ? itsModule->absolutePath(rem) : rem;
1774 
1775  try { runScriptFromFile(fname, s, true); return true; }
1776  catch (...) { errmsg = "Script " + fname + " execution failed"; }
1777  }
1778 
1779  // ----------------------------------------------------------------------------------------------------
1780  if (cmd == "shell")
1781  {
1782  std::string ret = jevois::system(rem, true);
1783  std::vector<std::string> rvec = jevois::split(ret, "\n");
1784  for (std::string const & r : rvec) s->writeString(pfx, r);
1785  return true;
1786  }
1787 
1788  // ----------------------------------------------------------------------------------------------------
1789  if (cmd == "fileget")
1790  {
1791  std::shared_ptr<jevois::Serial> ser = std::dynamic_pointer_cast<jevois::Serial>(s);
1792  if (!ser)
1793  errmsg = "File transfer only supported over USB or Hard serial ports";
1794  else
1795  {
1796  std::string const abspath = itsModule ? itsModule->absolutePath(rem) : rem;
1797  ser->fileGet(abspath);
1798  return true;
1799  }
1800  }
1801 
1802  // ----------------------------------------------------------------------------------------------------
1803  if (cmd == "fileput")
1804  {
1805  std::shared_ptr<jevois::Serial> ser = std::dynamic_pointer_cast<jevois::Serial>(s);
1806  if (!ser)
1807  errmsg = "File transfer only supported over USB or Hard serial ports";
1808  else
1809  {
1810  std::string const abspath = itsModule ? itsModule->absolutePath(rem) : rem;
1811  ser->filePut(abspath);
1812  if (std::system("sync")) { } // quietly ignore any errors on sync
1813  return true;
1814  }
1815  }
1816 
1817 #ifdef JEVOIS_PLATFORM
1818  // ----------------------------------------------------------------------------------------------------
1819  if (cmd == "restart")
1820  {
1821  s->writeString(pfx, "Restart command received - bye-bye!");
1822 
1823  if (itsStreaming.load())
1824  s->writeString(pfx, "ERR Video streaming is on - you should quit your video viewer before rebooting");
1825 
1826  // Turn off the SD storage if it is there:
1827  std::ofstream(JEVOIS_USBSD_SYS).put('\n'); // ignore errors
1828  if (std::system("sync")) s->writeString(pfx, "ERR Disk sync failed -- IGNORED");
1829 
1830  // Hard reboot:
1831  this->reboot();
1832  return true;
1833  }
1834  // ----------------------------------------------------------------------------------------------------
1835 #else
1836  // ----------------------------------------------------------------------------------------------------
1837  if (cmd == "quit")
1838  {
1839  s->writeString(pfx, "Quit command received - bye-bye!");
1840  itsGadget->abortStream();
1841  itsCamera->abortStream();
1842  itsStreaming.store(false);
1843  itsGadget->streamOff();
1844  itsCamera->streamOff();
1845  itsRunning.store(false);
1846  return true;
1847  }
1848  // ----------------------------------------------------------------------------------------------------
1849 #endif
1850  }
1851 
1852  // If we make it here, we did not parse the command. If we have an error message, that means we had started parsing
1853  // the command but it was buggy, so let's throw. Otherwise, we just return false to indicate that we did not parse
1854  // this command and maybe it is for the Module:
1855  if (errmsg.size()) throw std::runtime_error("Command error [" + str + "]: " + errmsg);
1856  return false;
1857 }
1858 
1859 // ####################################################################################################
1860 void jevois::Engine::runScriptFromFile(std::string const & filename, std::shared_ptr<jevois::UserInterface> ser,
1861  bool throw_no_file)
1862 {
1863  // itsMtx should be locked by caller
1864 
1865  // Try to find the file:
1866  std::ifstream ifs(filename);
1867  if (!ifs) { if (throw_no_file) LFATAL("Could not open file " << filename); else return; }
1868 
1869  // 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
1870  // none is specified there, the first available serial:
1871  if (!ser)
1872  {
1873  if (itsSerials.empty()) LFATAL("Need at least one active serial to run script");
1874  switch (serlog::get())
1875  {
1876  case jevois::engine::SerPort::Hard:
1877  for (auto & s : itsSerials) if (s->type() == jevois::UserInterface::Type::Hard) { ser = s; break; }
1878  break;
1879 
1880  case jevois::engine::SerPort::USB:
1881  for (auto & s : itsSerials) if (s->type() == jevois::UserInterface::Type::USB) { ser = s; break; }
1882  break;
1883 
1884  default: break;
1885  }
1886  if (!ser) ser = itsSerials.front();
1887  }
1888 
1889  // Ok, run the script, plowing through any errors:
1890  size_t linenum = 1;
1891  for (std::string line; std::getline(ifs, line); /* */)
1892  {
1893  // Strip any extra whitespace at end, which could be a CR if the file was edited in Windows:
1894  line = jevois::strip(line);
1895 
1896  // Skip comments and empty lines:
1897  if (line.length() == 0 || line[0] == '#') continue;
1898 
1899  // Go and parse that line:
1900  try
1901  {
1902  bool parsed = false;
1903  try { parsed = parseCommand(line, ser); }
1904  catch (std::exception const & e)
1905  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum) + ": " + e.what()); }
1906  catch (...)
1907  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum) + ": Bogus command ["+line+"] ignored"); }
1908 
1909  if (parsed == false)
1910  {
1911  if (itsModule)
1912  {
1913  try { itsModule->parseSerial(line, ser); }
1914  catch (std::exception const & me)
1915  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum) + ": " + me.what()); }
1916  catch (...)
1917  { ser->writeString("ERR " + filename + ':' + std::to_string(linenum)+": Bogus command ["+line+"] ignored"); }
1918  }
1919  else ser->writeString("ERR Unsupported command [" + line + "] and no module");
1920  }
1921  }
1922  catch (...) { jevois::warnAndIgnoreException(); }
1923 
1924  ++linenum;
1925  }
1926 }
#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
std::string strip(std::string const &str)
Strip white space (including CR, LF, tabs, etc) from the end of a string.
Definition: Utils.C:180
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:922
size_t numVideoMappings() const
Return the number of video mappings.
Definition: Engine.C:907
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:356
std::vector< std::string > setParamString(std::string const &paramdescriptor, std::string const &val)
Set a parameter value, by string.
Definition: Component.C:347
void postInit() override
Override of Manager::postInit()
Definition: Engine.C:349
std::shared_ptr< VideoInput > itsCamera
Our camera.
Definition: Engine.H:360
#define V4L2_CTRL_CLASS_DETECT
Definition: Engine.C:48
void streamOff()
Stop streaming on video from camera, processing, and USB.
Definition: Engine.C:552
void preInit() override
Calls parseCommandLine()
Definition: Manager.C:49
void preInit() override
Override of Manager::preInit()
Definition: Engine.C:338
std::unique_ptr< DynamicLoader > itsLoader
Our module loader.
Definition: Engine.H:363
std::atomic< bool > itsStreaming
True when we are streaming video.
Definition: Engine.H:367
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:541
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:962
#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:700
#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
Interface to a serial port.
Definition: Serial.H:84
void sendSerial(std::string const &str, bool islog=false)
Send a string to all serial ports.
Definition: Engine.C:859
bool parseCommand(std::string const &str, std::shared_ptr< UserInterface > s, std::string const &pfx="")
Parse a user command received over serial port.
Definition: Engine.C:1285
std::string str() const
Convenience function to print out the whole mapping in a human-friendly way.
Definition: VideoMapping.C:87
size_t frameNum() const
Get frame number.
Definition: Engine.C:897
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:361
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 getParamStringUnique(std::string const &paramdescriptor) const
Get a parameter value by string, simple version assuming only one parameter match.
Definition: Component.C:390
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:358
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:913
~Engine()
Destructor.
Definition: Engine.C:471
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
std::string system(std::string const &cmd, bool errtoo=true)
Execute a command and grab stdout output to a string.
Definition: Utils.C:248
VideoMapping const & getCurrentVideoMapping() const
Get the current video mapping.
Definition: Engine.C:901
std::atomic< bool > itsStopMainLoop
Flag used to stop the main loop.
Definition: Engine.H:368
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:166
std::string fccstr(unsigned int fcc)
Convert a V4L2 four-cc code (V4L2_PIX_FMT_...) to a 4-char string.
Definition: Utils.C:39
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:357
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:957
std::istream & setParamsFromStream(std::istream &is, std::string const &absfile)
Set some parameters from an open stream.
Definition: Component.C:452
virtual void paramInfo(std::shared_ptr< UserInterface > s, std::map< std::string, std::string > &categs, bool skipFrozen, std::string const &cname="", std::string const &pfx="")
Get machine-oriented descriptions of all parameters.
Definition: Component.C:522
Video output to local screen.
Definition: VideoDisplay.H:34
Wrapper module to allow users to develop new modules written in Python.
Definition: PythonModule.H:189
std::vector< std::pair< std::string, std::string > > getParamString(std::string const &paramdescriptor) const
Get a parameter value, by string.
Definition: Component.C:374
void runScriptFromFile(std::string const &filename, std::shared_ptr< UserInterface > ser, bool throw_no_file)
Run a script from file.
Definition: Engine.C:1860
std::string to_string(T const &val)
Convert from type to string.
Definition: UtilsImpl.H:58
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:370
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:953
bool ispython
True if the module is written in Python; affects behavior of sopath() only.
Definition: VideoMapping.H:60
void postInit() override
Checks for the –help flag.
Definition: Manager.C:58
std::string const & instanceName() const
The instance name of this component.
Definition: Component.C:49
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:573
#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:366
std::shared_ptr< Module > itsModule
Our current module.
Definition: Engine.H:364
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:142
#define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE