Commit 3f787424 authored by Mikhail Karpenko's avatar Mikhail Karpenko

Add imgsrv from elphel353

This commit adds almost non modified files from elphel353 source tree.
Changes made to source files include additional debug output, commented
out code and updates to source paths in makefile and includes.
parents
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/imgsrv/run_bitbake.sh}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="incremental,"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="apps-imgsrv -c compile -f"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>
<?xml version="1.0" standalone="yes"?>
<!--
attributes:
tag - Exif tag (full tag in the camera will combine tag and group<<16
format: format (BYTE/ASCII/SHORT/LONG/RATIONAL/UNDEFINED?SLONG?SRATIONAL
count: number of values (characters in ASCII)
seq: sequence number of the variable data field (stored in a frame buffer)
If not specified - static data
dlen: length of a variable data field, stored in frame buffer
ltag: Exif_tag+(group<<16). If specified, is used by the software, while the Exif output will still have tag
SubSecTimeOriginal should go immediately after DateTimeOriginal (in the sequence numbers, not in the Exif templete)
-->
<Exif>
<Image>
<ImageDescription tag="0x010e" format="ASCII" count="65" seq="16" dlen="64">
<!-- <value>Description 0x41 bytes long </value>-->
<value>Description 0x40 bytes long</value>
</ImageDescription>
<Make tag="0x010f" format="ASCII" function="BRAND"/>
<Model tag="0x0110" format="ASCII" function="MODEL"/>
<Software tag="0x0131" format="ASCII" function="SOFTWARE"/>
<DateTime tag="0x0132" format="ASCII" count="20" seq="1" dlen="20">
<value>2001:06:21 12:00:00</value>
</DateTime>
<HostComputer tag="0x013c" format="ASCII" function="SERIAL"/>
<FrameNumber tag="0x83bb" format="LONG" count="1" seq="25" dlen="4"/>
<Orientation tag="0x112" format="SHORT" count="1" seq="27" dlen="2"/>
<ExifTag tag="0x8769" format="LONG" function="EXIFTAG"/>
<GPSTag tag="0x08825" format="LONG" function="GPSTAG"/>
</Image>
<Photo>
<ExposureTime tag="0x829a" format="RATIONAL" seq="3" dlen="4">
<nominator>1</nominator> <denominator>1000000</denominator>
</ExposureTime>
<DateTimeOriginal tag="0x9003" format="ASCII" count="20" seq="5" dlen="20">
<value>2001:06:21 12:00:00</value>
</DateTimeOriginal>
<SubSecTimeOriginal tag="0x9291" format="ASCII" count="7" seq="6" dlen="7">
<value>0 </value>
</SubSecTimeOriginal>
<MakerNote tag="0x927c" format="LONG" count="16" seq="26" dlen="64"/>
</Photo>
<GPSInfo>
<GPSVersionID tag="0x0" format= "BYTE" count="4">
<value>2</value>
<value>2</value>
<value>0</value>
<value>0</value>
</GPSVersionID>
<GPSLatitudeRef tag="0x1" format= "ASCII" count="2" seq="7" dlen="1">
<value>N</value>
</GPSLatitudeRef>
<GPSLatitude tag="0x2" format= "RATIONAL" count="3" seq="8" dlen="16">
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
</GPSLatitude>
<GPSLongitudeRef tag="0x3" format= "ASCII" count="2" seq="9" dlen="1">
<value>W</value>
</GPSLongitudeRef>
<GPSLongitude tag="0x4" format= "RATIONAL" count="3" seq="10" dlen="16">
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
</GPSLongitude>
<GPSAltitudeRef tag="0x5" format= "BYTE" count="1" seq="11" dlen="1">
<value>0x0</value>
</GPSAltitudeRef>
<GPSAltitude tag="0x6" format= "RATIONAL" count="1" seq="12" dlen="8">
<nominator>0</nominator><denominator>1</denominator>
</GPSAltitude>
<GPSTimeStamp tag="0x7" format= "RATIONAL" count="3" seq="13" dlen="24">
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
</GPSTimeStamp>
<GPSMeasureMode tag="0xa" format= "ASCII" count="2" seq="15" dlen="1">
<value>0</value>
</GPSMeasureMode>
<GPSDateStamp tag="0x1d" format= "ASCII" count="11" seq="14" dlen="11">
<value>0000:00:00</value>
</GPSDateStamp>
<!--Compass fileds - hack: using dest lat/long as no roll/pitch fields are available in Exif-->
<CompassDirectionRef tag="0x10" format= "ASCII" count="2">
<value>M</value>
</CompassDirectionRef>
<CompassDirection tag="0x11" format= "RATIONAL" count="1" seq="20" dlen="8">
<nominator>0</nominator><denominator>10</denominator>
</CompassDirection>
<CompassPitchRef tag="0x13" format= "ASCII" count="2" seq="21" dlen="1">
<value>N</value>
</CompassPitchRef>
<CompassPitch tag="0x14" format= "RATIONAL" count="3" seq="22" dlen="8">
<nominator>0</nominator><denominator>10</denominator>
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
</CompassPitch>
<CompassRollRef tag="0x15" format= "ASCII" count="2" seq="23" dlen="1">
<value>E</value>
</CompassRollRef>
<CompassRoll tag="0x16" format= "RATIONAL" count="3" seq="24" dlen="8">
<nominator>0</nominator><denominator>10</denominator>
<nominator>0</nominator><denominator>1</denominator>
<nominator>0</nominator><denominator>1</denominator>
</CompassRoll>
</GPSInfo>
</Exif>
AXIS_USABLE_LIBS = UCLIBC GLIBC
#include $(AXIS_TOP_DIR)/tools/build/Rules.axis
INSTDIR = $(prefix)/usr/local/sbin/
PHPDIR = $(prefix)/usr/html/
CONFDIR = $(prefix)/etc/
INSTMODE = 0755
INSTOTHER = 0644
INSTOWNER = root
INSTGROUP = root
INCDIR = $(prefix)/include
PROGS = imgsrv
#OTHERFILES = exif_init.php
PHPCLI = exif.php imu_setup.php start_gps_compass.php
CONFFILES = Exif_template.xml
SRCS = imgsrv.c
OBJS = imgsrv.o
CFLAGS += -Wall -I$(ELPHEL_KERNEL_DIR)/include/elphel
#CFLAGS += -Wall -I$(INCDIR) -I$(ELPHEL_KERNEL_DIR)/include
#CFLAGS += -Wall -I$(INCDIR) -I$(AXIS_KERNEL_DIR)/include -save-temps -dA -dP
all: $(PROGS)
$(PROGS): $(OBJS)
$(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@
# cris-strip -s $@
install: $(PROGS)
$(INSTALL) -d $(INSTDIR)
$(INSTALL) -m $(INSTMODE) -o $(INSTOWNER) -g $(INSTGROUP) $(PROGS) $(INSTDIR)
$(INSTALL) -d $(PHPDIR)
$(INSTALL) -m $(INSTMODE) -o $(INSTOWNER) -g $(INSTGROUP) $(PHPCLI) $(PHPDIR)
$(INSTALL) -d $(CONFDIR)
$(INSTALL) -m $(INSTOTHER) -o $(INSTOWNER) -g $(INSTGROUP) $(CONFFILES) $(CONFDIR)
clean:
rm -rf $(PROGS) *.o core
dependency:
make depend
depend:
makedepend -Y -- $(CFLAGS) -- $(SRCS) 2>/dev/null
touch dependency
# DO NOT DELETE
#!/usr/local/sbin/php -q
<?php
/*!
*! FILE NAME : exif.php
*! DESCRIPTION: This program collects information about the camera (version, software, sensor)
*! and combines it with the Exif template (default is /etc/Exif_template.xml) to prepare generation
*! of Exif headers.
*! It works in a command line with a single optional parameter - location of the template file and
*! trough the CGI interface. In that case it accepts the following parameter
*! init - program Exif with default /etc/Exif_template.xml
*! init=path - program Exif with alternative file
*! noGPS - don't include GPS-related fields
*! nocompass - don't include compass-related fields
*! template - print currently loaded template data (hex dump)
*! metadir - print currently loaded meta directory that matches variable Exif fields with the template
*! exif=0 - print current Exif page (updated in real time)
*! exif=NNN - print one of the Exif pages in the buffer (debug feature, current buffer pointer is not known here)
*!
*! Copyright (C) 2007-2008 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/>.
*! -----------------------------------------------------------------------------**
*! $Log: exif.php,v $
*! Revision 1.2 2010/08/10 21:14:31 elphel
*! 8.0.8.39 - added EEPROM support for multiplexor and sensor boards, so autocampars.php uses application-specific defaults. Exif Orientation tag support, camera Model reflects application and optional mode (i.e. camera number in Eyesis)
*!
*! Revision 1.1.1.1 2008/11/27 20:04:01 elphel
*!
*!
*! Revision 1.2 2008/08/11 19:11:32 elphel
*! comments
*!
*! Revision 1.1 2008/04/07 09:12:14 elphel
*! New Exif template generation
*!
*! $Log: exif.php,v $
*! Revision 1.2 2010/08/10 21:14:31 elphel
*! 8.0.8.39 - added EEPROM support for multiplexor and sensor boards, so autocampars.php uses application-specific defaults. Exif Orientation tag support, camera Model reflects application and optional mode (i.e. camera number in Eyesis)
*!
*! Revision 1.1.1.1 2008/11/27 20:04:01 elphel
*!
*!
*! Revision 1.2 2008/08/11 19:11:32 elphel
*! comments
*!
*! Revision 1.1 2008/04/07 09:12:14 elphel
*! New Exif template generation
*!
*! Revision 1.1.1.1 2007/10/03 19:05:53 elphel
*! This is a fresh tree based on elphel353-2.10
*!
*! Revision 1.6 2007/10/03 19:05:53 elphel
*! cosmetic
*!
*! Revision 1.5 2007/10/03 18:37:53 elphel
*! Made nice html output to see the result data
*!
*! Revision 1.4 2007/10/03 06:33:31 elphel
*! fixed wrong copyright year
*!
*! Revision 1.3 2007/10/02 19:44:03 elphel
*! minor bug fixes, added "manufacturer note" field for raw frame metadata (36 bytes - /include/asm-cris/c313.h frame_params_t)
*!
*! Revision 1.2 2007/09/25 23:34:02 elphel
*! Fixed time strings to the right length
*!
*! Revision 1.1 2007/09/24 07:27:57 elphel
*! Started php script that prepares Exif header information for serving images by imgsrv
*!
*/
//TODO: Decide with the start sequence, more data is availble after the sensor is initialized.
// Or leave it to imgsrv (it still needs sensor to start first), just put placeholders
// use http://www.exiv2.org/tags.html for reference of the Exif fields if you need to add modify
// the data below
$ExifDeviceTemplateFilename="/dev/exif_template";
$ExifDeviceMetadirFilename= "/dev/exif_metadir";
$ExifDeviceExifFilename= "/dev/exif_exif";
$ExifDeviceMetaFilename= "/dev/exif_meta";
//! if called from the command line - accepts just one parameter - configuration file,
//! through CGI - accepts more parameters
$ExifXMLName="/etc/Exif_template.xml";
$init=false;
if ($_SERVER['REQUEST_METHOD']=="GET") {
if ($_GET["init"]!==NULL) {
if ($_GET["init"]) $ExifXMLName=$_GET["init"];
$init=true; // in any case - filename specified or not
$noGPS= ($_GET["noGPS"]!==NULL);
$nocompass= ($_GET["nocompass"]!==NULL);
}
} else {
foreach ($_SERVER['argv'] as $param) if (substr($param,0,4)=="init") {
$param=substr($param,5);
if (strlen($param)>0) $ExifXMLName=$param;
$init=true; //
break;
}
if ($init) {
$noGPS= in_array ('noGPS' , $_SERVER['argv']);
$nocompass= in_array ('nocompass', $_SERVER['argv']);
} else {
echo <<<USAGE
Usage: {$_SERVER['argv'][0]} [init[=filename.xml] [noGPS] [nocompass]]
USAGE;
exit (0);
}
}
define("EXIF_BYTE", 1);
define("EXIF_ASCII", 2);
define("EXIF_SHORT", 3);
define("EXIF_LONG", 4);
define("EXIF_RATIONAL", 5);
define("EXIF_SBYTE", 6);
define("EXIF_UNDEFINED", 7);
define("EXIF_SSHORT", 8); //obsolete?
define("EXIF_SLONG", 9);
define("EXIF_SRATIONAL",10);
define("EXIF_LSEEK_ENABLE", 2); // rebuild buffer
/// ===== init/init= CGI parameters or command line mode =======
if ($init) { // configure Exif data
$exif_head= array (
0xff, 0xe1, // APP1 marker
// offset=2 - start of Exif header
0x00, 0x00, // - length of the Exif header (including this length bytes) - we'll fill it later, we do not know it yet
0x45,0x78,0x69,0x66,0x00,0x00); // Exif header
$Exif_length_offset= 2; // put total length here (big endian, 2 bytes)
$exif_data= array (// start of TIFF Header, data offsets will match indexes in this array
0x4d,0x4d, // (MM) Big endian, MSB goes first in multi-byte data
0x00,0x2a, // Tag Mark
0x00,0x00,0x00,0x08); //offset to first IDF (from the beginning of the TIFF header, so 8 is minimum)
$xml_exif = simplexml_load_file($ExifXMLName);
if ($xml_exif->GPSInfo) {
/// remove all tags named "Compass..."
if ($nocompass) {
$tounset=array();
foreach ($xml_exif->GPSInfo->children() as $entry) if (strpos ($entry->getName() , "Compass" )!==false) $tounset[]=$entry->getName();
foreach ($tounset as $entry) unset ($xml_exif->GPSInfo->{$entry});
}
if ($noGPS) {
unset($xml_exif->GPSInfo);
unset($xml_exif->Image->GPSTag);
}
}
$IFD_offset= count($exif_data);
$SUB_IFD_offset= 12*count($xml_exif->Image->children())+2+4+$IFD_offset;
$GPSInfo_offset= 12*count($xml_exif->Photo->children())+2+4+$SUB_IFD_offset;
$data_offset= $GPSInfo_offset+(($xml_exif->GPSInfo)?(12*count($xml_exif->GPSInfo->children())+2+4):0); //$GPSInfo is optional
if ($_SERVER['REQUEST_METHOD']) {
echo "<pre>";
printf ("IFD_offset=0x%x\n",$IFD_offset);
printf ("SUB_IFD_offset=0x%x\n",$SUB_IFD_offset);
printf ("GPSInfo_offset=0x%x\n",$GPSInfo_offset);
printf ("data_offset=0x%x\n",$data_offset);
}
/// Now modify variable fields substituting values
foreach ($xml_exif->Image->children() as $entry) substitute_value($entry);
foreach ($xml_exif->Photo->children() as $entry) substitute_value($entry);
if ($xml_exif->GPSInfo) {
foreach ($xml_exif->GPSInfo->children() as $entry) substitute_value($entry);
}
$ifd_pointer=$IFD_offset;
$data_pointer=$data_offset;
start_ifd(count($xml_exif->Image->children()));
foreach ($xml_exif->Image->children() as $entry) process_ifd_entry($entry,0);
finish_ifd();
$ifd_pointer=$SUB_IFD_offset;
start_ifd(count($xml_exif->Photo->children()));
foreach ($xml_exif->Photo->children() as $entry) process_ifd_entry($entry,1);
finish_ifd();
if ($xml_exif->GPSInfo) {
$ifd_pointer=$GPSInfo_offset;
start_ifd(count($xml_exif->GPSInfo->children()));
foreach ($xml_exif->GPSInfo->children() as $entry) process_ifd_entry($entry,2);
finish_ifd();
}
$exif_len=count($exif_head)+count($exif_data)-$Exif_length_offset;
$exif_head[$Exif_length_offset]= ($exif_len >> 8) & 0xff;
$exif_head[$Exif_length_offset+1]= $exif_len & 0xff;
$Exif_str="";
for ($i=0; $i<count($exif_head);$i++) $Exif_str.= chr ($exif_head[$i]);
for ($i=0; $i<count($exif_data);$i++) $Exif_str.= chr ($exif_data[$i]);
$Exif_file = fopen($ExifDeviceTemplateFilename, 'w');
fwrite ($Exif_file,$Exif_str); /// will disable and invalidate Exif data
fclose($Exif_file);
///Exif template is done, now we need a directory to map frame meta data to fields in the template.
$dir_sequence=array();
$dir_entries=array();
foreach ($xml_exif->Image->children() as $entry) addDirEntry($entry);
foreach ($xml_exif->Photo->children() as $entry) addDirEntry($entry);
if ($xml_exif->GPSInfo) {
foreach ($xml_exif->GPSInfo->children() as $entry) addDirEntry($entry);
}
array_multisort($dir_sequence,$dir_entries);
$frame_meta_size=0;
for ($i=0;$i<count($dir_entries);$i++) {
$dir_entries[$i]["src"]=$frame_meta_size;
$frame_meta_size+=$dir_entries[$i]["len"];
}
$Exif_str="";
foreach ($dir_entries as $entry) $Exif_str.=pack("V*",$entry["ltag"],$entry["len"],$entry["src"],$entry["dst"]);
$Exif_meta_file = fopen($ExifDeviceMetadirFilename, 'w');
fwrite ($Exif_meta_file,$Exif_str); /// will disable and invalidate Exif data
fclose($Exif_meta_file);
///Rebuild buffer and enable Exif generation/output:
$Exif_file = fopen($ExifDeviceTemplateFilename, 'w');
fseek ($Exif_file, EXIF_LSEEK_ENABLE, SEEK_END) ;
fclose($Exif_file);
if ($_SERVER['REQUEST_METHOD']) {
echo "</pre>";
}
if ($_SERVER['REQUEST_METHOD']) {
echo "<hr/>\n";
test_print_header();
echo "<hr/>\n";
test_print_directory();
}
} //if ($init) // configure Exif data
/// ===== processing optional parameters =======
/// ===== read template =======
if ($_GET["description"]!==NULL) {
/// Read metadir to find the length of the description field
$Exif_file = fopen($ExifDeviceMetadirFilename, 'r');
fseek ($Exif_file, 0, SEEK_END) ;
fseek ($Exif_file, 0, SEEK_SET) ;
$metadir=fread ($Exif_file, 4096);
fclose($Exif_file);
$dir_entries=array();
for ($i=0; $i<strlen($metadir);$i+=16) {
$dir_entries[]=unpack("V*",substr($metadir,$i,16));
}
foreach ($dir_entries as $entry)
if ($entry[1]==0x010e) {
$descr=$_GET["description"];
$Exif_file = fopen($ExifDeviceMetaFilename, 'w+');
fseek ($Exif_file, $entry[3], SEEK_SET) ;
$descr_was=fread ($Exif_file, $entry[2]);
$zero=strpos($descr_was,chr(0));
if ($zero!==false) $descr_was=substr($descr_was,0, $zero);
if ($descr) {
$descr= str_pad($descr, $entry[2], chr(0));
fseek ($Exif_file, $entry[3], SEEK_SET) ;
fwrite($Exif_file, $descr,$entry[2]);
}
fclose($Exif_file);
var_dump($descr_was); echo "<br/>\n";
break;
}
}
/// ===== read template =======
if ($_GET["template"]!==NULL) {
$Exif_file = fopen($ExifDeviceTemplateFilename, 'r');
fseek ($Exif_file, 0, SEEK_END) ;
echo "<hr/>\n";
echo "ftell()=".ftell($Exif_file).", ";
fseek ($Exif_file, 0, SEEK_SET) ;
$template=fread ($Exif_file, 4096);
fclose($Exif_file);
echo "read ".strlen($template)." bytes<br/>\n";
hexdump($template);
}
/// ===== read meta directory =======
if ($_GET["metadir"]!==NULL) {
$Exif_file = fopen($ExifDeviceMetadirFilename, 'r');
fseek ($Exif_file, 0, SEEK_END) ;
echo "<hr/>\n";
echo "ftell()=".ftell($Exif_file).", ";
fseek ($Exif_file, 0, SEEK_SET) ;
$metadir=fread ($Exif_file, 4096);
fclose($Exif_file);
echo "read ".strlen($metadir)." bytes<br/>\n";
$dir_entries=array();
for ($i=0; $i<strlen($metadir);$i+=16) {
$dir_entries[]=unpack("V*",substr($metadir,$i,16));
}
print_directory($dir_entries);
}
/// ===== read one of the Exif pages (0 - current, 1..512 - buffer) =======
if ($_GET["exif"]!==NULL) {
$frame=$_GET["exif"]+0;
echo "<hr/>\n";
printf ("Reading frame %d, ",$frame);
$Exif_file = fopen($ExifDeviceExifFilename, 'r');
fseek ($Exif_file, 1, SEEK_END) ;
$exif_size=ftell($Exif_file);
if ($frame) fseek ($Exif_file, $frame, SEEK_END) ;
else fseek ($Exif_file, 0, SEEK_SET) ;
echo "ftell()=".ftell($Exif_file).", ";
$exif_data=fread ($Exif_file, $exif_size);
fclose($Exif_file);
echo "read ".strlen($exif_data)." bytes<br/>\n";
hexdump($exif_data);
}
exit(0);
/// ======================================= Functions ======================================
function hexdump($data) {
global $exif_head, $exif_data;
$l=strlen($data);
printf ("<h2>Exif size=%d bytes</h2>\n",$l);
printf ("<table border=\"0\">\n");
for ($i=0; $i<$l;$i=$i+16) {
printf("<tr><td>%03x</td><td>|</td>\n",$i);
for ($j=$i; $j<$i+16;$j++) {
printf("<td>");
if ($j<$l) {
$d=ord($data[$j]);
printf(" %02x",$d);
} else printf (" ");
printf("</td>");
}
printf("<td>|</td>");
for ($j=$i; $j< ($i+16);$j++) {
printf("<td>");
if ($j<$l) {
$d=ord($data[$j]);
if ($d<32 or $d>126) printf(".");
else printf ("%c",$d);
} else printf (" ");
printf("</td>");
}
printf("</tr>\n");
}
printf ("</table>");
}
function print_directory($dir_entries) {
$meta_size=0;
foreach ($dir_entries as $entry) if (($entry[3]+$entry[2])>$meta_size) $meta_size=$entry[3]+$entry[2];
printf ("<h2>Frame meta data size=%d bytes</h2>\n",$meta_size);
printf ("<table border=\"1\">\n");
printf ("<tr><td>ltag</td><td>meta offset</td><td>Exif offset</td><td>length</td></tr>\n");
foreach ($dir_entries as $entry) {
printf ("<tr><td>0x%x</td><td>0x%x</td><td>0x%x</td><td>0x%x</td></tr>\n",$entry[1],$entry[3],$entry[4],$entry[2]);
}
printf ("</table>");
}
function test_print_header() {
global $exif_head, $exif_data;
$lh=count($exif_head);
$ld=count($exif_data);
printf ("<h2>Exif size=%d bytes (head=%d, data=%d)</h2>\n",$lh+$ld,$lh,$ld);
printf ("<table border=\"0\">\n");
for ($i=0; $i<$lh+$ld;$i=$i+16) {
printf("<tr><td>%03x</td><td>|</td>\n",$i);
for ($j=$i; $j<$i+16;$j++) {
printf("<td>");
if ($j<($lh+$ld)) {
$d=($j<$lh)?$exif_head[$j]:$exif_data[$j-$lh];
printf(" %02x",$d);
} else printf (" ");
printf("</td>");
}
printf("<td>|</td>");
for ($j=$i; $j< ($i+16);$j++) {
printf("<td>");
if ($j<($lh+$ld)) {
$d=($j<$lh)?$exif_head[$j]:$exif_data[$j-$lh];
if ($d<32 or $d>126) printf(".");
else printf ("%c",$d);
} else printf (" ");
printf("</td>");
}
printf("</tr>\n");
}
printf ("</table>");
}
function test_print_directory() {
global $dir_entries,$frame_meta_size;
printf ("<h2>Frame meta data size=%d bytes</h2>\n",$frame_meta_size);
printf ("<table border=\"1\">\n");
printf ("<tr><td>ltag</td><td>meta offset</td><td>Exif offset</td><td>length</td></tr>\n");
foreach ($dir_entries as $entry)
printf ("<tr><td>0x%x</td><td>0x%x</td><td>0x%x</td><td>0x%x</td></tr>\n",$entry["ltag"],$entry["src"],$entry["dst"],$entry["len"]);
printf ("</table>");
}
function start_ifd($count) {
global $exif_data, $ifd_pointer;
// printf("start_ifd: ifd_pointer=0x%04x \n", $ifd_pointer);
$exif_data[$ifd_pointer++]= ($count >> 8) & 0xff;
$exif_data[$ifd_pointer++]= $count & 0xff; // may apply & 0xff in the end to all elements
}
function finish_ifd() { // we do not have additional IFDs
global $exif_data, $ifd_pointer;
// printf("finish_ifd: ifd_pointer=0x%04x \n", $ifd_pointer);
$exif_data[$ifd_pointer++]=0;
$exif_data[$ifd_pointer++]=0;
$exif_data[$ifd_pointer++]=0;
$exif_data[$ifd_pointer++]=0;
}
//pass2 - building map from frame meta to Exif template
function addDirEntry($ifd_entry) {
global $dir_sequence,$dir_entries,$exif_head;
$lh=count($exif_head);
$attrs = $ifd_entry->attributes();
// var_dump($attrs);
// if (array_key_exists ( "seq" , $attrs )) {
if ($attrs["seq"]) {
// echo $attrs["seq"].;
$dir_sequence[]=((string) $attrs["seq"])+0;
$len= (integer) $ifd_entry->value_length;
$offs=$lh+(integer) $ifd_entry->value_offest;
// if (array_key_exists ( "dlen" , $attrs ))
if ($attrs["dlen"]) $len=min($len,((string) $attrs["dlen"])+0);
$dir_entries[]=array("ltag"=>((integer)$ifd_entry->ltag),"dst"=>$offs,"len"=>$len);
}
}
function substitute_value($ifd_entry) {
global $SUB_IFD_offset,$GPSInfo_offset;
$attrs = $ifd_entry->attributes();
switch ($attrs["function"]) {
case "BRAND":
$ifd_entry->addChild ('value',exec("bootblocktool -x BRAND"));
break;
case "MODEL":
if (file_exists ('/var/state/APPLICATION')) {
$model= file_get_contents('/var/state/APPLICATION');
if (file_exists ('/var/state/APPLICATION_MODE')) {
$model.=' CHN'.file_get_contents('/var/state/APPLICATION_MODE');
}
} else {
$model= exec("bootblocktool -x MODEL").exec("bootblocktool -x REVISION");
}
/// $ifd_entry->addChild ('value',exec("bootblocktool -x MODEL").exec("bootblocktool -x REVISION"));
$ifd_entry->addChild ('value',$model);
break;
case "SOFTWARE":
$ifd_entry->addChild ('value',exec("ls /usr/html/docs/")); // filter
break;
case "SERIAL":
$s=exec("bootblocktool -x SERNO");
$ifd_entry->addChild ('value',substr($s,0,2).":".substr($s,2,2).":".substr($s,4,2).":".substr($s,6,2).":".substr($s,8,2).":".substr($s,10,2));
break;
case "EXIFTAG":
$ifd_entry->addChild ('value',$SUB_IFD_offset);
break;
case "GPSTAG":
$ifd_entry->addChild ('value',$GPSInfo_offset);
break;
}
}
function process_ifd_entry($ifd_entry, $group) {
global $exif_data, $ifd_pointer, $data_pointer,$SUB_IFD_offset,$GPSInfo_offset;
$attrs = $ifd_entry->attributes();
$ifd_tag= ((string) $attrs["tag"])+0;
$ifd_format=constant("EXIF_".$attrs["format"]);
$ifd_count= $attrs["count"];
// echo "\nifd_tag=$ifd_tag, entry=";print_r($ifd_entry);
// echo "\nifd_count=$ifd_count";
// echo "\nifd_bytes:";var_dump($ifd_bytes);
if (!$ifd_count) {
if($ifd_format==EXIF_ASCII) $ifd_count=strlen($ifd_entry->value)+1;
else $ifd_count=1 ; /// may change?
}
//echo "\nifd_count=$ifd_count";
$exif_data[$ifd_pointer++]= ($ifd_tag >> 8) & 0xff;
$exif_data[$ifd_pointer++]= $ifd_tag & 0xff;
$exif_data[$ifd_pointer++]= ($ifd_format >> 8 ) & 0xff;
$exif_data[$ifd_pointer++]= $ifd_format & 0xff;
$exif_data[$ifd_pointer++]= ($ifd_count >> 24) & 0xff;
$exif_data[$ifd_pointer++]= ($ifd_count >> 16) & 0xff;
$exif_data[$ifd_pointer++]= ($ifd_count >> 8) & 0xff;
$exif_data[$ifd_pointer++]= $ifd_count & 0xff;
$ifd_bytes=0;
switch ($ifd_format) {
case EXIF_SHORT:
case EXIF_SSHORT: $ifd_bytes=2; break;
case EXIF_LONG:
case EXIF_SLONG: $ifd_bytes=4; break;
case EXIF_RATIONAL:
case EXIF_SRATIONAL: $ifd_bytes=8; break;
default: $ifd_bytes=1; //1,2,6,7
}
$ifd_bytes=$ifd_bytes*$ifd_count;
// now prepare ifd_data - array of bytes
switch ($ifd_format) {
case EXIF_BYTE:
case EXIF_SBYTE:
$ifd_data= array ();
foreach ($ifd_entry->value as $a) $ifd_data[]= $a & 0xff;
break;
case EXIF_ASCII:
$ifd_data= str_split($ifd_entry->value);
foreach($ifd_data as &$d) $d=ord($d);
break;
case EXIF_SHORT:
case EXIF_SSHORT:
$ifd_data= array ();
foreach ($ifd_entry->value as $a) $ifd_data=array_merge($ifd_data,array(($a >> 8) & 0xff, $a & 0xff));
break;
case EXIF_LONG:
case EXIF_SLONG:
$ifd_data= array ();
foreach ($ifd_entry->value as $a) $ifd_data=array_merge($ifd_data,array(($a >> 24) & 0xff,($a >> 16) & 0xff,($a >> 8) & 0xff, $a & 0xff));
break;
case EXIF_RATIONAL:
case EXIF_SRATIONAL:
$nom= array ();
foreach ($ifd_entry->nominator as $a) $nom[]= array(($a >> 24) & 0xff,($a >> 16) & 0xff,($a >> 8) & 0xff, $a & 0xff);
$denom= array ();
foreach ($ifd_entry->denominator as $a) $denom[]=array(($a >> 24) & 0xff,($a >> 16) & 0xff,($a >> 8) & 0xff, $a & 0xff);
$ifd_data= array ();
/*
var_dump($nom);
echo "\n";
var_dump($denom);
echo "\n";
//exit(0);
*/
for ($i=0;$i<count($nom);$i++) {
// echo "i=$i\n";
// echo "\nnom=";var_dump($nom[$i]);
// echo "\ndenom=";var_dump($denom[$i]);
$ifd_data=array_merge($ifd_data,$nom[$i],$denom[$i]);
}
break; // rational, (un)signed
case EXIF_UNDEFINED: // undefined
$ifd_data= array_fill(0,$ifd_bytes,0); // will just fill with "0"-s
break;
}
// echo "\nifd_tag=$ifd_tag, entry=";print_r($i=$ifd_entry->value);
// echo "\nifd_data:";var_dump($ifd_data);
// echo "\nifd_bytes:";var_dump($ifd_bytes);
$ifd_data=array_pad($ifd_data,$ifd_bytes,0);
$ifd_entry->addChild ('value_length',count($ifd_data));
// if (array_key_exists ( "ltag" , $attrs )) $ltag= ((string) $attrs["ltag"])+0;
if ($attr["ltag"]) $ltag= ((string) $attrs["ltag"])+0;
else $ltag= $ifd_tag+($group<<16) ;
$ifd_entry->addChild ("ltag",$ltag );
if (count($ifd_data) <=4) {
$ifd_entry->addChild ('value_offest',$ifd_pointer);
$ifd_data= array_pad($ifd_data,-4,0); // add leading zeroes if <4 bytes
for ($i=0;$i<4;$i++) $exif_data[$ifd_pointer++]=$ifd_data[$i];
} else { //pointer, not data
$ifd_entry->addChild ('value_offest',$data_pointer);
$exif_data[$ifd_pointer++]= ($data_pointer >> 24) & 0xff;
$exif_data[$ifd_pointer++]= ($data_pointer >> 16) & 0xff;
$exif_data[$ifd_pointer++]= ($data_pointer >> 8) & 0xff;
$exif_data[$ifd_pointer++]= $data_pointer & 0xff;
for ($i=0;$i<count($ifd_data);$i++) {
$exif_data[$data_pointer++]=$ifd_data[$i];
}
}
}
?>
/*!***************************************************************************
*! FILE NAME : imgsrv.c
*! DESCRIPTION: Simple and fast HTTP server to send camera still images
*! Copyright (C) 2007-2008 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/>.
*! -----------------------------------------------------------------------------**
*!
*! $Log: imgsrv.c,v $
*! Revision 1.15 2014/06/25 23:32:26 dzhimiev
*! 1. fixed imgsrv /n -> /r/n
*! 2. updated revision number
*!
*! Revision 1.14 2012/04/08 04:11:28 elphel
*! 8.2.2 changes related to temperatures measurement and embedding in the Exif MakerNote
*!
*! Revision 1.13 2011/12/22 05:33:06 elphel
*! Added trigger command
*!
*! Revision 1.12 2010/08/16 17:10:24 elphel
*! added reporting frame number (for inter-camera synchronization)
*!
*! Revision 1.11 2010/08/10 21:14:31 elphel
*! 8.0.8.39 - added EEPROM support for multiplexor and sensor boards, so autocampars.php uses application-specific defaults. Exif Orientation tag support, camera Model reflects application and optional mode (i.e. camera number in Eyesis)
*!
*! Revision 1.10 2010/08/03 06:13:51 elphel
*! bugfix - was not copying last 8 bytes of MakerNote
*!
*! Revision 1.9 2010/08/01 19:30:24 elphel
*! new readonly parameter FRAME_SIZE and it support in the applications
*!
*! Revision 1.8 2010/07/20 20:13:34 elphel
*! 8.0.8.33 - added MakerNote info for composite images made with multisensor cameras (with 10359 board)
*!
*! Revision 1.7 2010/03/04 06:41:40 elphel
*! 8.0.7.3 - more data to makerNote
*!
*! Revision 1.6 2010/02/18 22:59:26 elphel
*! 8.0.7.1 - file extension/mime type depends on color mode now (*.jpeg, *.jp4, *.jp46)
*!
*! Revision 1.5 2009/12/28 06:24:17 elphel
*! 8.0.6.6 - added MakerNote to Exif, it icludes channels gains and gammas/black levels
*!
*! Revision 1.4 2009/10/12 19:20:23 elphel
*! Added "Content-Disposition" support to suggest filenames to save images
*!
*! Revision 1.3 2009/02/25 17:47:51 spectr_rain
*! removed deprecated dependency
*!
*! Revision 1.2 2009/02/18 06:25:41 elphel
*! fixed unterminated string of 1 character (GPS mode - 2/3)
*!
*! Revision 1.1.1.1 2008/11/27 20:04:01 elphel
*!
*!
*! Revision 1.11 2008/11/03 18:42:21 elphel
*! comment typo
*!
*! Revision 1.10 2008/10/29 04:18:28 elphel
*! v.8.0.alpha10 made a separate structure for global parameters (not related to particular frames in a frame queue)
*!
*! Revision 1.9 2008/10/25 19:51:40 elphel
*! updated copyright year
*!
*! Revision 1.8 2008/10/21 21:28:52 elphel
*! support for xml meta output
*!
*! Revision 1.7 2008/10/13 16:55:53 elphel
*! removed (some) obsolete P_* parameters, renamed CIRCLSEEK to LSEEK_CIRC constants (same as other similar)
*!
*! Revision 1.6 2008/10/11 18:46:07 elphel
*! snapshot
*!
*! Revision 1.5 2008/10/06 08:31:08 elphel
*! snapshot, first images
*!
*! Revision 1.4 2008/09/07 19:48:08 elphel
*! snapshot
*!
*! Revision 1.3 2008/08/11 19:10:45 elphel
*! reduced syntax "complaints" from KDevelop
*!
*! Revision 1.2 2008/05/16 06:06:54 elphel
*! supporting variable JPEG header length
*!
*! Revision 1.14 2008/04/22 22:14:56 elphel
*! Added malloc failures handling, syslog logging of such events
*!
*! Revision 1.13 2008/04/16 20:30:33 elphel
*! added optional fps reduction to multipart JPEGs
*!
*! Revision 1.11 2008/04/07 09:13:35 elphel
*! Changes related to new Exif generation/processing
*!
*! Revision 1.10 2008/03/22 04:39:53 elphel
*! remove complaints about "&_time=..."
*!
*! Revision 1.9 2007/12/03 08:28:45 elphel
*! Multiple changes, mostly cleanup
*!
*! Revision 1.8 2007/11/16 08:56:19 elphel
*! Added support for 2 additional commands to check circbuf usage
*!
*! Revision 1.7 2007/11/04 23:25:16 elphel
*! removed extra (used during debug) munmap that caused segfault after sending "img" (so no /nxt/save)
*!
*! Revision 1.6 2007/11/04 05:47:40 elphel
*! Cleaned up from debug code inserted to fight mmap/caching bug (fixed by now)
*!
*! Revision 1.5 2007/11/01 18:59:37 elphel
*! debugging mmap/caching problems
*!
*! Revision 1.4 2007/10/30 16:56:06 elphel
*! release 7.1.4.5 - working on "can not find 0xffff in frame parameters" bug. Temporary fix
*!
*! Revision 1.3 2007/10/27 00:55:32 elphel
*! untested revision - need to go
*!
*! Revision 1.2 2007/10/11 06:42:28 elphel
*! Fixed bug - /meta command should return trivial xml file, not 1x1 pixel gif
*!
*! Revision 1.1.1.1 2007/10/02 19:44:54 elphel
*! This is a fresh tree based on elphel353-2.10
*!
*! Revision 1.4 2007/10/02 19:44:54 elphel
*! More functionality (buffer manipulation commands, clean interface, xml responces)
*!
*! Revision 1.3 2007/09/29 16:21:25 elphel
*! removed IOCTL usage from /dev/circbuf, improved comments, other minor changes
*!
*! Revision 1.2 2007/09/25 23:35:16 elphel
*! added Exif initialization, made it to work in background mode
*!
*! Revision 1.1 2007/09/23 06:49:10 elphel
*! Simple web server designed for particular task - serving camera JPEG images. It is faster, than through any of the web servers tested. Only some of the functionality is implemented (no Exif yet, no synchronization with the camera)
*!
*!
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
//#include <ctype.h>
//#include <getopt.h>
#include <time.h>
#include <string.h>
#include <syslog.h>
#include <netinet/in.h>
#include <sys/mman.h> /* mmap */
#include <sys/ioctl.h>
//#include <elphel/c313a.h>
//#include <elphel/exifa.h>
#include <c313a.h>
#include <exifa.h>
#include <asm/byteorder.h>
#if ELPHEL_DEBUG
#define ELPHEL_DEBUG_THIS 1
#else
#define ELPHEL_DEBUG_THIS 0
#endif
#if ELPHEL_DEBUG_THIS
#define D(x) fprintf(stderr,"%s:%d:%s: ",__FILE__,__LINE__,__FUNCTION__);x
#else
#define D(x)
#endif
//#define USEHTTP10(x)
#define USEHTTP10(x) x
// HEADER_SIZE is defined to be larger than actual header (later - with EXIF) to use compile-time buffer
//#define JPEG_HEADER_SIZE 0x26f // will not change
#define JPEG_HEADER_MAXSIZE 0x300 // will not change
#define TRAILER_SIZE 0x02
#define MAP_OPTIONS MAP_FILE|MAP_PRIVATE
//#define GLOBALPARS(x) globalPars[(x)-FRAMEPAR_GLOBALS] // should work in drivers and application
unsigned long * ccam_dma_buf; /* mmapped array */
char trailer[TRAILER_SIZE] = {0xff,0xd9};
const char url_args[]="This server supports sequence of commands entered in the URL (separated by \"/\", case sensitive )\n"
"executing them from left to right as they appear in the URL\n"
"img - send image at the current pointer (if it is first command - use last acquired image, if none availabe - send 1x1 gif)\n"
"bimg - same as above, but save the whole image in the memory before sending - useful to avoid overruns with slow connection \n"
"simg, sbimg - similar to img, bimg but will imemdiately suggest to save instead of opening image in the browser\n"
"mimg[n] - send images as a multipart JPEG (all commands after will be ignored), possible to specify optional fps reduction\n"
" i.e. mimg4 - skip 3 frames for each frame output (1/4 fps) \n"
"bmimg[n] - same as above, buffered\n"
"pointers - send XML-formatted data about frames available in the camera circular buffer)\n"
"frame - return current frame number as plain text\n"
"wframe - wait for the next frame sync, return current frame number as plain text\n\n"
"Any of the 7 commands above can appear only once in the URL string, the second instance will be ignored. If none of the 5\n"
"are present in the URL 1x1 pixel gif will be returned to the client after executing the URL command.\n\n"
"torp - set frame pointer to global read pointer, maintained by the camera driver. If frame at that pointer\n"
" is invalid, use scnd (see below)\n"
"towp - set frame pointer to hardware write pointer - position where next frame will be aquired\n"
"prev - move to previous frame in buffer, nop if there are none\n"
"next - move to the next frame in buffer (will stop at write pointer, see towp above)\n"
"last - move to the most recently acquired frame, or to write pointer if there are none.\n"
" this command is implied at the start of the url command sequence.\n"
"first - move to the oldest frame still available in the buffer. It is not safe to rely on it if\n"
" more frames are expected - data might be overwritten at any moment and the output will be corrupted.\n"
"second - move to the second oldest frame in the buffer - somewhat safer than \"first\" - there will be time for\n"
" \"next\" command at least before frame data (and pointer structures) will be overwritten.\n"
"save - save current frame pointer as a global read pointer that holds it values between server requests.\n"
" This pointer is shared between all the clients and applications that use it.\n"
"wait - Wait until there will be a frame at current pointer ready\n"
"trig - send a single internal trigger (and puts internal trigger in single-shot mode\n"
" In this special mode autoexposure/white balance will not work in most cases,\n"
" camera should be set in triggered mode (TRIG=4), internal (TRIG_CONDITION=0).\n"
" No effect on free-running or \"slave\" cameras, so it is OK to send it to all.";
//int sendImage(int bufferImageData, int fd_circ, int use_Exif);
int sendImage(int bufferImageData, int fd_circ, int use_Exif, int saveImage);
void sendBuffer(void * buffer, int len);
void listener_loop(int port);
void errorMsgXML(char * msg);
int framePointersXML(int fd_circ);
int metaXML(int fd_circ, int mode); /// mode: 0 - new (send headers), 1 - continue, 2 - finish
int printExifXML(int exif_page);
int out1x1gif(void);
void waitFrameSync();
unsigned long getCurrentFrameNumber();
#define saferead255(f,d,l) read(f,d,((l)<256)?(l):255)
int printExifXML(int exif_page) {
int indx;
long numfields=0;
struct exif_dir_table_t dir_table_entry;
int fd_exifdir;
struct exif_dir_table_t exif_dir[ExifKmlNumber] ; /// store locations of the fields needed for KML generations in the Exif block
/// Create Exif directory
/// Read the size of the Exif data
fd_exifdir = open(EXIFDIR_DEV_NAME, O_RDONLY);
if (fd_exifdir <0) {
printf ("<error>\"Opening %s\"</error>\n",EXIFDIR_DEV_NAME);
return -2 ; /// Error opening Exif directory
}
for (indx=0; indx<ExifKmlNumber; indx++) exif_dir[indx].ltag=0;
while (read(fd_exifdir, &dir_table_entry, sizeof(dir_table_entry))>0) {
switch (dir_table_entry.ltag) {
case Exif_Image_ImageDescription: indx= Exif_Image_ImageDescription_Index; break;
case Exif_Image_FrameNumber: indx= Exif_Image_FrameNumber_Index; break;
case Exif_Photo_DateTimeOriginal: indx= Exif_Photo_DateTimeOriginal_Index; break;
case Exif_Photo_SubSecTimeOriginal: indx= Exif_Photo_SubSecTimeOriginal_Index; break;
case Exif_Photo_ExposureTime: indx= Exif_Photo_ExposureTime_Index; break;
case Exif_Photo_MakerNote: indx= Exif_Photo_MakerNote_Index; break;
case Exif_Image_Orientation: indx= Exif_Image_Orientation_Index; break;
case Exif_GPSInfo_GPSLatitudeRef: indx= Exif_GPSInfo_GPSLatitudeRef_Index; break;
case Exif_GPSInfo_GPSLatitude: indx= Exif_GPSInfo_GPSLatitude_Index ; break;
case Exif_GPSInfo_GPSLongitudeRef: indx= Exif_GPSInfo_GPSLongitudeRef_Index ; break;
case Exif_GPSInfo_GPSLongitude: indx= Exif_GPSInfo_GPSLongitude_Index; break;
case Exif_GPSInfo_GPSAltitudeRef: indx= Exif_GPSInfo_GPSAltitudeRef_Index; break;
case Exif_GPSInfo_GPSAltitude: indx= Exif_GPSInfo_GPSAltitude_Index; break;
case Exif_GPSInfo_GPSTimeStamp: indx= Exif_GPSInfo_GPSTimeStamp_Index; break;
case Exif_GPSInfo_GPSDateStamp: indx= Exif_GPSInfo_GPSDateStamp_Index; break;
case Exif_GPSInfo_GPSMeasureMode: indx= Exif_GPSInfo_GPSMeasureMode_Index; break;
case Exif_GPSInfo_CompassDirectionRef: indx= Exif_GPSInfo_CompassDirectionRef_Index; break;
case Exif_GPSInfo_CompassDirection: indx= Exif_GPSInfo_CompassDirection_Index; break;
case Exif_GPSInfo_CompassPitchRef: indx= Exif_GPSInfo_CompassPitchRef_Index; break;
case Exif_GPSInfo_CompassPitch: indx= Exif_GPSInfo_CompassPitch_Index; break;
case Exif_GPSInfo_CompassRollRef: indx= Exif_GPSInfo_CompassRollRef_Index; break;
case Exif_GPSInfo_CompassRoll: indx= Exif_GPSInfo_CompassRoll_Index; break;
default: indx=-1;
}
if (indx>=0) {
memcpy(&(exif_dir[indx]),&dir_table_entry,sizeof(dir_table_entry));
numfields++;
}
}
close (fd_exifdir);
/// Create XML files iteslf
long rational3[6];
long makerNote[14];
long exif_page_start;
char val[256];
int hours=0, minutes=0;
double seconds=0.0;
double longitude=0.0, latitude=0.0, altitude=0.0, heading=0.0, roll=0.0, pitch=0.0, exposure=0.0;
val[255]='\0';
int fd_exif= open(EXIF_DEV_NAME, O_RDONLY);
if (fd_exif <0) {
printf ("<error>\"Opening %s\"</error>\n",EXIF_DEV_NAME);
return -3 ;
}
exif_page_start= lseek (fd_exif, exif_page, SEEK_END); /// select specified Exif page
if (exif_page_start<0) {
printf ("<error>\"Exif page (%d) is out of range\"</error>\n",exif_page);
close (fd_exif);
return -1 ; /// Error opening Exif
}
///Image Description
if (exif_dir[Exif_Image_ImageDescription_Index].ltag==Exif_Image_ImageDescription) { // Exif_Image_ImageDescription is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Image_ImageDescription_Index].dst,
SEEK_SET);
saferead255(fd_exif, val, exif_dir[Exif_Image_ImageDescription_Index].len);
printf("<ImageDescription>\"%s\"</ImageDescription>\n",val);
}
///Exif_Image_FrameNumber_Index 0x13
if (exif_dir[Exif_Image_FrameNumber_Index].ltag==Exif_Image_FrameNumber) { // Exif_Image_FrameNumber_Index is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Image_FrameNumber_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 4);
sprintf (val,"%ld", (long) __cpu_to_be32( rational3[0]));
printf("<FrameNumber>\"%s\"</FrameNumber>\n",val);
}
///Exif_Image_Orientation_Index 0x15
if (exif_dir[Exif_Image_Orientation_Index].ltag==Exif_Image_Orientation) { // Exif_Image_Orientation_Index is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Image_Orientation_Index].dst,
SEEK_SET);
rational3[0]=0;
read(fd_exif, rational3, 2);
sprintf (val,"%ld", (long) ( rational3[0]>>8));
printf("<Orientation>\"%s\"</Orientation>\n",val);
}
///DateTimeOriginal (with subseconds)
if (exif_dir[Exif_Photo_DateTimeOriginal_Index].ltag==Exif_Photo_DateTimeOriginal) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Photo_DateTimeOriginal_Index].dst,
SEEK_SET);
read(fd_exif, val, 19);
val[19]='\0';
if (exif_dir[Exif_Photo_SubSecTimeOriginal_Index].ltag==Exif_Photo_SubSecTimeOriginal) {
val[19]='.';
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Photo_SubSecTimeOriginal_Index].dst,
SEEK_SET);
read(fd_exif, &val[20], 7);
val[27]='\0';
}
printf("<DateTimeOriginal>\"%s\"</DateTimeOriginal>\n",val);
}
///Exif_Photo_ExposureTime
if (exif_dir[Exif_Photo_ExposureTime_Index].ltag==Exif_Photo_ExposureTime) { // Exif_Photo_ExposureTime is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Photo_ExposureTime_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 8);
exposure=(1.0*__cpu_to_be32( rational3[0]))/__cpu_to_be32( rational3[1]);
sprintf (val,"%f",exposure);
printf("<ExposureTime>\"%s\"</ExposureTime>\n",val);
}
///Exif_Photo_MakerNote
if (exif_dir[Exif_Photo_MakerNote_Index].ltag==Exif_Photo_MakerNote) { // Exif_Photo_MakerNote is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_Photo_MakerNote_Index].dst,
SEEK_SET);
read(fd_exif, makerNote, 64);
sprintf (val,
"0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx",
(long) __cpu_to_be32(makerNote[0]),
(long) __cpu_to_be32(makerNote[1]),
(long) __cpu_to_be32(makerNote[2]),
(long) __cpu_to_be32(makerNote[3]),
(long) __cpu_to_be32(makerNote[4]),
(long) __cpu_to_be32(makerNote[5]),
(long) __cpu_to_be32(makerNote[6]),
(long) __cpu_to_be32(makerNote[7]),
(long) __cpu_to_be32(makerNote[8]),
(long) __cpu_to_be32(makerNote[9]),
(long) __cpu_to_be32(makerNote[10]),
(long) __cpu_to_be32(makerNote[11]),
(long) __cpu_to_be32(makerNote[12]),
(long) __cpu_to_be32(makerNote[13]),
(long) __cpu_to_be32(makerNote[14]),
(long) __cpu_to_be32(makerNote[15]));
printf("<MakerNote>\"%s\"</MakerNote>\n",val);
}
/// GPS measure mode
if (exif_dir[Exif_GPSInfo_GPSMeasureMode_Index].ltag==Exif_GPSInfo_GPSMeasureMode) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSMeasureMode_Index].dst,
SEEK_SET);
read(fd_exif, val, 1);
val[1]='\0';
printf("<GPSMeasureMode>\"%s\"</GPSMeasureMode>\n",val);
}
///GPS date/time
if (exif_dir[Exif_GPSInfo_GPSDateStamp_Index].ltag==Exif_GPSInfo_GPSDateStamp) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSDateStamp_Index].dst,
SEEK_SET);
read(fd_exif, val, 10);
val[10]='\0';
if (exif_dir[Exif_GPSInfo_GPSTimeStamp_Index].ltag==Exif_GPSInfo_GPSTimeStamp) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSTimeStamp_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 24);
hours= __cpu_to_be32( rational3[0]);
minutes= __cpu_to_be32( rational3[2]);
seconds= (1.0*(__cpu_to_be32( rational3[4])+1))/__cpu_to_be32( rational3[5]); /// GPS likes ".999", let's inc by one - anyway will round that out
sprintf (&val[10]," %02d:%02d:%05.2f",hours,minutes,seconds);
}
printf("<GPSDateTime>\"%s\"</GPSDateTime>\n",val);
}
/// knowing format provided from GPS - degrees and minutes only, no seconds:
///GPS Longitude
if (exif_dir[Exif_GPSInfo_GPSLongitude_Index].ltag==Exif_GPSInfo_GPSLongitude) { // Exif_GPSInfo_GPSLongitude is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSLongitude_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 24);
longitude=__cpu_to_be32( rational3[0])/(1.0*__cpu_to_be32( rational3[1])) + __cpu_to_be32( rational3[2])/(60.0*__cpu_to_be32( rational3[3]));
if (exif_dir[Exif_GPSInfo_GPSLongitudeRef_Index].ltag==Exif_GPSInfo_GPSLongitudeRef) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSLongitudeRef_Index].dst,
SEEK_SET);
read(fd_exif, val, 1);
if (val[0]!= 'E') longitude=-longitude;
}
sprintf (val,"%f",longitude);
printf("<GPSLongitude>\"%s\"</GPSLongitude>\n",val);
}
///GPS Latitude
if (exif_dir[Exif_GPSInfo_GPSLatitude_Index].ltag==Exif_GPSInfo_GPSLatitude) { // Exif_GPSInfo_GPSLatitude is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSLatitude_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 24);
latitude=__cpu_to_be32( rational3[0])/(1.0*__cpu_to_be32( rational3[1])) + __cpu_to_be32( rational3[2])/(60.0*__cpu_to_be32( rational3[3]));
if (exif_dir[Exif_GPSInfo_GPSLatitudeRef_Index].ltag==Exif_GPSInfo_GPSLatitudeRef) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSLatitudeRef_Index].dst,
SEEK_SET);
read(fd_exif, val, 1);
if (val[0] != 'N') latitude=-latitude;
}
sprintf (val,"%f",latitude);
printf("<GPSLatitude>\"%s\"</GPSLatitude>\n",val);
}
///GPS Altitude
if (exif_dir[Exif_GPSInfo_GPSAltitude_Index].ltag==Exif_GPSInfo_GPSAltitude) { // Exif_GPSInfo_GPSAltitude is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSAltitude_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 8);
altitude=(1.0*__cpu_to_be32( rational3[0]))/__cpu_to_be32( rational3[1]);
if (exif_dir[Exif_GPSInfo_GPSAltitudeRef_Index].ltag==Exif_GPSInfo_GPSAltitudeRef) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_GPSAltitudeRef_Index].dst,
SEEK_SET);
read(fd_exif, val, 1);
if (val[0] != '\0') altitude=-altitude;
}
sprintf (val,"%f",altitude);
printf("<GPSAltitude>\"%s\"</GPSAltitude>\n",val);
}
///Compass Direction (magnetic)
if (exif_dir[Exif_GPSInfo_CompassDirection_Index].ltag==Exif_GPSInfo_CompassDirection) { // Exif_GPSInfo_CompassDirection is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_CompassDirection_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 8);
heading=(1.0*__cpu_to_be32( rational3[0]))/__cpu_to_be32( rational3[1]);
sprintf (val,"%f",heading);
printf("<CompassDirection>\"%s\"</CompassDirection>\n",val);
}
///Processing 'hacked' pitch and roll (made of Exif destination latitude/longitude)
///Compass Roll
if (exif_dir[Exif_GPSInfo_CompassRoll_Index].ltag==Exif_GPSInfo_CompassRoll) { // Exif_GPSInfo_CompassRoll is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_CompassRoll_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 8);
roll=(1.0*__cpu_to_be32( rational3[0]))/__cpu_to_be32( rational3[1]);
if (exif_dir[Exif_GPSInfo_CompassRollRef_Index].ltag==Exif_GPSInfo_CompassRollRef) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_CompassRollRef_Index].dst,
SEEK_SET);
read(fd_exif, val, 1);
if (val[0] != EXIF_COMPASS_ROLL_ASCII[0]) roll=-roll;
}
sprintf (val,"%f",roll);
printf("<CompassRoll>\"%s\"</CompassRoll>\n",val);
}
///Compass Pitch
if (exif_dir[Exif_GPSInfo_CompassPitch_Index].ltag==Exif_GPSInfo_CompassPitch) { // Exif_GPSInfo_CompassPitch is present in template
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_CompassPitch_Index].dst,
SEEK_SET);
read(fd_exif, rational3, 8);
pitch=(1.0*__cpu_to_be32( rational3[0]))/__cpu_to_be32( rational3[1]);
if (exif_dir[Exif_GPSInfo_CompassPitchRef_Index].ltag==Exif_GPSInfo_CompassPitchRef) {
lseek (fd_exif,
exif_page_start+exif_dir[Exif_GPSInfo_CompassPitchRef_Index].dst,
SEEK_SET);
read(fd_exif, val, 1);
if (val[0] != EXIF_COMPASS_PITCH_ASCII[0]) pitch=-pitch;
}
sprintf (val,"%f",pitch);
printf("<CompassPitch>\"%s\"</CompassPitch>\n",val);
}
close (fd_exif);
return 0;
}
int metaXML(int fd_circ, int mode) { /// mode: 0 - new (send headers), 1 - continue, 2 - finish
int frameParamPointer=0;
struct interframe_params_t frame_params;
int jpeg_len,jpeg_start,buff_size,timestamp_start;
if (mode==2) {/// just close the xml file
printf ("</meta>\n");
return 0;
} else if (mode==0) { /// open the XML output (length is undefined - multiple frames meta data might be output)
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Content-Type: text/xml\r\n");
printf("Pragma: no-cache\r\n");
printf("\r\n");
printf ("<?xml version=\"1.0\"?>\n" \
"<meta>\n");
}
jpeg_start=lseek(fd_circ,0,SEEK_CUR); //get the current read pointer
D(fprintf(stderr,"jpeg_start= (long)=0x%x\n",jpeg_start>>2));
if (jpeg_start <0 ) {
printf("<error>\"No frame at the current pointer\"</error>\n");
return -1;
}
buff_size=lseek(fd_circ,0,SEEK_END);
/// restore file poinetr after lseek-ing the end
lseek(fd_circ, jpeg_start, SEEK_SET);
frameParamPointer=jpeg_start-32;
if (frameParamPointer<0) frameParamPointer+=buff_size;
memcpy (&frame_params, (unsigned long * ) &ccam_dma_buf[frameParamPointer>>2],32); /// ccam_dma_buf - global
// jpeg_len=frame_params.frame_length;
///// Copy timestamp (goes after the image data)
// timestamp_start=jpeg_start+((jpeg_len+CCAM_MMAP_META+3) & (~0x1f)) + 32 - CCAM_MMAP_META_SEC; //! magic shift - should index first byte of the time stamp
// if (timestamp_start >= buff_size) timestamp_start-=buff_size;
// memcpy (&(frame_params.timestamp_sec), (unsigned long * ) &ccam_dma_buf[timestamp_start>>2],8);
/////TODO: Parse Exif data if available and add here
// printf ("<frame>\n" \
// "<start> 0x%x </start>\n" \
// "<hash32_r> 0x%x </hash32_r>\n" \
// "<hash32_g> 0x%x </hash32_g>\n" \
// "<hash32_gb>0x%x </hash32_gb>\n" \
// "<hash32_b> 0x%x </hash32_b>\n" \
// "<quality2> 0x%x </quality2>\n" \
// "<color> 0x%x </color>\n" \
// "<byrshift> 0x%x </byrshift>\n" \
// "<width> 0x%x </width>\n" \
// "<height> 0x%x </height>\n" \
// "<meta_index> 0x%x </meta_index>\n" \
// "<timestamp> %ld.%06ld</timestamp>\n" \
// "<signffff> 0x%x </signffff>\n"
// , (int) jpeg_start
// , (int) frame_params.hash32_r
// , (int) frame_params.hash32_g
// , (int) frame_params.hash32_gb
// , (int) frame_params.hash32_b
// , (int) frame_params.quality2
// , (int) frame_params.color /// color mode //18
// , (int) frame_params.byrshift /// bayer shift in compressor //19
// , (int) frame_params.width /// frame width, pixels 20-21 - NOTE: should be 20-21
// , (int) frame_params.height /// frame height, pixels 22-23
// , (int) frame_params.meta_index //! index of the linked meta page
// , frame_params.timestamp_sec
// , frame_params.timestamp_usec
// , (int) frame_params.signffff
// );
/////28-31 unsigned long timestamp_sec ; //! number of seconds since 1970 till the start of the frame exposure
/////28-31 unsigned long frame_length ; //! JPEG frame length in circular buffer, bytes
///// };
/////32-35 unsigned long timestamp_usec; //! number of microseconds to add
//
// if (frame_params.signffff !=0xffff) {
// printf("<error>\"wrong signature (should be 0xffff)\"</error>\n");
// } else {
/////Put Exif data here
// printf ("<Exif>\n");
// printExifXML(frame_params.meta_index);
// printf ("</Exif>\n");
// }
// printf ("</frame>\n");
return 0;
}
unsigned long getCurrentFrameNumber() {
const char ctlFileName[]="/dev/frameparsall";
int fd_fparmsall = open(ctlFileName, O_RDWR);
unsigned long frame_number=lseek(fd_fparmsall, 0, SEEK_CUR );
close(fd_fparmsall);
return frame_number;
}
void waitFrameSync() {
const char ctlFileName[]="/dev/frameparsall";
int fd_fparmsall = open(ctlFileName, O_RDWR);
lseek(fd_fparmsall, LSEEK_FRAME_WAIT_REL+1, SEEK_END); /// skip 1 frame before returning
close(fd_fparmsall);
}
int framePointersXML(int fd_circ) {
const char ctlFileName[]="/dev/frameparsall";
int fd_fparmsall;
char s[512]; // 341;
int p, wp, rp;
int nf=0;
int nfl=0;
int buf_free, buf_used, frame_size;
int save_p; //! save current file pointer, then restore it before return
int frame8, frame_number, sensor_state, compressor_state;
char *cp_sensor_state, *cp_compressor_state;
struct framepars_all_t *frameParsAll;
struct framepars_t *framePars;
unsigned long *globalPars;
fd_fparmsall = open(ctlFileName, O_RDWR);
if (fd_fparmsall<0) { // check control OK
printf ("Error opening %s\n", ctlFileName);
fprintf(stderr,"%s:%d:%s: Error opening %s\n",__FILE__,__LINE__,__FUNCTION__, ctlFileName);
return -1;
}
//! now try to mmap
frameParsAll = (struct framepars_all_t *) mmap(0, sizeof (struct framepars_all_t) , PROT_READ, MAP_SHARED, fd_fparmsall, 0);
if((int)frameParsAll == -1) {
frameParsAll=NULL;
printf("Error in mmap /dev/frameparsall");
fprintf(stderr,"%s:%d:%s: Error in mmap in %s\n",__FILE__,__LINE__,__FUNCTION__,ctlFileName);
close (fd_fparmsall);
fd_fparmsall = -1;
return -1;
}
framePars=frameParsAll->framePars;
globalPars=frameParsAll->globalPars;
// Read current sensor state - defined in c313a.h
frame_number=lseek(fd_fparmsall, 0, SEEK_CUR );
frame8= frame_number & PARS_FRAMES_MASK;
// printf ("Current frame number is %d\n",frame_number);
sensor_state=framePars[frame8].pars[P_SENSOR_RUN];
compressor_state=framePars[frame8].pars[P_COMPRESSOR_RUN];
cp_sensor_state= (sensor_state==0)?
"SENSOR_RUN_STOP":
((sensor_state==1)?
"SENSOR_RUN_SINGLE":
((sensor_state==2)?"SENSOR_RUN_CONT":"UNKNOWN"));
cp_compressor_state= (compressor_state==0)?
"COMPRESSOR_RUN_STOP":
((compressor_state==1)?
"COMPRESSOR_RUN_SINGLE":
((compressor_state==2)?"COMPRESSOR_RUN_CONT":"UNKNOWN"));
save_p=lseek(fd_circ,0,SEEK_CUR); //!save current file pointer before temporarily moving it
rp=lseek(fd_circ,LSEEK_CIRC_TORP,SEEK_END); //! set current rp global rp (may be invalid <0)
wp=lseek(fd_circ,LSEEK_CIRC_TOWP,SEEK_END); //! set current rp pointer to FPGA write pointer
p=wp;
while ((p>=0) & (nf<500)) {
if (p==rp) nfl=nf;
p=lseek(fd_circ,LSEEK_CIRC_PREV,SEEK_END);
nf++;
}
buf_free=GLOBALPARS(G_FREECIRCBUF);
frame_size=GLOBALPARS(G_FRAME_SIZE);
lseek(fd_circ,save_p,SEEK_SET); //! restore file pointer after temporarily moving it
buf_free=lseek(fd_circ,LSEEK_CIRC_FREE,SEEK_END); //! will change file pointer
lseek(fd_circ,save_p,SEEK_SET); //! restore file pointer after temporarily moving it
buf_used=lseek(fd_circ,LSEEK_CIRC_USED,SEEK_END); //! will change file pointer
lseek(fd_circ,save_p,SEEK_SET); //! restore file pointer after temporarily moving it
sprintf (s,"<?xml version=\"1.0\"?>\n" \
"<frame_pointers>\n" \
" <this>%d</this>\n" \
" <write>%d</write>\n" \
" <read>%d</read>\n" \
" <frames>%d</frames>\n" \
" <left>%d</left>\n" \
" <free>%d</free>\n" \
" <used>%d</used>\n" \
" <frame>%d</frame>\n" \
" <frame_size>%d</frame_size>\n" \
" <sensor_state>\"%s\"</sensor_state>\n" \
" <compressor_state>\"%s\"</compressor_state>\n" \
"</frame_pointers>\n",
save_p,
wp,
rp,
nf-1,
nfl,
buf_free,
buf_used,
frame_number,
frame_size,
cp_sensor_state,
cp_compressor_state);
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Content-Length: %d\r\n",strlen(s));
printf("Content-Type: text/xml\r\n");
printf("Pragma: no-cache\r\n");
printf("\r\n");
printf(s);
//! No need to unmap?
close(fd_fparmsall);
D(fprintf (stderr,">%s< [%d bytes]\n",s,strlen(s)));
return 0;
}
//fwrite (&cbuffer[offset],1,bytesLeft,stdout);
int out1x1gif(void) {
char s[]="HTTP/1.0 200 OK\r\n" \
"Server: Elphel Imgsrv\r\n" \
"Content-Length: 35\r\n" \
"Content-Type: image/gif\r\n" \
"\r\n" \
"GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00" \
"\xff\xff\xff\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x4c" \
"\x01\x00\x3b";
fwrite (s,1,sizeof(s),stdout); //! we have zeros in the string
return 0; //! always good
}
void errorMsgXML(char * msg) {
char s[1024]; // was 701 acrtually
sprintf (s,"<?xml version=\"1.0\"?>\n" \
"<frame_params>\n" \
"<error>%s</error>\n" \
"</frame_params>\n",msg);
D(fprintf (stderr,">%s< [%d bytes]",s,strlen(s)));
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Content-Length: %d\r\n",strlen(s));
printf("Content-Type: text/xml\r\n");
printf("Pragma: no-cache\r\n");
printf("\r\n");
printf(s);
}
//! read pointer in fd_circ should be at the start of the frame to be sent
//! mmap will be opened in this function
int sendImage(int bufferImageData, int fd_circ, int use_Exif, int saveImage) {
const char HeadFileName[]="/dev/jpeghead0";
const char ExifFileName[]="/dev/exif_exif";
int exifDataSize=0;
/// int exifIndexPointer=0;
int frameParamPointer=0;
struct interframe_params_t frame_params;
/// struct frame_exif_t frame_exif; //just 8 bytes
int buff_size;
int jpeg_len; //bytes
int jpeg_start; // bytes
int fd_head;
int fd_exif;
int head_size;
int jpeg_full_size, jpeg_this_size;
char * jpeg_copy;
int l,i;
int color_mode;
char * mime_type;
char * extension;
/// int metadata_start; //metadata pointer (in bytes, from the start of the ccam_dma_buf)
jpeg_start=lseek(fd_circ,0,SEEK_CUR); //get the current read pointer
D(fprintf(stderr,"jpeg_start (long) = 0x%x\n",jpeg_start));
fd_head = open(HeadFileName, O_RDWR);
if (fd_head<0) { // check control OK
fprintf (stderr,"Error opening %s\n", HeadFileName);
return -1;
}
lseek(fd_head,jpeg_start+1,SEEK_END); /// create JPEG header, find out it's size TODO:
head_size=lseek(fd_head,0,SEEK_END);
if (head_size>JPEG_HEADER_MAXSIZE) {
fprintf(stderr,"%s:%d: Too big JPEG header (%d > %d)",__FILE__,__LINE__,head_size, JPEG_HEADER_MAXSIZE );
close (fd_head);
return -2;
}
/*! find total buffer length (it is in defines, actually in c313a.h */
buff_size=lseek(fd_circ,0,SEEK_END);
/*! restore file poinetr after lseek-ing the end */
lseek(fd_circ, jpeg_start, SEEK_SET);
D(fprintf(stderr,"position (longs) = 0x%x\n", (int) lseek(fd_circ,0,SEEK_CUR)));
/*! now let's try mmap itself */
/// exifIndexPointer=jpeg_start-8;
frameParamPointer = jpeg_start - sizeof(struct interframe_params_t);
if (frameParamPointer < 0)
frameParamPointer += buff_size;
fprintf(stderr, "frameParamPointer = 0x%x, jpeg_start = 0x%x, buff_size = 0x%x\n",
frameParamPointer, jpeg_start, buff_size);
memcpy(&frame_params, (unsigned long *) &ccam_dma_buf[frameParamPointer >> 2], sizeof(struct interframe_params_t));
jpeg_len=frame_params.frame_length;
//color_mode=frame_params.color;
if (frame_params.signffff != 0xffff) {
fprintf(stderr, "wrong signature signff = 0x%x \n", (int)frame_params.signffff);
close (fd_head);
return -4;
}
if (use_Exif) {
//D(fprintf(stderr,"frame_params.meta_index=0x%x\n",(int) frame_params.meta_index));
/// read Exif to buffer:
fd_exif = open(ExifFileName, O_RDONLY);
if (fd_exif<0) { // check control OK
fprintf (stderr,"Error opening %s\n", ExifFileName);
close (fd_head);
return -5;
}
exifDataSize=lseek(fd_exif,1,SEEK_END); // at the beginning of page 1 - position == page length
if (exifDataSize < 0) exifDataSize=0; // error from lseek;
if (!exifDataSize) close(fd_exif);
} else {
//frame_params.meta_index=0;
fd_exif=-1;
}
///Maybe make buffer that will fit both Exif and JPEG?
//!Get metadata, update Exif and JFIF headers if ep and ed poinetrs are non-zero (NULL will generate files with JFIF-only headers)
/// Now we always malloc buffer, before - only for bimg, using fixed-size header buffer - was it faster?
jpeg_full_size=jpeg_len+head_size+2+exifDataSize;
fprintf(stderr, "jpeg_len = 0x%x, head_size = 0x%x, exifDataSize = 0x%x, jpeg_full_size = 0z%x\n",
jpeg_len, head_size, exifDataSize, jpeg_full_size);
if (bufferImageData) jpeg_this_size=jpeg_full_size; /// header+frame
else jpeg_this_size=head_size+exifDataSize; /// only header
jpeg_copy=malloc(jpeg_this_size);
if (!jpeg_copy) {
syslog(LOG_ERR, "%s:%d malloc (%d) failed", __FILE__,__LINE__,jpeg_this_size);
/// If we really want it, but don't get it - let's try more
for (i=0;i<10;i++) {
usleep(((jpeg_this_size & 0x3ff) + 5) * 100); // up to 0.1 sec
jpeg_copy=malloc(jpeg_this_size);
if (jpeg_copy) break;
syslog(LOG_ERR, "%s:%d malloc (%d) failed", __FILE__,__LINE__,jpeg_this_size);
}
if (!jpeg_copy) {
syslog(LOG_ERR, "%s:%d malloc (%d) failed 10 times - giving up", __FILE__,__LINE__,jpeg_this_size);
exit (1);
}
}
lseek(fd_head,0,0);
read (fd_head,&jpeg_copy[exifDataSize],head_size);
close (fd_head);
if (exifDataSize>0) {//! insert Exif
memcpy (jpeg_copy,&jpeg_copy[exifDataSize],2); //! copy first 2 bytes of the JFIF header before Exif
//lseek(fd_exif,frame_params.meta_index,SEEK_END); //! select meta page to use (matching frame)
read (fd_exif,&jpeg_copy[2],exifDataSize); //! Insert Exif itself
close(fd_exif);
}
switch (color_mode) {
// case COLORMODE_MONO6: //! monochrome, (4:2:0),
// case COLORMODE_COLOR: //! color, 4:2:0, 18x18(old)
case COLORMODE_JP46: //! jp4, original (4:2:0)
case COLORMODE_JP46DC: //! jp4, dc -improved (4:2:0)
mime_type="jp46";
extension="jp46";
break;
// case COLORMODE_COLOR20: //! color, 4:2:0, 20x20, middle of the tile (not yet implemented)
case COLORMODE_JP4: //! jp4, 4 blocks, (legacy)
case COLORMODE_JP4DC: //! jp4, 4 blocks, dc -improved
case COLORMODE_JP4DIFF: //! jp4, 4 blocks, differential red := (R-G1), blue:=(B-G1), green=G1, green2 (G2-G1). G1 is defined by Bayer shift, any pixel can be used
case COLORMODE_JP4HDR: //! jp4, 4 blocks, differential HDR: red := (R-G1), blue:=(B-G1), green=G1, green2 (high gain)=G2) (G1 and G2 - diagonally opposite)
case COLORMODE_JP4DIFF2: //! jp4, 4 blocks, differential, divide differences by 2: red := (R-G1)/2, blue:=(B-G1)/2, green=G1, green2 (G2-G1)/2
case COLORMODE_JP4HDR2: //! jp4, 4 blocks, differential HDR: red := (R-G1)/2, blue:=(B-G1)/2, green=G1, green2 (high gain)=G2),
mime_type="jp4";
extension="jp4";
break;
// case COLORMODE_MONO4: //! monochrome, 4 blocks (but still with 2x2 macroblocks)
default:
mime_type="jpeg";
extension="jpeg";
}
// char * mime_type;
// char * extension;
/*
#define COLORMODE_MONO6 0 // monochrome, (4:2:0),
#define COLORMODE_COLOR 1 // color, 4:2:0, 18x18(old)
#define COLORMODE_JP46 2 // jp4, original (4:2:0)
#define COLORMODE_JP46DC 3 // jp4, dc -improved (4:2:0)
#define COLORMODE_COLOR20 4 // color, 4:2:0, 20x20, middle of the tile (not yet implemented)
#define COLORMODE_JP4 5 // jp4, 4 blocks, (legacy)
#define COLORMODE_JP4DC 6 // jp4, 4 blocks, dc -improved
#define COLORMODE_JP4DIFF 7 // jp4, 4 blocks, differential red := (R-G1), blue:=(B-G1), green=G1, green2 (G2-G1). G1 is defined by Bayer shift, any pixel can be used
#define COLORMODE_JP4HDR 8 // jp4, 4 blocks, differential HDR: red := (R-G1), blue:=(B-G1), green=G1, green2 (high gain)=G2) (G1 and G2 - diagonally opposite)
#define COLORMODE_JP4DIFF2 9 // jp4, 4 blocks, differential, divide differences by 2: red := (R-G1)/2, blue:=(B-G1)/2, green=G1, green2 (G2-G1)/2
#define COLORMODE_JP4HDR2 10 // jp4, 4 blocks, differential HDR: red := (R-G1)/2, blue:=(B-G1)/2, green=G1, green2 (high gain)=G2),
#define COLORMODE_MONO4 14 // monochrome, 4 blocks (but still with 2x2 macroblocks)
*/
printf("Content-Type: image/%s\r\n",mime_type);
if (saveImage) printf("Content-Disposition: attachment; filename=\"elphelimg_%ld.%s\"\r\n",frame_params.timestamp_sec,extension); /// does not open, asks for filename to save
else printf("Content-Disposition: inline; filename=\"elphelimg_%ld.%s\"\r\n",frame_params.timestamp_sec,extension); /// opens in browser, asks to save on right-click
if (bufferImageData) { /*! Buffer the whole file before sending over the network to make sure it will not be corrupted if the circular buffer will be overrun) */
l=head_size+exifDataSize;
/*! JPEG image data may be split in two segments (rolled over buffer end) - process both variants */
if ((jpeg_start+jpeg_len) > buff_size) { // two segments
memcpy (&jpeg_copy[l], (unsigned long * ) &ccam_dma_buf[jpeg_start>>2],buff_size-jpeg_start);
l+=buff_size-jpeg_start;
memcpy (&jpeg_copy[l],(unsigned long * ) &ccam_dma_buf[0],jpeg_len-(buff_size-jpeg_start));
} else { /*! single segment */
memcpy (&jpeg_copy[l],(unsigned long * ) &ccam_dma_buf[jpeg_start>>2],jpeg_len);
}
memcpy (&jpeg_copy[jpeg_len+head_size+exifDataSize],trailer,2);
printf("Content-Length: %d\r\n",jpeg_full_size);
printf("\r\n");
sendBuffer(jpeg_copy, jpeg_full_size);
} else { /*! fast connection, no need to buffer image, so we'll try to run it faster */
printf("Content-Length: %d\r\n",jpeg_full_size);
printf("\r\n");
sendBuffer(jpeg_copy, head_size+exifDataSize); //JPEG+Exif
/*! JPEG image data may be split in two segments (rolled over buffer end) - process both variants */
if ((jpeg_start+jpeg_len) > buff_size) { // two segments
/*! copy from the beginning of the frame to the end of the buffer */
sendBuffer((void *) &ccam_dma_buf[jpeg_start>>2], buff_size-jpeg_start);
/*! copy from the beginning of the buffer to the end of the frame */
sendBuffer((void *) &ccam_dma_buf[0], jpeg_len-(buff_size-jpeg_start));
} else { // single segment
/*! copy from the beginning of the frame to the end of the frame (no buffer rollovers) */
sendBuffer((void *) &ccam_dma_buf[jpeg_start>>2], jpeg_len);
}
sendBuffer(trailer,2);
}
free(jpeg_copy);
return 0;
}
/*! repeat writes to stdout until all data is sent */
void sendBuffer(void * buffer, int len) {
int bytesLeft=len;
int offset=0;
int bytesWritten;
char * cbuffer= (char *) buffer;
D(fprintf (stderr,"buffer=%p, len=%d\n",buffer, len));
while (bytesLeft>0) {
D(fprintf (stderr," --bytesLeft=%d\n",bytesLeft));
bytesWritten= fwrite (&cbuffer[offset],1,bytesLeft,stdout);
bytesLeft-= bytesWritten;
offset+= bytesWritten;
}
}
void listener_loop(int port)
{
char errormsg[1024];
const char circbufFileName[]="/dev/circbuf0";
int fd_circ;
int this_p; //! current frame pointer (bytes)
int rslt;
int buf_images=0;
int suggest_save_images=0;
char buf [1024];
int len=0;
int current_len;
char * cp, *cp1, *cp2;
int slow,skip; // reduce frame rate by slow
int sent2socket=-1; // 1 - img, 2 - meta, 3 - pointers
struct sockaddr_in sock;
int res;
int one=1;
int buff_size;
memset((char *)&sock, 0, sizeof(sock));
sock.sin_port = htons(port);
sock.sin_family = AF_INET;
res = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
bind(res, (struct sockaddr * ) &sock,sizeof(sock));
listen(res, 10);
int exif_enable=1;
while (1) {
int fd;
fd = accept(res,NULL,0);
if (fd == -1) continue;
signal(SIGCHLD, SIG_IGN); // no zombies, please!
/*! do we need any fork at all if we now serve images to one client at a time? */
if (fork() == 0) {
close(res);
/*! setup stdin and stdout */
fflush(stdout);
fflush(stderr);
dup2(fd, 0);
dup2(fd, 1);
close(fd);
/*! We need just the first line of the GET to read parameters */
if (fgets(buf, sizeof(buf)-1, stdin)) len=strlen(buf);
cp=buf;
strsep(&cp, "/?"); // ignore everything before first "/" or "?"
if (cp) {
//! Now cp points to the first character after the first "/" or "?" in the url
//! we need to remove everything after (and including) the first space
cp1=strchr(cp,' ');
if (cp1) cp1[0]='\0';
}
if (!cp || (strlen(cp)==0)) { //!no url commands - probably the server url was manually entered
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Content-Length: %d\r\n",strlen(url_args));
printf("Content-Type: text/plain\r\n");
printf("\r\n");
printf(url_args);
fflush(stdout);
_exit(0);
}
/// Process 'frame' and 'wframe' commands - theys do not need circbuf
if ((strncmp(cp, "frame",5)==0) || (strncmp(cp, "wframe",6)==0)){
if (strncmp(cp, "wframe",6)==0) waitFrameSync();
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Content-Length: 11\r\n");
printf("Content-Type: text/plain\r\n");
printf("\r\n");
printf("%010ld\r\n",getCurrentFrameNumber());
fflush(stdout);
_exit(0);
}
//!now process the commands one at a time, but first - open the circbuf file and setup the pointer
fd_circ = open(circbufFileName, O_RDWR);
if (fd_circ<0) { // check control OK
fprintf (stderr,"Error opening %s\n", circbufFileName);
out1x1gif();
fflush(stdout);
_exit(0);
}
/*! find total buffer length (it is in defines, actually in c313a.h */
buff_size=lseek(fd_circ,0,SEEK_END);
fprintf(stderr, "%s: read circbuf size: %d\n", __func__, buff_size);
/*! now let's try mmap itself */
ccam_dma_buf = (unsigned long *) mmap(0, buff_size, PROT_READ, MAP_SHARED, fd_circ, 0);
if((int)ccam_dma_buf == -1) {
fprintf(stderr, "Error in mmap\n");
close(fd_circ); // - caller opened, caller - to close
out1x1gif();
fflush(stdout);
_exit(0);
}
this_p=lseek(fd_circ,LSEEK_CIRC_LAST,SEEK_END);
D(fprintf(stderr, "%s: current frame pointer this_p (in bytes): 0x%x\n", __func__, this_p));
//!continue with iterating through the commands
while ((cp1=strsep(&cp, "/?&"))) {
// printf ("1->%s", cp1);
// fprintf (stderr, "1->%s",cp1);
//!if the first caracter is digit,it is a file pointer
if (strchr("0123456789",cp1[0])) {
this_p= lseek(fd_circ,strtol(cp1, NULL, 10),SEEK_SET);
} else if ((strcmp(cp1, "img")==0) || (strcmp(cp1, "bimg")==0) || (strcmp(cp1, "simg")==0) || (strcmp(cp1, "sbimg")==0)) {
fprintf(stderr, "%s: processing img command\n", __func__);
if (sent2socket>0) break; //! image/xmldata was already sent to socket, ignore
if (lseek(fd_circ,LSEEK_CIRC_READY,SEEK_END)<0) { //! here passes OK, some not ready error is later, in sendimage (make it return different numbers)
rslt=out1x1gif();
fprintf(stderr, "%s: no frame is available\n", __func__);
} else {
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Expires: 0\r\n");
printf("Pragma: no-cache\r\n");
buf_images= ((strcmp(cp1, "img")==0) || (strcmp(cp1, "simg")==0))?0:1;
suggest_save_images=((strcmp(cp1, "simg")==0) || (strcmp(cp1, "sbimg")==0))?1:0;
fprintf(stderr, "%s: sending image\n", __func__);
rslt=sendImage(buf_images, fd_circ, exif_enable, suggest_save_images); //! verify driver that file pointer did not move
}
sent2socket=1;
if (rslt<0) {
if (sent2socket==1) out1x1gif();
else {
sprintf(errormsg,"sendImage error = %d (%s:line %d)",rslt,__FILE__,__LINE__);
errorMsgXML(errormsg);
}
}
fflush(stdout); //! let's not keep client waiting - anyway we've sent it all even when more commands maybe left
///multipart - always last
} else if ((strncmp(cp1, "mimg",4)==0) || (strncmp(cp1, "bmimg",5)==0) || (strncmp(cp1, "mbimg",5)==0)) {
if (sent2socket>0) break; //! image/xmldata was already sent to socket, ignore
if (lseek(fd_circ,LSEEK_CIRC_READY,SEEK_END)<0) //! here passes OK, some not ready error is later, in sendimage (make it return different numbers)
rslt=out1x1gif();
else {
//TODO:
buf_images= (strncmp(cp1, "mimg",4)==0)?0:1;
cp2=cp1+(buf_images?5:4);
slow=strtol(cp2, NULL, 10);
if (slow < 1) slow =1;
printf("HTTP/1.0 200 OK\r\n");
printf("Server: Elphel Imgsrv\r\n");
printf("Expires: 0\r\n");
printf("Pragma: no-cache\r\n");
printf("Content-Type: multipart/x-mixed-replace;boundary=ElphelMultipartJPEGBoundary\r\n");
rslt=0;
while (rslt>=0) {
printf("\r\n--ElphelMultipartJPEGBoundary\r\n");
rslt=sendImage(buf_images, fd_circ, exif_enable, 0); //! verify driver that file pointer did not move
fflush(stdout);
if (rslt>=0) for (skip=0;skip<slow;skip++) {
this_p=lseek(fd_circ,LSEEK_CIRC_NEXT, SEEK_END);
/// If these "next" is not ready yet - wait, else - use latest image
if ((lseek(fd_circ,LSEEK_CIRC_VALID,SEEK_END) >= 0) && //! no sense to wait if the pointer is invalid
(lseek(fd_circ,LSEEK_CIRC_READY,SEEK_END) < 0) && //! or the frame is already ready
(lseek(fd_circ,LSEEK_CIRC_VALID,SEEK_END) >= 0)) //! test valid once again, after not ready - it might change
this_p=lseek(fd_circ,LSEEK_CIRC_WAIT,SEEK_END);
else this_p=lseek(fd_circ,LSEEK_CIRC_LAST, SEEK_END);
}
}
_exit(0);
}
} else if (strcmp(cp1, "pointers")==0) {
if (sent2socket>0) break; //! image/xmldata was already sent to socket, ignore
framePointersXML(fd_circ); //! will restore file pointer after itself
sent2socket=3;
fflush(stdout); //! let's not keep client waiting - anyway we've sent it all even when more commands maybe left
} else if (strcmp(cp1, "meta")==0) {
if ((sent2socket>0) && (sent2socket!=2)) break; //! image/xmldata was already sent to socket, ignore
metaXML(fd_circ,(sent2socket>0)?1:0); /// 0 - new (send headers), 1 - continue, 2 - finish
sent2socket=2;
fflush(stdout); //! let's not keep client waiting - anyway we've sent it all even when more commands maybe left
} else if (strcmp(cp1, "noexif")==0) {
exif_enable=0;
} else if (strcmp(cp1, "exif")==0) {
exif_enable=1;
} else if (strcmp(cp1, "torp")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_TORP, SEEK_END);
} else if (strcmp(cp1, "towp")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_TOWP, SEEK_END);
} else if (strcmp(cp1, "prev")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_PREV, SEEK_END);
} else if (strcmp(cp1, "next")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_NEXT, SEEK_END);
} else if (strcmp(cp1, "last")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_LAST, SEEK_END);
} else if (strcmp(cp1, "first")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_FIRST,SEEK_END);
} else if (strcmp(cp1, "second")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_SCND, SEEK_END);
} else if (strcmp(cp1, "save")==0) {
this_p=lseek(fd_circ,LSEEK_CIRC_SETP,SEEK_END);
} else if (strcmp(cp1, "wait")==0) {
if ((lseek(fd_circ,LSEEK_CIRC_VALID,SEEK_END) >= 0) && //! no sense to wait if the pointer is invalid
(lseek(fd_circ,LSEEK_CIRC_READY,SEEK_END) < 0) && //! or the frame is already ready
(lseek(fd_circ,LSEEK_CIRC_VALID,SEEK_END) >= 0)) //! test valid once again, after not ready - it might change
this_p=lseek(fd_circ,LSEEK_CIRC_WAIT,SEEK_END);
} else if (strcmp(cp1, "trig")==0) {
// printf ("trig argument\n");
int fd_fpga=open("/dev/fpgaio", O_RDWR);
// printf ("fd_fpga = 0x%x\n",fd_fpga);
if (fd_fpga>=0){
//int aaa;
lseek (fd_fpga, 0x7b,SEEK_SET) ; //!TODO: remove absolute register address from user application! 32-bit registers, not bytes
//printf ("lseek()-> 0x%x\n",aaa);
long data=1;
write(fd_fpga,&data,4); // actually send the trigger pulse (will leave camera in single-shot mode)
//printf ("write()-> 0x%x\n",aaa);
close (fd_fpga);
}
} else if (strcmp(cp1, "favicon.ico")==0) {
///ignore silently - for now, later make an icon?
} else {
if (cp1[0]!='_') fprintf(stderr,"Unrecognized URL command: \"%s\" - ignoring\n",cp1); //!allow "&_time=..." be silently ignored - needed for javascript image reload
}
} //!while ((cp1=strsep(&cp, "/?&")))
if (sent2socket<=0) { //! Nothing was sent to the client so far and the command line is over. Let's return 1x1 pixel gif
out1x1gif();
} else if (sent2socket==2) {
metaXML(fd_circ,2); /// 0 - new (send headers), 1 - continue, 2 - finish
}
fflush(stdout); // probably it is not needed anymore, just in case
_exit(0);
} // end of child process
close(fd); // parent
} // while (1)
}
/*! set port, start listening/answering HTTP requests */
int main(int argc, char *argv[])
{
const char usage[]= "Usage:\n%s -p <port_number>\n" \
"Start image server, bind it to port <port_number>\n";
int port;
if ((argc < 3) || (strcasecmp(argv[1], "-p"))) {
printf (usage,argv[0]);
printf (url_args);
return 0;
}
port=strtol(argv[2], NULL, 10);
if (!port) {printf ("Invalid port number %d\n", port); return -1;}
signal(SIGCHLD, SIG_IGN); // no zombies, please!
if (fork() == 0) { // child
listener_loop(port);
_exit(0); // should not get here?
} // end of child process
return 0;
}
#!/usr/local/sbin/php -q
<?php
/*
*! FILE NAME : imu_setup.php
*! DESCRIPTION: Handles GPS/compass and IMU/logger. Will replace star-compass_gps.php
*!
*! Copyright (C) 2008 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/>.
*! -----------------------------------------------------------------------------**
*! $Log: imu_setup.php,v $
*! Revision 1.8 2012/07/03 20:54:36 elphel
*! bug fix
*!
*! Revision 1.7 2011/12/22 05:40:36 elphel
*! missed revision
*!
*! Revision 1.5 2011/09/06 22:02:49 elphel
*! added 'list' link
*!
*! Revision 1.4 2011/09/06 21:56:31 elphel
*! help typo
*!
*! Revision 1.3 2011/09/06 21:53:49 elphel
*! adding to help
*!
*! Revision 1.2 2011/09/06 21:31:48 elphel
*! added help
*!
*! Revision 1.1 2011/09/06 19:07:50 elphel
*! initial release, based on start_gps_compass.php
*!
*/
require 'i2c.inc';
$xclk_freq=80000000; // 80 MHz
$messageOffset=0xb0; // offset to start of "odometer" message in the device driver file
$config_name="/etc/imu_logger.xml";
if (isset($_SERVER["SERVER_PROTOCOL"])) {
// echo "web server\n";
if (isset($_GET['msg'])) {
setMessage(urldecode($_GET['msg']));
} else if (isset($_GET['lmsg'])) {
setMessage(urldecode($_GET['msg']));
// software toggle input "odometer" line
}
/// modify parameters if specified
$conf=readSettings(init_default_config()); // read current settings
$apply=0;
// echo "<pre>\n";
if (count($_GET)==0) {
help();
exit(0);
}
if (array_key_exists('source',$_GET)) {
$source=file_get_contents ($_SERVER['SCRIPT_FILENAME']);
header("Content-Type: text/php");
header("Content-Length: ".strlen($source)."\n");
header("Pragma: no-cache\n");
echo $source;
exit (0);
}
foreach ($_GET as $key=>$value) {
$access=split(':',$key);
if ($value==='') continue;
if (count($access)<1) continue;
if (!isset($conf[$access[0]])) continue;
if (count($access)==1) {
if (($access[0]=='imu_period') && ($value=='auto')) $value = 0xffffff00;
if (is_string($conf[$access[0]])) $conf[$access[0]]=$value;
else $conf[$access[0]]=$value+0;
$apply++;
} else { // count($access)>1
if (!isset($conf[$access[0]][$access[1]])) continue;
if (count($access)==2) {
if (is_string($conf[$access[0]][$access[1]])) $conf[$access[0]][$access[1]]=$value;
else $conf[$access[0]][$access[1]]=$value+0;
$apply++;
} else { // count($access)>2)
if (count($access)>3) continue;
if ($access[2]=='sentence') $access[2]=0;
else if ($access[2]=='format') $access[2]=1;
if (!isset($conf[$access[0]][$access[1]][$access[2]])) continue;
if (is_string($conf[$access[0]][$access[1]][$access[2]])) $conf[$access[0]][$access[1]][$access[2]]=$value;
else $conf[$access[0]][$access[1]][$access[2]]=$value+0;
$apply++;
}
}
/*
echo 'key='.$key."\n";
print_r($access);
var_dump($value);
*/
}
if ($apply>0) {
echo 'modified '.$apply."parameters<br/>\n";
// print_r($conf);
setup_IMU_logger($conf);
}
if (isset($_GET['save'])) {
// if ($verbose) echo 'Writing IMU logger configuration to '. $config_name."\n";
$conf=readSettings(init_default_config());
$logger_xml=loggerConfigToXML($conf);
$conf_file=fopen($config_name,"w");
fwrite($conf_file,$logger_xml->asXML());
fclose($conf_file);
exec ('sync');
}
if (isset($_GET['list'])) {
$conf=readSettings(init_default_config());
$logger_xml=loggerConfigToXML($conf);
$logger_xml_text=$logger_xml->asXML();
header("Content-Type: text/xml");
header("Content-Length: ".strlen($logger_xml_text)."\n");
header("Pragma: no-cache\n");
printf($logger_xml_text);
} else echo 'OK';
exit(0);
} else {
// echo "CGI\n";
}
/*
echo "<!--\n";
var_dump($_GET);
var_dump($_SERVER);
echo "-->";
echo 'OK';
exit(0);
*/
//! Here comes if CLI
$ids=scanGrandDaughters();
$b_index=indexGrandDaughters($ids);
// print_r($ids);
// print_r($b_index);
$baud=null;
if (isset($b_index[103696])) {
$baud=$ids[$b_index[103696]]['baud'];
if ($baud===0) $baud=='auto';
}
// exit (0);
$wait_time=20; // wait for $wait_time if both devices were not found, retry
$compass=null;
$GPS=null;
$verbose=true;
foreach ($_SERVER['argv'] as $param) {
if ((substr($param,0,2)=="-q") || (substr($param,0,8)=="--silent")){
$verbose=false;
}
}
/// kill those GPS and compass if they are running already
exec('killall -q garminusb2exif');
exec('killall -q nmea2exif');
exec('killall -q compass');
// find_gps_compass();
$devs=find_gps_compass($baud);
// echo "compass: ";var_dump($compass);echo "\n";
// echo "GPS: ";var_dump($GPS);echo "\n";
// if ((!$compass || !$GPS) && ((exec('date +%s')+0) <30)) {
if ((count($devs)==0) && ((exec('date +%s')+0) <30)) {
if ($verbose) echo "waiting $wait_time sec for USB devices to start up\n";
sleep($wait_time);
if ($verbose) echo "Retrying detection\n";
$devs=find_gps_compass($baud);
}
listSensorDevices($devs,$b_index,$ids);
//var_dump($GPS);
// if (file_exists ($sensor_state_file)) $sensor_board=parse_ini_file($sensor_state_file);
// exec ('sync');
$logger_config=null;
$write_config=false;
if (file_exists ($config_name)) {
if ($verbose) echo 'Reading IMU logger configuration from '. $config_name."\n";
$config_xml = simplexml_load_file($config_name);
$logger_config=loggerConfigFromXML($config_xml);
} else if (isset($b_index[103696]) || isset($b_index[103696])) {
if ($verbose) echo "Generating IMU logger configuration\n";
// $default_config=init_default_config();
// $logger_config=init_default_config();
$logger_config=array();
if (isset($GPS) && isset($b_index[103696])) {
$logger_config['baud_rate']=$GPS['baud'];
$logger_config['gps_slot']=$ids[$b_index[103696]]['port'];
$logger_config['gps_mode']=$ids[$b_index[103696]]['sync'];
}
if (isset($b_index[103695])) {
$logger_config['imu_slot']=$ids[$b_index[103695]]['port'];
$logger_config['imu_sa']=$b_index[103695];
}
$write_config=true; // write configuration to /etc after applying defaults
}
if (isset($logger_config)){
// var_dump($logger_config);
$logger_config=combineLoggerConfigs($logger_config,init_default_config());
// var_dump($logger_config);
// var_dump($default_config);
$logger_xml=loggerConfigToXML($logger_config);
$conf_file=fopen('/var/html/logger_config.xml',"w");
fwrite($conf_file,$logger_xml->asXML());
fclose($conf_file);
setup_IMU_logger($logger_config);
if ($write_config) {
if ($verbose) echo 'Writing IMU logger configuration to '. $config_name."\n";
$conf_file=fopen($config_name,"w");
fwrite($conf_file,$logger_xml->asXML());
fclose($conf_file);
exec ('sync');
}
}
// echo "compass: ";var_dump($compass);echo "\n";
// echo "GPS: ";var_dump($GPS);echo "\n";
$noGPS= ($compass || $GPS)?"" : "noGPS";
$nocompass=($compass)?"" : "nocompass";
$cmd="/usr/html/exif.php init $noGPS $nocompass";
if ($verbose) echo "Initializing Exif template: $cmd\n";
exec($cmd);
if ($GPS) {
if ($verbose) echo "Starting ".$GPS["name"]. " as ". $GPS["file"]. "\n";
if (strpos($GPS['name'],'NMEA')!==false) {
$cmd ="/usr/local/bin/nmea2exif ". $GPS["file"]." &";
} else {
$cmd ="/usr/local/bin/garminusb2exif ". $GPS["file"]." &";
}
if ($verbose) echo "exec: $cmd \n";
popen($cmd,"r");
}
if ($compass) {
if ($verbose) echo "Starting ".$compass["name"]. " as ". $compass["file"]. "\n";
exec ("stty -F ".$compass["file"]." -echo speed 19200");
$cmd="/usr/local/bin/compass ". $compass["file"]." &";
if ($verbose) echo "exec: $cmd \n";
popen($cmd,"r");
}
exit ((isset($b_index[103695])?4:0) | ($compass?2:0) | ($GPS?1:0));
function help(){
$GP='$GP';
$GPRMC='$GPRMC';
$GPGGA='$GPGGA';
$GPGSA='$GPGSA';
$GPVTG='$GPVTG';
$script_name=$_SERVER['SCRIPT_NAME'];
$prefix_url='http://'.$_SERVER['SERVER_ADDR'].$_SERVER['SCRIPT_NAME'];
// echo <<<USAGE
// <h4> Control links:</h4>
// <ul>
// <li><a href="?$url_init">Initialization Parameters (i.e. after powerup)</a></li>
echo <<<USAGE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Usage of IMU/GPS logger ($script_name)</title>
</head>
<body>
<h2>Usage of IMU/GPS logger ($script_name)</h2>
<p>This script controls IMU/GPS logger. When the camera starts, the script looks for the <i>/etc/imu_logger.xml</i>" and if it is found, the settings from this file are applied to the logger. If there is no such file (i.e. at first boot after reflashing the camera) script looks for the optional extension boards <a href=""http://wiki.elphel.com/index.php?title=103695>103695</a> and <a href="http://wiki.elphel.com/index.php?title=103696">103696</a> and uses the information from their flash memory (not erased during reflash) combined with the defaults to create initial <i>/etc/imu_logger.xml</i> file that can be modified later</p>
<p>Script receives parameters as HTTP GET request, there are five special parameters:
<ul>
<li><b><a href="$prefix_url?source">source</a></b> - returns the source of this script</li>
<li><b><a href="$prefix_url?list">list</a></b> - returns an XML containing current logger settings, the names of the nodes can be used to modify specific settings</li>
<li><b>save</b> - overwrite <i>/etc/imu_logger.xml</i> with the current settings - they will be used next time camera will boot up</li>
<li><b>msg=url-encoded-text-up-to-56-bytes</b> - set the &quot;odometer&quot; message that will be logged next time the external input is toggled </li>
<li><b>smsg=url-encoded-text-up-to-56-bytes</b> - (not yet implemented) set the &quot;odometer&quot; message and trigger logging immediately</li>
</ul>
Other parameters are just <i>name=value</i> pairs with colons separating names and subnames
<ul>
<li><b>imu_period</b> - set the IMU logging period in SPI SCLK periods, maybe set to <i>auto</i> (default value, same as 0xff000000) to log when the IMU data is ready. Value 0 turns the IMU logging off</li>
<li><b>sclk_freq</b> - set SPI clock frequency, in Hz. Default is 5000000 (5MHz)</li>
<li><b>stall</b> - set SPI 'stall' time, in microseconds. Default is 2 usec</li>
<li><b>baud_rate</b> - set baud rate for the serial GPS, default is 19200</li>
<li><b>imu_slot</b> - specify the IMU board (<a href="http://wiki.elphel.com/index.php?title=103695">103695</a>) connection to the <a href="http://wiki.elphel.com/index.php?title=10369">10369</a> board 0 - none, 1 - J9, 2 - J10, 3 - J11. Default is 1 (J9)</li>
<li><b>gps_slot</b> - specify the GPS board (<a href="http://wiki.elphel.com/index.php?title=103696">103696</a>) connection to the <a href="http://wiki.elphel.com/index.php?title=10369">10369</a> board 0 - none, 1 - J9, 2 - J10, 3 - J11. Default is 2 (J10)</li>
<li><b>gps_mode</b> - synchronization mode for the GPS: 0 - pulse-per-sample external input, negative front, 1 - pps input positive front, 2 - start of a first sentence after pause, 3 - start of each individual sentence. Mode 2 is the default, modes 0 and 1 require that GPS has a dedicated synchro output</li>
<li><b>msg_conf</b> - GPIO number and polarity (+16 - invert polarity) uses to log external events (i.e. odometer pulses from a vehicle wheel sensor). Timestamp uses leading edge, software may write to the 56-byte buffer (see 'msg=' command above) before the trailing edge to attach the message to the event after the event occured. In the case of short external pulses the logged message will be the last written before the event</li>
<li><b>img_sync</b> - 0 - disable logging of the images, 1 - enable. In the case of the multiple synchronized cameras this provides a way to match external (master) camera timestamps transmitted over the synchronization cable, with the local camera timestamps used by the logger - both are logged. Default is 1</li>
<li><b>extra_conf</b> - Development signals (0 - config_long_sda_en, 1 -config_late_clk, 2 - config_single_wire, should be set for 103695 rev A). Default is 4</li>
<li><b>slow_spi</b> - may be set to 1 for slow SPI devices (other changes may be needed, i.e. changing power from 3.3V to 5.0V selected by a resistor divider). Default is 0 </li>
<li><b>imu_sa</b> - i2c slave address modifier (matches hardware jumpers). Default is 3</li>
<li><b>sleep_busy</b> - setting for the driver. It is a sleep time (in microseconds) before the driver will poll the logger buffer if it does not have the full sample record (64 bytes of data) ready</li>
<li><b>imu_registers</b> - setting the IMU register addresses to be logged (total number of logged registers is 28). You may see the complete list of the registers in the IMU datasheet. The registers are addressed as 'imu_registers:NN', where NN is the register sequnce number, starting with 0. Below are the default values:
<ul>
<li><b>imu_registers:0</b>=0x10 - x gyro low</li>
<li><b>imu_registers:1</b>=0x12 - x gyro high</li>
<li><b>imu_registers:2</b>=0x14 - y gyro low</li>
<li><b>imu_registers:3</b>=0x16 - y gyro high</li>
<li><b>imu_registers:4</b>=0x18 - z gyro low</li>
<li><b>imu_registers:5</b>=0x1a - z gyro high</li>
<li><b>imu_registers:6</b>=0x1c - x accel low</li>
<li><b>imu_registers:7</b>=0x1e - x accel high</li>
<li><b>imu_registers:8</b>=0x20 - y accel low</li>
<li><b>imu_registers:9</b>=0x22 - y accel high</li>
<li><b>imu_registers:10</b>=0x24 - z accel low</li>
<li><b>imu_registers:11</b>=0x26 - z accel high</li>
<li><b>imu_registers:12</b>=0x40 - x delta angle low</li>
<li><b>imu_registers:13</b>=0x42 - x delta angle high</li>
<li><b>imu_registers:14</b>=0x44 - y delta angle low</li>
<li><b>imu_registers:15</b>=0x46 - y delta angle high</li>
<li><b>imu_registers:16</b>=0x48 - z delta angle low</li>
<li><b>imu_registers:17</b>=0x4a - z delta angle high</li>
<li><b>imu_registers:18</b>=0x4c - x delta velocity low</li>
<li><b>imu_registers:19</b>=0x4e - x delta velocity high</li>
<li><b>imu_registers:20</b>=0x50 - y delta velocity low</li>
<li><b>imu_registers:21</b>=0x52 - y delta velocity high</li>
<li><b>imu_registers:22</b>=0x54 - z delta velocity low</li>
<li><b>imu_registers:23</b>=0x56 - z delta velocity high</li>
<li><b>imu_registers:24</b>=0x0e - temperature</li>
<li><b>imu_registers:25</b>=0x70 - time m/s</li>
<li><b>imu_registers:26</b>=0x72 - time d/h</li>
<li><b>imu_registers:27</b>=0x74 - time y/m</li>
</ul></li>
<li><b>nmea</b> - set format of the four logged NMEA sentences. For each sentence two text fields have to be specified - 'sentence' (the three letters following the comman prefix '$GP'), and 'format' that consists of a sequence of 'n' (for number) and 'b' (for bytes), up to 24 total. Numbers consisting of digits, minus sign and decimal point are encoded with 2 digits per byte (to make sure the longest sentence fits into the 56 byte logger payload buffer), followed by the 0xf nibble (half-byte). Bytes are encoded with MSB cleared ( & 0x7f) for all bytes in a field but the last, the last byte has it set (|0x80). Empty byte field is logged as 0xff. Below are the default settings:
<ul>
<li><b>nmea:0:sentence</b>=RMC - sentence $GPRMC</li>
<li><b>nmea:0:format</b>=nbnbnbnnnnb - format for the $GPRMC</li>
<li><b>nmea:1:sentence</b>=GGA - sentence $GPGGA</li>
<li><b>nmea:1:format</b>=nnbnbnnnnbnbbb - format for the $GPGGA</li>
<li><b>nmea:2:sentence</b>=GSA - sentence $GPGSA</li>
<li><b>nmea:2:format</b>=bnnnnnnnnnnnnnnnn - format for the $GPGSA</li>
<li><b>nmea:3:sentence</b>=VTG - sentence $GPVTG</li>
<li><b>nmea:3:format</b>=nbnbnbnb - format for the $GPVTG</li>
</ul>
</li>
</ul>
</p>
<p>You may record the log to a file (i.e. on external USB stick or SSD/HDD) with teh following command:<br/>
<b>cat /dev/imu &gt;<i>log-file-path</i></b></p>
<p>Test logger and GPS:<br/>
<b>fpcf -imu 10000 | grep &quot;1:&quot;</b><p/>
<p>The fpcf output starts the line (logged sample) with the source of the sample:
<ul>
<li><b>0:</b> - IMU (normally 2560 samples/sec)</li>
<li><b>1:</b> - GPS </li>
<li><b>2:</b> - camera images</li>
<li><b>3:</b> - 'odometer' - external events</li>
</ul>
'10000' means that fpcf should output 10000 samples, that takes approximately 4 seconds if IMU output is being logged.
</p>
</body>
USAGE;
}
function scanGrandDaughters(){
$ids=array();
$id="";
for ($i=2;$i<8;$i++) {
$id=i2c_read256b(0xa0+2*$i,1);
$xml=simplexml_load_string($id);
if (($xml!==false) && ($xml->getName()=='board')) {
$ids[$i]=array();
foreach ($xml->children() as $entry) {
$ids[$i][$entry->getName()]=(string) $entry ;
}
}
}
return $ids;
}
function indexGrandDaughters($ids) {
$index=array();
foreach($ids as $i=>$id) if (isset($id['model'])) {
$index[$id['model']]=$i;
}
return $index;
}
/// compass/GPS programs should be killed before detection
// baud=null - search USB Garmin and compass
// baud=auto - try to autodetect baud rate
// baud=number - used specified baud rate, do not wait for the GPS response
function find_gps_compass($baud=null,$timeout=5) {
global $verbose;
$ttyOptions=array (
'-echo speed 19200', /// maybe other options, like '-echo speed 4800 -ixoff'
'-echo speed 9600',
'-echo speed 4800',
'-echo speed 2400'
);
if (isset($baud) && ($baud!='auto') && ($baud!=0)) {
$ttyOptions=array (
'-echo speed '.$baud);
}
// global $GPS, $compass;
$devices=array(
"compass"=>array(array("name"=>"Ocean Server OS-5000","driver"=>"cp2101")),
"GPS" =>array(array("name"=>"Garmin GPS 18 USB","driver"=>"garmin_gps")));
exec("ls /sys/bus/usb-serial/devices",$usb_ser_devs); // ("ttyUSB0","ttyUSB1")
$devs = new SimpleXMLElement("<?xml version='1.0' standalone='yes'?><USB_serial_devices/>");
$serialDevices=array();
$compassPresent=false;
$gpsPresent=false;
$driver=array();
//echo "usb_ser_devs"; var_dump($usb_ser_devs);
foreach ($usb_ser_devs as $dev) {
//echo "dev=$dev\n";
$arr=split("/",exec("ls /sys/bus/usb-serial/devices/".$dev."/driver -l"));
$driver[$dev]=$arr[count($arr)-1];
$serialDevices[$dev]='';
if (!isset($baud)) { // if baud is set (auto or number - skip compass, it is 103696)
foreach ($devices["compass"] as $d) {
if ($d["driver"]==$driver[$dev]) {
$dd=$devs->addChild ('compass');
$dd->addChild ('name',$d["name"]);
$dd->addChild ('driver',$d["driver"]);
$dd->addChild ('file',"/dev/".$dev);
$serialDevices[$dev]='compass';
$compassPresent=true;
}
}
}
if ($serialDevices[$dev]) continue;
foreach ($devices["GPS"] as $d) {
if ($d["driver"]==$driver[$dev]) {
$dd=$devs->addChild ('GPS');
$dd->addChild ('name',$d["name"]);
$dd->addChild ('driver',$d["driver"]);
$dd->addChild ('file',"/dev/".$dev);
$serialDevices[$dev]='gps';
$gpsPresent=true;
}
}
}
/// Do we need to look for a NMEA GPS?
if (!$gpsPresent) foreach ($serialDevices as $dev=>$type) if (!$type && !$gpsPresent) {
if ($verbose) printf ("could be $dev\n");
foreach ($ttyOptions as $ttyOpt) {
$cmd='stty -F /dev/'.$dev.' '.$ttyOpt;
if (count($ttyOptions)==1) { /// single baud option, will not wait for confirmation. Has to be only one serial adapter !!
if ($verbose) echo "Setting: $cmd\n";
exec ($cmd);
$gpsPresent=true;
} else {
if ($verbose) echo "Trying: $cmd\n";
exec ($cmd);
unset ($fullOutput);
exec ('timeout '.$timeout.' cat /dev/'.$dev, &$fullOutput);
//var_dump($fullOutput);
foreach ($fullOutput as $line) if (strpos ($line, '$GP')===0) {
$gpsPresent=true;
break;
}
}
if ($gpsPresent) {
$dd=$devs->addChild ('GPS');
$dd->addChild ('name','NMEA 0183 GPS receiver');
$dd->addChild ('driver',$driver[$dev]);
$dd->addChild ('file',"/dev/".$dev);
$arr=split(" ",$ttyOpt);
$dd->addChild ('baud',$arr[count($arr)-1]);
$serialDevices[$dev]='gps';
if ($verbose) echo "\nfound NMEA GPS unit\n";
break;
}
// var_dump($fullOutput);
}
}
/// list unused USB serial adapters
foreach ($serialDevices as $dev=>$type) if (!$type) {
$dd=$devs->addChild ('unused');
$dd->addChild ('name','USB serial converter');
$dd->addChild ('driver',$driver[$dev]);
$dd->addChild ('file',"/dev/".$dev);
}
return $devs;
}
function listSensorDevices($devs,$b_index,$ids) {
global $GPS, $compass;
foreach ($devs->compass as $a) {
$compass=array("file"=>(string) $a->file, "name"=> (string) $a->name);
break; // use first one
}
foreach ($devs->GPS as $a) {
$GPS=array("file"=>(string) $a->file, "name"=> (string) $a->name, "baud"=>(string) $a->baud);
if (isset($b_index[103696])) {
$a->addChild ('part_number',$ids[$b_index[103696]]['part']);
$a->addChild ('port',$ids[$b_index[103696]]['port']);
$a->addChild ('mode',$ids[$b_index[103696]]['mode']);
}
break; // use first one
}
$state_file=fopen("/var/html/gps_compass.xml","w");
fwrite($state_file,$devs->asXML());
fclose($state_file);
}
function loggerConfigToXML($conf){
$logger_xml = new SimpleXMLElement("<?xml version='1.0' standalone='yes'?><Logger_configuration/>");
foreach ($conf as $key=>$value) {
switch ($key) {
case 'imu_registers':
$subtree=$logger_xml->addChild ($key);
for ($i=0;$i<count($value);$i++) {
$subtree->addChild ('R_'.sprintf('%02d',$i),sprintf("0x%02x",$value[$i]));
}
break;
case 'nmea':
$subtree=$logger_xml->addChild ($key);
for ($i=0;$i<count($value);$i++) {
$sentence=$subtree->addChild ('S_'.sprintf('%01d',$i));
$sentence->addChild ('sentence',$value[$i][0]);
$sentence->addChild ('format',$value[$i][1]);
}
break;
default:
$logger_xml->addChild ($key,$value);
}
}
return $logger_xml;
}
function loggerConfigFromXML($confXML){
$conf=array();
// var_dump($confXML);
foreach ($confXML as $item) {
// var_dump($item);
$key=$item->getName();
switch ($key) {
case 'imu_registers':
$conf[$key]=array();
foreach ($item as $reg) {
$rname=substr($reg->getName(),2);
$conf[$key][$rname+0]=((string) $reg)+0;
}
break;
case 'nmea':
$conf[$key]=array();
foreach ($item as $reg) {
$rname=substr($reg->getName(),2);
$conf[$key][$rname+0]=array((string) $reg->sentence, (string) $reg->format);
}
break;
case 'imu_period':
$conf[$key]=(string) $item;
if ($conf[$key]!='auto') $conf[$key]+=0;
break;
case 'message':
$conf[$key]=(string) $item;
break;
default:
// $conf[$key]=(int) $item;
$conf[$key]=((string) $item)+0;
}
}
return $conf;
}
function init_default_config(){
$default_config=array(
'imu_period'=>'auto',// 0xFFFFFFFF, // 0 - off, >=0xff000000 - "when ready", else - number of SCLK periods
'sclk_freq'=>5000000, // $clkr_divr= 8, // 80MHz divisor to get half SCLK rate (defaulkt SCLK=5MHz)
'stall' => 2, // SPI stall time in usec
'baud_rate'=>19200, // $rs232_div=80/2/$baud
'imu_slot'=>1,
'gps_slot'=>2,
'gps_mode'=>2, // 0 - pps neg, 1 - pps pos, 2 - start of first sentence after pause, 3 start of sentence
'msg_conf'=>10, // GPIO bit number for external (odometer) input (+16 - invert polarity). Timestamp uses leading edge, software may write to 56-byte buffer before the trailing edge
'img_sync'=>1, // enable logging image acquisition starts (0 - disable)
'extra_conf'=>4, // 0 - config_long_sda_en, 1 -config_late_clk, 2 - config_single_wire, should be set for 103695 rev "A"
'slow_spi'=>0, // set to 1 for slow SPI devices (0 for ADIS-16375)
'imu_sa'=>3, // i2c slave address modifier for the 103695A pca9500
'sleep_busy'=>30000, //microseconds
'imu_registers'=>array( /// Up to 28 total
0x10, // x gyro low
0x12, // x gyro high
0x14, // y gyro low
0x16, // y gyro high
0x18, // z gyro low
0x1a, // z gyro high
0x1c, // x accel low
0x1e, // x accel high
0x20, // y accel low
0x22, // y accel high
0x24, // z accel low
0x26, // z accel high
0x40, // x delta angle low
0x42, // x delta angle high
0x44, // y delta angle low
0x46, // y delta angle high
0x48, // z delta angle low
0x4a, // z delta angle high
0x4c, // x delta velocity low
0x4e, // x delta velocity high
0x50, // y delta velocity low
0x52, // y delta velocity high
0x54, // z delta velocity low
0x56, // z delta velocity high
0x0e, // temperature
0x70, // time m/s
0x72, // time d/h
0x74// time y/m
),
'nmea'=>array(
/// first three letters - sentence to log (letters after "$GP"). next "n"/"b" (up to 24 total) - "n" number (will be encoded 2 digits/byte, follwed by "0xF"
/// "b" - byte - all but last will have MSB 0 (& 0x7f), the last one - with MSB set (| 0x80). If there are no characters in the field 0xff will be output
array('RMC','nbnbnbnnnnb'),
array('GGA','nnbnbnnnnbnbbb'),
array('GSA','bnnnnnnnnnnnnnnnn'),
array('VTG','nbnbnbnb')
),
'message'=>'Odometer message' // Message - up to 56 bytes
);
return $default_config;
}
/**
Combines $conf and $dflt arrays - all driver parameters are overwritten aftre the call
*/
function combineLoggerConfigs($new_conf,$dflt=null){
global $default_config;
$xclk_freq=80000000; // 80 MHz
$data=array();
$index=0;
if (!isset ($dflt)) {
$dflt=$default_config;
}
$conf=$dflt;
if (isset($new_conf)) foreach ($conf as $key=>$oldvalue) if (isset($new_conf[$key])) $conf[$key]=$new_conf[$key];
/// fix insufficient data from default
while (count($conf['imu_registers'])<28) $conf['imu_registers'][count($conf['imu_registers'])]=0; // zero pad if less than 28 registers
/// Configure NMEA sentences to log. If there are less than 4 - copy additional (unique) from defaults
while (count($conf['nmea'])<4) {
for ($i=0;$i<4;$i++) {
$new=true;
for ($j=0;$j<count($conf['nmea']);$j++) if ($conf['nmea'][$j][0]==$dflt['nmea'][$i][0]){ // compare sentence code last 3 letters
$new=false;
break;
}
if ($new) {
$conf['nmea'][count($conf['nmea'])]=$dflt['nmea'][$i];
break;
}
}
}
for ($i=0;$i<4;$i++) {
while (strlen($conf['nmea'][$i][0])<3) $conf['nmea'][$i][0].="A"; // just to avoid errors - nonexistent sentences will not hurt, just never logged
}
return $conf;
}
function setup_IMU_logger($conf){
global $verbose,$xclk_freq;
$data=array();
$index=0;
/// program period
if (strtolower($conf['imu_period'])=='auto') $conf['imu_period']=0xffffffff;
else $conf['imu_period']+=0;
$data[$index++]= $conf['imu_period'] & 0xff;
$data[$index++]=($conf['imu_period']>> 8) & 0xff;
$data[$index++]=($conf['imu_period']>>16) & 0xff;
$data[$index++]=($conf['imu_period']>>24) & 0xff;
/// program SCLK divisor and SPI stall time
$sclk_div=round($xclk_freq/$conf['sclk_freq']/2);
if ($sclk_div<1) $sclk_div=1;
else if ($sclk_div>255) $sclk_div=255;
$conf['sclk_freq']=$xclk_freq/$sclk_div/2;
$stall=(( $conf['stall'] * ( $xclk_freq / $sclk_div )) / 1000000 );
if ($stall< 1) $stall= 1; /// does 0 work? need to verify
else if ($stall>255) $stall=255;
$conf['stall']=$stall * 1000000 / ($xclk_freq / $sclk_div);
$data[$index++]= $sclk_div;
$data[$index++]= $stall;
$data[$index++]= 0;
$data[$index++]= 0;
/// Program rs232 baud rate
$rs232_div=round($xclk_freq /2/$conf['baud_rate']);
$conf['baud_rate']=$xclk_freq /2/$rs232_div;
$data[$index++]= $rs232_div & 0xff;
$data[$index++]=($rs232_div>> 8) & 0xff;
$data[$index++]=($rs232_div>>16) & 0xff;
$data[$index++]=($rs232_div>>24) & 0xff;
/// Program logger configuration (possible to modify only some fields - maybe support it here?)
$logger_conf=0;
/// #define IMUCR__IMU_SLOT__BITNM 0 // slot, where 103695 (imu) board is connected: 0 - none, 1 - J9, 2 - J10, 3 - J11)
/// #define IMUCR__IMU_SLOT__WIDTH 2
$logger_conf |= (($conf['imu_slot'] & 0x3) | 0x4 )<< 0; /// "4" (bit 2 set) here means that the data in bits 0,1 will be applied in the FPGA register
/// #define IMUCR__GPS_CONF__BITNM 3 // slot, where 103695 (imu) bnoard is connected: 0 - none, 1 - J9, 2 - J10, 3 - J11)
/// #define IMUCR__GPS_CONF__WIDTH 4 // bits 0,1 - slot #, same as for IMU_SLOT, bits 2,3:
// 0 - ext pulse, leading edge,
// 1 - ext pulse, trailing edge
// 2 - start of the first rs232 character after pause
// 3 - start of the last "$" character (start of each NMEA sentence)
$logger_conf |= ((($conf['gps_slot'] & 0x3) | (($conf['gps_mode'] & 0x3)<<2) ) | 0x10 )<< 3;
/// #define IMUCR__MSG_CONF__BITNM 8 // source of external pulses to log:
/// #define IMUCR__MSG_CONF__WIDTH 5 // bits 0-3 - number of fpga GPIO input 0..11 (i.e. 0x0a - external optoisolated sync input (J15)
// 0x0f - disable MSG module
// bit 4 - invert polarity: 0 - timestamp leading edge, log at trailing edge, 1 - opposite
// software may set (up to 56 bytes) log message before trailing end of the pulse
$logger_conf |= (($conf['msg_conf'] & 0x1f) | 0x20 )<< 8;
/// #define IMUCR__SYN_CONF__BITNM 14 // logging frame time stamps (may be synchronized by another camera and have timestamp of that camera)
/// #define IMUCR__SYN_CONF__WIDTH 1 // 0 - disable, 1 - enable
$logger_conf |= (($conf['img_sync'] & 0x1) | 0x2 )<< 14;
/// #define IMUCR__RST_CONF__BITNM 16 // reset module
/// #define IMUCR__RST_CONF__WIDTH 1 // 0 - enable, 1 -reset (needs resettimng DMA address in ETRAX also)
/// #define IMUCR__DBG_CONF__BITNM 18 // several extra IMU configuration bits
/// #define IMUCR__DBG_CONF__WIDTH 4 // 0 - config_long_sda_en, 1 -config_late_clk, 2 - config_single_wire, should be set for 103695 rev "A"
$logger_conf |= (($conf['extra_conf'] & 0xf) | 0x10 )<< 18;
/// next bits used by the driver only, not the FPGA
/// ((SLOW_SPI & 1)<<23) | \
/// (DFLT_SLAVE_ADDR << 24))
$logger_conf |= ($conf['slow_spi'] & 0x1)<< 23;
$logger_conf |= ($conf['imu_sa'] & 0x7)<< 24;
$data[$index++]= $logger_conf & 0xff;
$data[$index++]=($logger_conf>> 8) & 0xff;
$data[$index++]=($logger_conf>>16) & 0xff;
$data[$index++]=($logger_conf>>24) & 0xff;
/// Set time driver will go to sleep if the data is not ready yet (less than full sample in the buffer)
$data[$index++]= $conf['sleep_busy'] & 0xff;
$data[$index++]=($conf['sleep_busy']>> 8) & 0xff;
$data[$index++]=($conf['sleep_busy']>>16) & 0xff;
$data[$index++]=($conf['sleep_busy']>>24) & 0xff;
/// Set IMU register addresses to logger
// echo "1\n";
for ($i=0;$i<28;$i++) $data[$index++]= $conf['imu_registers'][$i]; // truncate to 28
/// Configure NMEA sentences to log. If there are less than 4 - copy additional (unique) from defaults
// echo "2\n";
for ($i=0;$i<4;$i++) {
$d =str_split($conf['nmea'][$i][0]);
// print_r($d);
for ($j=0;$j<3;$j++) $data[$index++]=ord($d[$j]);
$d =str_split($conf['nmea'][$i][1]);
// print_r($d);
for ($j=0;$j<29;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
}
// echo "3\n";
/// Set default message
$d =str_split($conf['message']);
for ($j=0;$j<56;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
// Print the result array as hex data
/*
print_r($conf);
echo "\n";
for ($i=0;$i<count($data);$i++) {
if (($i & 0xf)==0) printf ("\n%04x:",$i);
printf (" %02x",$data[$i]);
}
echo "\n";
*/
$bindata="";
for($i=0;$i<count($data);$i++) $bindata.=chr($data[$i]);
$dev_imu_ctl = fopen('/dev/imu_ctl', 'w');
fwrite($dev_imu_ctl, $bindata, strlen($bindata));
fseek($dev_imu_ctl,3,SEEK_END); // start IMU
fclose($dev_imu_ctl);
/// Readback - just testing
$bd=file_get_contents('/dev/imu_ctl');
$data =str_split($bd);
if ($verbose) {
echo "\n";
for ($i=0;$i<count($data);$i++) {
if (($i & 0xf)==0) printf ("\n%04x:",$i);
printf (" %02x",ord($data[$i]));
}
echo "\n";
}
}
function setMessage($msg) {
global $messageOffset;
$data=array();
$d =str_split($msg);
$index=0;
for ($j=0;$j<56;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
$bindata="";
for($i=0;$i<count($data);$i++) $bindata.=chr($data[$i]);
$dev_imu_ctl = fopen('/dev/imu_ctl', 'w');
fseek($dev_imu_ctl,$messageOffset,SEEK_SET); // start IMU
echo ftell($dev_imu_ctl)."<br/>\n";
fwrite($dev_imu_ctl, $bindata, strlen($bindata));
// fseek($dev_imu_ctl,3,SEEK_END); // start IMU
fclose($dev_imu_ctl);
var_dump ( $bindata);
}
function readSettings($conf=null) {
global $xclk_freq; // =80000000; // 80 MHz
$bd=file_get_contents('/dev/imu_ctl');
$data =str_split($bd);
for ($i=0;$i<count($data);$i++) $data[$i]=ord($data[$i]);
/*
// if ($verbose) {
echo "\n";
for ($i=0;$i<count($data);$i++) {
if (($i & 0xf)==0) printf ("\n%04x:",$i);
printf (" %02x",$data[$i]);
}
echo "\n";
// }
*/
if ($conf!=null) {
/// read current period
$conf['imu_period'] =$data[$index++];
$conf['imu_period']|=$data[$index++]<<8;
$conf['imu_period']|=$data[$index++]<<16;
$conf['imu_period']|=$data[$index++]<<24;
/// read current SCLK divisor and SPI stall time
$sclk_div =$data[$index++];
$stall =$data[$index++];
$index++;
$index++;
$conf['sclk_freq']=$xclk_freq/$sclk_div/2;
$conf['stall']=$stall * 1000000 / ($xclk_freq / $sclk_div);
/// read current rs232 baud rate
$rs232_div =$data[$index++];
$rs232_div|=$data[$index++]<<8;
$rs232_div|=$data[$index++]<<16;
$rs232_div|=$data[$index++]<<24;
$conf['baud_rate']=$xclk_freq /2/$rs232_div;
/// read current logger configuration (possible to modify only some fields - maybe support it here?)
/// assuming set bits are set, otherwise it is impossible to find out the old value
$logger_conf =$data[$index++];
$logger_conf|=$data[$index++]<<8;
$logger_conf|=$data[$index++]<<16;
$logger_conf|=$data[$index++]<<24;
/// #define IMUCR__IMU_SLOT__BITNM 0 // slot, where 103695 (imu) board is connected: 0 - none, 1 - J9, 2 - J10, 3 - J11)
/// #define IMUCR__IMU_SLOT__WIDTH 2
$conf['imu_slot']= ($logger_conf>>0) & 3;
/// #define IMUCR__GPS_CONF__BITNM 3 // slot, where 103695 (imu) bnoard is connected: 0 - none, 1 - J9, 2 - J10, 3 - J11)
/// #define IMUCR__GPS_CONF__WIDTH 4 // bits 0,1 - slot #, same as for IMU_SLOT, bits 2,3:
// 0 - ext pulse, leading edge,
// 1 - ext pulse, trailing edge
// 2 - start of the first rs232 character after pause
// 3 - start of the last "$" character (start of each NMEA sentence)
// $logger_conf |= ((($conf['gps_slot'] & 0x3) | (($conf['gps_mode'] & 0x3)<<2) ) | 0x10 )<< 3;
$conf['gps_slot']= ($logger_conf >> 3) & 3;
$conf['gps_mode']= ($logger_conf >> 5) & 3;
/// #define IMUCR__MSG_CONF__BITNM 8 // source of external pulses to log:
/// #define IMUCR__MSG_CONF__WIDTH 5 // bits 0-3 - number of fpga GPIO input 0..11 (i.e. 0x0a - external optoisolated sync input (J15)
// 0x0f - disable MSG module
// bit 4 - invert polarity: 0 - timestamp leading edge, log at trailing edge, 1 - opposite
// software may set (up to 56 bytes) log message before trailing end of the pulse
// $logger_conf |= (($conf['msg_conf'] & 0x1f) | 0x20 )<< 8;
$conf['msg_conf']= ($logger_conf >> 8) & 0x1f;
/// #define IMUCR__SYN_CONF__BITNM 14 // logging frame time stamps (may be synchronized by another camera and have timestamp of that camera)
/// #define IMUCR__SYN_CONF__WIDTH 1 // 0 - disable, 1 - enable
// $logger_conf |= (($conf['img_sync'] & 0x1) | 0x2 )<< 14;
$conf['img_sync']= ($logger_conf >> 14) & 0x1;
/// #define IMUCR__RST_CONF__BITNM 16 // reset module
/// #define IMUCR__RST_CONF__WIDTH 1 // 0 - enable, 1 -reset (needs resettimng DMA address in ETRAX also)
/// #define IMUCR__DBG_CONF__BITNM 18 // several extra IMU configuration bits
/// #define IMUCR__DBG_CONF__WIDTH 4 // 0 - config_long_sda_en, 1 -config_late_clk, 2 - config_single_wire, should be set for 103695 rev "A"
// $logger_conf |= (($conf['extra_conf'] & 0xf) | 0x10 )<< 18;
$conf['extra_conf']= ($logger_conf >> 18) & 0xf;
/// next bits used by the driver only, not the FPGA
/// ((SLOW_SPI & 1)<<23) | \
/// (DFLT_SLAVE_ADDR << 24))
// $logger_conf |= ($conf['slow_spi'] & 0x1)<< 23;
// $logger_conf |= ($conf['imu_sa'] & 0x7)<< 24;
$conf['slow_spi']= ($logger_conf >> 23) & 0x1;
$conf['imu_sa']= ($logger_conf >> 24) & 0x7;
/// read current time driver will go to sleep if the data is not ready yet (less than full sample in the buffer)
$conf['sleep_busy'] =$data[$index++];
$conf['sleep_busy']|=$data[$index++]<<8;
$conf['sleep_busy']|=$data[$index++]<<16;
$conf['sleep_busy']|=$data[$index++]<<24;
/// read current IMU register addresses to logger
// echo "1\n";
// for ($i=0;$i<28;$i++) $data[$index++]= $conf['imu_registers'][$i]; // truncate to 28
for ($i=0;$i<28;$i++) $conf['imu_registers'][$i]=$data[$index++];
/// read current NMEA sentences to log. If there are less than 4 - copy additional (unique) from defaults
// echo "2\n";
$conf['nmea']=array(array("",""),array("",""),array("",""),array("",""));
for ($i=0;$i<count($conf['nmea']);$i++) {
// $d =str_split($conf['nmea'][$i][0]);
// for ($j=0;$j<3;$j++) $data[$index++]=ord($d[$j]);
for ($j=0;$j<3;$j++) $conf['nmea'][$i][0].=chr($data[$index++]);
// $d =str_split($conf['nmea'][$i][1]);
// for ($j=0;$j<29;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
for ($j=0;$j<29;$j++) {
$d=$data[$index++];
if ($d!=0) $conf['nmea'][$i][1].=chr($d);
else {
$index+=(29-1-$j);
break;
}
}
}
/// read current message
// $conf['message_offset']=$index;
// $d =str_split($conf['message']);
// for ($j=0;$j<56;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
$conf['message']="";
for ($j=0;$j<56;$j++) {
$d=$data[$index++];
if ($d!=0) $conf['message'].=chr($d);
else {
$index+=(56-1-$j);
break;
}
}
// var_dump ($conf);
return $conf;
}
}
?>
#!/bin/bash
args="$@"
while (( "$#" )); do
shift
done
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "Launching bitbake $args"
cd $DIR/../../poky
. ./oe-init-build-env
bitbake $args | sed -u 's@| @@'
exit 0
#!/usr/local/sbin/php -q
<?php
/*
*! FILE NAME : start_gps_compass.php
*! DESCRIPTION: Looks for USB GPS (currently Garmin GPS 18 USB) and compass
*! (currently Ocean Server OS-5000), re-initializes Exif header
*! and starts the devices if found
*!
*! Copyright (C) 2008 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/>.
*! -----------------------------------------------------------------------------**
*! $Log: start_gps_compass.php,v $
*! Revision 1.6 2012/03/14 00:05:41 elphel
*! 8.2.1 - GPS speed, x353.bit file tested on Eyesis
*!
*! Revision 1.5 2011/08/13 00:55:14 elphel
*! support for detection 103595 and 103696 boards, programming the logger
*!
*! Revision 1.4 2011/01/15 23:22:10 elphel
*! added 19200
*!
*! Revision 1.3 2009/02/20 21:49:52 elphel
*! bugfix - was killing daemons after detection, not before (as should)
*!
*! Revision 1.2 2009/02/19 22:38:37 elphel
*! 8.0.2.3 - added several USB serial adapters, nmea->exif support, detection of NMEA GPS at boot
*!
*! Revision 1.1.1.1 2008/11/27 20:04:01 elphel
*!
*!
*! Revision 1.2 2008/11/20 07:03:40 elphel
*! exit value now encodes detected devices
*!
*! Revision 1.1 2008/04/07 09:14:47 elphel
*! Discover/startup GPS and compass
*!
*/
//look uptime, sleep if just started (no USB yet)
//require '/usr/html/includes/i2c.inc';
require 'i2c.inc';
$config_name="/etc/imu_logger.xml";
$ids=scanGrandDaughters();
$b_index=indexGrandDaughters($ids);
// print_r($ids);
// print_r($b_index);
$baud=null;
if (isset($b_index[103696])) {
$baud=$ids[$b_index[103696]]['baud'];
if ($baud===0) $baud=='auto';
}
// exit (0);
$wait_time=20; // wait for $wait_time if both devices were not found, retry
$compass=null;
$GPS=null;
$verbose=true;
foreach ($_SERVER['argv'] as $param) {
if ((substr($param,0,2)=="-q") || (substr($param,0,8)=="--silent")){
$verbose=false;
}
}
/// kill those GPS and compass if they are running already
exec('killall -q garminusb2exif');
exec('killall -q nmea2exif');
exec('killall -q compass');
// find_gps_compass();
$devs=find_gps_compass($baud);
// echo "compass: ";var_dump($compass);echo "\n";
// echo "GPS: ";var_dump($GPS);echo "\n";
// if ((!$compass || !$GPS) && ((exec('date +%s')+0) <30)) {
if ((count($devs)==0) && ((exec('date +%s')+0) <30)) {
if ($verbose) echo "waiting $wait_time sec for USB devices to start up\n";
sleep($wait_time);
if ($verbose) echo "Retrying detection\n";
$devs=find_gps_compass($baud);
}
listSensorDevices($devs,$b_index,$ids);
//var_dump($GPS);
// if (file_exists ($sensor_state_file)) $sensor_board=parse_ini_file($sensor_state_file);
// exec ('sync');
$logger_config=null;
$write_config=false;
if (file_exists ($config_name)) {
if ($verbose) echo 'Reading IMU logger configuration from '. $config_name."\n";
$config_xml = simplexml_load_file($config_name);
$logger_config=loggerConfigFromXML($config_xml);
} else if (isset($b_index[103696]) || isset($b_index[103696])) {
if ($verbose) echo "Generating IMU logger configuration\n";
// $default_config=init_default_config();
// $logger_config=init_default_config();
$logger_config=array();
if (isset($GPS) && isset($b_index[103696])) {
$logger_config['baud_rate']=$GPS['baud'];
$logger_config['gps_slot']=$ids[$b_index[103696]]['port'];
$logger_config['gps_mode']=$ids[$b_index[103696]]['sync'];
}
if (isset($b_index[103695])) {
$logger_config['imu_slot']=$ids[$b_index[103695]]['port'];
$logger_config['imu_sa']=$b_index[103695];
}
$write_config=true; // write configuration to /etc after applying defaults
}
if (isset($logger_config)){
// var_dump($logger_config);
$logger_config=combineLoggerConfigs($logger_config,init_default_config());
// var_dump($logger_config);
// var_dump($default_config);
$logger_xml=loggerConfigToXML($logger_config);
$conf_file=fopen('/var/html/logger_config.xml',"w");
fwrite($conf_file,$logger_xml->asXML());
fclose($conf_file);
setup_IMU_logger($logger_config);
if ($write_config) {
if ($verbose) echo 'Writing IMU logger configuration to '. $config_name."\n";
$conf_file=fopen($config_name,"w");
fwrite($conf_file,$logger_xml->asXML());
fclose($conf_file);
exec ('sync');
}
}
// echo "compass: ";var_dump($compass);echo "\n";
// echo "GPS: ";var_dump($GPS);echo "\n";
$noGPS= ($compass || $GPS)?"" : "noGPS";
$nocompass=($compass)?"" : "nocompass";
$cmd="/usr/html/exif.php init $noGPS $nocompass";
if ($verbose) echo "Initializing Exif template: $cmd\n";
exec($cmd);
if ($GPS) {
if ($verbose) echo "Starting ".$GPS["name"]. " as ". $GPS["file"]. "\n";
if (strpos($GPS['name'],'NMEA')!==false) {
$cmd ="/usr/local/bin/nmea2exif ". $GPS["file"]." &";
} else {
$cmd ="/usr/local/bin/garminusb2exif ". $GPS["file"]." &";
}
if ($verbose) echo "exec: $cmd \n";
popen($cmd,"r");
}
if ($compass) {
if ($verbose) echo "Starting ".$compass["name"]. " as ". $compass["file"]. "\n";
exec ("stty -F ".$compass["file"]." -echo speed 19200");
$cmd="/usr/local/bin/compass ". $compass["file"]." &";
if ($verbose) echo "exec: $cmd \n";
popen($cmd,"r");
}
exit ((isset($b_index[103695])?4:0) | ($compass?2:0) | ($GPS?1:0));
function scanGrandDaughters(){
$ids=array();
$id="";
for ($i=2;$i<8;$i++) {
$id=i2c_read256b(0xa0+2*$i,1);
$xml=simplexml_load_string($id);
if (($xml!==false) && ($xml->getName()=='board')) {
$ids[$i]=array();
foreach ($xml->children() as $entry) {
$ids[$i][$entry->getName()]=(string) $entry ;
}
}
}
return $ids;
}
function indexGrandDaughters($ids) {
$index=array();
foreach($ids as $i=>$id) if (isset($id['model'])) {
$index[$id['model']]=$i;
}
return $index;
}
/// compass/GPS programs should be killed before detection
// baud=null - search USB Garmin and compass
// baud=auto - try to autodetect baud rate
// baud=number - used specified baud rate, do not wait for the GPS response
function find_gps_compass($baud=null,$timeout=5) {
global $verbose;
$ttyOptions=array (
'-echo speed 115200',
'-echo speed 57600',
'-echo speed 56000',
'-echo speed 38400',
'-echo speed 19200', /// maybe other options, like '-echo speed 4800 -ixoff'
'-echo speed 9600',
'-echo speed 4800',
'-echo speed 2400'
);
if (isset($baud) && ($baud!='auto') && ($baud!=0)) {
$ttyOptions=array (
'-echo speed '.$baud);
}
// global $GPS, $compass;
$devices=array(
"compass"=>array(array("name"=>"Ocean Server OS-5000","driver"=>"cp2101")),
"GPS" =>array(array("name"=>"Garmin GPS 18 USB","driver"=>"garmin_gps")));
exec("ls /sys/bus/usb-serial/devices",$usb_ser_devs); // ("ttyUSB0","ttyUSB1")
$devs = new SimpleXMLElement("<?xml version='1.0' standalone='yes'?><USB_serial_devices/>");
$serialDevices=array();
$compassPresent=false;
$gpsPresent=false;
$driver=array();
//echo "usb_ser_devs"; var_dump($usb_ser_devs);
foreach ($usb_ser_devs as $dev) {
//echo "dev=$dev\n";
$arr=split("/",exec("ls /sys/bus/usb-serial/devices/".$dev."/driver -l"));
$driver[$dev]=$arr[count($arr)-1];
$serialDevices[$dev]='';
if (!isset($baud)) { // if baud is set (auto or number - skip compass, it is 103696)
foreach ($devices["compass"] as $d) {
if ($d["driver"]==$driver[$dev]) {
$dd=$devs->addChild ('compass');
$dd->addChild ('name',$d["name"]);
$dd->addChild ('driver',$d["driver"]);
$dd->addChild ('file',"/dev/".$dev);
$serialDevices[$dev]='compass';
$compassPresent=true;
}
}
}
if ($serialDevices[$dev]) continue;
foreach ($devices["GPS"] as $d) {
if ($d["driver"]==$driver[$dev]) {
$dd=$devs->addChild ('GPS');
$dd->addChild ('name',$d["name"]);
$dd->addChild ('driver',$d["driver"]);
$dd->addChild ('file',"/dev/".$dev);
$serialDevices[$dev]='gps';
$gpsPresent=true;
}
}
}
/// Do we need to look for a NMEA GPS?
if (!$gpsPresent) foreach ($serialDevices as $dev=>$type) if (!$type && !$gpsPresent) {
if ($verbose) printf ("could be $dev\n");
foreach ($ttyOptions as $ttyOpt) {
$cmd='stty -F /dev/'.$dev.' '.$ttyOpt;
if (count($ttyOptions)==1) { /// single baud option, will not wait for confirmation. Has to be only one serial adapter !!
if ($verbose) echo "Setting: $cmd\n";
exec ($cmd);
$gpsPresent=true;
} else {
if ($verbose) echo "Trying: $cmd\n";
exec ($cmd);
unset ($fullOutput);
exec ('timeout '.$timeout.' cat /dev/'.$dev, &$fullOutput);
//var_dump($fullOutput);
foreach ($fullOutput as $line) if (strpos ($line, '$GP')===0) {
$gpsPresent=true;
break;
}
}
if ($gpsPresent) {
$dd=$devs->addChild ('GPS');
$dd->addChild ('name','NMEA 0183 GPS receiver');
$dd->addChild ('driver',$driver[$dev]);
$dd->addChild ('file',"/dev/".$dev);
$arr=split(" ",$ttyOpt);
$dd->addChild ('baud',$arr[count($arr)-1]);
$serialDevices[$dev]='gps';
if ($verbose) echo "\nfound NMEA GPS unit\n";
break;
}
// var_dump($fullOutput);
}
}
/// list unused USB serial adapters
foreach ($serialDevices as $dev=>$type) if (!$type) {
$dd=$devs->addChild ('unused');
$dd->addChild ('name','USB serial converter');
$dd->addChild ('driver',$driver[$dev]);
$dd->addChild ('file',"/dev/".$dev);
}
return $devs;
}
function listSensorDevices($devs,$b_index,$ids) {
global $GPS, $compass;
foreach ($devs->compass as $a) {
$compass=array("file"=>(string) $a->file, "name"=> (string) $a->name);
break; // use first one
}
foreach ($devs->GPS as $a) {
$GPS=array("file"=>(string) $a->file, "name"=> (string) $a->name, "baud"=>(string) $a->baud);
if (isset($b_index[103696])) {
$a->addChild ('part_number',$ids[$b_index[103696]]['part']);
$a->addChild ('port',$ids[$b_index[103696]]['port']);
$a->addChild ('mode',$ids[$b_index[103696]]['mode']);
}
break; // use first one
}
$state_file=fopen("/var/html/gps_compass.xml","w");
fwrite($state_file,$devs->asXML());
fclose($state_file);
}
function loggerConfigToXML($conf){
$logger_xml = new SimpleXMLElement("<?xml version='1.0' standalone='yes'?><Logger_configuration/>");
foreach ($conf as $key=>$value) {
switch ($key) {
case 'imu_registers':
$subtree=$logger_xml->addChild ($key);
for ($i=0;$i<count($value);$i++) {
$subtree->addChild ('R_'.sprintf('%02d',$i),sprintf("0x%02x",$value[$i]));
}
break;
case 'nmea':
$subtree=$logger_xml->addChild ($key);
for ($i=0;$i<count($value);$i++) {
$sentence=$subtree->addChild ('S_'.sprintf('%01d',$i));
$sentence->addChild ('sentence',$value[$i][0]);
$sentence->addChild ('format',$value[$i][1]);
}
break;
default:
$logger_xml->addChild ($key,$value);
}
}
return $logger_xml;
}
function loggerConfigFromXML($confXML){
$conf=array();
// var_dump($confXML);
foreach ($confXML as $item) {
// var_dump($item);
$key=$item->getName();
switch ($key) {
case 'imu_registers':
$conf[$key]=array();
foreach ($item as $reg) {
$rname=substr($reg->getName(),2);
$conf[$key][$rname+0]=((string) $reg)+0;
}
break;
case 'nmea':
$conf[$key]=array();
foreach ($item as $reg) {
$rname=substr($reg->getName(),2);
$conf[$key][$rname+0]=array((string) $reg->sentence, (string) $reg->format);
}
break;
case 'imu_period':
$conf[$key]=(string) $item;
if ($conf[$key]!='auto') $conf[$key]+=0;
break;
case 'message':
$conf[$key]=(string) $item;
break;
default:
// $conf[$key]=(int) $item;
$conf[$key]=((string) $item)+0;
}
}
return $conf;
}
function init_default_config(){
$default_config=array(
'imu_period'=>'auto',// 0xFFFFFFFF, // 0 - off, >=0xff000000 - "when ready", else - number of SCLK periods
'sclk_freq'=>5000000, // $clkr_divr= 8, // 80MHz divisor to get half SCLK rate (defaulkt SCLK=5MHz)
'stall' => 2, // SPI stall time in usec
'baud_rate'=>19200, // $rs232_div=80/2/$baud
'imu_slot'=>1,
'gps_slot'=>2,
'gps_mode'=>2, // 0 - pps pos, 1 - pps neg, 2 - start of first sesntence after pause, 3 start of sentence
'msg_conf'=>10, // GPIO bit number for external (odometer) input (+16 - invert polarity). Timestamp uses leading edge, software may write to 56-byte buffer before the trailing edge
'img_sync'=>1, // enable logging image acquisition starts (0 - disable)
'extra_conf'=>4, // 0 - config_long_sda_en, 1 -config_late_clk, 2 - config_single_wire, should be set for 103695 rev "A"
'slow_spi'=>0, // set to 1 for slow SPI devices (0 for ADIS-16375)
'imu_sa'=>3, // i2c slave address modifier for the 103695A pca9500
'sleep_busy'=>30000, //microseconds
'imu_registers'=>array( /// Up to 28 total
0x10, // x gyro low
0x12, // x gyro high
0x14, // y gyro low
0x16, // y gyro high
0x18, // z gyro low
0x1a, // z gyro high
0x1c, // x accel low
0x1e, // x accel high
0x20, // y accel low
0x22, // y accel high
0x24, // z accel low
0x26, // z accel high
0x40, // x delta angle low
0x42, // x delta angle high
0x44, // y delta angle low
0x46, // y delta angle high
0x48, // z delta angle low
0x4a, // z delta angle high
0x4c, // x delta velocity low
0x4e, // x delta velocity high
0x50, // y delta velocity low
0x52, // y delta velocity high
0x54, // z delta velocity low
0x56, // z delta velocity high
0x0e, // temperature
0x70, // time m/s
0x72, // time d/h
0x74// time y/m
),
'nmea'=>array(
/// first three letters - sentence to log (letters after "$GP"). next "n"/"b" (up to 24 total) - "n" number (will be encoded 4 digits/byte, follwed by "0xF"
/// "b" - byte - all but last will have MSB 0 (& 0x7f), the last one - with MSB set (| 0x80). If there are no characters in the field 0xff will be output
array('RMC','nbnbnbnnnnb'),
array('GGA','nnbnbnnnnbnbbb'),
array('GSA','bnnnnnnnnnnnnnnnn'),
array('VTG','nbnbnbnb')
),
'message'=>'Odometer message' // Message - up to 56 bytes
);
return $default_config;
}
/**
Combines $conf and $dflt arrays - all driver parameters are overwritten aftre the call
*/
function combineLoggerConfigs($new_conf,$dflt=null){
global $default_config;
$xclk_freq=80000000; // 80 MHz
$data=array();
$index=0;
if (!isset ($dflt)) {
$dflt=$default_config;
}
$conf=$dflt;
if (isset($new_conf)) foreach ($conf as $key=>$oldvalue) if (isset($new_conf[$key])) $conf[$key]=$new_conf[$key];
/// fix insufficient data from default
while (count($conf['imu_registers'])<28) $conf['imu_registers'][count($conf['imu_registers'])]=0; // zero pad if less than 28 registers
/// Configure NMEA sentences to log. If there are less than 4 - copy additional (unique) from defaults
while (count($conf['nmea'])<4) {
for ($i=0;$i<4;$i++) {
$new=true;
for ($j=0;$j<count($conf['nmea']);$j++) if ($conf['nmea'][$j][0]==$dflt['nmea'][$i][0]){ // compare sentence code last 3 letters
$new=false;
break;
}
if ($new) {
$conf['nmea'][count($conf['nmea'])]=$dflt['nmea'][$i];
break;
}
}
}
for ($i=0;$i<4;$i++) {
while (strlen($conf['nmea'][$i][0])<3) $conf['nmea'][$i][0].="A"; // just to avoid errors - nonexistent sentences will not hurt, just never logged
}
return $conf;
}
function setup_IMU_logger($conf){
global $verbose;
$xclk_freq=80000000; // 80 MHz
$data=array();
$index=0;
/// program period
if (strtolower($conf['imu_period'])=='auto') $conf['imu_period']=0xffffffff;
else $conf['imu_period']+=0;
$data[$index++]= $conf['imu_period'] & 0xff;
$data[$index++]=($conf['imu_period']>> 8) & 0xff;
$data[$index++]=($conf['imu_period']>>16) & 0xff;
$data[$index++]=($conf['imu_period']>>24) & 0xff;
/// program SCLK divisor and SPI stall time
$sclk_div=round($xclk_freq/$conf['sclk_freq']/2);
if ($sclk_div<1) $sclk_div=1;
else if ($sclk_div>255) $sclk_div=255;
$conf['sclk_freq']=$xclk_freq/$sclk_div/2;
$stall=(( $conf['stall'] * ( $xclk_freq / $sclk_div )) / 1000000 );
if ($stall< 1) $stall= 1; /// does 0 work? need to verify
else if ($stall>255) $stall=255;
$conf['stall']=$stall * 1000000 / ($xclk_freq / $sclk_div);
$data[$index++]= $sclk_div;
$data[$index++]= $stall;
$data[$index++]= 0;
$data[$index++]= 0;
/// Program rs232 baud rate
$rs232_div=round($xclk_freq /2/$conf['baud_rate']);
$conf['baud_rate']=$xclk_freq /2/$rs232_div;
$data[$index++]= $rs232_div & 0xff;
$data[$index++]=($rs232_div>> 8) & 0xff;
$data[$index++]=($rs232_div>>16) & 0xff;
$data[$index++]=($rs232_div>>24) & 0xff;
/// Program logger configuration (possible to modify only some fields - maybe support it here?)
$logger_conf=0;
/// #define IMUCR__IMU_SLOT__BITNM 0 // slot, where 103695 (imu) board is connected: 0 - none, 1 - J9, 2 - J10, 3 - J11)
/// #define IMUCR__IMU_SLOT__WIDTH 2
$logger_conf |= (($conf['imu_slot'] & 0x3) | 0x4 )<< 0; /// "4" (bit 2 set) here means that the data in bits 0,1 will be applied in the FPGA register
/// #define IMUCR__GPS_CONF__BITNM 3 // slot, where 103695 (imu) bnoard is connected: 0 - none, 1 - J9, 2 - J10, 3 - J11)
/// #define IMUCR__GPS_CONF__WIDTH 4 // bits 0,1 - slot #, same as for IMU_SLOT, bits 2,3:
// 0 - ext pulse, leading edge,
// 1 - ext pulse, trailing edge
// 2 - start of the first rs232 character after pause
// 3 - start of the last "$" character (start of each NMEA sentence)
$logger_conf |= ((($conf['gps_slot'] & 0x3) | (($conf['gps_mode'] & 0x3)<<2) ) | 0x10 )<< 3;
/// #define IMUCR__MSG_CONF__BITNM 8 // source of external pulses to log:
/// #define IMUCR__MSG_CONF__WIDTH 5 // bits 0-3 - number of fpga GPIO input 0..11 (i.e. 0x0a - external optoisolated sync input (J15)
// 0x0f - disable MSG module
// bit 4 - invert polarity: 0 - timestamp leading edge, log at trailing edge, 1 - opposite
// software may set (up to 56 bytes) log message before trailing end of the pulse
$logger_conf |= (($conf['msg_conf'] & 0x1f) | 0x20 )<< 8;
/// #define IMUCR__SYN_CONF__BITNM 14 // logging frame time stamps (may be synchronized by another camera and have timestamp of that camera)
/// #define IMUCR__SYN_CONF__WIDTH 1 // 0 - disable, 1 - enable
$logger_conf |= (($conf['img_sync'] & 0x1) | 0x2 )<< 14;
/// #define IMUCR__RST_CONF__BITNM 16 // reset module
/// #define IMUCR__RST_CONF__WIDTH 1 // 0 - enable, 1 -reset (needs resettimng DMA address in ETRAX also)
/// #define IMUCR__DBG_CONF__BITNM 18 // several extra IMU configuration bits
/// #define IMUCR__DBG_CONF__WIDTH 4 // 0 - config_long_sda_en, 1 -config_late_clk, 2 - config_single_wire, should be set for 103695 rev "A"
$logger_conf |= (($conf['extra_conf'] & 0xf) | 0x10 )<< 18;
/// next bits used by the driver only, not the FPGA
/// ((SLOW_SPI & 1)<<23) | \
/// (DFLT_SLAVE_ADDR << 24))
$logger_conf |= ($conf['slow_spi'] & 0x1)<< 23;
$logger_conf |= ($conf['imu_sa'] & 0x7)<< 24;
$data[$index++]= $logger_conf & 0xff;
$data[$index++]=($logger_conf>> 8) & 0xff;
$data[$index++]=($logger_conf>>16) & 0xff;
$data[$index++]=($logger_conf>>24) & 0xff;
/// Set time driver will go to sleep if the data is not ready yet (less than full sample in the buffer)
$data[$index++]= $conf['sleep_busy'] & 0xff;
$data[$index++]=($conf['sleep_busy']>> 8) & 0xff;
$data[$index++]=($conf['sleep_busy']>>16) & 0xff;
$data[$index++]=($conf['sleep_busy']>>24) & 0xff;
/// Set IMU register addresses to logger
// echo "1\n";
for ($i=0;$i<28;$i++) $data[$index++]= $conf['imu_registers'][$i]; // truncate to 28
/// Configure NMEA sentences to log. If there are less than 4 - copy additional (unique) from defaults
// echo "2\n";
for ($i=0;$i<4;$i++) {
$d =str_split($conf['nmea'][$i][0]);
// print_r($d);
for ($j=0;$j<3;$j++) $data[$index++]=ord($d[$j]);
$d =str_split($conf['nmea'][$i][1]);
// print_r($d);
for ($j=0;$j<29;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
}
// echo "3\n";
/// Set default message
$d =str_split($conf['message']);
for ($j=0;$j<56;$j++) $data[$index++]=($j<count($d))?ord($d[$j]):0;
// Print the result array as hex data
/*
print_r($conf);
echo "\n";
for ($i=0;$i<count($data);$i++) {
if (($i & 0xf)==0) printf ("\n%04x:",$i);
printf (" %02x",$data[$i]);
}
echo "\n";
*/
$bindata="";
for($i=0;$i<count($data);$i++) $bindata.=chr($data[$i]);
$dev_imu_ctl = fopen('/dev/imu_ctl', 'w');
fwrite($dev_imu_ctl, $bindata, strlen($bindata));
fseek($dev_imu_ctl,3,SEEK_END); // start IMU
fclose($dev_imu_ctl);
/// Readback - just testing
$bd=file_get_contents('/dev/imu_ctl');
$data =str_split($bd);
if ($verbose) {
echo "\n";
for ($i=0;$i<count($data);$i++) {
if (($i & 0xf)==0) printf ("\n%04x:",$i);
printf (" %02x",ord($data[$i]));
}
echo "\n";
}
}
//ls /sys/bus/usb-serial/devices/ttyUSB0/driver -l
// $xml->addChild ('error','No sync capable board detected, use "role=self" for the onboard timer');
// $sxml=$xml->asXML();
?>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment