Subversion Repositories NaviCtrl

Rev

Rev 378 | Blame | Compare with Previous | 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 <string.h>
#include "91x_lib.h"
#include "config.h"
#include "main.h"
#include "uart1.h"
#include "mkprotocol.h"
#include "waypoints.h"
#include "gps.h"
#include "timer1.h"
#include "uart0.h"
#include "uart1.h"
#include "uart2.h"
#include "menu.h"
#include "usb.h"

#define ABO_TIMEOUT 4000 // disable abo after 4 seconds
u32 USB_AboTimeOut = 0;

u16 Echo; // 2 bytes recieved will be sent back as echo

// the primary rx fifo
#define USB_RX_FIFO_LEN 512
u8 USB_rxfifobuffer[USB_RX_FIFO_LEN];
fifo_t USB_rx_fifo;

// the tx buffer
#define USB_TX_BUFFER_LEN  150
u8 USB_tbuffer[USB_TX_BUFFER_LEN];
Buffer_t USB_tx_buffer;

// the rx buffer
#define USB_RX_BUFFER_LEN  150
u8 USB_rbuffer[USB_RX_BUFFER_LEN];
Buffer_t USB_rx_buffer;

u8 USB_Request_VersionInfo      = FALSE;
u8 USB_Request_SendFollowMe     = FALSE;
u8 USB_Request_ExternalControl= FALSE;
u8 USB_Request_Display          = FALSE;
u8 USB_Request_Display1         = FALSE;
u8 USB_Request_DebugData        = FALSE;
u8 USB_Request_DebugLabel       = 255;
u8 USB_Request_NaviData         = FALSE;
u8 USB_Request_ErrorMessage     = FALSE;
u8 USB_Request_Data3D           = FALSE;
u8 USB_Request_Echo                 = FALSE;
u8 USB_DisplayKeys = 0;
u8 USB_DisplayLine                      = 0;
u8 USB_ConfirmFrame = 0;

u32 USB_DebugData_Timer = 0;
u32 USB_DebugData_Interval = 0; // in ms
u32 USB_NaviData_Timer = 0;
u32 USB_NaviData_Interval = 0;  // in ms
u32 USB_Data3D_Timer = 0;
u32 USB_Data3D_Interval = 0;    // in ms
u32 USB_Display_Timer = 0;
u32 USB_Display_Interval = 0;   // in ms

//-----------------------------------------------------------------
void USB_ConfigInit(void)
{
        GPIO_InitTypeDef GPIO_InitStructure;

        UART1_PutString("\r\n USB init...");
        #ifdef MCLK96MHZ
        //USB clock = MCLK/2 = 48MHz
        SCU_USBCLKConfig(SCU_USBCLK_MCLK2);
        #else
        //USB clock = MCLK = 48MHz
        SCU_USBCLKConfig(SCU_USBCLK_MCLK);
        #endif
        //Enable USB clock
        SCU_AHBPeriphClockConfig(__USB,ENABLE);
        SCU_AHBPeriphReset(__USB,DISABLE);
        SCU_AHBPeriphClockConfig(__USB48M,ENABLE);

        //Configure GPIO0 (D+ Pull-Up on P0.1)
        SCU_APBPeriphClockConfig(__GPIO0 ,ENABLE);
        SCU_APBPeriphReset(__GPIO0,DISABLE);

        // GPIO_DeInit(P0.1);
        GPIO_StructInit(&GPIO_InitStructure);
        GPIO_InitStructure.GPIO_Direction = GPIO_PinOutput;
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
        GPIO_InitStructure.GPIO_Type = GPIO_Type_PushPull ;
        GPIO_InitStructure.GPIO_IPInputConnected = GPIO_IPInputConnected_Enable;
        GPIO_InitStructure.GPIO_Alternate=GPIO_OutputAlt1;
        GPIO_Init (GPIO0, &GPIO_InitStructure);

        // initialize the rx fifo, block UART IRQ geting a byte from fifo
        fifo_init(&USB_rx_fifo, USB_rxfifobuffer, USB_RX_FIFO_LEN, NO_ITLine, USBLP_ITLine);

        // initialize txd buffer
        Buffer_Init(&USB_tx_buffer, USB_tbuffer, USB_TX_BUFFER_LEN);

        // initialize rxd buffer
        Buffer_Init(&USB_rx_buffer, USB_rbuffer, USB_RX_BUFFER_LEN);

        VIC_Config(USBLP_ITLine, VIC_IRQ, PRIORITY_USB);
//##    VIC_ITCmd(USBLP_ITLine, ENABLE);

        USB_Init();

        UART1_PutString("ok");
}


/**************************************************************/
/* Process incomming data from debug uart                     */
/**************************************************************/
void USB_ProcessRxData(void)
{
        u8 c;
        SerialMsg_t SerialMsg;

        // if data in the rxd buffer are not locked immediately return
        // if rx buffer is not locked
        if(USB_rx_buffer.Locked == FALSE)
        {
                //collect data from primary rx fifo
                while(fifo_get(&USB_rx_fifo, &c))
                {
                        // break if complete frame has been collected
                        if(MKProtocol_CollectSerialFrame(&USB_rx_buffer, c)) break;
                }
        }
        if(USB_rx_buffer.Locked == FALSE) return;

        MKProtocol_DecodeSerialFrameHeader(&USB_rx_buffer, &SerialMsg); // decode serial frame in rxd buffer
        MKProtocol_DecodeSerialFrameData(&USB_rx_buffer, &SerialMsg); // decode serial frame in rxd buffer

    if(SerialMsg.CmdID != 'z') SerialLinkOkay = 250;      // reset SerialTimeout, but not in case of the "ping"
        switch(SerialMsg.Address) // check for Slave Address
        {
                case NC_ADDRESS:  // own Slave Address
                switch(SerialMsg.CmdID)
                {
                        case 'z': // connection checker
                                memcpy(&Echo, SerialMsg.pData, sizeof(Echo)); // copy echo pattern
                                USB_Request_Echo = TRUE;
                                break;

                        case 'e': // request for the text of the error status
                                USB_Request_ErrorMessage = TRUE;
                                break;

                        default:
                                // unsupported command recieved
                                break;
                } // case NC_ADDRESS
                // "break;" is missing here to fall thru to the common commands

                default:  // and any other Slave Address

                switch(SerialMsg.CmdID) // check CmdID
                {
                        case 'a':// request for the labels of the analog debug outputs
                                USB_Request_DebugLabel = SerialMsg.pData[0];
                                if(USB_Request_DebugLabel > 31) USB_Request_DebugLabel = 31;
                                break;
                        /*
                        case 'b': // submit extern control
                                memcpy(&ExternControl, SerialMsg.pData, sizeof(ExternControl));
                                USB_ConfirmFrame = ExternControl.Frame;
                                break;
                        */

                        case 'd': // request for debug data;
                                USB_DebugData_Interval = (u32) SerialMsg.pData[0] * 10;
                                if(USB_DebugData_Interval > 0) USB_Request_DebugData = TRUE;
                                USB_AboTimeOut = SetDelay(ABO_TIMEOUT);
                                break;

                        case 'c': // request for 3D data;
                                USB_Data3D_Interval = (u32) SerialMsg.pData[0] * 10;
                                if(USB_Data3D_Interval > 0) USB_Request_Data3D = TRUE;
                                USB_AboTimeOut = SetDelay(ABO_TIMEOUT);
                                break;

                        case 'h':// reqest for display line
                                if((SerialMsg.pData[0]& 0x80) == 0x00)// old format
                                {
                                        USB_DisplayLine = 2;
                                        USB_Display_Interval = 0;
                                }
                                else
                                {
                                        USB_DisplayKeys |= ~SerialMsg.pData[0];
                                        USB_Display_Interval = (u32) SerialMsg.pData[1] * 10;
                                        USB_DisplayLine = 4;
                                        USB_AboTimeOut = SetDelay(ABO_TIMEOUT);
                                }
                                USB_Request_Display = TRUE;
                                break;

                        case 'l':// reqest for display columns
                                MenuItem = SerialMsg.pData[0];
                                USB_Request_Display1 = TRUE;
                                break;

                        case 'o': // request for navigation information
                                USB_NaviData_Interval = (u32) SerialMsg.pData[0] * 10;
                                if(USB_NaviData_Interval > 0) USB_Request_NaviData = TRUE;
                                USB_AboTimeOut = SetDelay(ABO_TIMEOUT);
                                break;

                        case 'v': // request for version info
                                USB_Request_VersionInfo = TRUE;
                                break;
                        default:
                                // unsupported command recieved
                                break;
                }
                break; // default:
        }
        Buffer_Clear(&USB_rx_buffer);
}


//-----------------------------------------------------------------
void USB_CableConfig(FunctionalState NewState)
{
        if (NewState == ENABLE)
        GPIO_WriteBit(GPIO0, GPIO_Pin_1, Bit_RESET);
        else
        GPIO_WriteBit(GPIO0, GPIO_Pin_1, Bit_SET);
}
//-----------------------------------------------------------------
void USB_EnterLowPowerMode(void)
{
  /* Set the device state to suspend */
  bDeviceState = SUSPENDED;
}
//-----------------------------------------------------------------
void USB_LeaveLowPowerMode(void)
{
  DEVICE_INFO *pInfo = &Device_Info;

  /* Set the device state to the correct state */
  if (pInfo->Current_Configuration != 0)
  {
    /* Device configured */
    bDeviceState = CONFIGURED;
  }
  else
  {
    bDeviceState = ATTACHED;
  }
}


//-----------------------------------------------------------------
void USB_PutString(u8 *string)
{
        u8 i = 0;
        u16 timeout = 0;

        while (string[i++] != 0){} // get string len
        while (_GetEPTxStatus(ENDP1) != EP_TX_NAK){ if (timeout++ > 60000) return;}
        UserToPMABufferCopy(string, ENDP1_TXADDR, ++i); // copy string to usb buffer
        SetEPTxCount(ENDP1,i);
        SetEPTxValid(ENDP1);
}

//-----------------------------------------------------------------
void USB_PutChar(u8 c)
{
        u16 timeout = 0;
        while (_GetEPTxStatus(ENDP1) != EP_TX_NAK){ if (timeout++ > 60000) return;}
        UserToPMABufferCopy(&c, ENDP1_TXADDR, 2);
        SetEPTxCount(ENDP1,2);
        SetEPTxValid(ENDP1);
}

//-----------------------------------------------------------------
void USB_SendData(u8 *pdata, u16 count)
{
        u8 i;
        count++;
        u16 timeout = 0;

        for (i=0;i< (count/64)+1;i++)
        {
                while (_GetEPTxStatus(ENDP1) != EP_TX_NAK){if (timeout++ > 60000) return;}
                if (i < (count/64))
                {
                        UserToPMABufferCopy(&pdata[i*64], ENDP1_TXADDR, 64);
                        SetEPTxCount(ENDP1,64);
                }
                else
                {
                        UserToPMABufferCopy(&pdata[i*64], ENDP1_TXADDR, count % 64);
                        SetEPTxCount(ENDP1, count % 64);
                }
                SetEPTxValid(ENDP1);
        }
}

/**************************************************************/
/*         Transmit tx buffer via usb                         */
/**************************************************************/
void USB_Transmit(void)
{   // nur blockweises kopieren des sendebuffers, nicht alles mit einem mal
        // if something has to be send and the txd fifo is not full

        if(USB_tx_buffer.Locked == TRUE)
        {
                if(_GetEPTxStatus(ENDP1) == EP_TX_NAK)
                {
                        u16 i;
                        if(USB_tx_buffer.Position < USB_tx_buffer.DataBytes)
                        {
                                i = USB_tx_buffer.DataBytes - USB_tx_buffer.Position; // bytes to send
                                if(i > 64) i = 64; // limit packet size to 64 bytes
                                UserToPMABufferCopy(&(USB_tx_buffer.pData[USB_tx_buffer.Position]), ENDP1_TXADDR, i);
                                SetEPTxCount(ENDP1,i);
                                SetEPTxValid(ENDP1);
                        USB_tx_buffer.Position += i;
                        }
                }
                if(USB_tx_buffer.Position >= USB_tx_buffer.DataBytes) // all bytes transfered
                {
                        Buffer_Clear(&USB_tx_buffer); // clear buffer
                }
        }
}

/**************************************************************/
/* Send the answers to incomming commands at the debug uart   */
/**************************************************************/
void USB_TransmitTxData(void)
{
        USB_Transmit(); // output pending bytes in tx buffer
        if((USB_tx_buffer.Locked == TRUE)) return;

        if(CheckDelay(USB_AboTimeOut))
        {
                USB_DebugData_Interval = 0;
                USB_NaviData_Interval = 0;
                USB_Data3D_Interval = 0;
                USB_Display_Interval = 0;
        }

        if((USB_Request_DebugLabel != 0xFF) && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'A', NC_ADDRESS, 2, &USB_Request_DebugLabel, sizeof(USB_Request_DebugLabel), (u8 *) ANALOG_LABEL[USB_Request_DebugLabel], 16);
                USB_Request_DebugLabel = 0xFF;
        }
        else if(USB_ConfirmFrame && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'B', NC_ADDRESS, 1, &USB_ConfirmFrame, sizeof(USB_ConfirmFrame));
                USB_ConfirmFrame = 0;
        }
        else if( (( (USB_DebugData_Interval > 0) && CheckDelay(USB_DebugData_Timer)) || USB_Request_DebugData) && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'D', NC_ADDRESS, 1,(u8 *)&DebugOut, sizeof(DebugOut));
                USB_DebugData_Timer = SetDelay(USB_DebugData_Interval);
                USB_Request_DebugData = FALSE;
        }
        else if((( (USB_Data3D_Interval > 0) && CheckDelay(USB_Data3D_Timer) ) || USB_Request_Data3D) && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'C', NC_ADDRESS, 1,(u8 *)&Data3D, sizeof(Data3D));
                USB_Data3D_Timer = SetDelay(USB_Data3D_Interval);
                USB_Request_Data3D = FALSE;
        }
        else if(USB_Request_ExternalControl && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'G', NC_ADDRESS, 1, (u8 *)&ExternControl, sizeof(ExternControl));
                USB_Request_ExternalControl = FALSE;
        }
        else if( (( (USB_Display_Interval > 0) && CheckDelay(USB_Display_Timer)) || USB_Request_Display) && (USB_tx_buffer.Locked == FALSE))
        {
                Menu_Update(USB_DisplayKeys);
                USB_DisplayKeys = 0;
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'H', NC_ADDRESS, 1, (u8*)DisplayBuff, sizeof(DisplayBuff));
                USB_Request_Display = FALSE;
        }
        else if(USB_Request_Display1 && (USB_tx_buffer.Locked == FALSE))
        {
                Menu_Update(0);
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'L', NC_ADDRESS, 3, (u8*)&MenuItem, sizeof(MenuItem), (u8*)&MaxMenuItem, sizeof(MaxMenuItem),(u8*)DisplayBuff, sizeof(DisplayBuff));
                USB_Request_Display1 = FALSE;
        }
        else if(USB_Request_VersionInfo && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'V', NC_ADDRESS,1, (u8 *)&UART_VersionInfo, sizeof(UART_VersionInfo));
                USB_Request_VersionInfo = FALSE;
        }
        else if(( (USB_NaviData_Interval && CheckDelay(USB_NaviData_Timer) ) || USB_Request_NaviData) && (USB_tx_buffer.Locked == FALSE))
        {
                NaviData.Errorcode = ErrorCode;
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'O', NC_ADDRESS,1, (u8 *)&NaviData, sizeof(NaviData));
                USB_NaviData_Timer = SetDelay(USB_NaviData_Interval);
                USB_Request_NaviData = FALSE;
        }
        else if(USB_Request_ErrorMessage && (USB_tx_buffer.Locked == FALSE))
        {
                MKProtocol_CreateSerialFrame(&USB_tx_buffer, 'E', NC_ADDRESS, 1, (u8 *)&ErrorMSG, sizeof(ErrorMSG));
                USB_Request_ErrorMessage = FALSE;
        }
        USB_Transmit(); // output pending bytes in tx buffer
}