lwir16.php 46 KB
Newer Older
1
#!/usr/bin/php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
<?php
/*!*******************************************************************************
*! FILE NAME  : lwir.php
*! DESCRIPTION: Subcameras initialization and capturing of synchronized scene
*  sequences               
*! Copyright (C) 2021 Elphel, Inc
*! -----------------------------------------------------------------------------**
*!
*!  This program is free software: you can redistribute it and/or modify
*!  it under the terms of the GNU General Public License as published by
*!  the Free Software Foundation, either version 3 of the License, or
*!  (at your option) any later version.
*!
*!  This program is distributed in the hope that it will be useful,
*!  but WITHOUT ANY WARRANTY; without even the implied warranty of
*!  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*!  GNU General Public License for more details.
*!
*!  You should have received a copy of the GNU General Public License
*!  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*! -----------------------------------------------------------------------------**
*!
*/
   set_include_path ( get_include_path () . PATH_SEPARATOR . '/www/pages/include' );
   include 'show_source_include.php';
   include "elphel_functions_include.php"; // includes curl functions
28 29 30 31 32 33 34 35 36 37 38
   define('REG_FFC_FRAMES',     'SENSOR_REGS4');     // Register for the number of FFC frames to integrate
   define('REG_FFC_RUN',        'SENSOR_REGS26');    // Register to trigger FFC
   define('SCRIPT_RESET',       'reset_frames.php'); // Reset frame numbers
   define('SCRIPT_WAIT',        'wait_frame.php');   // wait frame
   define('DEFAULT_IPS',        '192.168.0.41,192.168.0.42,192.168.0.43,192.168.0.44,192.168.0.45');
   define('PIPE_CMD',           '/tmp/pipe_cmd');
   define('PIPE_RESPONSE',      '/tmp/pipe_response');
   define('PIPE_MODE',          0600);
   define('CONF_LWIR16',        '/etc/elphel393/lwir16.ini');
   define('EO_DECIMATE',        6);
   // GLOBALS field name
39 40
   define('CAM_IP_PREF',        'cam_'); // camera
   define('CAM_PORT_SEP',       '_'); // camera ip to port seperator
41
   define('IPS',                'ips');
42 43 44 45 46 47 48 49 50
   define('PORT_MASKS',         'port_masks');
   define('ALL_PORTS',          15);
   define('IMGSRV_PORT0',       2323);
   define('TIFF_TELEM',         'tiff_telem');
   define('TIFF_MN',            'tiff_mn');
   define('TIFF_MX',            'tiff_mx');
   define('TIFF_BIN_SHIFT',     'tiff_bin');
   define('TIFF_STATS',         'tiff_stats');
   define('TIFF_AUTO',          'tiff_auto');
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
   define('DURATION',           'duration');
   define('DURATION_EO',        'duration_eo');
   define('PRE_DELAY',          'pre_delay');
   define('FFC',                'ffc'); // use FFC
   define('FFC_PERIOD',         'ffc_period');
   define('FFC_GROUPS',         'ffc_groups');
   define('FFC_FRAMES',         'ffc_frames');
   define('COMPRESSOR_RUN',     'compressor_run'); // after init
   define('DEBUG',              'debug');
   define('DAEMON_RUN',         'daemon_run');  // not read through ini
   define('CAPTURE_RUN',        'capture_run'); // not read through ini
   define('LAST_FFC',           'last_ffc'); // not read through ini
   define('SECUENCE_NUM',       'sequence_num'); // not read through ini
   define('TIME_TO_FFC',        'time_to_ffc'); // not read through ini
   define('DAEMON_CMD',         'CMD'); // command to be executed by a daemon
   define('CMD_INIT',           'INIT'); // passed commands
   define('CMD_START',          'START'); // passed commands
   define('CMD_STOP',           'STOP'); // passed commands
   define('CMD_EXIT',           'EXIT'); // passed commands
   define('CMD_STATUS',         'STATUS'); // passed commands
   define('CMD_REBOOT',         'REBOOT'); // passed commands
   define('CR_EXTRA',           2); // not currenly used - wait extra frames in capture_range
   // daemon control $_GET
   define('DAEMON_CTRL',        'daemon');
   define('DAEMON_CTRL_CMDS',   'cmd'); //comma-separated commands to be sent to the daemon
76
   define('OUTPUT_LOG',         'output_log'); // redirect daemon output
77
   define('CAMERA_STATE',       '/var/state/camera');
78
   
79 80
//   print_r($_GET); // magic
//   exit(0); // magic
81 82 83 84 85
   
   // initializations before reading lwir16.ini
   $GLOBALS[COMPRESSOR_RUN] = 0;
   $GLOBALS[DURATION] = 100;
   $GLOBALS[PRE_DELAY] = 5.0; // seconds
86
   $GLOBALS[FFC] =        0; // perform FFC before starting a sequence (and before delay? reduce delay ?)
87 88 89
//   $ffc =        false; 
   $GLOBALS[FFC_GROUPS] = 2; // 1/2/4 - do not run FFC on all channels simultaneously (43 failed)
   $GLOBALS[FFC_FRAMES] = 8; // read actual?
90 91
   $GLOBALS[OUTPUT_LOG] = '/dev/null';
   
92 93 94 95 96 97 98
   /*
   $GLOBALS[TIFF_TELEM] =     1; // one top line
   $GLOBALS[TIFF_MN] =        0;
   $GLOBALS[TIFF_MX] =        0xffff;
   $GLOBALS[TIFF_BIN_SHIFT] = 1; // bin_size = 2
   $GLOBALS[TIFF_AUTO] =      0; // use very min/veri max (1 - 0.1%, 2 - 0.5%, 3 - 1%, 4 - 5%, 5 - 10%)
   */
99 100 101 102
   
   $ini =    parse_ini_file(CONF_LWIR16);
   applyConf($ini);
   
103
   $ffc_wait_frames =      10; // extra wait after FFC finished (2xffc_frames)
104 105 106 107 108 109 110 111 112 113 114
   $compressor_run =       0; // stop all
   
   if (!($_SERVER ['REQUEST_METHOD'] == "GET")){
       lwir16_daemon();
       exit (0);
   }
   
   if (isset($_GET[DAEMON_CTRL])){
       daemon_control($_GET['daemon']);
       exit(0);
   }
115 116
   
   
117 118
   
   unset($duration);unset($duration_eo);
119
   unset ($masks);
120 121
   foreach($_GET as $key=>$value) {
       if (($key == 'ip') || ($key == 'ips')){ //  multicamera operation
122
           $GLOBALS[IPS] = explode(',',$value);
123 124 125 126
           unset ($GLOBALS[PORT_MASKS]); // invalidate
       } else if ($key == PORT_MASKS){ //
           $masks = explode(',',$value);
           unset ($GLOBALS[PORT_MASKS]); // invalidate
127 128 129
       } else if (($key == 'lwir16') || ($key == 'cmd')){
           $lswir16cmds = explode(',',$value);
       } else if ($key == 'pre_delay'){
130
           $GLOBALS[PRE_DELAY] = (double) $value; // only used with capture
131
       } else if (($key == 'd')   || ($key == 'duration')){
132
          $duration = (int) $value; // EO - make 1/6 +1 frames
133 134 135 136 137
       } else if (($key == 'de')   || ($key == 'duration_eo')){
           $duration_eo = (int) $value; // EO - make 1/6 +1 frames
       } else if ($key == 'nowait'){
           $nowait = 1;
       } else if ($key == 'run'){
138
           $GLOBALS[COMPRESSOR_RUN] = 2;
139
       } else if ($key == 'ffc'){
140
           $GLOBALS[FFC] = 1;
141 142 143
           if ($value) { // string "0" will also be false
               $v = (int) $value;
               if (($v == 1) || ($v == 2) || ($v == 4)){
144
                   $$GLOBALS[FFC_GROUPS] = $v;
145 146 147
               }
           }
       }
148 149 150 151 152
       else if ($key == TIFF_TELEM)     $GLOBALS[TIFF_TELEM] =     (int) $value;
       else if ($key == TIFF_MN)        $GLOBALS[TIFF_MN] =        (int) $value;
       else if ($key == TIFF_MX)        $GLOBALS[TIFF_MX] =        (int) $value;
       else if ($key == TIFF_BIN_SHIFT) $GLOBALS[TIFF_BIN_SHIFT] = (int) $value;
       else if ($key == TIFF_AUTO)      $GLOBALS[TIFF_AUTO] =      (int) $value;
153
       else if ($key == OUTPUT_LOG)     $GLOBALS[OUTPUT_LOG] =           $value;
154 155 156 157 158 159 160 161 162 163 164 165
   }
   if (!isset($GLOBALS[PORT_MASKS])){
       $GLOBALS[PORT_MASKS] = array();
       for ($i = 0; $i < count($GLOBALS[IPS]); $i++){
//           print ('<pre>'.$i."\n</pre>");
           if (isset($masks) && (count($masks) > $i)){
               $GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]] = (int) ($masks[$i]);
           } else {
               $GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]] = ALL_PORTS;
//               print ('<pre>'.$i."->".$GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]]."\n</pre>");
           }
       }
166
   }
167 168
//   print_r($lswir16cmds);
//   exit(0);
169 170 171 172 173 174 175
    /*
   echo"<pre>\n"; //****************
   print_r($ini);
   print_r($GLOBALS);
   echo"</pre>";
   exit(0);
   */
176 177
   if (isset($duration) && !isset($duration_eo)){
       $duration_eo = (int) ($duration/EO_DECIMATE + 1);
178
   }
179 180 181 182
   if (isset($duration))    $GLOBALS[DURATION] = $duration;
   if (isset($duration_eo)) $GLOBALS[DURATION_EO] = $duration_eo;
   if ($GLOBALS[DURATION] < 1)    $GLOBALS[DURATION] = 1;
   if ($GLOBALS[DURATION_EO] < 1) $GLOBALS[DURATION_EO] = 1;
183 184
   
   
185 186 187 188 189 190 191 192 193 194 195 196
   if (isset($lswir16cmds)){
       $lwir_trig_dly =       0;
       $eo_quality =         97;
       $exposure =         1000; // 1 ms
       $autoExposureMax= 500000;
       $autoExp=              1;
       $gain=            2*0x10000;
       $rScale =         1*0x10000;
       $bScale =         1*0x10000;
       $gScale =         1*0x10000;
       $autoWB =              1;
       
197
///       $extra = 2;
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
       $wait = 1;
       if ($nowait){
           $wait = 0;
       }
       $COLOR_JP4 = 5;
       $COLOR_RAW = 15;
       $LWIR_HEIGHT = 512;
       $LWIR_TELEMETRY_LINES = 1;
       $LWIR_TELEMETRY = 1;
       $FRAMES_SKIP = 4;
       $FFC_FRAMES = 8;
       $REG_FFC_FRAMES= 'SENSOR_REGS4';      // Register for the number of FFC frames to integrate
       $REG_FFC_RUN=    'SENSOR_REGS26';     // Register to trigger FFC
//       print("1");
//       print("2");
//       exit(0);
       
215 216 217
       $lwir_ips= array($GLOBALS[IPS][0],$GLOBALS[IPS][1],$GLOBALS[IPS][2],$GLOBALS[IPS][3]);
//       $twoIPs= array($GLOBALS[IPS][0],$GLOBALS[IPS][4]);
       $twoIPs= $GLOBALS[IPS]; // array($GLOBALS[IPS][0],$GLOBALS[IPS][4]); wait all
218
//       print_r($lswir16cmds);
219
 
220 221 222
       for ($ncmd = 0; $ncmd < count($lswir16cmds); $ncmd++){
           $cmd = $lswir16cmds[$ncmd];
           if ($cmd == 'init'){
223
               $results = runInit();
224 225
               $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><lwir16_init/>");
               for ($i = 0; $i<count($results); $i++){
226
                   $xml_ip = $xml->addChild (CAM_IP_PREF.$GLOBALS[IPS][$i]);
227 228 229 230 231 232 233 234 235 236 237
                   foreach ($results[$i] as $key=>$value){
                       $xml_ip->addChild($key,$value);
                   }
               }
               $rslt=$xml->asXML();
               header("Content-Type: text/xml");
               header("Content-Length: ".strlen($rslt)."\n");
               header("Pragma: no-cache\n");
               printf($rslt);
               exit(0);
           } else if ($cmd == 'capture'){
238
               $results =  runCapture($GLOBALS[FFC], $nowait); // runCapture($run_ffc, $nowait = 0, $debug=0)
239
               $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><capture_range/>");
240
               $xml->addChild ('ffc', $GLOBALS[FFC]);
241 242 243 244
               $xml->addChild (FFC_GROUPS,$GLOBALS[FFC_GROUPS]);
               $xml->addChild (FFC_FRAMES,$GLOBALS[FFC_FRAMES]);
               for ($i = 0; $i<count($GLOBALS[IPS]); $i++){
                   $xml_ip = $xml->addChild ('ip_'.$GLOBALS[IPS][$i]);
245 246 247 248 249 250 251 252 253 254 255 256 257
                   foreach ($results[$i] as $key=>$value){
                       $xml_ip->addChild($key,$value);
                   }
               }
               $rslt=$xml->asXML();
               header("Content-Type: text/xml");
               header("Content-Length: ".strlen($rslt)."\n");
               header("Pragma: no-cache\n");
               printf($rslt);
               exit(0);
           } else if ($cmd == 'reboot'){
               //log_msg('running autocampars.py ['.implode(',',$IPs).'] pyCmd reboot');
               $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><lwir16_reboot/>");
258 259
               for ($i = 0; $i<count($GLOBALS[IPS]); $i++){
                   $xml_ip = $xml->addChild ('ip_'.$GLOBALS[IPS][$i]);
260 261 262 263 264 265 266
                   $xml_ip->addChild('reboot','started');
               }
               $rslt=$xml->asXML();
               header("Content-Type: text/xml");
               header("Content-Length: ".strlen($rslt)."\n");
               header("Pragma: no-cache\n");
               printf($rslt);
267
               exec ( 'autocampars.py ['.implode(',',$GLOBALS[IPS]).'] pyCmd reboot', $output, $retval );
268 269 270
               exit(0); // no time to close log
           } else if ($cmd == 'state'){
               // TODO: read all subcameras
271
               $state = file(CAMERA_STATE);
272 273 274 275 276 277 278 279 280 281 282 283 284
               $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><lwir16_state/>");
               foreach ($state as $line){
                   $kv = explode('=',$line);
                   if (count ($kv) > 1){
                        $xml->addChild (trim($kv[0]),trim($kv[1]));
                   }
               }
               $rslt=$xml->asXML();
               header("Content-Type: text/xml");
               header("Content-Length: ".strlen($rslt)."\n");
               header("Pragma: no-cache\n");
               printf($rslt);
               exit (0);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
           } else if ($cmd == TIFF_STATS) {
            /*
            echo "<pre>\n"; // ****************
            print_r($ini);
            print_r($GLOBALS);
            echo "</pre>";
            exit(0);
            */
            $urls = array();
            $xml_names = array();
            for ($i = 0; $i < count($GLOBALS[IPS]); $i ++) {
                // $_SERVER[SCRIPT_NAME] STARTS WITH '/'
                for ($port = 0; $port < 4; $port ++) if ($GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]] & (1 << $port)){
                    $url = 'http://' . $GLOBALS[IPS][$i] . ':'.(IMGSRV_PORT0+$port).
                    '/'.TIFF_TELEM.'='.$GLOBALS[TIFF_TELEM].
                    '/'.TIFF_MN.'='.$GLOBALS[TIFF_MN].
                    '/'.TIFF_MX.'='.$GLOBALS[TIFF_MX].
                    '/'.TIFF_BIN_SHIFT.'='.$GLOBALS[TIFF_BIN_SHIFT].
                    '/'.TIFF_STATS;
                    $urls[] = $url;
                    $xml_names[] = CAM_IP_PREF.$GLOBALS[IPS][$i].CAM_PORT_SEP.$port;
                }
            }
            
///            echo "<pre>\n"; // ****************
///            print_r($urls);
            $curl_data = curl_multi_start($urls);
            $enable_echo = false;
            $results = curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
///            print_r($xml_names);
//            if ($debug) {
///                printf("--- results:\n");
///                print_r($results);
                
 //           }
//            echo "</pre>";
//            exit(0);
            $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><".TIFF_STATS."/>");
            for ($i = 0; $i<count($results); $i++){
                $xml_ip_port = $xml->addChild ($xml_names[$i]);
///                echo("\n".$xml_names[$i]);
///                print_r($results[$i]);
                foreach ($results[$i] as $key=>$value){
                    $xml_ip_port->addChild($key,$value);
                }
            }
            $rslt=$xml->asXML();
///            var_dump($xml);
///            echo $rslt;
///            echo "</pre>";
///            exit(0);
            
            header("Content-Type: text/xml");
            header("Content-Length: ".strlen($rslt)."\n");
            header("Pragma: no-cache\n");
            printf($rslt);
            exit(0);
        }
      }
344 345
   } else { // Just output usage?
       echo <<<EOT
346 347 348 349 350 351 352 353 354 355 356 357 358
            <pre>
            This script supports initialization of the LWIR16 camera (16 LWIR 640x512 sensors and 4 2592x1936 color ones)
            and capturing of short image sequences (100 frames fit into 64MB per-channel image buffer) for (relatively)
            slow recording with camogm. Untill videocompression for 16-bit TIFFs is not implemented, recording is not fast
            enough for continupous recording. This script should be launched in the 'master' subcamera only, it will
            communidate with the other ones.
            
            URL parameters:
            <b>lwir16=init</b> - syncronize all 5 cameras, set acquisition parameters
            <b>lwir16=capture</b> - wait specified time, synchronously turn on compressors in each channel of each subcamera,
                                    acquire specified number of frames in each channel (reduced, and turn compressors off.
             
            </pre>
359
EOT;
360 361 362 363 364 365
// Watch EOT w/o any spaces! 
   }
   function runInit($debug = 0) {
        // TODO: use lwir16.ini
        $eo_quality = 97;
        $exposure = 1000; // 1 ms
366
        $autoExposureMax = 25000; // 500000; ~28ms - max for 10Hz
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        $autoExp = 1;
        $gain = 2 * 0x10000;
        $rScale = 1 * 0x10000;
        $bScale = 1 * 0x10000;
        $gScale = 1 * 0x10000;
        $autoWB = 1;
///        $extra = 2;
//        $wait = 1;
//        if ($nowait) {
//            $wait = 0;
//        }
        $COLOR_JP4 = 5;
        $COLOR_RAW = 15;
        $LWIR_HEIGHT = 512;
        $LWIR_TELEMETRY_LINES = 1;
        $LWIR_TELEMETRY = 1;
        $FRAMES_SKIP = 4;
        $FFC_FRAMES = 8;
        $REG_FFC_FRAMES = 'SENSOR_REGS4'; // Register for the number of FFC frames to integrate
        $REG_FFC_RUN = 'SENSOR_REGS26'; // Register to trigger FFC
        $lwir_ips = array(
            $GLOBALS[IPS][0],
            $GLOBALS[IPS][1],
            $GLOBALS[IPS][2],
            $GLOBALS[IPS][3]
        );
        $twoIPs = $GLOBALS[IPS]; // array($GLOBALS[IPS][0],$GLOBALS[IPS][4]); wait all
        if ($debug) {
            printf("--- twoIPs:\n");
            print_r($twoIPs);
        }
        
        $results0 = skipFrames($twoIPs, 2, $debug);
        
        
        // print_r($results0);
        $results1 = resetIPs($GLOBALS[IPS],$debug); // sync channels in each subcamera
                                             // print_r($results1);
        $results2 = skipFrames($twoIPs, 16,$debug); // was 1
                                             // print_r($results2); print("<br/>");
        $urls = array(); // eo - individual
        for ($i = 0; $i < (count($GLOBALS[IPS]) + 3); $i ++) {
            $nip = $i;
            if ($nip >= count($GLOBALS[IPS])) {
                $nip = count($GLOBALS[IPS]) - 1;
            }
            $urls[$i] = 'http://' . $GLOBALS[IPS][$nip] . '/parsedit.php?immediate&sensor_port=' . ($i - $nip);
            $urls[$i] .= '&TRIG_OUT=0x66555' . '&TRIG_CONDITION=0x95555' . '&TRIG_BITLENGTH=31' . '&EXTERN_TIMESTAMP=1' . '&XMIT_TIMESTAMP=1';
        }
        // print_r($urls); print("<br/>");
        // exit(0);
        for ($i = 0; $i < count($lwir_ips); $i ++) {
            $urls[$i] .= '&TRIG_DELAY=' . $lwir_trig_dly . '&*TRIG_DELAY=15' . // apply to all ports
            '&BITS=16&*BITS=15' . '&COLOR=' . $COLOR_RAW . '&*COLOR=15' . '&WOI_HEIGHT=' . ($LWIR_HEIGHT + ($LWIR_TELEMETRY ? $LWIR_TELEMETRY_LINES : 0)) . '&*WOI_HEIGHT=15' . '&' . $REG_FFC_FRAMES . '=' . $FFC_FRAMES . '&*' . $REG_FFC_FRAMES . '=15'; // apply to all channels
            $urls[$i] .= '&COMPRESSOR_RUN=2&*COMPRESSOR_RUN=15';
        }
        if ($debug) {
            print_r($GLOBALS[IPS]);
            print_r($urls);
        }
        for ($chn = 0; $chn < 4; $chn ++) {
            $urls[count($GLOBALS[IPS]) - 1 + $chn] .=
            "&COLOR=" . $COLOR_JP4 .
            "&QUALITY=" . $eo_quality .
            "&EXPOS=" . $exposure .
            "&AUTOEXP_EXP_MAX=" . $autoExposureMax .
            "&AUTOEXP_ON=" . $autoExp .
            "&GAING=" . $gain .
            "&RSCALE=" . $rScale . // "*0".
            "&BSCALE=" . $bScale . // "*0".
            "&GSCALE=" . $gScale . // "*0". // GB/G ratio
            "&WB_EN=" . $autoWB . // "*0".
            "&DAEMON_EN_TEMPERATURE=1"; // "*0";
            if (lrp . eo_full_window) {
                $urls[count($GLOBALS[IPS]) - 1 + $chn] .= "&WOI_LEFT=0" . "&WOI_TOP=0" . "&WOI_WIDTH=2592" . "&WOI_HEIGHT=1936";
            }
            if ($chn == 0) {
                $urls[count($GLOBALS[IPS]) - 1] .= '&COMPRESSOR_RUN=2&*COMPRESSOR_RUN=15';
            }
        }
        if ($debug) {
            printf("--- setting camera parameters, urls:\n");
            print_r($urls);
        }
        // print_r($urls);
        // exit(0);
        $curl_data = curl_multi_start($urls);
        $enable_echo = false;
        $results3 = curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
        if ($debug) {
            printf("--- results3:\n");
            print_r($results3);
        }
        
        
        
        $results4 = skipFrames($twoIPs, 16,$debug);
        // set external trigger mode for all LWIR and EO cameras
        $urls = array();
        for ($i = 0; $i < count($GLOBALS[IPS]); $i ++) {
            $urls[] = 'http://' . $GLOBALS[IPS][$i] .
            '/parsedit.php?immediate&sensor_port=0&TRIG=4&*TRIG=15' .
            '&COMPRESSOR_RUN=' . $GLOBALS[COMPRESSOR_RUN] . '*5&*COMPRESSOR_RUN=15'; // delay turning off COMPRESSOR_RUN
        }
        if ($debug) {
            printf("--- finally setting camera parameters (see COMPRESSOR_RUN), urls:\n");
            print_r($urls);
        }
        
        $curl_data = curl_multi_start($urls);
        $enable_echo = false;
        $results5 = curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
        if ($debug) {
            printf("--- results5:\n");
            print_r($results5);
        }
        
        $results6 = skipFrames($twoIPs, 16,$debug); // make sure all previous parameters are applied // waits for both LWIR and EO
                                             // second reset after cameras running synchronously
        $results7 = resetIPs($GLOBALS[IPS]); // sync channels in each subcamera
        $results8 = skipFrames($twoIPs, 16,$debug); // was 2
    
        $results9 = resetIPs($GLOBALS[IPS]); // sync channels in each subcamera
        $results10 = skipFrames($twoIPs, 16,$debug); // was 2
        $results = $results10;
        return $results;
   }

495
   function runCapture($run_ffc, $nowait = 0, $debug=0) { // works, but the main script hangs
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
       // TODO: use lwir16.ini
//       $eo_quality = 97;
//       $exposure = 1000; // 1 ms
//       $autoExposureMax = 500000;
//       $autoExp = 1;
//       $gain = 2 * 0x10000;
//       $rScale = 1 * 0x10000;
//       $bScale = 1 * 0x10000;
//       $gScale = 1 * 0x10000;
//       $autoWB = 1;
//       $extra = 2;
       $wait = 1;
       if ($nowait) {
           $wait = 0;
       }
       $COLOR_JP4 = 5;
       $COLOR_RAW = 15;
       $LWIR_HEIGHT = 512;
       $LWIR_TELEMETRY_LINES = 1;
       $LWIR_TELEMETRY = 1;
       $FRAMES_SKIP = 4;
       $FFC_FRAMES = 8;
       $REG_FFC_FRAMES = 'SENSOR_REGS4'; // Register for the number of FFC frames to integrate
       $REG_FFC_RUN = 'SENSOR_REGS26'; // Register to trigger FFC
       $lwir_ips = array(
           $GLOBALS[IPS][0],
           $GLOBALS[IPS][1],
           $GLOBALS[IPS][2],
           $GLOBALS[IPS][3]
       );
       $twoIPs = $GLOBALS[IPS]; // array($GLOBALS[IPS][0],$GLOBALS[IPS][4]); wait all
       $sensor_port = 0;
       if ($debug) {
           printf("--- runCapture: run_ffc=%d, wait=%d\n",$run_ffc,$wait);
           print_r($lwir_ips);
       }
       
       if ($run_ffc){ // may move after measuring time, but need to make sure it will be not too late
           runFFC($lwir_ips, $ffc_wait_frames, $debug);
       }
536
       
537 538 539
       $this_frame=elphel_get_frame($sensor_port);
       $this_timestamp=elphel_frame2ts($sensor_port,$this_frame);
       $timestamp = $this_timestamp + $GLOBALS[PRE_DELAY]; // this will be a delay between capture sequences
540
       
541 542 543 544 545
       $urls = array();
       for ($i = 0; $i<count($GLOBALS[IPS]); $i++){
           // $_SERVER[SCRIPT_NAME] STARTS WITH '/'
           $url = 'http://'.$GLOBALS[IPS][$i].'/capture_range.php?sensor_port='.$sensor_port; //
           $url .= '&ts='.$timestamp; // &timestamp" -> ×tamp
546 547
//           $url .= '&port_mask=15'; // .$port_mask[$i];
           $url .= '&port_mask='.$GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]]; //indexed by IPs
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
           $dur = ($i < 4) ? $GLOBALS[DURATION] : $GLOBALS[DURATION_EO];
           $url .= '&duration='. $dur;
           //                   $url .= '&maxahead='. $maxahead;
           //                   $url .= '&minahead='. $minahead;
           $url .= '&extra='.    CR_EXTRA; // $extra;
           if ($wait && ($i == (count($GLOBALS[IPS]) - 1))){ // addd to the last ip in a list
               $url .= '&wait';
           }
           $urls[] = $url;
       }
       if ($debug) {
           printf("--- runCapture: URLs:\n");
           print_r($urls);
       }
       
       $curl_data = curl_multi_start ($urls);
       $enable_echo = false;
       $results =  curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
       return $results;       
567 568
   }
   
569
   function runFFC($lwir_ips, $ffc_wait_frames, $debug=0) { // return number of frames used
570 571
       $skipped = 0;
       $port_masks =array();
572 573
       foreach ($lwir_ips as $lip){
           $port_masks[] = $GLOBALS[PORT_MASKS][$lip]; // select all 4 ports 
574
       }
575 576
       if      ($GLOBALS[FFC_GROUPS] == 1) $group_masks = array(15);
       else if ($GLOBALS[FFC_GROUPS] == 2) $group_masks = array(5, 10);
577
       else                       $group_masks = array(1, 2, 4, 8);
578 579 580 581 582 583 584
       if ($debug) {
           printf('$GLOBALS[FFC_GROUPS]=     '.$GLOBALS[FFC_GROUPS]."\n");
           printf('$GLOBALS[FFC_FRAMES]=     '.$GLOBALS[FFC_FRAMES]."\n");
           printf('$ffc_wait_frames='.$ffc_wait_frames."\n");
           print_r($group_masks);
       }
       for ($ig = 0; $ig < $GLOBALS[FFC_GROUPS]; $ig++){
585 586 587 588 589 590 591 592 593 594 595 596 597 598
           $urls = array();
           $ip0 = -1;
           for ($i = 0; $i < count($lwir_ips); $i++) { // start urls for 4 of lwir port0
               $mask = $port_masks[$i] & $group_masks[$ig];
               if ($mask != 0) {
                   $p=0;
                   for (;((1 << $p) & $mask) == 0; $p++); // find lowest non-zero bit
                   $urls[] = sprintf("http://%s/parsedit.php?immediate&sensor_port=%d&%s=1&*%s=%d",$lwir_ips[$i],$p,REG_FFC_RUN,REG_FFC_RUN,$mask);
                   if ($ip0 < 0) {
                       $ip0 = $i; // first used ip index
                   }
               }
               
           }
599 600 601 602
           if ($debug) {
               printf('$ig=    '.$ig."\n");
               print_r($urls);
           }
603 604 605 606 607
           if ($urls){ // not empty
               $curl_data = curl_multi_start ($urls);
               $enable_echo = false;
               $results =  curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
           }
608
           $skip_frames = 2 * $GLOBALS[FFC_FRAMES] + $ffc_wait_frames;
609
           skipFrames(array($lwir_ips[$ip0]),  $skip_frames);
610 611 612 613
           if ($debug) {
               printf("FFC done, result:\n");
               print_r($results);
           }
614 615 616 617 618 619 620 621
       }
       return $skipped; // better read actual frame after
   }
 
//   define("REG_FFC_FRAMES",     "SENSOR_REGS4");   // Register for the number of FFC frames to integrate
//   define("REG_FFC_RUN",        "SENSOR_REGS26"); // Register to trigger FFC
   
   
622
   function resetIPs($ips,$debug=0) {
623 624 625 626 627 628 629
       $frame = -2; // skip 2 frames before reset
       $urls = array();
       for ($i = 0; $i<count($ips); $i++){
           // $_SERVER[SCRIPT_NAME] STARTS WITH '/'
           $url = 'http://'.$ips[$i].'/'.SCRIPT_RESET.'?frame='.$frame; //
           $urls[] = $url;
       }
630 631 632 633
       if ($debug) {
           printf("--- resetIPs(), urls=\n");
           print_r($urls);
       }
634 635 636 637 638 639
       
       $curl_data = curl_multi_start ($urls);
       $enable_echo = false;
       return curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
   }

640
   function skipFrames($ips, $skip, $debug=0) {
641 642 643 644 645 646
       $urls = array();
       for ($i = 0; $i<count($ips); $i++){
//           $url = 'http://'.$ips[$i].$_SERVER[SCRIPT_NAME].'?frame='.$frame; //
           $url = 'http://'.$ips[$i].'/'.SCRIPT_WAIT.'?frame='.(-$skip); //
           $urls[] = $url;
       }
647 648 649 650
       if ($debug) {
           printf("--- skipFrames(%d), urls=\n",$skip);
           print_r($urls);
       }
651 652 653 654
       $curl_data = curl_multi_start ($urls);
       $enable_echo = false;
       return curl_multi_finish($curl_data, true, 0, $enable_echo); // Switch true -> false if errors are reported (other output damaged XML)
   }
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
   
   function lwir16_daemon() {
       // ini parameters are already read in
       declare(ticks = 1);
       set_time_limit(0); // no limit - run forever
       pcntl_signal(SIGTERM, "signal_handler");
       pcntl_signal(SIGINT, "signal_handler");
       
       if(file_exists(PIPE_CMD)){
           unlink(PIPE_CMD); //delete pipe if it was already there - waiting prevents signal handling!
       }
       $GLOBALS[DAEMON_RUN] = 1;
       $GLOBALS[CAPTURE_RUN] = 0; // until command
       $GLOBALS[LAST_FFC] = 0; // overdue
       $GLOBALS[SECUENCE_NUM] = 0;
670
       if ($GLOBALS[DEBUG] > 1)  { // was if ($GLOBALS[DEBUG > 1])  {
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
           printf("--- GLOBALS: ---\n");
           print_r($GLOBALS);
       }
//       exit(0);
       $from_pipe = false; // first commands are form INI
       while ($GLOBALS[DAEMON_RUN]){
           if (isset($GLOBALS[DAEMON_CMD])){ // execute command (INIT, RUN, STOP)
               $commands = explode(',',$GLOBALS[DAEMON_CMD]);
               unset($GLOBALS[DAEMON_CMD]);
               if ($GLOBALS[DEBUG])  {
                   printf("--- executing commands: ---\n");
                   print_r($commands);
               }
               
               foreach($commands as $cmd){
                   if ($cmd == CMD_INIT){
                       if ($GLOBALS[DEBUG])  printf("--- got command: INIT ---\n");
                       $result = runInit($GLOBALS[DEBUG]); // debug
                       if ($GLOBALS[DEBUG]){
                           printf("--- command: INIT done, result ---\n");
                           print_r($result);
                       }
                   } else if ($cmd == CMD_START){
                       $GLOBALS[CAPTURE_RUN] = 1;
                   } else if ($cmd == CMD_STOP){
                       $GLOBALS[CAPTURE_RUN] = 0;
                   } else if ($from_pipe && ($cmd == CMD_STATUS)){ // generate status data and send over response pipe
                       $state = file('/var/state/camera');
                       //TODO: add daemon status itself
                       $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><lwir16_status/>");
                       $xml_state = $xml->addChild ('state');
                       foreach ($state as $line){
                           $kv = explode('=',$line);
                           if (count ($kv) > 1){
                               $xml_state->addChild (trim($kv[0]),trim($kv[1]));
                           }
                       }
708 709 710
                       $GLOBALS[TIME_TO_FFC] = $GLOBALS[LAST_FFC] + $GLOBALS[FFC_PERIOD] - time();
                       $xml->addChild (SECUENCE_NUM,    $GLOBALS[SECUENCE_NUM]);
                       $xml->addChild (TIME_TO_FFC,     $GLOBALS[TIME_TO_FFC]);
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
                       $xml->addChild (IPS, implode(',',$GLOBALS[IPS]));
                       $xml->addChild (DURATION,        $GLOBALS[DURATION]);
                       $xml->addChild (DURATION_EO,     $GLOBALS[DURATION_EO]);
                       $xml->addChild (PRE_DELAY,       $GLOBALS[PRE_DELAY]);
                       $xml->addChild (FFC,             $GLOBALS[FFC]);
                       $xml->addChild (FFC_PERIOD,      $GLOBALS[FFC_PERIOD]);
                       $xml->addChild (FFC_GROUPS,      $GLOBALS[FFC_GROUPS]);
                       $xml->addChild (FFC_FRAMES,      $GLOBALS[FFC_FRAMES]);
                       $xml->addChild (COMPRESSOR_RUN,  $GLOBALS[COMPRESSOR_RUN]);
                       $xml->addChild (DEBUG,           $GLOBALS[DEBUG]);
                       $xml->addChild (DAEMON_RUN,      $GLOBALS[DAEMON_RUN]);
                       $xml->addChild (CAPTURE_RUN,     $GLOBALS[CAPTURE_RUN]);
                       $xml->addChild (LAST_FFC,        $GLOBALS[LAST_FFC]);
                       $rslt=$xml->asXML();
                       if(!file_exists(PIPE_RESPONSE)) {
                           // create the pipe
                           umask(0);
                           posix_mkfifo(PIPE_RESPONSE,PIPE_MODE);
                       }
                       $fr = fopen(PIPE_RESPONSE,"w");
                       fwrite($fr,$rslt);
                       fclose ($fr);
                       if ($GLOBALS[DEBUG]){
                           printf('--- command: Sent status report ---\n');
                           printf($rslt);
                       }
                   } else if ($cmd == CMD_EXIT){
                       $GLOBALS[CAPTURE_RUN] = 0;
                       unset($GLOBALS[DAEMON_RUN]);
                       continue;
                   } else if ($cmd == CMD_REBOOT){
                       exec ( 'autocampars.py ['.implode(',',$GLOBALS[IPS]).'] pyCmd reboot', $output, $retval );
                       exit(0);
                   }
               }
               continue; // try read new commands befor capturing
           }
           // Read / execute commands
           if(file_exists(PIPE_CMD)) {
               if ($GLOBALS[DEBUG]){
                   printf("--- got from pipe: ---\n");
               }
               /*
               $f = fopen(PIPE_CMD,"r");
               if ($GLOBALS[DEBUG]) echo "(r) opened cmd\n";
               $cmd_lines = fgets($f);
               fclose ($f);
               */
               $cmd_lines = file_get_contents(PIPE_CMD);
               if ($GLOBALS[DEBUG]) echo $cmd_lines."\n";
               if ($GLOBALS[DEBUG]) echo "(r) closed cmd\n";
               unlink(PIPE_CMD); //delete pipe
               $ini = parse_ini_string($cmd_lines); // parse_ini_file(PIPE_CMD); does not work!
               if ($GLOBALS[DEBUG]){
                   print_r($ini);
               }
767 768 769
               unset ($GLOBALS[DAEMON_CMD]);
               
               
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
               applyConf ($ini); // update $GLOBALS
               $from_pipe = true;
               if ($GLOBALS[DEBUG] > 1){
                   printf("--- update GLOBALS: ---\n");
                   print_r($GLOBALS);
               }
               continue; // will execute commands
           }
           if ($GLOBALS[DEBUG] > 1){
               printf("--- capture_run: ---%d \n",$GLOBALS[CAPTURE_RUN]);
           }
           if ($GLOBALS[CAPTURE_RUN]){
               $ffc_due = $GLOBALS[LAST_FFC] + $GLOBALS[FFC_PERIOD];
               $run_ffc = false;
               $now = time();
               if ($GLOBALS[FFC] && ($now > $ffc_due)){
                   $run_ffc = true;
                   $GLOBALS[LAST_FFC] = $now;
               }
               $result =  runCapture($run_ffc, false, $GLOBALS[DEBUG]);
               $GLOBALS[SECUENCE_NUM]++;
               if ($GLOBALS[DEBUG] > 1){
                   printf("--- capture_run: ---\n");
                   print_r($result);
               }
           } else {
               // jusrt skip a frame
               $ips0 = array($GLOBALS[IPS][0]); // just master camera IP
               $skip = 10; // OK if more
               $rslt = skipFrames($ips0,$skip);
           }
           
           
       }
       if ($GLOBALS[DEBUG]){
           printf("--- Exiting ...\n");
           if ($GLOBALS[DEBUG]>1){
               print_r($GLOBALS);
           }
       }
   }
   
   function signal_handler($signal) {
       switch($signal) {
           case SIGTERM:
               print "Caught SIGTERM\n";
               $GLOBALS[DAEMON_RUN] = 0;
               return; //  exit;
           case SIGKILL:
               print "Caught SIGKILL\n";
               $GLOBALS[DAEMON_RUN] = 0;
               return; //  exit;
           case SIGINT:
               print "Caught SIGINT\n";
               $GLOBALS[DAEMON_RUN] = 0;
               return; //  exit;
       }
   }
   
   function applyConf($arr){
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
       //port_masks=  "15,15,15,15,15"
       if (isset($arr[IPS])) {
           $GLOBALS[IPS] =        explode(',',$arr[IPS]);
           if (isset ($arr[PORT_MASKS])){
               $masks = explode(',',$arr[PORT_MASKS]);
           }
           // Add port masks incdexed by IPs. Changing IPs resets masks
           $GLOBALS[PORT_MASKS] = array();
           for ($i = 0; $i < count($GLOBALS[IPS]); $i++){
               if (isset($masks) && (count($masks) > $i)){
                   $GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]] = (int) $masks[$i];
               } else {
                   $GLOBALS[PORT_MASKS][$GLOBALS[IPS][$i]] = ALL_PORTS;
               }
           }
       }
846 847 848 849 850 851 852 853 854 855 856 857
       if (isset($arr[DURATION])){
           $GLOBALS[DURATION] =   (int)       $arr[DURATION];
           $GLOBALS[DURATION_EO] = (int) ($GLOBALS[DURATION]/EO_DECIMATE+1);
       }
       if (isset($arr[DURATION_EO]))     $GLOBALS[DURATION_EO] = (int)      $arr[DURATION_EO];
       if (isset($arr[PRE_DELAY]))       $GLOBALS[PRE_DELAY] =  (double)    $arr[PRE_DELAY];
       if (isset($arr[FFC_PERIOD]))      $GLOBALS[FFC_PERIOD] = (double)    $arr[FFC_PERIOD];
       if (isset($arr[FFC_GROUPS]))      $GLOBALS[FFC_GROUPS] = (int)       $arr[FFC_GROUPS];
       if (isset($arr[FFC_FRAMES]))      $GLOBALS[FFC_FRAMES] = (int)       $arr[FFC_FRAMES];
       if (isset($arr[DAEMON_CMD]))      $GLOBALS[DAEMON_CMD] =             $arr[DAEMON_CMD];
       if (isset($arr[DEBUG]))           $GLOBALS[DEBUG] = (int)            $arr[DEBUG];
       if (isset($arr[COMPRESSOR_RUN]))  $GLOBALS[COMPRESSOR_RUN] = (int)   $arr[COMPRESSOR_RUN]; // only after INIT
858
       if (isset($arr[FFC]))             $GLOBALS[FFC] =                    $arr[FFC]?1:0;
859 860 861 862 863
       if (isset($arr[TIFF_TELEM]))      $GLOBALS[TIFF_TELEM] = (int)       $arr[TIFF_TELEM];
       if (isset($arr[TIFF_MN]))         $GLOBALS[TIFF_MN] = (int)          $arr[TIFF_MN];
       if (isset($arr[TIFF_MX]))         $GLOBALS[TIFF_MX] = (int)          $arr[TIFF_MX];
       if (isset($arr[TIFF_BIN_SHIFT]))  $GLOBALS[TIFF_BIN_SHIFT] = (int)   $arr[TIFF_BIN_SHIFT];
       if (isset($arr[TIFF_AUTO]))       $GLOBALS[TIFF_AUTO] = (int)        $arr[TIFF_AUTO];
864
       if (isset($arr[OUTPUT_LOG]))      $GLOBALS[OUTPUT_LOG] =             $arr[OUTPUT_LOG];
865 866 867 868 869 870 871 872 873
   }

/**
 * start/stop/restart/status/pars daemon
 *
 * @param string $cmd
 */
    function daemon_control($cmd)
    {
874 875 876 877
//        echo "<pre>\n";
//        print_r($_SERVER);
//        echo "</pre>\n";
//        exit(0);
878
        // see if it already running
879
        $debug = 0;
880 881 882 883 884
        $max_wait = 10; // seconds
//        $sript_name = substr($_SERVER['SCRIPT_NAME'], 1); // remove leading '/'
        $sript_path = $_SERVER['SCRIPT_FILENAME'];
        $sript_name = basename($sript_path);
        $pids = getPIDByName($sript_name, 'php', $active_only = false);
885 886 887 888 889
        
//        echo "<pre>0:\n";
//        print_r($pids);
//        echo "</pre>\n";
        
890 891
        // Stop if needed
        if ($pids && (($cmd == 'restart') || ($cmd == 'stop'))) {
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
            // below - does not work with non-blocking "w+", will take care later
            /*
         * $mode = 0600;
         * if (! file_exists(PIPE_CMD)) {
         * // create the pipe
         * umask(0);
         * posix_mkfifo(PIPE_CMD, $mode);
         * }
         * $f = fopen(PIPE_CMD, "w+"); // make it non-blocking as the receiver may be hang
         * fwrite($f, "CMD=EXIT");
         * fclose($f);
         * for ($i = 0; $pids && ($i < $max_wait); $i ++) {
         * sleep (1);
         * $pids = getPIDByName($sript_name, 'php', $active_only = false);
         * }
         */

            // if(file_exists(PIPE_CMD)) unlink(PIPE_CMD); //delete pipe
            // if(file_exists(PIPE_RESPONSE)) unlink(PIPE_RESPONSE); //delete pipe

            // print_r($pids);
        if ($debug) {
            echo "<pre>1:\n";
            print_r($pids);
            echo "</pre>\n";
        }
            
            if ($pids) { // did not exit, ask politely
                foreach ($pids as $proc) {
                    exec('kill ' . $proc['pid'], $output, $retval);
                }
923
            }
924 925 926 927 928 929 930 931
            if ($debug) {
                echo "<pre>2:\n";
                print_r($pids);
                echo "</pre>\n";
            }
            
            for ($i = 0; $pids && ($i < $max_wait); $i ++) {
                sleep (1);
932 933
                $pids = getPIDByName($sript_name, 'php', $active_only = false);
            }
934 935 936 937 938 939
            if ($debug) {
                echo "<pre>3:\n";
                print_r($pids);
                echo "</pre>\n";
            }
            if ($pids) { // did not exit - just kill them
940 941 942 943
                foreach ($pids as $proc) {
                    exec('kill -9 ' . $proc['pid'], $output, $retval);
                }
            }
944 945 946 947 948 949 950
            $pids = getPIDByName($sript_name, 'php', $active_only = false);
            if ($debug) {
                echo "<pre>4\n";
                print_r($pids);
                echo "</pre>\n";
            }
            
951 952
        }
        $pids = getPIDByName($sript_name, 'php', $active_only = false);
953 954 955
        
//        print_r($pids);
        
956
        if (!$pids && ($cmd != 'stop')) {
957 958 959
//            exec($sript_path . ' > /dev/null 2>&1 &'); // "> /dev/null 2>&1 &" makes sure it is really really run as a background job that does not wait for input
            exec($sript_path . ' > '.  $GLOBALS[OUTPUT_LOG] .' 2>&1 &'); // "> /dev/null 2>&1 &" makes sure it is really really run as a background job that does not wait for input
            // wait it to run
960 961 962 963 964 965
            for ($i = 0; $i < $max_wait; $i ++) {
                $pids = getPIDByName($sript_name, 'php', $active_only = false);
                if ($pid) break;
            }
            
        }
966 967 968 969 970 971 972 973
        /*
        $exit_ps = ($cmd == 'stop') || !pids ; // nothing else to do if it is not running
        if (($cmd == 'restart') || ($cmd == 'start')){
            if (!isset ($_GET[DAEMON_CTRL_CMDS]) && !isset ($_GET[DAEMON_CMD])){ // no other commands (like "status")
                $exit_ps = true;
            }
        }
        */
974
        if (($cmd == 'restart') || ($cmd == 'start') || ($cmd == 'stop') || !pids) { // nothing else to do if it is not running
975
//        if ($exit_ps) { // nothing else to do if it is not running just respond with $pids xml
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><lwir16_daemon_status/>");
            if ($pids) {
                /*
                echo "<pre>\n";
                print_r($pids);
                echo "</pre>\n";
                exit(0);
                */
                foreach ($pids[0] as $key => $value) {
                    if (is_array($value)){
                        $xml_arr= $xml->addChild($key);
                        for ($i = 0; $i < count($value); $i++) {
                            $xml_arr->addChild($key.$i, $value[$i]);
                        }
                       // $value = serialize($value);
                    } else {
                        $xml->addChild($key, $value);
                    }
                    
                }
                if (count($pids) > 1) { // abnormal
                    $arr = array();
                    for ($i = 1; $i < count($pids); $i ++) {
                        $arr[] = $pids[$i]['pid'];
                    }
                    $xml->addChild('other_pids', implode(',', $arr));
                }
            } else {
                $xml->addChild($sript_name, 'not running');
            }
            $rslt=$xml->asXML();
            header("Content-Type: text/xml");
            header("Content-Length: ".strlen($rslt)."\n");
            header("Pragma: no-cache\n");
            printf($rslt);
            exit(0);
        }
        // process other commands (all but status are 'silent'
        $parameters = array();
        unset ($daemon_cmds);
        foreach($_GET as $key=>$value) {
            if ($key != DAEMON_CTRL){ // already processed
                if (($key == DAEMON_CTRL_CMDS) || ($key == DAEMON_CMD)){ // CMD/cmd confusion
                    $daemon_cmds = $value;
                } else {
                    $parameters[$key]= $value;
                }
            }
        }
        if ($cmd == 'status'){
            if (!isset($daemon_cmds)){
                $daemon_cmds=CMD_STATUS;
            } else if (strstr($daemon_cmds,CMD_STATUS) === false){
                $daemon_cmds .= ','.CMD_STATUS;
            }
        }
        $cmds_to_send = "";
        foreach ($parameters as $key=>$value){
            $cmds_to_send .= sprintf("%s = %s\n",$key,$value);
        }
        $cmds_to_send .= sprintf("%s = %s\n",DAEMON_CMD,$daemon_cmds);
        $has_status= strstr($daemon_cmds,CMD_STATUS) !== false;
        
        $mode=0600;
        if(!file_exists(PIPE_CMD)) {
            // create the pipe
            umask(0);
            posix_mkfifo(PIPE_CMD,$mode);
        }
        if (file_exists(PIPE_RESPONSE)){
            unlink(PIPE_RESPONSE); //delete old pipe
        }
        /*
        echo "<pre>\n";
        print_r($cmds_to_send);
        echo 'has_status='.$has_status."\n";
        echo 'daemon_cmds='.$daemon_cmds."\n";
        echo "parameters\n";
        print_r($parameters);
        echo "</pre>\n";
        exit(0);
        */
        $f = fopen(PIPE_CMD,"w");
        fwrite($f,$cmds_to_send);
//        echo "(w) sent commands:\n".$cmds."\n";
        fclose ($f);
//        echo "(w) closed\n";
        if ($has_status) {
            while (!file_exists(PIPE_RESPONSE)); // just wait
//            echo "(w) got PIPE_RESPONSE\n";
            $rslt = file_get_contents(PIPE_RESPONSE);
//            var_dump($fl);
            unlink(PIPE_RESPONSE); //delete pipe
            header("Content-Type: text/xml");
            header("Content-Length: ".strlen($rslt)."\n");
            header("Pragma: no-cache\n");
            printf($rslt);
            exit(0);
        } else {
            $xml = new SimpleXMLElement("<?xml version='1.0'  standalone='yes'?><lwir16_daemon_input/>");
            foreach ($parameters as $key => $value) {
                $xml->addChild($key, $value);
            }
            if ($daemon_cmds) {
                $xml->addChild(DAEMON_CMD, $daemon_cmds);
            }
            $rslt=$xml->asXML();
            header("Content-Type: text/xml");
            header("Content-Length: ".strlen($rslt)."\n");
            header("Pragma: no-cache\n");
            printf($rslt);
            exit(0);
        }
    }
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    
    function isCameraBooted(){
        return (getCameraState(CAMERA_STATE) == 'INITIALIZED');
    }
    
    function getCameraState($camera_state_file){
        if (!file_exists($camera_state_file)){
            return NULL;
        }
        $camera_state =  parse_ini_file($camera_state_file);
        return $camera_state['state'];
    }
1102
   
1103
?>