Subversion Repositories NaviCtrl

Rev

Rev 881 | Blame | Last modification | View Log | RSS feed

/*#######################################################################################*/
/* !!! THIS IS NOT FREE SOFTWARE !!!                                                     */
/*#######################################################################################*/
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software Nutzungsbedingungen (english version: see below)
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
// + des Mitverschuldens offen.
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
// +  Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software LICENSING TERMS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
// + The Software may only be used with the Licensor's products.
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
// + agreement shall be the property of the Licensor.
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
// + features that can be used to identify the program may not be altered or defaced by the customer.
// + The customer shall be responsible for taking reasonable precautions
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
// + #### END OF LICENSING TERMS ####
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <stdio.h>
#include <stdlib.h>
#include "91x_lib.h"
#include "main.h"
#include "timer1.h"
#include "timer2.h"
#include "uart1.h"
#include "uart2.h"
#include "triggerlog.h"
#include "gpx.h"
#include "ssc.h"
#include "settings.h"
#include "led.h"
#include "logging.h"
#include "timer1.h"
#include "gps.h"
#include "spi_slave.h"
#include "camctrl.h"

u16 Logged_TRIG_Counter = 0;
u16 TRIG_Filenum = 0;
u8  BlitzSchuhConnected = 1;
u8  LogGimbalData = 0;
u8  LogLaserData = 0;

TrigLog_t TrigLogging;

void TriggerInput(void) // triggerinput on IO1
{
 if(NMEA_Position.Status != INVALID)
 {
  TrigLogging.Longitude = NMEA_Position.Longitude;
  TrigLogging.Latitude =  NMEA_Position.Latitude;
 }
 else
 {
  TrigLogging.Longitude = GPSData.Position.Longitude;
  TrigLogging.Latitude = GPSData.Position.Latitude;
 }
 TrigLogging.Count++;
 if(BlitzSchuhConnected)        TrigLogging.CountExternal++;
 else                                           TrigLogging.CountExternal = 0;
 TrigLogging.AltiBaro = NaviData.Altimeter_5cm * 5; // in cm
 TrigLogging.ShutterCounter = NaviData_Volatile.ShutterCounter;

 TrigLogging.AltiGPS = GPSData.Position.Altitude;
 TrigLogging.Hour = SystemTime.Hour;
 TrigLogging.Min = SystemTime.Min;
 TrigLogging.Sec = SystemTime.Sec;
 TrigLogging.mSec = SystemTime.mSec;
 TrigLogging.ServoControlNick = FromFC_ServoNickControl;
 TrigLogging.ServoControlPoi = POI_KameraNick;
 if(SimulationFlags) TrigLogging.Yaw = CompassSetpointCorrected;
 else TrigLogging.Yaw = GyroCompassCorrected;
 TrigLogging.NewData++;

 if(NMEA_cnt)
  {
   u8 i;
   for(i=0; i<10;i++)
    {
          TrigLogging.NMEA_Alt[i] = NMEA_In_Alt_Txt[i];
        }
  }
  else
  {
   TrigLogging.NMEA_Alt[0] = 0;
  }
}

const s8 TRIG_DOCUMENT_FOOTER[] =
{
         "\r\n"
         "#Triggerlogfile closed\r\n"
};

//________________________________________________________________________________________________________________________________________
// Function:    TRIG_DocumentInit(TRIG_Document_t *)
//
// Description: This function initializes the kml-document for further use.
//
//
// Returnvalue: '1' if document was initialized
//________________________________________________________________________________________________________________________________________

u8 TRIG_DocumentInit(TRIG_Document_t *doc)
{                                                                                                              
        doc->state       = TRIG_DOC_CLOSED;                                                                                                     // state of the kml-document
        doc->file        = NULL;
        return(1);
}


//________________________________________________________________________________________________________________________________________
// Function:    DocumentClose(TRIG_Document_t *doc);
//
// Description: This function closes the document specified by doc.
//
//
// Returnvalue: '1' if the KML- file could be closed.
//________________________________________________________________________________________________________________________________________

u8 TRIG_DocumentClose(TRIG_Document_t *doc)
{

        u8 retvalue = 1;

        if(doc == NULL) return(0);

        while(doc->state != TRIG_DOC_CLOSED)                                                            // close linestring, placemark and document before closing the file on the memorycard
        {
                switch(doc->state)
                {
                        case TRIG_DOC_LINESTRING_OPENED:
                                TRIG_LineStringEnd(doc);                                                        // write terminating tag to end linestring.
                                break;

                        case TRIG_DOC_PLACEMARK_OPENED:                                                 // write terminating tag to close placemark.
                                TRIG_PlaceMarkClose(doc);
                                break;

                        case TRIG_DOC_OPENED:                                                                   // close the file on the memorycard
                                if(doc->file != NULL)
                                {
                                        fwrite_((void*)TRIG_DOCUMENT_FOOTER, sizeof(TRIG_DOCUMENT_FOOTER)-1,1,doc->file);       // write the KML- footer to the document.
                                        fclose_(doc->file);
                                        retvalue = 1;
                                }
                                doc->state = TRIG_DOC_CLOSED;
                                break;

                        default:
                                doc->state = TRIG_DOC_CLOSED;
                                break;

                }
        }
        return(retvalue);
}

//________________________________________________________________________________________________________________________________________
// Function:    u8 TRIG_PlaceMarkOpen(TRIG_Document_t *doc);
//
// Description: This function adds a placemark to the document.
//
//
// Returnvalue: '1' if the PlaceMark could be opened
//________________________________________________________________________________________________________________________________________

u8 TRIG_PlaceMarkOpen(TRIG_Document_t *doc)
{
        u8 retvalue = 0;
        if(doc->state == TRIG_DOC_OPENED)
        {
                if(doc->file != NULL)
                {
                        doc->state = TRIG_DOC_PLACEMARK_OPENED;
                        retvalue = 1;
//                      fwrite_((void*)TRIG_PLACEMARK_HEADER, sizeof(TRIG_PLACEMARK_HEADER)-1,1,doc->file);
                }
        }
        return(retvalue);
}

//________________________________________________________________________________________________________________________________________
// Function:    u8 PlaceMarkClose(TRIG_PlaceMark_t *place, File *file);
//
// Description: This function ends the placemark opened before.
//
//
// Returnvalue: 1' if the PlaceMark could be closed
//________________________________________________________________________________________________________________________________________

u8 TRIG_PlaceMarkClose(TRIG_Document_t *doc)
{

        u8 retvalue = 0;                                                                                                                        // close the Placemark-tag of the corosponding document.

        if(doc->state == TRIG_DOC_PLACEMARK_OPENED)
        {
                if(doc->file != NULL)
                {
                        doc->state = TRIG_DOC_OPENED;
//                      fwrite_((void*)TRIG_PLACEMARK_FOOTER, sizeof(TRIG_PLACEMARK_FOOTER)-1,1,doc->file);
                        retvalue = 1;
                }
        }

        return(retvalue);
}

//________________________________________________________________________________________________________________________________________
// Function:    u8 LineStringBegin(TRIG_Document_t *doc);
//
// Description: This function ends the placemark opened before.
//
//
// Returnvalue: '1' if the LineString could be started
//________________________________________________________________________________________________________________________________________

u8 TRIG_LineStringBegin(TRIG_Document_t *doc)
{

        u8 retvalue = 0;

        if(doc->state == TRIG_DOC_PLACEMARK_OPENED)
        {
                if(doc->file != NULL)
                {
                        doc->state = TRIG_DOC_LINESTRING_OPENED;
//                      fwrite_((void*)TRIG_LINESTRING_HEADER, sizeof(TRIG_LINESTRING_HEADER)-1,1,doc->file);
                        Logged_TRIG_Counter = 0;
                        TrigLogging.NewData = 0;
                        retvalue = 1;
                }
        }
        return(retvalue);
}

//________________________________________________________________________________________________________________________________________
// Function:    u8 TRIG_LineStringEnd(TRIG_Document_t *doc)
//
// Description: This function ends the placemark opened before.
//
//
// Returnvalue: '1' if the LineString could be terminated
//________________________________________________________________________________________________________________________________________

u8 TRIG_LineStringEnd(TRIG_Document_t *doc)
{
        u8 retvalue = 0;
        if(doc->state == TRIG_DOC_LINESTRING_OPENED)
        {
                if(doc->file != NULL)
                {
                        doc->state = TRIG_DOC_PLACEMARK_OPENED;
//                      fwrite_((void*)TRIG_LINESTRING_FOOTER, sizeof(TRIG_LINESTRING_FOOTER)-1,1,doc->file);
                        retvalue = 1;
                }
        }
        return(retvalue);
}

//________________________________________________________________________________________________________________________________________
// Function:    TRIG_Document_Open(void);
//
// Description: This function opens a new KML- document with the specified name and creates the document header within the file.
//
//
// Returnvalue: '1' if the KML- file could be created.
//________________________________________________________________________________________________________________________________________

u8 TRIG_DocumentOpen(s8 *name, TRIG_Document_t *doc)
{

        u8 retvalue = 0;
        s8 string[150];

        if(doc == NULL) return(0);

        TRIG_DocumentInit(doc);                                                                                                         // intialize the document with resetvalues
        doc->file = fopen_(name,'a');                                                                                           // open a new file with the specified filename on the memorycard.

        if(doc->file != NULL)                                                                                                           // could the file be opened?
        {
                retvalue = 1;                                                                                                                   // the document could be created on the drive.
                doc->state = TRIG_DOC_OPENED;                                                                                           // change document state to opened. At next a placemark has to be opened.
                sprintf(string, "#Counter;Time;Latitude;Longitude;GPSAltitude[m](raw);BaroAltitude[m];Compass[deg];ServoSetpoint(raw);ServoPoi[deg]");
                fputs_(string, doc->file);
if(FromLaserCtrl.LaserStatus)
 {
                sprintf(string, ";Laser[m]");
                fputs_(string, doc->file);
                LogLaserData = 1;
 } else LogLaserData = 0;

if(FromGimbalCtrl.GimbalStatus)
 {
                sprintf(string, ";Gimbal_N[0,1deg];Gimbal_R[0,1deg]");
                fputs_(string, doc->file);
                LogGimbalData = 1;
 } else LogGimbalData = 0;

                sprintf(string, "\r\n#%4i.%02i.%02i Nr:%i (%02i%02i%02i%02i.GPX)", SystemTime.Year, SystemTime.Month, SystemTime.Day, TRIG_Filenum, SystemTime.Year%100, SystemTime.Month, SystemTime.Day, GPX_Filenum);
                fputs_(string, doc->file);
                if(SimulationFlags) { sprintf(string, " SIMULATED"); fputs_(string, doc->file);};
                if(BlitzSchuhConnected){ sprintf(string, "\r\n#External hotshoe sensor connected");     fputs_(string, doc->file);};
                if(NMEA_cnt){ sprintf(string, "\r\n#External GNSS-Data (NMEA) used");   fputs_(string, doc->file);};
        }
        return(retvalue);
}


//________________________________________________________________________________________________________________________________________
// Function:    u8 LineStringAddPoint(gps_data_t, TRIG_Document_t *doc)
//
// Description: This function adds a point to the specified document.
//
//
// Returnvalue: '1' if a ppoint was added could be started
//________________________________________________________________________________________________________________________________________

u8 TRIG_LineStringAddPoint(TRIG_Document_t *doc)
{

        u8 retvalue = 0;
        s8 string[70];
        s32 rel_altitude = 0;

        if(doc == NULL) return(0);

        if(GPSData.Position.Status != INVALID)
        {
                if(doc->state == TRIG_DOC_LINESTRING_OPENED)
                {
                        if(doc->file != NULL)
                        {
                                s32 i1, i2;
                                u8 sign;
// Counter
                                sprintf(string,"\r\n%d",TrigLogging.Count);
                                fputs_(string, doc->file);
// Time
                                sprintf(string, ";%04d-%02d-%02dT%02d:%02d:%02d.%dZ",SystemTime.Year, SystemTime.Month, SystemTime.Day, SystemTime.Hour, SystemTime.Min, SystemTime.Sec,SystemTime.mSec/100);
                                fputs_(string, doc->file);
// Position
                                if(TrigLogging.Latitude < 0) sign = '-';
                                else sign = '+';
                                i1 = abs(TrigLogging.Latitude)/10000000L;
                                i2 = abs(TrigLogging.Latitude)%10000000L;
                                sprintf(string,";%c%ld.%07ld",sign, i1, i2);
                                fputs_(string, doc->file);
                               
                                if(TrigLogging.Longitude < 0) sign = '-';
                                else sign = '+';
                                i1 = abs(TrigLogging.Longitude)/10000000L;
                                i2 = abs(TrigLogging.Longitude)%10000000L;
                                sprintf(string,";%c%ld.%07ld",sign, i1, i2);
                                fputs_(string, doc->file);
                                // calculate relative altitude with respect to the altitude of the home position

// Altitude GPS
                        if(TrigLogging.NMEA_Alt[0])
                        {
                                sprintf(string,";%s",TrigLogging.NMEA_Alt);
                                fputs_(string, doc->file);
                        }
                        else
                        {
                                rel_altitude = TrigLogging.AltiGPS;// - NaviData.HomePosition.Altitude;
//                              if(rel_altitude < 0) rel_altitude = 0; // avoid negative altitudes in log
                                i1 = rel_altitude/1000L;
                                i2 = rel_altitude%1000L;
                                sprintf(string,";%ld.%03ld",i1, labs(i2));
                                fputs_(string, doc->file);
                        }
// Altitude Baro
                                sprintf(string,";%ld.%02d",TrigLogging.AltiBaro/100,abs(TrigLogging.AltiBaro%100));
                                fputs_(string, doc->file);
// Yaw angle
                                sprintf(string,";%d.%d",TrigLogging.Yaw/10,abs(TrigLogging.Yaw%10));
                                fputs_(string, doc->file);
// ServoSet; ServoPoi
                                sprintf(string,";%d;%d.%d",TrigLogging.ServoControlNick,TrigLogging.ServoControlPoi/10,abs(TrigLogging.ServoControlPoi%10));
                                fputs_(string, doc->file);
// laser connected?
if(LogLaserData)
 {
                                sprintf(string,";%d.%02d",FromLaserCtrl.Distance/100,abs(FromLaserCtrl.Distance%100));
                                fputs_(string, doc->file);
 }
// Gimbal Interface connected?
if(LogGimbalData)
 {
                                sprintf(string,";%d.%01d;%d.%01d",FromGimbalCtrl.Nick/10,abs(FromGimbalCtrl.Nick%10),FromGimbalCtrl.Roll/10,abs(FromGimbalCtrl.Roll%10));
                                fputs_(string, doc->file);
 }
                                Logged_TRIG_Counter++;
                                retvalue = 1;
                        }
                }
        }
        else
        {
                if(doc->state == TRIG_DOC_LINESTRING_OPENED)
                {
                        if(doc->file != NULL)
                        {
                                sprintf(string,"\r\n");
                                fputs_(string, doc->file);
                                Logged_TRIG_Counter++;
                                retvalue = 1;
                        }
                }
        }
        return(retvalue);
}

//________________________________________________________________________________________________________________________________________
// Function:    u8 TRIG_LoggGPSCoordinates(gps_data_t *, TRIG_Document_t *)
//
// Description: This function opens adds gpscoordinates to an KML-Document. The document will be opened, if not already done
//
//
// Returnvalue: '1' if an gps coordinate was logged
//________________________________________________________________________________________________________________________________________

u8 TRIG_LoggGPSCoordinates(TRIG_Document_t *doc)
{
        u8 retval = 0;
        while(doc->state != TRIG_DOC_LINESTRING_OPENED)                                 // automatic create document with default filename on the card.
        {
                switch(doc->state)
                {
                        case TRIG_DOC_CLOSED:                                                                   // document hasn't been opened yet therefore it will be initialized automatically
//                              retval = TRIG_DocumentOpen("default.kml",doc);  // open the kml-document with a standardname.
                        break;

                        case TRIG_DOC_OPENED:                                                                   // if a document has been opened before but no placemark exists:
                                retval = TRIG_PlaceMarkOpen(doc);
                        break;

                        case TRIG_DOC_PLACEMARK_OPENED:                                                 // add linestring to the placemark
                                retval = TRIG_LineStringBegin(doc);
                        break;

                        default:
                                retval = 0;
                        break;

                }
                if(retval != 1) return(retval); // stop on error
        }

        if(doc->state == TRIG_DOC_LINESTRING_OPENED)                                            // if the document was opened add coordinates to the document.
        {
                retval = TRIG_LineStringAddPoint(doc);
        }
        return(retval);
}



//----------------------------------------------------------------------------------------------------
s8* GenerateTriggLogFileName(void)
{
        static u16 filenum = 0; // file name counter
        static s8 filename[40];

        static DateTime_t LastTime = {0,0,0,0,0,0,0,0};
        if(filenum < GPX_Filenum) filenum = GPX_Filenum;
        if(SystemTime.Valid)
        {
                // if the day has been changed
                if((LastTime.Year != SystemTime.Year) || (LastTime.Month != SystemTime.Month) || (LastTime.Day != SystemTime.Day))
                {
                        LastTime.Year = SystemTime.Year;
                        LastTime.Month = SystemTime.Month;
                        LastTime.Day = SystemTime.Day;
                        LastTime.Valid = 1;
                        filenum = 0; // reset file counter
                }
        if(!(SimulationFlags & SIMULATION_ACTIVE))
        {
                if(filenum < 100) sprintf(filename, "/LOG/%04i%02i%02i/GPX/%02i%02i%02i%02i.TXT", SystemTime.Year, SystemTime.Month, SystemTime.Day, SystemTime.Year % 100, SystemTime.Month, SystemTime.Day, filenum);
                else sprintf(filename, "/LOG/%04i%02i%02i/GPX/GPS%05i.TXT", SystemTime.Year, SystemTime.Month, SystemTime.Day, filenum);
        }
        else
        {
                if(filenum < 100 && SystemTime.Year > 2000) sprintf(filename, "/SIMULATE/%04i%02i%02i/GPX/S%i%02i%02i%02i.TXT", SystemTime.Year, SystemTime.Month, SystemTime.Day, SystemTime.Year % 10, SystemTime.Month, SystemTime.Day, filenum);
                else sprintf(filename, "/SIMULATE/%04i%02i%02i/GPX/SIM%05i.TXT", SystemTime.Year, SystemTime.Month, SystemTime.Day, filenum);
        }
                TRIG_Filenum = filenum;
                filenum++;
                return filename;
        }
        else return NULL;
}



//----------------------------------------------------------------------------------------------------
// logs the current gps position to a csv file
logfilestate_t LoggingTrigger(u32 LogDelay)
{
        static  logfilestate_t logfilestate = LOGFILE_IDLE; // the current logfilestate
        static  s8* logfilename = NULL;                                         // the pointer to the logfilename
        static  u32 logtimer = 0, flushtimer = 0;               // the log update timer
        static  TRIG_Document_t logfile;                                        // the logfilehandle
        static  u32 appendtimer = 0;            // the log update timer
        static  u8 logging_active = 0;

        // initialize if LogDelay is zero
        if(!LogDelay)
        {
                switch(logfilestate)
                {
                        case LOGFILE_OPENED:
                                TRIG_DocumentClose(&logfile); // try to close it
                                break;
                        default:
                                break;
                }
                logfilestate = LOGFILE_IDLE;
                logfilename = NULL;
                TRIG_DocumentInit(&logfile);
                logtimer = SetDelay(0); // set logtimer to now
                return logfilestate;
        }
        // no init
        if(CheckDelay(logtimer) || (TrigLogging.NewData && logging_active))
        {
                logtimer = SetDelay(LogDelay);  // standard interval

                if(FC.StatusFlags & FC_STATUS_MOTOR_RUN)
                {
                        logging_active = 1;
                        appendtimer = SetDelay(APPEND_LOG_TIME_MS);
                }
                else
                {
                        if(CheckDelay(appendtimer)) logging_active = 0;
                }

                if(logging_active)
                {
                        switch(logfilestate)
                        {
                                case LOGFILE_IDLE:
                                case LOGFILE_CLOSED:
                                        if(GPX_logging_active == 2)       // start after GPX-Log
                                        {
                                                logfilestate = LOGFILE_START;
                                        }
                                        break;
                                case LOGFILE_START:
                                        // find unused logfile name
                                        do
                                        {        // try to generate a new logfile name
                                                 logfilename = GenerateTriggLogFileName();
                                        }while((logfilename != NULL) && fexist_(logfilename));
                                        // if logfilename exist
                                        if(logfilename != NULL)
                                        {
                                                // try to create the log file
                                                if(TRIG_DocumentOpen(logfilename, &logfile))
                                                {
                                                        flushtimer = SetDelay(LOG_FLUSH_INTERVAL);
                                                        logfilestate = LOGFILE_OPENED; // goto next step
                                                        UART1_PutString("\r\nOpening trigger-file:");
                                                        UART1_PutString(logfilename);
                                                        UART1_PutString("\r\n");
TrigLogging.NewData = 0;
TrigLogging.Count = 0;
TrigLogging.CountExternal = 0;
fflush_(logfile.file);
                                                }
                                                else // could not be openend
                                                {
                                                        logfilestate = LOGFILE_ERROR;
                                                        UART1_PutString("\r\nError opening trigger-file: ");
                                                        UART1_PutString(logfilename);
                                                        UART1_PutString("\r\n");
                                                        logtimer = SetDelay(10);  // try again in open logfile in 10 mili sec
                                                        SD_LoggingError = 1;
                                                }
                                        }
                                        else
                                        {
                                                logfilestate = LOGFILE_ERROR;
                                                UART1_PutString("\r\nError getting free trigger-file name\r\n");
                                                SD_LoggingError = 2;
                                        }
                                        // else retry in next loop
                                        break;
                                case LOGFILE_OPENED:
                                        // append new gps log data
if(TrigLogging.NewData)
 {
TrigLogging.NewData--;
                                        if((GPSData.Status != INVALID))// && (GPSData.Flags & FLAG_GPSFIXOK) && (GPSData.SatFix == SATFIX_3D))
                                        {
                                                if(!TRIG_LoggGPSCoordinates(&logfile))
                                                {       // error logging data
                                                        UART1_PutString("\r\nError logging to trigger-file\r\n");
                                                        SD_LoggingError = 3;
                                                        TRIG_DocumentClose(&logfile);
                                                        logfilestate = LOGFILE_ERROR;
                                                        TrigLogging.NewData = 0;
                                                }
                                                else // sucessfully logged
                                                {
                                                        SD_LoggingError = 0;
//                                                      if(CheckDelay(flushtimer))
                                                        {
//                                                              flushtimer = SetDelay(LOG_FLUSH_INTERVAL);
                                                                fflush_(logfile.file);
                                                        }
                                                }

                                        }
 }
                                        break;

                                case LOGFILE_ERROR:
                                        break;

                                default:
                                        logfilestate = LOGFILE_IDLE;
                                        break;
                        }
                } // EOF motors are not running
                else // model is not flying
                {   // close log file if opened
                        if(logfilestate == LOGFILE_OPENED)
                        {
                                if(TRIG_DocumentClose(&logfile))
                                {
                                        UART1_PutString("\r\nClosing trigger-file\r\n");
                                        logfilestate = LOGFILE_CLOSED;
                                }
                                else  // could not be closed
                                {
                                        UART1_PutString("\r\nError closing trigger-file\r\n");
                                        SD_LoggingError = 4;
                                        logfilestate =  LOGFILE_ERROR;
                                }
                        }
                        else
                        {
                          if(logfilestate == LOGFILE_ERROR) logfilestate = LOGFILE_IDLE;
                        }
                } //EOF motors are not running
        } // EOF Check LogTimer

        return logfilestate;
}