u32_t sys_arch_sem_wait(sys_sem_t sem, u32_t timeout)
{
    volatile UINT32* semaphore = (volatile UINT32*)sem;

    if(timeout != 0) 
    {
        INT64 now = ::HAL_Time_CurrentTime();
        INT64 elapsed = now + (timeout * 10000);
        
        while(elapsed > ::HAL_Time_CurrentTime()) 
        {
            if(IsSemaphoreGreen(semaphore)) 
            {
                AcquireSemaphore(semaphore); 
                break;
            }

            if(INTERRUPTS_ENABLED_STATE())
            {
                if(Events_WaitForEvents(SYSTEM_EVENT_FLAG_NETWORK, timeout))
                {
                    Events_Clear(SYSTEM_EVENT_FLAG_NETWORK);
                }
            }
            else
            {
                break;
            }
        }
    }
    else
    {
        while(1) 
        {
            // wait and call the continuation for tcpip_thread
            if(IsSemaphoreGreen(semaphore)) 
            {
                AcquireSemaphore(semaphore);
                break;
            }
            
            if(INTERRUPTS_ENABLED_STATE())
            {
                Events_WaitForEvents(SYSTEM_EVENT_FLAG_NETWORK, EVENTS_TIMEOUT_INFINITE);
                Events_Clear(SYSTEM_EVENT_FLAG_NETWORK);
            }
            else
            {
                break;
            }
        }
    }
    
    return *semaphore;
}
Ejemplo n.º 2
0
////////////////////////////////////////////////////////////////////////////////
// The WaitForTinyBooterUpload method was designed to allow porting kit partners
// to define how/when tinybooter mode is entered as well as configure default
// timeout values.  
//
// timeout_ms   - this parameter determines the time in milliseconds TinyBooter is
//                supposed to wait for commands from the host.  A -1 value will 
//                indicate to wait forever.
// return value - the boolean return value indicates whether TinyBooter should enter
//                upload mode.  If false is returned the booter will attempt to
//                launch the first application in FLASH that it finds.  If the return
//                value is true, TinyBooter will wait for the given timeout value
//                (parameter timeout_ms) for valid commands before launching the first
//                application
////////////////////////////////////////////////////////////////////////////////
bool WaitForTinyBooterUpload( INT32 &timeout_ms )
{
    bool enterBooterMode = false;
    GPIO_BUTTON_CONFIG *  ButtonConfig = &g_GPIO_BUTTON_Config;

// wait forever when using RAM build 
#if defined(TARGETLOCATION_RAM)
    enterBooterMode = true;
    timeout_ms = -1;
#endif

    // user override (UP+DOWN buttons held)
    if (ButtonConfig->Mapping[BUTTON_USER_IDX].m_HW != GPIO_PIN_NONE)
    {
        Events_WaitForEvents(0,100); // wait for buttons to init
        if(!CPU_GPIO_GetPinState( ButtonConfig->Mapping[BUTTON_USER_IDX].m_HW ))
        {
            // user override, so lets stay forever
            timeout_ms = -1;
            enterBooterMode = true;
        }
    }

    return enterBooterMode;
}
////////////////////////////////////////////////////////////////////////////////
// The WaitForTinyBooterUpload method was designed to allow porting kit partners
// to define how/when tinybooter mode is entered as well as configure default
// timeout values.  
//
// timeout_ms   - this parameter determines the time in milliseconds TinyBooter is
//                supposed to wait for commands from the host.  A -1 value will 
//                indicate to wait forever.
// return value - the boolean return value indicates whether TinyBooter should enter
//                upload mode.  If false is returned the booter will attempt to
//                launch the first application in FLASH that it finds.  If the return
//                value is true, TinyBooter will wait for the given timeout value
//                (parameter timeout_ms) for valid commands before launching the first
//                application
////////////////////////////////////////////////////////////////////////////////
bool WaitForTinyBooterUpload( INT32 &timeout_ms )
{
    bool enterBooterMode = false;
    GPIO_BUTTON_CONFIG *  ButtonConfig = &g_GPIO_BUTTON_Config;

// wait forever when using RAM build 
#if defined(TARGETLOCATION_RAM)
    enterBooterMode = true;
    timeout_ms = -1;
#endif

    // user override (UP+DOWN buttons held)
    if ((ButtonConfig->Mapping[BUTTON_ENTR_IDX].m_HW != GPIO_PIN_NONE))
    {
        Events_WaitForEvents(0,100); // wait for buttons to init

        if(!CPU_GPIO_GetPinState( ButtonConfig->Mapping[BUTTON_ENTR_IDX].m_HW))
        {
            UINT32 down, up;

            // user override, so lets stay for 2sec
            timeout_ms = 2000;
            enterBooterMode = true;

            while(Buttons_GetNextStateChange(down, up) && (0 != (down & BUTTON_ENTR)));
        }
    }

    return enterBooterMode;
}
Ejemplo n.º 4
0
void ApplicationEntryPoint()
{
    while(true)
    {
        hal_printf("Hello World!\n");

        Events_WaitForEvents(0, 3000);
    }
}
Ejemplo n.º 5
0
UINT32 Events_WaitForEventsInternal( UINT32 sleepLevel, UINT32 WakeupSystemEvents, UINT32 Timeout_Milliseconds )
{
    NATIVE_PROFILE_PAL_EVENTS();
    UINT32 events;

    // for internal HAL calls, we don't allow continuations
    SystemState_Set( SYSTEM_STATE_NO_CONTINUATIONS );

    events = Events_WaitForEvents( sleepLevel, WakeupSystemEvents, Timeout_Milliseconds );    // no indirection, we already have one here

    SystemState_Clear( SYSTEM_STATE_NO_CONTINUATIONS );   // nestable

    return events;
}
Ejemplo n.º 6
0
int DebuggerPort_Write( COM_HANDLE ComPortNum, const char* Data, size_t size )
{
    NATIVE_PROFILE_PAL_COM();
    
    UINT32       transport = ExtractTransport(ComPortNum);
    const char*  dataTmp   = Data;
    INT32        totWrite  = 0;
    int          retries   = 100;

    while(size > 0 && retries--)
    {
        int ret = 0;
        
        switch(transport)
        {
            case USART_TRANSPORT:
                ret = USART_Write( ConvertCOM_ComPort( ComPortNum ), dataTmp, size );
                break;
            case USB_TRANSPORT:
                ret = USB_Write( ConvertCOM_UsbStream( ComPortNum ), dataTmp, size );
                break;
            case SOCKET_TRANSPORT:
                ret = SOCKETS_Write( ConvertCOM_SockPort(ComPortNum), dataTmp, size );
                break;
        }
        if(ret < 0)
        {
            break;
        }
        else if(ret == 0)
        {
            // if interrupts are off and our buffer is full then there is nothing we can do
            if(!INTERRUPTS_ENABLED_STATE()) break;

            Events_WaitForEvents(0, 1);
        }
        else
        {
            retries   = 50;   // reset retries
            size     -= ret;
            dataTmp  += ret;
            totWrite += ret;
        }
    }

    return totWrite;
}
BOOL EnterMicroBooter(INT32& timeout)
{
    CPU_GPIO_Initialize();
    
    Events_WaitForEvents(0,100); // wait for buttons to init

    // check up/down button state
    if(!CPU_GPIO_GetPinState( MC9328MXL_GPIO::c_Port_B_10 ) && !CPU_GPIO_GetPinState( MC9328MXL_GPIO::c_Port_B_11 ))
    {
        // user override, so lets stay forever
        timeout = -1;
        return TRUE;
    }
    
    timeout = 0;
    return FALSE;
}
Ejemplo n.º 8
0
BOOL EnterMicroBooter(INT32& timeout)
{
    CPU_GPIO_Initialize();
    
    Events_WaitForEvents(0,100); // wait for buttons to init

    // check up/down button state
    if(!CPU_GPIO_GetPinState( AT91_GPIO_Driver::PA25 ) && !CPU_GPIO_GetPinState( AT91_GPIO_Driver::PA27 ))
    {
        // user override, so lets stay forever
        timeout = -1;
        return TRUE;
    }
    
    timeout = 0;
    return FALSE;
}
Ejemplo n.º 9
0
BOOL TEvents::TEvents_1()
{
   UINT32         count = 100;
   UINT32         signaled;
   HAL_COMPLETION compObj;


   compObj.InitializeForISR(CompletionCallback, NULL);

    while (count--)
    {
        compObj.EnqueueDelta(1000*2);
        signaled = Events_WaitForEvents(s_event,50);

        if (signaled != s_event)
        {
            return false; 
        }
    }


    return true; 
}
Ejemplo n.º 10
0
void ApplicationEntryPoint()
{
    char Data[1], previousChar = '\0';
    int ret = 0, TestItem = 0;
    BOOL validCommand = TRUE;
	
	MEMORY_MAPPED_NOR_BLOCK_CONFIG* config;
	
//    BlockStorageDevice *device;
//    ByteAddress datByteAddress;

//    BlockStorageList::FindDeviceForPhysicalAddress( &device, 0, datByteAddress );
//    const BlockDeviceInfo * deviceInfo=device->GetDeviceInfo();


    
    Data[1] = '\0';
    char ip[15];
    int length;
    unsigned long dest_ip=0;
    UINT32 sleep = 100;

//    TimedEvents eventsTest;
 //   UART        usartTest  ( COMTestPort, 9600, USART_PARITY_NONE, 8, USART_STOP_BITS_ONE, USART_FLOW_NONE );
//    GPIO        gpioTest   ( GPIOTestPin );

    do
    {
        lcd_printf( "\n\n\n\n\n\n\n\n   SH7619 EVB\n" );
        lcd_printf( " Renesas America       Inc." );
                
        //Serial TEST
        hal_printf( "\r\nSH7619 EVB .NET Micro Framework NativeSample\r\n" );
        hal_printf( "Renesas Electronics America Inc.\r\n" );
        hal_printf( "61 MHz Clk,Big-endian\r\n" );      
        hal_printf( ">" );
        
        NATIVE_PROFILE_PAL_EVENTS();
        do
        {
            UINT32 Events = Events_WaitForEvents( SYSTEM_EVENT_FLAG_COM_IN | SYSTEM_EVENT_FLAG_ETHER, sleep );

            // if(Events == 0)
            // {
                // hal_printf("Slept %d sec\r\n", sleep / 1000);
                // sleep += 1000; 
                // continue;
            // }
            
            if(Events & SYSTEM_EVENT_FLAG_ETHER)            
            {
                //Network_Interface_Process_Packet();
				//hal_printf("ETHER event\r\n");
                Events_Clear( SYSTEM_EVENT_FLAG_ETHER );
            }
                        
            if(Events & SYSTEM_EVENT_FLAG_COM_IN)           
            {
                Events_Clear( SYSTEM_EVENT_FLAG_COM_IN );
                while((ret = DebuggerPort_Read( HalSystemConfig.DebugTextPort, Data, 1 )) > 0)
                {                   
                    switch(TestItem)
                    {
                        case 0:     //None
                            if(Data[0] == 0xD)              //0xD: ENTER key
                            {                               
                                hal_printf( "\r\n" );
                                if(validCommand)
                                {
                                    TestItem = 1;           //Enter test
                                    validCommand = FALSE;
                                    previousChar = '\0';
                                    hal_printf( "\r\nTest Menu:\r\n" );
                                    hal_printf( "   [L]CD Tests\r\n" );
                                    hal_printf( "   [K]eypad Tests\r\n" );
                                    hal_printf( "   [N]etwork Tests\r\n" );
                                    hal_printf( "   [F]lash memory Tests\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                }
                                else if(previousChar == 'I')
                                {
                                    hal_printf("** Invalid Selection\r\n>");
                                    previousChar = '\0';
                                }
                                else
                                    hal_printf( ">" );
                            }
                            else
                            {
                                hal_printf( Data );
                                if(Data[0] == 'd' || Data[0] == 'D')
                                {
                                    if(previousChar == '\0')
                                        previousChar = 'd';
                                    else
                                    {
                                        validCommand = FALSE;
                                        previousChar = 'I';     //Invalid character input
                                    }
                                }
                                else if(Data[0] == 't' || Data[0] == 'T')
                                {
                                    if(previousChar == 'd')
                                    {
                                        previousChar = 't';
                                        validCommand = TRUE;
                                    }
                                    else
                                    {
                                        validCommand = FALSE;
                                        previousChar = 'I';     //Invalid character input
                                    }
                                }
                                else
                                {
                                    validCommand = FALSE;
                                    previousChar = 'I';         //Invalid character input
                                }
                            }
                            break;
                        case 1:     //Enter test
                            hal_printf( Data );
                            switch(Data[0])
                            {
                                case 'X':
                                case 'x':
                                    TestItem = 0;
                                    hal_printf( "\r\n\n>" );
                                    break;
                                case 'L':
                                case 'l':
                                    TestItem = 5;
                                    hal_printf( "\r\n\nLCD Menu:\r\n" );
                                    hal_printf( "   1: Display colorful rectangles\r\n" );
                                    hal_printf( "   2: Colorful wireframe rectangle\r\n" );
                                    hal_printf( "   3: Colorful solid rectangle\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case 'K':
                                case 'k':
                                    KeyPad_Test();                                  
                                    break;
                                case 'N':
                                case 'n':
                                    TestItem = 7;
                                    hal_printf( "\r\n\nEthernet Menu:\r\n" );
                                    hal_printf( "   [1]Read IP Address\r\n" );
                                    hal_printf( "   [2]Read EtherC Registers\r\n" );
                                    hal_printf( "   [3]Read E-DMAC Registers\r\n" );
                                    hal_printf( "   [4]Ping Test\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;                              
                                case 'F':
                                case 'f':
                                    TestItem = 8;
                                    hal_printf( "\r\n\nFlash memory Menu:\r\n" );
                                    hal_printf( "   [1]Erase block\r\n" );
                                    hal_printf( "   [2]write block\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;                              
                                default:
                                    hal_printf( "\r\n\nTest Menu:\r\n" );
                                    hal_printf( "   [L]CD Tests\r\n" );
                                    hal_printf( "   [K]eypad Tests\r\n" );
                                    hal_printf( "   [N]etwork Tests\r\n" );
                                    hal_printf( "   [F]lash memory Tests\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                            }
                            break;
                        case 5:     //LCD test
                            hal_printf( Data );
                            switch(Data[0])
                            {
                                case 'X':
                                case 'x':
                                    TestItem = 1;
                                    hal_printf( "\r\n\nTest Menu:\r\n" );
                                    hal_printf( "   [L]CD Tests\r\n" );
                                    hal_printf( "   [K]eypad Tests\r\n" );
                                    hal_printf( "   [N]etwork Tests\r\n" );
                                    hal_printf( "   [F]lash memory Tests\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '1':
                                    LCDTest_Driver::LCD_Sample1();
                                    hal_printf( "\r\n\nLCD Menu:\r\n" );
                                    hal_printf( "   1: Display colorful rectangles\r\n" );
                                    hal_printf( "   2: Colorful wireframe rectangle\r\n" );
                                    hal_printf( "   3: Colorful solid rectangle\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '2':
                                    LCDTest_Driver::LCD_Sample2(0);
                                    hal_printf( "\r\n\nLCD Menu:\r\n" );
                                    hal_printf( "   1: Display colorful rectangles\r\n" );
                                    hal_printf( "   2: Colorful wireframe rectangle\r\n" );
                                    hal_printf( "   3: Colorful solid rectangle\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '3':
                                    LCDTest_Driver::LCD_Sample2(1);
                                    hal_printf( "\r\n\nLCD Menu:\r\n" );
                                    hal_printf( "   1: Display colorful rectangles\r\n" );
                                    hal_printf( "   2: Colorful wireframe rectangle\r\n" );
                                    hal_printf( "   3: Colorful solid rectangle\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                default:
                                    hal_printf( "\r\n\nLCD Menu:\r\n" );
                                    hal_printf( "   1: Display colorful rectangles\r\n" );
                                    hal_printf( "   2: Colorful wireframe rectangle\r\n" );
                                    hal_printf( "   3: Colorful solid rectangle\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                            }
                            break;
                        case 7:     //Ethernet test
                            hal_printf( Data );
                            hal_printf( "\r\n" );
                            switch(Data[0])
                            {
                                case 'X':
                                case 'x':
                                    TestItem = 1;
                                    hal_printf( "\r\n\nTest Menu:\r\n" );
                                    hal_printf( "   [L]CD Tests\r\n" );
                                    hal_printf( "   [K]eypad Tests\r\n" );
                                    hal_printf( "   [N]etwork Tests\r\n" );
                                    hal_printf( "   [F]lash memory Tests\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '1':
                                    //Network_Interface_IP_Address();                                 
                                    hal_printf( "\r\n\nEthernet Menu:\r\n" );
                                    hal_printf( "   [1]Read IP Address\r\n" );
                                    hal_printf( "   [2]Read EtherC Registers\r\n" );
                                    hal_printf( "   [3]Read E-DMAC Registers\r\n" );
                                    hal_printf( "   [4]Ping Test\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '2':
                                    //Network_Interface_EtherC_Registers();
                                    hal_printf( "\r\n\nEthernet Menu:\r\n" );
                                    hal_printf( "   [1]Read IP Address\r\n" );
                                    hal_printf( "   [2]Read EtherC Registers\r\n" );
                                    hal_printf( "   [3]Read E-DMAC Registers\r\n" );
                                    hal_printf( "   [4]Ping Test\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '3':
                                    //Network_Interface_EDMAC_Registers();
                                    hal_printf( "\r\n\nEthernet Menu:\r\n" );
                                    hal_printf( "   [1]Read IP Address\r\n" );
                                    hal_printf( "   [2]Read EtherC Registers\r\n" );
                                    hal_printf( "   [3]Read E-DMAC Registers\r\n" );
                                    hal_printf( "   [4]Ping Test\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;                              
                                case '4':
                                    //do
                                    //{
                                    //    hal_printf( "\r\nEnter dest IP: " );
                                    //    Get_IP_String(ip, &length);
                                    //    if( (dest_ip = Is_IP_Address(ip, length)) == 0)
                                    //        hal_printf( "\r\n*** Invalid IP Address!\r\n" );
                                    //}while(dest_ip == 0);
                                    //Ether_Ping(dest_ip, 4); 
                                    hal_printf( "\r\n\nEthernet Menu:\r\n" );
                                    hal_printf( "   [1]Read IP Address\r\n" );
                                    hal_printf( "   [2]Read EtherC Registers\r\n" );
                                    hal_printf( "   [3]Read E-DMAC Registers\r\n" );
                                    hal_printf( "   [4]Ping Test\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;                          
                                default:
                                    hal_printf( "\r\n\nEthernet Menu:\r\n" );
                                    hal_printf( "   [1]Read IP Address\r\n" );
                                    hal_printf( "   [2]Read EtherC Registers\r\n" );
                                    hal_printf( "   [3]Read E-DMAC Registers\r\n" );
                                    hal_printf( "   [4]Ping Test\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                            }
                            break;
                        case 8:     //Flash memory test
                            hal_printf( Data );
                            hal_printf( "\r\n" );
                            switch(Data[0])
                            {
                                case 'X':
                                case 'x':
                                    TestItem = 1;
                                    hal_printf( "\r\n\nTest Menu:\r\n" );
                                    hal_printf( "   [L]CD Tests\r\n" );
                                    hal_printf( "   [K]eypad Tests\r\n" );
                                    hal_printf( "   [N]etwork Tests\r\n" );
                                    hal_printf( "   [F]lash memory Tests\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '1':
									g_AM29DL_16_BS_DeviceTable.InitializeDevice(pBLOCK_CONFIG);
									g_AM29DL_16_BS_DeviceTable.EraseBlock(pBLOCK_CONFIG,0xa0080000);
                                    hal_printf( "\r\n\nFlash memory Menu:\r\n" );
                                    hal_printf( "   [1]Erase block\r\n" );
                                    hal_printf( "   [2]write block\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                case '2':
									BYTE Buff[0x10];
									for(int i=0; i<0x10; i++) Buff[i]=i;
									g_AM29DL_16_BS_DeviceTable.InitializeDevice(pBLOCK_CONFIG);
									g_AM29DL_16_BS_DeviceTable.Write(pBLOCK_CONFIG,0xa0080000,0x10,Buff,0x0);
                                    hal_printf( "\r\n\nFlash memory Menu:\r\n" );
                                    hal_printf( "   [1]Erase block\r\n" );
                                    hal_printf( "   [2]write block\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                                default:
                                    hal_printf( "\r\n\nFlash memory Menu:\r\n" );
                                    hal_printf( "   [1]Erase block\r\n" );
                                    hal_printf( "   [2]write block\r\n" );
                                    hal_printf( "   E[x]it\r\n" );
                                    hal_printf( "Your choice: " );
                                    break;
                            }
                            break;
                    }
                }
            }           
        } while(TRUE);
    } while(FALSE); // run only once!
}
Ejemplo n.º 11
0
void ApplicationEntryPoint()
{
    UINT32 ComEvent;

    g_State.Initialize();

    ComEvent = 0;
    if(COM_IsSerial(g_State.UsartPort) && (g_State.UsartPort != COM_NULL))
    {
        ComEvent = SYSTEM_EVENT_FLAG_COM_IN;
    }

#if !defined(TARGETLOCATION_RAM)
    g_State.WaitForActivity = (g_State.ProgramCount != 0); // is there a main app?

#else
    g_State.WaitForActivity = FALSE;      // forever
#endif

    {
        UINT32 ButtonsPressed;
        UINT32 ButtonsReleased;
        char   c;

        // clear any events present from startup
        while(Events_Get( SYSTEM_EVENT_FLAG_ALL ));

        // clear any junk from com port buffers
        while(DebuggerPort_Read( g_State.UsartPort, &c, sizeof(c) ));

        // clear any junk from button buffer
        while(Buttons_GetNextStateChange( ButtonsPressed, ButtonsReleased ));
    }

    {
        BOOL       ProcessingSREC     = FALSE;
        BOOL       ProcessingXREC     = FALSE;
        INT32      ProcessingZENFLASH = 0;
        INT32      Mode               = 0;
        INT32      MenuChoice         = 1;      // main application location when USB not enabled
        BOOL       MenuUpdate         = TRUE;
        UINT32     USBEvent           = 0;
        COM_HANDLE ReadPort           = COM_NULL;
        int        MenuOffset         = 1;      // no USB enabled
        INT64      WaitTimeout        = 0;

#if defined(PLATFORM_ARM_MOTE2)
        CPU_GPIO_SetPinState( LED1_GREEN, LED_ON );
#endif

        if(g_State.WaitForActivity)
        {
            WaitTimeout = HAL_Time_CurrentTime() + (INT64)g_State.WaitInterval * (10 * 1000);

            hal_printf( "Waiting %d.%03d second(s) for hex upload\r\n", g_State.WaitInterval / 1000, g_State.WaitInterval % 1000 );
        }
        else
        {
            hal_printf( "Waiting forever for hex upload\r\n" );
        }

        // checking the existence of Usb Driver, all the default values are set to no USB
        if( USB_DEVICE_STATE_NO_CONTROLLER != USB_GetStatus( ConvertCOM_UsbController(g_State.UsbPort) ) )
        {
            g_State.UsingUsb = TRUE;

            MenuChoice = 2;
            MenuOffset = 2;
        }


        while(true)
        {
            if(MenuUpdate)
            {
                MenuUpdate = FALSE;

                LCD_Clear();
                hal_fprintf( STREAM_LCD, "\f");

                switch(Mode)
                {
                case 0:
                    hal_fprintf( STREAM_LCD, "   Zen Boot\r\n\r\n" );

                    hal_fprintf( STREAM_LCD, "%c PortBooter\r\n", MenuChoice == 0 ? '*' : ' ' );

                    if(g_State.UsingUsb)
                    {
                        hal_fprintf( STREAM_LCD, "%c FlashUSB\r\n", MenuChoice == 1 ? '*' : ' ' );
                    }


                    for(int i = 0; i < g_State.ProgramCount; i++)
                    {
                        hal_fprintf( STREAM_LCD, "%c Prg:%08x\r\n", (i+MenuOffset) == MenuChoice ? '*' : ' ', g_State.Programs[i] );
                    }
                    break;

                case 1:
                    hal_printf( "PortBooter v%d.%d.%d.%d\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION);
                    hal_fprintf( STREAM_LCD, "Waiting forever for hex upload\r\n"         );
                    break;

                case 2:
                    hal_fprintf( STREAM_LCD, "FlashUSB\r\n"                       );
                    hal_fprintf( STREAM_LCD, "Waiting forever for hex upload\r\n" );
                    break;
                }
            }

            UINT32 Events = Events_WaitForEvents( ComEvent | SYSTEM_EVENT_FLAG_BUTTON | SYSTEM_EVENT_FLAG_USB_IN, 2000 );

            if(Events & SYSTEM_EVENT_FLAG_BUTTON)
            {
                UINT32 ButtonsPressed;
                UINT32 ButtonsReleased;

                Events_Clear( SYSTEM_EVENT_FLAG_BUTTON );

                while(Buttons_GetNextStateChange( ButtonsPressed, ButtonsReleased ));
                {
                    if(g_State.SerialPortActive == FALSE)
                    {
                        //printf("%02x %02x\r\n", ButtonsPressed, ButtonsReleased);

                        // up
                        if(ButtonsPressed & BUTTON_UP)
                        {
                            switch(Mode)
                            {
                            case 0:
                                MenuChoice = __max( MenuChoice-1, 0 );
                                break;
                            }

                            g_State.WaitForActivity = FALSE;
                            MenuUpdate              = TRUE;
                        }

                        // down
                        if(ButtonsPressed & BUTTON_DOWN)
                        {
                            switch(Mode)
                            {
                            case 0:
                                MenuChoice = __min( MenuChoice+1, g_State.ProgramCount + MenuOffset-1 );
                                break;
                            }

                            g_State.WaitForActivity = FALSE;
                            MenuUpdate              = TRUE;
                        }

                        // enter button
                        if(ButtonsPressed & BUTTON_ENTR)
                        {
                            switch(Mode)
                            {
                            case 0:
                                if(MenuChoice == 0)
                                {
                                    Mode = 1;

                                    //UsingUsb = FALSE;
                                }
                                else if(g_State.UsingUsb && MenuChoice == 1)
                                {
                                    Mode = 2;
                                    USB_Configure( ConvertCOM_UsbController(g_State.UsbPort), &UsbDefaultConfiguration );
                                    USB_Initialize( ConvertCOM_UsbController(g_State.UsbPort) );
                                    USB_OpenStream( ConvertCOM_UsbStream(g_State.UsbPort), USB_DEBUG_EP_WRITE, USB_DEBUG_EP_READ );
                                    //UsingUsb = TRUE;
                                }
                                else
                                {
                                    StartApplication( (void (*)())g_State.Programs[MenuChoice-MenuOffset] );
                                }
                                break;

                            case 1:
                                Mode = 0;
                                break;

                            case 2:
                                // USB_Uninitialize();
                                Mode = 0;
                                break;
                            }

                            g_State.WaitForActivity = FALSE;
                            MenuUpdate              = TRUE;
                        }

                        if(ButtonsReleased)
                        {
                            MenuUpdate = TRUE;
                        }
                    }
                }
            }

            if((Events & ComEvent) || (Events & SYSTEM_EVENT_FLAG_USB_IN))
            {
                char c;

                if(Events & ComEvent)
                {
                    Events_Clear( ComEvent );

                    ReadPort              = g_State.UsartPort;
                    g_State.pStreamOutput = ReadPort;
                }
                else
                {
                    USBEvent = USB_GetEvent( ConvertCOM_UsbController(g_State.UsbPort), USB_EVENT_ALL );
                    if( !(USBEvent & g_State.UsbEventCode) )
                        continue;

                    g_State.pStreamOutput = g_State.UsbPort;
                    ReadPort              = g_State.UsbPort;
                }

                while(DebuggerPort_Read( ReadPort, &c, sizeof(c) ))
                {
                    if(ProcessingSREC)
                    {
                        ProcessingSREC = g_SREC.Process( c );
                    }
                    else if(ProcessingXREC)
                    {
                        ProcessingXREC = g_XREC.Process( c );
                    }
                    else if(ProcessingZENFLASH)
                    {
                        const char Signature[] = "ZENFLASH\r";

                        //printf( "Got %d at %d\r\n", c, ProcessingZENFLASH );
                        if(Signature[ProcessingZENFLASH++] == c)
                        {
                            if(Signature[ProcessingZENFLASH] == 0)
                            {
                                SignalActivity();
                                ProcessingZENFLASH = 0;
                            }
                        }
                        else
                        {
                            ProcessingZENFLASH = 0;
                        }
                    }
                    else if('S' == c)
                    {
                        ProcessingSREC = TRUE;
                    }
                    else if('X' == c)
                    {
                        ProcessingXREC = TRUE;
                    }
                    else if('Z' == c)
                    {
                        ProcessingZENFLASH = 1;
                    }
                }
            }

            if(g_State.WaitForActivity && WaitTimeout < HAL_Time_CurrentTime())
            {
#if defined(PLATFORM_ARM_MOTE2)
                CPU_GPIO_SetPinState(LED1_GREEN, LED_OFF);        // Turn off Green LED for iMOTE2
#endif
                // we didn't see anything on serial port for wait interval (2 seconds nominally),
                // continue with code - just run the normal application
                StartApplication( (void (*)())g_State.Programs[0] );
            }

        }
    }
}
Ejemplo n.º 12
0
    void Initialize()
    {
#if defined(PLATFORM_ARM_MOTE2)
        if (COM_IsUsb(HalSystemConfig.DebugTextPort))
            WaitInterval = 5000;        // The USB port must be selected and the Start button pressed all during this time
        else
            WaitInterval = 2000;        // The USART port may be selected before powering on the Imote2, so it takes less time
#else
        WaitInterval     = 2000;
#endif

        SerialPortActive = FALSE;

        UsartPort        = USART_DEFAULT_PORT;

        UsingUsb         = FALSE;
        UsbPort          = USB1;
        UsbEventCode     = USB_DEBUG_EVENT_IN;

        //--//

        // wait an extra second for buttons and COM port to stabilize
        Events_WaitForEvents( 0, 1000 );

        // COM init is now delayed for TinyBootloader, so we need to initialize it here
        CPU_InitializeCommunication();

        //--//

        // set default baud rate
        if(UsartPort != DEBUG_TEXT_PORT)
        {
            DebuggerPort_Initialize( UsartPort );
        }
        // extra time to allow USB setup, so that we can see the printf
        Events_WaitForEvents( 0, 1000 );


        hal_printf( "PortBooter v%d.%d.%d.%d\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION);
        hal_printf( "Build Date: %s %s\r\n",  __DATE__, __TIME__);

#if defined(__GNUC__)
        hal_printf( "GNU Compiler version %d\r\n", __GNUC__);
#elif defined(__ADSPBLACKFIN__)
        hal_printf( "Blackfin Compiler version %d\r\n", __VERSIONNUM__ );
#else
        hal_printf( "ARM Compiler version %d\r\n", __ARMCC_VERSION);
#endif
       
        //--//

        BlockStorageStream stream;
        FLASH_WORD ProgramWordCheck;

        if(!stream.Initialize(BlockUsage::CODE)) return;



        do
        {
            do
            {
            
                UINT32 addr = stream.CurrentAddress();
    			FLASH_WORD *pWord = &ProgramWordCheck;

                stream.Read( (BYTE**)&pWord, sizeof(FLASH_WORD) );

                if(*pWord == PROGRAM_WORD_CHECK)
                {
                    hal_printf("*** nXIP Program found at 0x%08x\r\n", addr );
    				Programs[ProgramCount++] = (UINT32)addr;
                }

                if(ProgramCount == MAX_PROGRAMS) break;
            }
            while( stream.Seek( BlockStorageStream::STREAM_SEEK_NEXT_BLOCK, BlockStorageStream::SeekCurrent ) );

        } while(stream.NextStream());

    }
Ejemplo n.º 13
0
RTP_BOOL SH7619_EDMAC_open(PIFACE pi)   
{
	PSH7619_EDMAC_SOFTC sc = iface_to_softc(pi);
    char c[1],Buffer[17];
	int i;
    UINT32 Events;
	BYTE Buff[6];

	if (!sc)
	{
		RTP_DEBUG_ERROR("SH7619_EDMAC_open: softc invalid!\r\n", NOVAR, 0, 0);
		set_errno(ENUMDEVICE);
		return(RTP_FALSE);
	}

	// Set Interface
	sc->iface = pi;
	iface = pi;

	int macLen = __min(g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressLen, sizeof(sc->mac_address));

	if(macLen > 0)
	{

	    int addr = MAC_address_area;
		for(i=0; i<macLen; i++) g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[i] = *(volatile char *)(addr+i);
	
        debug_printf( "MAC Address: %x.%x.%x.%x.%x.%x\r\n", (UINT8)g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[0], 
                                                             (UINT8)g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[1],
                                                             (UINT8)g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[2],
                                                             (UINT8)g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[3],
                                                             (UINT8)g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[4],
                                                             (UINT8)g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[5]);
	    debug_printf( "Do you need to change MAC Address? If yes, press 'Enter' key\r\n" );
		c[0] = 0x0;
    	for (i=0; i<0xff; i++){
			DebuggerPort_Read( HalSystemConfig.DebugTextPort, c, 1);
			if (c[0] == 0x0d){
			    hal_printf( "new MAC Address :" );
				while(c[0] == 0x0d) DebuggerPort_Read( HalSystemConfig.DebugTextPort, c, 1);
				for(i=0; i<17; ){
		            Events = Events_WaitForEvents( SYSTEM_EVENT_FLAG_COM_IN, 100 );
		            if(Events & SYSTEM_EVENT_FLAG_COM_IN){
						Events_Clear( SYSTEM_EVENT_FLAG_COM_IN );
						DebuggerPort_Read( HalSystemConfig.DebugTextPort, c, 1);
						Buffer[i] = c[0];
						i++;
					}
				}
				for (i=0; i<17; i++) hal_printf( "%c",Buffer[i] );
				hal_printf( "\r\n");

				for(i=0; i<macLen; i++) {
					Buff[i]=SH7619_EDMAC_AtoH(Buffer[i*3])*0x10;
					Buff[i]+=SH7619_EDMAC_AtoH(Buffer[i*3+1]);
				}

				for(i=0; i<macLen; i++) {
					g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[i]=Buff[i];
				}


				debug_printf( "Updating...\r\n" );
				g_AM29DL_16_BS_DeviceTable.InitializeDevice(pBLOCK_CONFIG);
				g_AM29DL_16_BS_DeviceTable.EraseBlock(pBLOCK_CONFIG,MAC_address_area);
				g_AM29DL_16_BS_DeviceTable.Write(pBLOCK_CONFIG,MAC_address_area,macLen,Buff,0x0);
				debug_printf( "Done\r\n" );

				i=0x100;
			}
		}
		memcpy(&sc->mac_address[0], &g_NetworkConfig.NetworkInterfaces[NETWORK_INTERFACE_INDEX_SH7619EMAC].macAddressBuffer[0], macLen);
	}
	else
	{
		RTP_DEBUG_ERROR("Device initialize without MAC address!!!\r\n", NOVAR, 0, 0);
}
    
	/* Now put in a dummy ethernet address */
	rtp_memcpy(&pi->addr.my_hw_addr[0], sc->mac_address, 6); // Get the ethernet address
    
	/* clear statistic information */
	sc->stats.packets_in     = 0L;
	sc->stats.packets_out    = 0L;
	sc->stats.bytes_in       = 0L;
	sc->stats.bytes_out      = 0L;
	sc->stats.errors_in      = 0L;
	sc->stats.errors_out     = 0L;    

	if(RTP_FALSE == SH7619_EDMAC_SetupDevice())
	{
		return RTP_FALSE;
	}
    
	rtp_irq_hook_interrupt( (RTP_PFVOID) pi, 
							(RTP_IRQ_FN_POINTER)SH7619_EDMAC_recv, 
							(RTP_IRQ_FN_POINTER) 0);

	return(RTP_TRUE);
}
Ejemplo n.º 14
0
void Test_OpenSSL_ClientServerAuth()
{
    LCD_Clear();
    lcd_printf("Testing SSL Client/Server negotiations...\n");
	int err;
	int client_numbytes, server_numbytes;
	int listen_sd;
	int server_sd;
	int client_sd;
	struct TINYCLR_SSL_SOCKADDR_IN sa_serv;
	struct TINYCLR_SSL_SOCKADDR_IN sa_cli;
	size_t client_len;
	SSL_CTX* server_ctx = NULL;
	SSL*     server_ssl = NULL;
	X509*    server_cert = NULL;
	SSL_CTX* client_ctx = NULL;
	SSL*     client_ssl = NULL;
	X509*    client_cert = NULL;
	char*    str = NULL;
	char     client_buf [256];
	char	 server_buf [256];
	SSL_METHOD *server_meth = NULL;
	SSL_METHOD *client_meth = NULL;
	BIO *cert = NULL;
	X509 *x = NULL;
	EVP_PKEY *pkey = NULL;

	// SSL preliminaries. 
	// create client ssl
	client_meth = (SSL_METHOD*)SSLv3_client_method();
	client_ctx = SSL_CTX_new (client_meth);
	if (!client_ctx) goto cleanup;

	server_meth = (SSL_METHOD*)SSLv3_server_method();
	server_ctx = SSL_CTX_new (server_meth);
	if (!server_ctx) goto cleanup;

	
	if ((cert=BIO_new(BIO_s_mem())) == NULL)
	{
		TINYCLR_SSL_PRINTF("Unable to create new BIO");
		goto cleanup;
	}
	BIO_puts(cert,server_pem);
	x=PEM_read_bio_X509_AUX(cert, NULL, 0, NULL);
	
	pkey=PEM_read_bio_PrivateKey(cert,NULL,
		server_ctx->default_passwd_callback,server_ctx->default_passwd_callback_userdata);
	//if (SSL_CTX_use_certificate_file(server_ctx, CERTF, SSL_FILETYPE_PEM) <= 0) {
	if (SSL_CTX_use_certificate(server_ctx, x) <= 0) 
	{ 
		TINYCLR_SSL_PRINTF("Use certifcate chain file failed");
		goto cleanup;
	}
	if (SSL_CTX_use_PrivateKey(server_ctx, pkey) <= 0) 
	{
		TINYCLR_SSL_PRINTF("Unable to use Private Key");
		goto cleanup;
	}

	if (!SSL_CTX_check_private_key(server_ctx)) {
		TINYCLR_SSL_PRINTF("Private key does not match the certificate public key\n");
		goto cleanup;
	}

	//if (SSL_CTX_set_cipher_list(server_ctx, );

	// ----------------------------------------------- 
	// Prepare TCP socket for receiving connections

	listen_sd = TINYCLR_SSL_SOCKET (AF_INET, SOCK_STREAM, IPPROTO_TCP);   
	if (listen_sd < 0) goto cleanup;

	// set it to non-blocking
	int nonblock = 1;
	err = TINYCLR_SSL_IOCTL(listen_sd,SOCK_FIONBIO,&nonblock);
	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Nonblocking call failed for server: %d.\n", wsa);
		goto cleanup;
	}

	TINYCLR_SSL_MEMSET(&sa_serv, '\0', sizeof(sa_serv));
	sa_serv.sin_family      		= AF_INET;
	sa_serv.sin_addr.S_un.S_addr 	= inet_addr("127.0.0.1");
	sa_serv.sin_port        		= TINYCLR_SSL_HTONS (1111);          /* Server Port number */

	TINYCLR_SSL_PRINTF("Binding to %d...\n", TINYCLR_SSL_NTOHS(sa_serv.sin_port));
	err = TINYCLR_SSL_BIND(listen_sd, (struct TINYCLR_SSL_SOCKADDR*) &sa_serv,
	     sizeof (sa_serv));                   

	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Bind Socket error %d\n", wsa);
		goto cleanup;
	}

	TINYCLR_SSL_PRINTF("Listening...\n");
	/* Receive a TCP connection. */     
	err = TINYCLR_SSL_LISTEN (listen_sd, 5);                    
	if (err < 0) 
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Listen Socket error %d\n", wsa);
		goto cleanup;
	}

	// create a client socket
	client_sd = TINYCLR_SSL_SOCKET (AF_INET, SOCK_STREAM, IPPROTO_TCP);   
	if (client_sd < 0) goto cleanup;

	// set it to non-blocking
	err = TINYCLR_SSL_IOCTL(client_sd,SOCK_FIONBIO,&nonblock);
	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Nonblocking call failed for client: %d.\n", wsa);
		goto cleanup;
	}
	// Set up a tcp connection for client: Bind, Connect
	err == TINYCLR_SSL_CONNECT( client_sd, (const struct TINYCLR_SSL_SOCKADDR*)&sa_serv, sizeof(sa_serv));
	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Client connect failed with: %d.\n", wsa);
	}

	
	client_len = sizeof(sa_cli);
	char nodename[128] = "";
	char servname[128] = "";
	SOCK_addrinfo hints;
	SOCK_addrinfo *res = NULL;
	
	TINYCLR_SSL_MEMSET(&hints, '\0', sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

	SOCK_getaddrinfo(nodename,servname,&hints,&res);

	SOCK_addrinfo *ptr = NULL;
	for (ptr=res; ptr!=NULL; ptr=ptr->ai_next)
	{	
		struct sockaddr_in *ip = (struct sockaddr_in*) ptr->ai_addr;
		TINYCLR_SSL_PRINTF("Accepting connections on...%s:%d\n", 
			inet_ntoa(ip->sin_addr), 1111 );
	}

	int counter=0;
	do
	{
		server_sd = TINYCLR_SSL_ACCEPT (listen_sd, (struct TINYCLR_SSL_SOCKADDR*) &sa_cli, (int*)&client_len);
        Events_WaitForEvents(0,2000);
		TINYCLR_SSL_PRINTF("Accept again %d:%d\n", TINYCLR_SSL_GETLASTSOCKETERROR(), counter++);
	} while (server_sd == -1);
	
	TINYCLR_SSL_CLOSESOCKET (listen_sd);

	TINYCLR_SSL_PRINTF ("Connection from %lx, port %x\n",
	sa_cli.sin_addr.S_un.S_addr, sa_cli.sin_port);


	// connections are completed between server & client
	// now lets do the SSL negotiations
	// create server ssl
	server_ssl = SSL_new(server_ctx);
	if (server_ssl == NULL) goto cleanup;
	SSL_set_fd (server_ssl, server_sd);

	//Create server bio and set as non-blocking
	BIO* server_bio = BIO_new(BIO_s_socket());
	if (server_bio == NULL) goto cleanup;
	//CHK_NULL(bio);
	BIO_set_nbio(server_bio,1);
	BIO_set_fd(server_bio, server_sd, BIO_NOCLOSE);
	SSL_set_bio(server_ssl,server_bio,server_bio);

	// create client ssl & connect
	client_ssl = SSL_new(client_ctx);
	if (client_ssl == NULL) goto cleanup;
	SSL_set_fd(client_ssl, client_sd);

	//Create client bio and set as non-blocking
	BIO* client_bio = BIO_new(BIO_s_socket());
	if (client_bio == NULL) goto cleanup;
	BIO_set_nbio(client_bio,1);
	BIO_set_fd(client_bio, client_sd, BIO_NOCLOSE);
	SSL_set_bio(client_ssl,client_bio,client_bio);

	
	
	// loop until server accepts ssl client connect
	int ssl_err =0;
	do
	{
		err = SSL_connect(client_ssl);
		if (err <= 0) 
		{
			ssl_err = SSL_get_error(client_ssl,err);
			TINYCLR_SSL_PRINTF("SSL_Connect error: %d\n", ssl_err);
		}
        Events_WaitForEvents(0,1000);
		err = SSL_accept (server_ssl);
		if (err <= 0) 
		{
			ssl_err = SSL_get_error(server_ssl, err);
			TINYCLR_SSL_PRINTF("SSL_Accept error: %d\n", ssl_err);
		}
        Events_WaitForEvents(0,1000);
	} while (err != 1);

	//Get the cipher - opt
	TINYCLR_SSL_PRINTF("SSL connection using %s\n", SSL_get_cipher (server_ssl));

	//Get client's certificate (note: beware of dynamic allocation) - opt
	client_cert = SSL_get_peer_certificate (server_ssl);
	if (client_cert != NULL) 
	{
		TINYCLR_SSL_PRINTF("Client certificate:\n");

		str = X509_NAME_oneline (X509_get_subject_name (client_cert), 0, 0);
		if (str == NULL) goto cleanup;

		TINYCLR_SSL_PRINTF("subject: %s\n", str);
		OPENSSL_free (str);

		str = X509_NAME_oneline (X509_get_issuer_name  (client_cert), 0, 0);
		if (str == NULL) goto cleanup;
		TINYCLR_SSL_PRINTF("issuer: %s\n", str);
		OPENSSL_free (str);

		//We could do all sorts of certificate verification stuff here before
		//   deallocating the certificate.

		X509_free (client_cert);
	} 
	else
		TINYCLR_SSL_PRINTF("Client does not have certificate.\n");
	
	//Get server's certificate (note: beware of dynamic allocation) - opt
	server_cert = SSL_get_peer_certificate (client_ssl);
	if (server_cert != NULL) 
	{
		TINYCLR_SSL_PRINTF("Server certificate:\n");

		str = X509_NAME_oneline (X509_get_subject_name (server_cert), 0, 0);
		if (str == NULL) goto cleanup;

		TINYCLR_SSL_PRINTF("subject: %s\n", str);
		OPENSSL_free (str);

		str = X509_NAME_oneline (X509_get_issuer_name  (server_cert), 0, 0);
		if (str == NULL) goto cleanup;
		TINYCLR_SSL_PRINTF("issuer: %s\n", str);
		OPENSSL_free (str);

		/* We could do all sorts of certificate verification stuff here before
		   deallocating the certificate. */

		X509_free (server_cert);
	} 
	else
		TINYCLR_SSL_PRINTF("Server with no certificate?!?!?.\n");

	do
	{

		// DATA EXCHANGE - Receive message and send reply. 
		err = SSL_write(client_ssl,"Hello World!",TINYCLR_SSL_STRLEN("Hello World!"));
		if (err <= 0) ssl_err = SSL_get_error(client_ssl, err);
        Events_WaitForEvents(0,1000);
		server_numbytes= SSL_read (server_ssl, server_buf, sizeof(server_buf) - 1);                   
		if (server_numbytes <= 0) 
			ssl_err = SSL_get_error(server_ssl, server_numbytes);
		else
			server_buf[server_numbytes] = '\0';
        Events_WaitForEvents(0,1000);

		err = SSL_write (server_ssl, "I hear you.", TINYCLR_SSL_STRLEN("I hear you."));  
		if (err <= 0) ssl_err = SSL_get_error(server_ssl, err);
        Events_WaitForEvents(0,1000);

		client_numbytes= SSL_read(client_ssl, client_buf, sizeof(client_buf) -1);
		if (client_numbytes <= 0) 
			ssl_err = SSL_get_error(client_ssl, client_numbytes);
		else
			client_buf[client_numbytes] = '\0';
        Events_WaitForEvents(0,1000);
		
	} while (err <= 0);

	TINYCLR_SSL_PRINTF("Server got %d chars:'%s'\n", server_numbytes, server_buf);
	TINYCLR_SSL_PRINTF("Client go %d chars:'%s'\n", client_numbytes, client_buf);
	/* Clean up. */

	cleanup:
	if (pkey) EVP_PKEY_free(pkey);
	if (cert) BIO_free(cert);
	if (x) X509_free(x);
	TINYCLR_SSL_CLOSESOCKET(server_sd);
	if (server_ssl) SSL_shutdown(server_ssl);
	if (server_ssl) SSL_free (server_ssl);
	server_ssl = NULL;
	if (server_ctx) SSL_CTX_free(server_ctx);
	server_ctx = NULL;
	TINYCLR_SSL_CLOSESOCKET(client_sd);
	if (client_ssl) SSL_shutdown(client_ssl);
	if (client_ssl) SSL_free (client_ssl);
	client_ssl = NULL;
	if (client_ctx) SSL_CTX_free(client_ctx);
	client_ctx = NULL;
}
Ejemplo n.º 15
0
u32_t sys_arch_mbox_fetch(sys_mbox_t* mbox, void **msg, u32_t timeout)
{
    if(mbox == NULL || *mbox == NULL) { ASSERT(FALSE); return SYS_ARCH_TIMEOUT; }

    Hal_Queue_UnknownSize<OpaqueQueueNode>* queue = (Hal_Queue_UnknownSize<OpaqueQueueNode>*)*mbox;
    bool didTimeout = false;

    if(timeout == 0) 
    {
        timeout = 0xFFFFFFFF;
    }

    INT64 now = ::HAL_Time_CurrentTime();
    INT64 elapsed = now + (timeout * 10000);
    
    while(elapsed > ::HAL_Time_CurrentTime() || timeout == 1) 
    {
        OpaqueQueueNode* node = queue->Pop();
        
        if(node) 
        {
            *msg = node->payload;

            Events_Set(SYSTEM_EVENT_FLAG_NETWORK);            

            SOCKETS_RestartTcpIpProcessor(0);
            
            return 0;
        }
        else if(timeout == 1)
        {
            break;
        }
        
        if(INTERRUPTS_ENABLED_STATE())
        {
            if(Events_WaitForEvents(SYSTEM_EVENT_FLAG_NETWORK, timeout))
            {
                Events_Clear(SYSTEM_EVENT_FLAG_NETWORK);
                
                INT64 curTime = ::HAL_Time_CurrentTime();

                if(elapsed > curTime)
                {
                    timeout -= (elapsed - HAL_Time_CurrentTime()) / 10000;
                }
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    if(timeout != 1)
    {
        Events_Set(SYSTEM_EVENT_FLAG_NETWORK);            
    }
    else
    {
        didTimeout = true;
    }

    *msg = NULL; 
    return didTimeout ? SYS_ARCH_TIMEOUT : SYS_MBOX_EMPTY;    
}
Ejemplo n.º 16
0
void ApplicationEntryPoint()
{

#if defined(TEST_DAC)
    UINT32 FramesNum = g_LPC24XX_DAC_Driver.GetBufferFrameCapacity();
    if (DAC_FRAME_BUFFERS_NUM!=FramesNum)
    {
        debug_printf( "Error, BufferFrameCapacity != DAC_FRAME_BUFFERS_NUM: %d != %d.\r\n", FramesNum, DAC_FRAME_BUFFERS_NUM );
    }

    UINT32 nextInFrameOffset=0;
    UINT16 frameLength = MAX_DECODED_FRAME_SIZE/2;
    short* frameSignedStart = NULL;


    LPC24XX_VIC& VIC = LPC24XX::VIC();

    /*debug_printf("VIC INTRSEL = 0x%08x\r\n", VIC.INTRSEL);
    VIC.INTRSEL |= 1 << LPC24XX_TIMER::getIntNo(LPC24XX_DAC::Timer);
    debug_printf("new VIC INTRSEL = 0x%08x\r\n", VIC.INTRSEL);*/

    VIC.VECTPRIORITY[LPC24XX_TIMER::getIntNo(LPC24XX_DAC::Timer)] = 0;

    for(int i= 0; i< 32; i++)
    {
        debug_printf("PRIO INTR%02d = %d \r\n", i,VIC.VECTPRIORITY[i]);
    }


    debug_printf( "Init DAC, 8kHz output.\r\n" );
    g_LPC24XX_DAC_Driver.Initialize(OUT_FREQ);




    debug_printf( "BUFFER PRE-FILL TEST.\r\n" );
    debug_printf( "Adding frames to the DAC driver buffer: " );


    debug_printf("total frames to be added = %d\r\n", TEST_SAMPLES_NUM/MAX_DECODED_FRAME_SIZE-CUTOUT);
    debug_printf("DAC frame buffers available = %d\r\n", DAC_FRAME_BUFFERS_NUM);
    if(DAC_FRAME_BUFFERS_NUM<(TEST_SAMPLES_NUM/MAX_DECODED_FRAME_SIZE-CUTOUT))
        debug_printf("ONLY THE FIRST %d FRAMES OF THE SAMPLE WILL BE PLAYED.\r\n", DAC_FRAME_BUFFERS_NUM);

    while(nextInFrameOffset+(MAX_DECODED_FRAME_SIZE*CUTOUT) < TEST_SAMPLES_NUM)
    {
        //if(i%(1024*256)) continue;


        frameSignedStart = (short*)(bin_data+nextInFrameOffset);

        if(g_LPC24XX_DAC_Driver.AddFrame(frameSignedStart, frameLength))
        {
            debug_printf( "     done.\r\n" );
            nextInFrameOffset+=MAX_DECODED_FRAME_SIZE;
        }
        else
        {
            debug_printf( "Buffer full, starting playout.\r\n");
            break;
        }
    }

    resetDACISRTiming();


    debug_printf( "DAC.On() in 2 seconds\r\n");
    Events_WaitForEvents( 0, 2000 );

    if(!hijackISRs())
        return;

    if(g_LPC24XX_DAC_Driver.On())
    {
        //debug_printf( "Done. 2sec wait.\r\n" ); don't output to avoid adding serial activity during the test
    }
    else
    {
        debug_printf( "FAILED.\r\n" );
    }

    while(g_LPC24XX_DAC_Driver.GetBufferLevel()>0)
    {
        //debug_printf("Samples left: %d\r\n", g_LPC24XX_DAC_Driver.GetBufferLevel());
        //debug_printf("Frames left:  %d\r\n", g_LPC24XX_DAC_Driver.GetFramesLeft());
    }

    //stop logging interrupts before starting to output again

    int finalIrqCount = irq_count;
    irq_count = 8192;

    Events_WaitForEvents( 0, 5000 );

    if(!restoreISRs())
        return;

    debug_printf("%d frames left.\r\n", g_LPC24XX_DAC_Driver.GetFramesLeft());
    debug_printf("Final IRQ count = %u\r\n", finalIrqCount);
    debug_printf( "BUFFER PRE-FILL TEST OVER.\r\n");

    displayRunTestResults();
    debug_printf("CSV DATA OUTPUT FOLLOWS\r\n");
    //csvRunTestResults();



    debug_printf("\r\nPARALLEL BUFFER FILL TEST\r\n" );


    Events_WaitForEvents( 0, 3000 );

    debug_printf( "DAC.Off()\r\n");
    if(g_LPC24XX_DAC_Driver.Off())
    {
        debug_printf( "Done.\r\n" );
    }
    else
    {
        debug_printf( "FAILED.\r\n" );
    }

    debug_printf( "Uninit DAC\r\n");
    g_LPC24XX_DAC_Driver.Uninitialize();
    debug_printf( "Done.\r\n");

    debug_printf( "Init DAC, 8kHz output.\r\n" );
    g_LPC24XX_DAC_Driver.Initialize(OUT_FREQ);

    resetDACISRTiming();

    debug_printf( "DAC.On() in 2 seconds\r\n");
    Events_WaitForEvents( 0, 2000 );
    if(g_LPC24XX_DAC_Driver.On())
    {
        //debug_printf( "Done.\r\n" );
    }
    else
    {
        debug_printf( "FAILED.\r\n" );
    }

    debug_printf( "Adding frames to the DAC driver buffer: " );

    nextInFrameOffset=0;

    debug_printf("total frames to be added = %d\r\n", TEST_SAMPLES_NUM/MAX_DECODED_FRAME_SIZE-CUTOUT);

    //FILL JUST ONCE
    while(nextInFrameOffset+(MAX_DECODED_FRAME_SIZE*CUTOUT) < TEST_SAMPLES_NUM)
    {
        //if(i%(1024*256)) continue;


        frameSignedStart = (short*)(bin_data+nextInFrameOffset);

        if(g_LPC24XX_DAC_Driver.AddFrame(frameSignedStart, frameLength))
        {
            debug_printf( "     done.\r\n" );
            nextInFrameOffset+=MAX_DECODED_FRAME_SIZE;
        }
        else
        {
            //debug_printf( "FAIL.\r\n");
        }
    }

    while(g_LPC24XX_DAC_Driver.GetBufferLevel()>0)
    {
        //debug_printf("Samples left: %d\r\n", g_LPC24XX_DAC_Driver.GetBufferLevel());
        //debug_printf("Frames left:  %d\r\n", g_LPC24XX_DAC_Driver.GetFramesLeft());
    }

    Events_WaitForEvents( 0, 3000 );

    displayRunTestResults();

    debug_printf("CSV DATA OUTPUT FOLLOWS\r\n");
    csvRunTestResults();

    /*CONTINUOUS REFILL with samples
    while(true)
    {
        //if(i%(1024*256)) continue;


        frameSignedStart = (short*)(bin_data+nextInFrameOffset);

        if(g_LPC24XX_DAC_Driver.AddFrame(frameSignedStart, frameLength))
        {
            //debug_printf( "     done.\r\n" );
            nextInFrameOffset+=MAX_DECODED_FRAME_SIZE;
            if(nextInFrameOffset+(MAX_DECODED_FRAME_SIZE*CUTOUT)>=TEST_SAMPLES_NUM)
                nextInFrameOffset = 0;
        }
        else
        {
            //debug_printf( "FAIL.\r\n");
        }
        debug_printf("Samples left: %d\r\n", g_LPC24XX_DAC_Driver.GetBufferLevel());
        debug_printf("Frames left:  %d\r\n", g_LPC24XX_DAC_Driver.GetFramesLeft());
    }*///end continuous refill


    debug_printf("%d frames left.\r\n", g_LPC24XX_DAC_Driver.GetFramesLeft());
    debug_printf( "PARALLEL BUFFER FILL TEST OVER.\r\n\r\n" );


    //Events_WaitForEvents( 0, 10000 );

    debug_printf( "DAC.Off()\r\n");
    if(g_LPC24XX_DAC_Driver.Off())
    {
        debug_printf( "Done.\r\n" );
    }
    else
    {
        debug_printf( "FAILED.\r\n" );
    }

    debug_printf( "Uninit DAC()\r\n");
    g_LPC24XX_DAC_Driver.Uninitialize();
    debug_printf( "Done.\r\n");

#endif


#if defined(TEST_JOYSTICK)
    extern LPC24XX_GPIO_Driver g_LPC24XX_GPIO_Driver;

    wait_joystick = true;

    for(UINT32 pin = LPC24XX_GPIO::c_P2_22; pin < LPC24XX_GPIO::c_P2_28; pin++)
    {
        if(pin == LPC24XX_GPIO::c_P2_24)
            continue;
        if(!g_LPC24XX_GPIO_Driver.EnableInputPin( pin, false,  joystickISR, NULL, GPIO_INT_EDGE_HIGH, (GPIO_RESISTOR)2 ))
        {
            debug_printf("Cannot enable pin %u as INPUT pin.\r\n", pin);
            exit(1);
        }
        debug_printf("Enabled pin %u as INPUT pin.\r\n", pin);
    }

    while(wait_joystick) {};

#endif

#if    defined(TEST_SST39WF)

    while(1)
    {
        lcd_printf  ( "Hello, world from the LCD!\r\n" );
        hal_printf  ( "Hello, world from the HAL!\r\n" );
        debug_printf( "Hello, world from the debug intf!\r\n" );
        if(BlockStorageList::GetNumDevices() != 1)
        {
            debug_printf( "%d Block Devices present!\r\n", BlockStorageList::GetNumDevices() );
            break;
        }

        BlockStorageDevice* SST = BlockStorageList::GetFirstDevice();
        if(SST == NULL)
        {
            debug_printf( "GetFirstDevice failed.\r\n" );
            break;
        }

        const BlockDeviceInfo* SSTInfo = SST->GetDeviceInfo();
        if(SSTInfo == NULL)
        {
            debug_printf( "GetDeviceInfo failed.\r\n" );
            break;
        }

        debug_printf( "NumRegions in BSDevice: %d\r\n", SSTInfo->NumRegions);

        ByteAddress PhyAddress = (ByteAddress) 0xC0FFEEEE;

        SectorAddress SectAddress = 0xC0FFEEEE;
        UINT32 RangeIndex;
        UINT32 RegionIndex;

        const BlockRegionInfo *pBlockRegionInfo;
        SST->FindForBlockUsage(    /*UINT32*/ BlockRange::BLOCKTYPE_DEPLOYMENT ,
                                              PhyAddress , RegionIndex, RangeIndex );
        if(PhyAddress == 0xC0FFEEEE)
        {
            debug_printf( "FindForBlockUsage failed.\r\n" );
            break;
        }


        debug_printf( "Sector 0x%08x physical address: 0x%08x\r\n", SectAddress, PhyAddress);

        BYTE pSectorBuf[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};

        //ERASE before writing!
        if(!SST->IsBlockErased(PhyAddress, 0x1000))
        {
            debug_printf( "Erasing block " );
            if(!SST->EraseBlock(SectAddress))
            {
                debug_printf( "failed.\r\n" );
                break;
            }
            debug_printf( "successful.\r\n" );
        }

        if(SST->Write(/*UINT32*/ PhyAddress, /*UINT32 NumOfBytes*/ 16, /*BYTE* */ pSectorBuf, /*SectorMetadata* */ FALSE))
            debug_printf( "Correctly written 16 bytes to Sector 0x%08x\r\n", SectAddress);

        Events_WaitForEvents( 0, 2000 );
    }
#endif        //TEST_SST39WF

#if defined(TEST_PWM)

    PWM_Initialize(PWM_CHANNEL_0);

    // NOTE: on the EA_LPC2478 board the first pin we will return is the 11th pin on the left side from the top of the J1 connector
    GPIO_PIN pin = PWM_GetPinForChannel( PWM_CHANNEL_0 );

    // from 90% to 2/3, to 50%, to 1/3 to 10%
    float dc[5] = { 0.9, 0.666, 0.5, 0.333, 0.1 };
    UINT32 period1 = 1000; // 1Kxz
    for(UINT32 idx = 0; idx < 5; ++idx)
    {
        UINT32 duration1 = (UINT32)((float)period1 * dc[idx]);

        PWM_ApplyConfiguration( PWM_CHANNEL_0, pin, period1, duration1, FALSE);
        PWM_Start             ( PWM_CHANNEL_0, pin );

        // 2 secs, then change
        HAL_Time_Sleep_MicroSeconds_InterruptEnabled(1 * 1000 * 1000);
        //Events_WaitForEvents( 0, 2 * 1000);

        PWM_Stop              ( PWM_CHANNEL_0, pin );
    }

    // from 10Khz to 1Khz, 50% duty cycle
    for(UINT32 period = 10000; period >= 1000; period -= 1000)
    {
        UINT32 duration = period / 2;

        PWM_ApplyConfiguration( PWM_CHANNEL_0, pin, period, duration, FALSE);
        PWM_Start             ( PWM_CHANNEL_0, pin );

        // 2 secs, then change
        HAL_Time_Sleep_MicroSeconds_InterruptEnabled(1 * 1000 * 1000);
        //Events_WaitForEvents( 0, 2 * 1000);

        PWM_Stop              ( PWM_CHANNEL_0, pin );
    }

    PWM_Uninitialize(PWM_CHANNEL_0);

#endif // TEST_PWM

    while(1)
    {
        lcd_printf  ( "Hello, world!\r\n" );
        hal_printf  ( "Hello, world!\r\n" );
        debug_printf( "Hello, world!\r\n" );


        Events_WaitForEvents( 0, 1000 );
    }

}