Exemple #1
0
/********* SHEULL MAIN LOOP ***********************************/
void shell_main(void *arg) {
    int i ; 
    func_args args ;
    int bf_flg ;
    osThreadId 	 cmd ;
    i = BackGround ; 
        /* Dummy for avoiding warning: BackGround is defined but not used. */
    
 #if defined(HAVE_KEIL_RTX) 
    wc_InitMutex(&command_mutex) ;
#endif
    help_comm(NULL) ;
    
    printf("Starting Shell\n") ;
    while(1) {
        if(getline(line,  LINESIZE, &args, &bf_flg) > 0) {
        for(i=0; commandTable[i].func != NULL; i++) {
            if(strcmp(commandTable[i].command, args.argv[0]) == 0) {
            args.argv[0] = (char *) commandTable[i].func ;
                if(bf_flg == FORGROUND) {
                    #if defined(HAVE_KEIL_RTX) && !defined(WOLFSSL_CMSIS_RTOS)
                        wc_UnLockMutex((wolfSSL_Mutex *)&command_mutex) ;
                        os_tsk_create_user_ex( (void(*)(void *))&command_invoke, 7,
                                 command_stack, COMMAND_STACK_SIZE, &args) ;
                        os_tsk_pass ();
                    #else
                        #if defined(WOLFSSL_CMSIS_RTOS)
                             wc_UnLockMutex((wolfSSL_Mutex *)&command_mutex) ;
                             cmd = osThreadCreate (osThread (command_invoke) , &args); 
                             if(cmd == NULL) {
															     printf("Cannon create command thread\n") ;
														 }
												     osThreadYield ();
                        #else
                              command_invoke(&args) ;
                        #endif
                    #endif
                    #ifdef  HAVE_KEIL_RTX
                    wc_LockMutex((wolfSSL_Mutex *)&command_mutex) ;
                    #endif
                } else {
                    #if (!defined(NO_SIMPLE_SERVER) && \
                         !defined(NO_ECHOSERVER)) && \
                         defined(HAVE_KEIL_RTX)
                    if(BackGround != 0) {
                        printf("Multiple background servers not supported.\n") ;
                    } else {
                        printf("\"%s\" is running with the background mode.\n", 
                                                     commandTable[i].command) ;
                        #if  defined(HAVE_KEIL_RTX) && !defined(WOLFSSL_CMSIS_RTOS)
                             os_tsk_create_user_ex( (void(*)(void *))&bg_job_invoke, 
                                   6, bg_job_stack, BG_JOB_STACK_SIZE, &args) ;
                        #else
                                osThreadCreate (osThread (bg_job_invoke),  &args); 
                                osDelay (500) ;
                        #endif
                    }
                    #else
                    printf("Invalid Command: no background job\n") ;
                    #endif
                }
                break ;
            }
        }
        if(commandTable[i].func == NULL)
            printf("Command not found\n") ;
        }
    }
}
void SensorsTask(void)
{   
    // Array storing the status of each physical sensor.
    // If a sensor fails to initialize, or fails 3 sensor reads in a row, 
    // it will be disabled here until the next system reboot
    // 0 = tmp0
    // 1 = tmp1
    // 2 = tmp3
    // 3 = humidity / air temp
    // 4 = pressure
    // 5 = accelerometer
    uint8_t enabledSensors[7] = {3, 3, 3, 3, 3, 3, 3};
    uint8_t i;
    I2C_Status retVal = I2C_OK;
    
    INFO("(SENSORS_TASK) I2C Sensor failed to initialize\r\n");
    
    for(i = 0; i < 3; i++)
    {
        // If the temperature sensor initialized, set its enabled value to 3 (so it has 3 chances to respond to a read request)
        // Else, disable the sensor
        if(InitTempSensor(i) != I2C_OK)
        {
            I2C_Reset(SLB_I2C);
            enabledSensors[i] = 0;
            WARN("(SENSORS_TASK) I2C Sensor failed to initialize\r\n"); 
        }
    }
    
    if(InitHumiditySensor() != I2C_OK)
    {
        I2C_Reset(ALB_I2C);
        enabledSensors[3] = 0;
        WARN("(SENSORS_TASK) Humidity sensor failed to initialize\r\n");
    }
    
    if(InitPressureSensor() != I2C_OK)
    {
        I2C_Reset(ALB_I2C);
        enabledSensors[4] = 0;
        WARN("(SENSORS_TASK) Pressure sensor failed to initialize\r\n");
    }
    
    if(InitAccelerometer() != I2C_OK)
    {
        I2C_Reset(ALB_I2C);
        enabledSensors[5] = 0;
        WARN("(SENSORS_TASK) Accelerometer failed to initialize\r\n");
    }
    
    // Let other tasks in the system warmup before entering the sensor polling loop
    osDelay(2000);
    
    // TODO: re-initialize the sensors once a day to check for failures and for sensors that have come back online
    // TODO: report to the base station when a sensor fails
    
    while(1)
    {
        for(i = 0; i < 3; i++)
        {
            if(enabledSensors[i] > 0)
            {
                switch(i)
                {
                    case 0:
                        retVal = ReadTempSensor(0, &sensorData.temp0);
                        break;
                    case 1:
                        retVal = ReadTempSensor(1, &sensorData.temp1);
                        break;
                    case 2:
                        retVal = ReadTempSensor(2, &sensorData.temp2);
                        break;
                    default:
                        retVal = ReadTempSensor(0, &sensorData.temp0);
                        break;
                }
                
                // If the sensor read failed, indicate that the sensor has one less chance to respond correctly before being disabled
                if(retVal != I2C_OK)
                {
                    I2C_Reset(SLB_I2C);
                    enabledSensors[i]--;
                    WARN("(SENSORS_TASK) Temp sensor read failed\r\n");
                }
                // The sensor is still alive! Restore it to a full 3 chances to respond
                else if(enabledSensors[i] != 3)
                {
                    enabledSensors[i] = 3;
                    DEBUG("(SENSORS_TASK) Temp sensor connection restored\r\n");
                }
            }
        }
        
        if(enabledSensors[3] > 0)
        {
           do {
                if(ReadHumiditySensor(&sensorData.humid) != I2C_OK)
                {
                    I2C_Reset(ALB_I2C);
                    enabledSensors[3]--;
                    WARN("(SENSORS_TASK) Humidity sensor read failed\r\n");
                    break;
                }
                else if(enabledSensors[3] != 3)
                {
                   enabledSensors[3] = 3;
                   DEBUG("(SENSORS_TASK) Humidity sensor connection restored\r\n");
                }
               
                if(ReadAirTempSensor(&sensorData.tempAir) != I2C_OK)
                {
                    I2C_Reset(ALB_I2C);
                    enabledSensors[3]--;
                    WARN("(SENSORS_TASK) Air temp sensor read failed\r\n");
                }
                else if(enabledSensors[3] != 3)
                {
                   enabledSensors[3] = 3;
                   DEBUG("(SENSORS_TASK) Air temp sensor connection restored\r\n");
                }
            }
            while(0);
        }
        
        if(enabledSensors[4] > 0)
        {
            if(ReadPressureSensor(&sensorData.alt) != I2C_OK)
            {
                I2C_Reset(ALB_I2C);
                enabledSensors[4]--;
                WARN("(SENSORS_TASK) Altimeter sensor read failed\r\n");
            }
        }
        
        if(enabledSensors[5] > 0)
        {
            uint16_t x, y, z;
            if(ReadAccelerometer(&x, &y, &z) != I2C_OK)
            {
                I2C_Reset(ALB_I2C);
                enabledSensors[5]--;
                WARN("(SENSORS_TASK) Accelerometer sensor read failed\r\n");
            }
            
            DEBUG("X: %d, Y: %d, Z: %d", x, y, z);
        }
        
        ReadSoilMoisture(&sensorData.moist0, &sensorData.moist1, &sensorData.moist2);
        
        // Send sensor Data to the base station
        SendSensorData();
        
        osDelay(pollingRate);
    }
}
/**
  * @brief  VNC Thread
* @param  argument: network interface
  * @retval None
  */
void VNC_Thread(void const * argument)
{

  for (;;)
  { 
    switch (VNC_State)
    {
    case VNC_LINK_UP:
      {
        gnetif.ip_addr.addr = 0;
        gnetif.netmask.addr = 0;
        gnetif.gw.addr = 0;
        dhcp_start(&gnetif);
        VNC_State = VNC_WAIT_FOR_ADDRESS;
        VNC_SERVER_LogMessage ("Waiting for DHCP server...\n");
        VNC_SERVER_StatusChanged(VNC_WAIT_FOR_ADDRESS);
      }
      break;
      
    case VNC_WAIT_FOR_ADDRESS:
      {        
        if (gnetif.ip_addr.addr!=0) 
        {
          dhcp_stop(&gnetif);
          VNC_State = VNC_START;
          VNC_SERVER_StatusChanged(VNC_START);          
        }
        else
        {
          /* DHCP timeout */
          if (gnetif.dhcp->tries > MAX_DHCP_TRIES)
          {
            VNC_State = VNC_ERROR;
            dhcp_stop(&gnetif);
            VNC_SERVER_LogMessage ("No reply from DHCP Server!\n");
          }
        }
      }
      break;
      
    case VNC_START: 
      
      sprintf((char*)iptxt, 
              "IP address : %d.%d.%d.%d\n", 
              (uint8_t)(gnetif.ip_addr.addr), 
              (uint8_t)((gnetif.ip_addr.addr) >> 8), 
              (uint8_t)((gnetif.ip_addr.addr) >> 16), 
              (uint8_t)((gnetif.ip_addr.addr) >> 24));       
      
      VNC_SERVER_LogMessage ((char *)iptxt);
      
      /* Init VNC context and attach to layer (so context is updated if the display-layer-contents change */
      GUI_VNC_AttachToLayer(&_Context, 0);
      _Context.ServerIndex = 0;
      GUI_VNC_SetProgName ("STM32 VNC Server");
      if(VNC_LockState)
      {
        GUI_VNC_SetPassword((U8 *)"STM32");
      }
      else
      {
        GUI_VNC_SetAuthentication(NULL);
      }
      VNC_State = VNC_PROCESS;
      break;
      
      
    case VNC_PROCESS: 
      VNC_Process();
      break;
      
    case VNC_IDLE:
      break;
      
    default: 
      break;
    }
    osDelay(250);
  }
}
Exemple #4
0
THREAD_RETURN CYASSL_THREAD client_test(void* args)
{
    SOCKET_T sockfd = 0;

    CYASSL_METHOD*  method  = 0;
    CYASSL_CTX*     ctx     = 0;
    CYASSL*         ssl     = 0;
    
    CYASSL*         sslResume = 0;
    CYASSL_SESSION* session = 0;
    char         resumeMsg[] = "resuming cyassl!";
    int          resumeSz    = sizeof(resumeMsg);

    char msg[32] = "hello cyassl!";   /* GET may make bigger */
    char reply[80];
    int  input;
    int  msgSz = (int)strlen(msg);

    int   port   = yasslPort;
    char* host   = (char*)yasslIP;
    char* domain = (char*)"www.yassl.com";

    int    ch;
    int    version = CLIENT_INVALID_VERSION;
    int    usePsk   = 0;
    int    sendGET  = 0;
    int    benchmark = 0;
    int    doDTLS    = 0;
    int    matchName = 0;
    int    doPeerCheck = 1;
    int    nonBlocking = 0;
    int    resumeSession = 0;
    int    trackMemory   = 0;
    int    useClientCert = 1;
    int    fewerPackets  = 0;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)caCert;
    char*  ourCert    = (char*)cliCert;
    char*  ourKey     = (char*)cliKey;

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif

    int     argc = ((func_args*)args)->argc;
    char**  argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)eccCert;
    ourCert    = (char*)cliEccCert;
    ourKey     = (char*)cliEccKey;
#endif
    (void)resumeSz;
    (void)session;
    (void)sslResume;
    (void)trackMemory;

    while ((ch = mygetopt(argc, argv, "?gdusmNrtfxh:p:v:l:A:c:k:b:zS:")) != -1){
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'g' :
                sendGET = 1;
                break;

            case 'd' :
                doPeerCheck = 0;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_CYASSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'm' :
                matchName = 1;
                break;

            case 'x' :
                useClientCert = 0;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'h' :
                host   = myoptarg;
                domain = myoptarg;
                break;

            case 'p' :
                port = atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'b' :
                benchmark = atoi(myoptarg);
                if (benchmark < 0 || benchmark > 1000000) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'N' :
                nonBlocking = 1;
                break;

            case 'r' :
                resumeSession = 1;
                break;

            case 'z' :
                #ifndef CYASSL_LEANPSK
                    CyaSSL_GetObjectSize();
                #endif
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = CyaSSLv3_client_method();
            break;
                
                
    #ifndef NO_TLS
        case 1:
            method = CyaTLSv1_client_method();
            break;

        case 2:
            method = CyaTLSv1_1_client_method();
            break;
    #endif /* NO_TLS */
                
#endif  /* NO_OLD_TLS */
                
#ifndef NO_TLS
        case 3:
            method = CyaTLSv1_2_client_method();
            break;
#endif

#ifdef CYASSL_DTLS
        case -1:
            method = CyaDTLSv1_client_method();
            break;

        case -2:
            method = CyaDTLSv1_2_client_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
            break;
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = CyaSSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");
		
    if (cipherList)
        if (CyaSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("client can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (fewerPackets)
        CyaSSL_CTX_set_group_messages(ctx);

    if (usePsk) {
#ifndef NO_PSK
        CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (CyaSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
                err_sys("client can't set cipher list 2");
        }
#endif
        useClientCert = 0;
    }

#ifdef OPENSSL_EXTRA
    CyaSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    if (cipherList == NULL) {
        /* don't use EDH, can't sniff tmp keys */
        if (CyaSSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) {
            err_sys("client can't set cipher list 3");
        }
    }
#endif

#ifdef USER_CA_CB
    CyaSSL_CTX_SetCACb(ctx, CaCb);
#endif

#ifdef VERIFY_CALLBACK
    CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
#endif
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (useClientCert){
        if (CyaSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS)
            err_sys("can't load client cert file, check file and run from"
                    " CyaSSL home dir");

        if (CyaSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load client private key file, check file and run "
                    "from CyaSSL home dir");
    }

    if (!usePsk) {
        if (CyaSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
                err_sys("can't load ca file, Please run from CyaSSL home dir");
    }
#endif
#if !defined(NO_CERTS)
    if (!usePsk && doPeerCheck == 0)
        CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
#endif

#ifdef HAVE_CAVIUM
    CyaSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID);
#endif

#ifdef HAVE_SNI
    if (sniHostName)
        if (CyaSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName))
                                                                 != SSL_SUCCESS)
            err_sys("UseSNI failed");
#endif

    if (benchmark) {
        /* time passed in number of connects give average */
        int times = benchmark;
        int i = 0;

        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            tcp_connect(&sockfd, host, port, doDTLS);

            ssl = CyaSSL_new(ctx);
            CyaSSL_set_fd(ssl, sockfd);
            if (CyaSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            CyaSSL_shutdown(ssl);
            CyaSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
        printf("CyaSSL_connect avg took: %8.3f milliseconds\n", avg);

        CyaSSL_CTX_free(ctx);
        ((func_args*)args)->return_code = 0;

        exit(EXIT_SUCCESS);
    }
    
    #if defined(CYASSL_MDK_ARM)
    CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
    #endif
    
    ssl = CyaSSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL object");

    CyaSSL_set_quiet_shutdown(ssl, 1) ;

    if (doDTLS) {
        SOCKADDR_IN_T addr;
        build_addr(&addr, host, port, 1);
        CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
        tcp_socket(&sockfd, 1);
    }
    else {
        tcp_connect(&sockfd, host, port, 0);
    }
    CyaSSL_set_fd(ssl, sockfd);
#ifdef HAVE_CRL
    if (CyaSSL_EnableCRL(ssl, CYASSL_CRL_CHECKALL) != SSL_SUCCESS)
        err_sys("can't enable crl check");
    if (CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
        err_sys("can't load crl, check crlfile and date validity");
    if (CyaSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
        err_sys("can't set crl callback");
#endif
    if (matchName && doPeerCheck)
        CyaSSL_check_domain_name(ssl, domain);
#ifndef CYASSL_CALLBACKS
    if (nonBlocking) {
        CyaSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&sockfd);
        NonBlockingSSL_Connect(ssl);
    }
    else if (CyaSSL_connect(ssl) != SSL_SUCCESS) {
        /* see note at top of README */
        int  err = CyaSSL_get_error(ssl, 0);
        char buffer[80];
        printf("err = %d, %s\n", err,
                                CyaSSL_ERR_error_string(err, buffer));
        err_sys("SSL_connect failed");
        /* if you're getting an error here  */
    }
#else
    timeout.tv_sec  = 2;
    timeout.tv_usec = 0;
    NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif
    showPeer(ssl);

    if (sendGET) {
        printf("SSL connect ok, sending GET...\n");
        msgSz = 28;
        strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz);
        msg[msgSz] = '\0';
    }
    if (CyaSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("SSL_write failed");

    input = CyaSSL_read(ssl, reply, sizeof(reply)-1);
    if (input > 0) {
        reply[input] = 0;
        printf("Server response: %s", reply);

        if (sendGET && (input == (sizeof(reply)-1))) {  /* get html */
            while (1) {
                input = CyaSSL_read(ssl, reply, sizeof(reply)-1);
                if (input > 0) {
                    reply[input] = 0;
                    printf("%s", reply);
                    if(input < sizeof(reply)-1)
                        break ;
                }
                else
                    break;
            }
        }
        printf("\n");
    }
    else if (input < 0) {
        int readErr = CyaSSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("CyaSSL_read failed");
    }
    
#ifdef CYASSL_CMSIS_RTOS
    osDelay(5000) ;
#endif

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            strncpy(msg, "break", 6);
            msgSz = (int)strlen(msg);
            /* try to send session close */
            CyaSSL_write(ssl, msg, msgSz);
        }
        session   = CyaSSL_get_session(ssl);
        sslResume = CyaSSL_new(ctx);
    }
#endif

    if (doDTLS == 0)            /* don't send alert after "break" command */
        CyaSSL_shutdown(ssl);  /* echoserver will interpret as new conn */
    CyaSSL_free(ssl);
    CloseSocket(sockfd);

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            SOCKADDR_IN_T addr;
            #ifdef USE_WINDOWS_API 
                Sleep(500);
            #else
                sleep(1);
            #endif
            build_addr(&addr, host, port, 1);
            CyaSSL_dtls_set_peer(sslResume, &addr, sizeof(addr));
            tcp_socket(&sockfd, 1);
        }
        else {
            tcp_connect(&sockfd, host, port, 0);
        }
        CyaSSL_set_fd(sslResume, sockfd);
        CyaSSL_set_session(sslResume, session);
       
        showPeer(sslResume);
#ifndef CYASSL_CALLBACKS
        if (nonBlocking) {
            CyaSSL_set_using_nonblock(sslResume, 1);
            tcp_set_nonblocking(&sockfd);
            NonBlockingSSL_Connect(sslResume);
        }
        else if (CyaSSL_connect(sslResume) != SSL_SUCCESS)
            err_sys("SSL resume failed");
#else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif

        if (CyaSSL_session_reused(sslResume))
            printf("reused session id\n");
        else
            printf("didn't reuse session id!!!\n");

        if (CyaSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz)
            err_sys("SSL_write failed");

        if (nonBlocking) {
            /* give server a chance to bounce a message back to client */
            #ifdef USE_WINDOWS_API
                Sleep(500);
            #else
                sleep(1);
            #endif
        }

        input = CyaSSL_read(sslResume, reply, sizeof(reply)-1);
        if (input > 0) {
            reply[input] = 0;
            printf("Server resume response: %s\n", reply);
        }

        /* try to send session break */
        CyaSSL_write(sslResume, msg, msgSz); 

        CyaSSL_shutdown(sslResume);
        CyaSSL_free(sslResume);
        CloseSocket(sockfd);
    }
#endif /* NO_SESSION_CACHE */

    CyaSSL_CTX_free(ctx);

    ((func_args*)args)->return_code = 0;

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */

    return 0;
}
Exemple #5
0
/**
 * Should be called at the beginning of the program to set up the
 * network interface.
 *
 * This function should be passed as a parameter to netif_add().
 *
 * @param[in] netif the lwip network interface structure for this netif
 * @return ERR_OK if the loopif is initialized
 *         ERR_MEM if private data couldn't be allocated
 *         any other err_t on error
 */
err_t eth_arch_enetif_init(struct netif *netif)
{
  err_t err;

  LWIP_ASSERT("netif != NULL", (netif != NULL));

  k64f_enetdata.netif = netif;

  /* set MAC hardware address */
#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE)
  netif->hwaddr[0] = MBED_MAC_ADDR_0;
  netif->hwaddr[1] = MBED_MAC_ADDR_1;
  netif->hwaddr[2] = MBED_MAC_ADDR_2;
  netif->hwaddr[3] = MBED_MAC_ADDR_3;
  netif->hwaddr[4] = MBED_MAC_ADDR_4;
  netif->hwaddr[5] = MBED_MAC_ADDR_5;
#else
  mbed_mac_address((char *)netif->hwaddr);
#endif
  netif->hwaddr_len = ETHARP_HWADDR_LEN;

  /* maximum transfer unit */
  netif->mtu = 1500;

  /* device capabilities */
  // TODOETH: check if the flags are correct below
  netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP;

  /* Initialize the hardware */
  netif->state = &k64f_enetdata;
  err = low_level_init(netif);
  if (err != ERR_OK)
    return err;

#if LWIP_NETIF_HOSTNAME
  /* Initialize interface hostname */
  netif->hostname = "lwipk64f";
#endif /* LWIP_NETIF_HOSTNAME */

  netif->name[0] = 'e';
  netif->name[1] = 'n';

  netif->output = k64f_etharp_output;
  netif->linkoutput = k64f_low_level_output;

  /* CMSIS-RTOS, start tasks */
#ifdef CMSIS_OS_RTX
  memset(k64f_enetdata.xTXDCountSem.data, 0, sizeof(k64f_enetdata.xTXDCountSem.data));
  k64f_enetdata.xTXDCountSem.def.semaphore = k64f_enetdata.xTXDCountSem.data;
#endif
  k64f_enetdata.xTXDCountSem.id = osSemaphoreCreate(&k64f_enetdata.xTXDCountSem.def, ENET_TX_RING_LEN);

  LWIP_ASSERT("xTXDCountSem creation error", (k64f_enetdata.xTXDCountSem.id != NULL));

  err = sys_mutex_new(&k64f_enetdata.TXLockMutex);
  LWIP_ASSERT("TXLockMutex creation error", (err == ERR_OK));

  /* Packet receive task */
  err = sys_sem_new(&k64f_enetdata.RxReadySem, 0);
  LWIP_ASSERT("RxReadySem creation error", (err == ERR_OK));
  sys_thread_new("receive_thread", packet_rx, netif->state, DEFAULT_THREAD_STACKSIZE, RX_PRIORITY);

  /* Transmit cleanup task */
  err = sys_sem_new(&k64f_enetdata.TxCleanSem, 0);
  LWIP_ASSERT("TxCleanSem creation error", (err == ERR_OK));
  sys_thread_new("txclean_thread", packet_tx, netif->state, DEFAULT_THREAD_STACKSIZE, TX_PRIORITY);

  /* PHY monitoring task */
  sys_thread_new("phy_thread", k64f_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_PRIORITY);

  /* Allow the PHY task to detect the initial link state and set up the proper flags */
  osDelay(10);

  return ERR_OK;
}
Exemple #6
0
void tcpIpStackTickTask(void *param)
{
   uint_t i;

   //Initialize prescalers
   uint_t nicTickPrescaler = 0;
#if (IPV4_SUPPORT == ENABLED)
   uint_t arpTickPrescaler = 0;
#endif
#if (IPV4_SUPPORT == ENABLED && IPV4_FRAG_SUPPORT == ENABLED)
   uint_t ipv4FragTickPrescaler = 0;
#endif
#if (IPV4_SUPPORT == ENABLED && IGMP_SUPPORT == ENABLED)
   uint_t igmpTickPrescaler = 0;
#endif
#if (IPV6_SUPPORT == ENABLED)
   uint_t ndpTickPrescaler = 0;
#endif
#if (IPV6_SUPPORT == ENABLED && IPV6_FRAG_SUPPORT == ENABLED)
   uint_t ipv6FragTickPrescaler = 0;
#endif
#if (IPV6_SUPPORT == ENABLED && MLD_SUPPORT == ENABLED)
   uint_t mldTickPrescaler = 0;
#endif
#if (TCP_SUPPORT == ENABLED)
   uint_t tcpTickPrescaler = 0;
#endif

   //Main loop
   while(1)
   {
      //Wait for the TCP/IP stack tick interval
      osDelay(TCP_IP_TICK_INTERVAL);

      //Update prescaler
      nicTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Handle periodic operations such as polling the link state
      if(nicTickPrescaler >= NIC_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               nicTick(&netInterface[i]);
         }

         //Clear prescaler
         nicTickPrescaler = 0;
      }

#if (IPV4_SUPPORT == ENABLED)
      //Update prescaler
      arpTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Manage ARP cache
      if(arpTickPrescaler >= ARP_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               arpTick(&netInterface[i]);
         }

         //Clear prescaler
         arpTickPrescaler = 0;
      }
#endif

#if (IPV4_SUPPORT == ENABLED && IPV4_FRAG_SUPPORT == ENABLED)
      //Update prescaler
      ipv4FragTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Handle IPv4 fragment reassembly timeout
      if(ipv4FragTickPrescaler >= IPV4_FRAG_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               ipv4FragTick(&netInterface[i]);
         }

         //Clear prescaler
         ipv4FragTickPrescaler = 0;
      }
#endif

#if (IPV4_SUPPORT == ENABLED && IGMP_SUPPORT == ENABLED)
      //Update prescaler
      igmpTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Handle IGMP related timers
      if(igmpTickPrescaler >= IGMP_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               igmpTick(&netInterface[i]);
         }

         //Clear prescaler
         igmpTickPrescaler = 0;
      }
#endif

#if (IPV6_SUPPORT == ENABLED)
      //Update prescaler
      ndpTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Manage Neighbor cache
      if(ndpTickPrescaler >= NDP_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               ndpTick(&netInterface[i]);
         }

         //Clear prescaler
         ndpTickPrescaler = 0;
      }
#endif

#if (IPV6_SUPPORT == ENABLED && IPV6_FRAG_SUPPORT == ENABLED)
      //Update prescaler
      ipv6FragTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Handle IPv4 fragment reassembly timeout
      if(ipv6FragTickPrescaler >= IPV6_FRAG_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               ipv6FragTick(&netInterface[i]);
         }

         //Clear prescaler
         ipv6FragTickPrescaler = 0;
      }
#endif

#if (IPV6_SUPPORT == ENABLED && MLD_SUPPORT == ENABLED)
      //Update prescaler
      mldTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Handle MLD related timers
      if(mldTickPrescaler >= MLD_TICK_INTERVAL)
      {
         //Loop through network interfaces
         for(i = 0; i < NET_INTERFACE_COUNT; i++)
         {
            //Make sure the interface has been properly configured
            if(netInterface[i].configured)
               mldTick(&netInterface[i]);
         }

         //Clear prescaler
         mldTickPrescaler = 0;
      }
#endif

#if (TCP_SUPPORT == ENABLED)
      //Update TCP tick prescaler
      tcpTickPrescaler += TCP_IP_TICK_INTERVAL;

      //Manage TCP related timers
      if(tcpTickPrescaler >= TCP_TICK_INTERVAL)
      {
         //TCP timer handler
         tcpTick();
         //Clear prescaler
         tcpTickPrescaler = 0;
      }
#endif
   }
}
Exemple #7
0
/** \brief  Low level output of a packet. Never call this from an
 *          interrupt context, as it may block until TX descriptors
 *          become available.
 *
 *  \param[in] netif the lwip network interface structure for this lpc_enetif
 *  \param[in] p the MAC packet to send (e.g. IP packet including MAC addresses and type)
 *  \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent
 */
static err_t lpc_low_level_output(struct netif *netif, struct pbuf *p)
{
	struct lpc_enetdata *lpc_enetif = netif->state;
	struct pbuf *q;
	u8_t *dst;
    u32_t idx, notdmasafe = 0;
	struct pbuf *np;
	s32_t dn;

	/* Zero-copy TX buffers may be fragmented across mutliple payload
	   chains. Determine the number of descriptors needed for the
	   transfer. The pbuf chaining can be a mess! */
	dn = (s32_t) pbuf_clen(p);

	/* Test to make sure packet addresses are DMA safe. A DMA safe
	   address is once that uses external memory or periphheral RAM.
	   IRAM and FLASH are not safe! */
	for (q = p; q != NULL; q = q->next)
		notdmasafe += lpc_packet_addr_notsafe(q->payload);

#if LPC_TX_PBUF_BOUNCE_EN==1
	/* If the pbuf is not DMA safe, a new bounce buffer (pbuf) will be
	   created that will be used instead. This requires an copy from the
	   non-safe DMA region to the new pbuf */
	if (notdmasafe) {
		/* Allocate a pbuf in DMA memory */
		np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
		if (np == NULL)
			return ERR_MEM;

		/* This buffer better be contiguous! */
		LWIP_ASSERT("lpc_low_level_output: New transmit pbuf is chained",
			(pbuf_clen(np) == 1));

		/* Copy to DMA safe pbuf */
		dst = (u8_t *) np->payload;
	 	for(q = p; q != NULL; q = q->next) {
			/* Copy the buffer to the descriptor's buffer */
	  		MEMCPY(dst, (u8_t *) q->payload, q->len);
		  dst += q->len;
		}
		np->len = p->tot_len;

		LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
			("lpc_low_level_output: Switched to DMA safe buffer, old=%p, new=%p\n",
			q, np));

		/* use the new buffer for descrptor queueing. The original pbuf will
		   be de-allocated outsuide this driver. */
		p = np;
		dn = 1;
	}
#else
	if (notdmasafe)
		LWIP_ASSERT("lpc_low_level_output: Not a DMA safe pbuf",
			(notdmasafe == 0));
#endif

	/* Wait until enough descriptors are available for the transfer. */
	/* THIS WILL BLOCK UNTIL THERE ARE ENOUGH DESCRIPTORS AVAILABLE */
	while (dn > lpc_tx_ready(netif))
#if NO_SYS == 0
	    osSemaphoreWait(lpc_enetif->xTXDCountSem.id, osWaitForever);
#else
		osDelay(1);
#endif

	/* Get free TX buffer index */
	idx = LPC_EMAC->TxProduceIndex;

#if NO_SYS == 0
	/* Get exclusive access */
	sys_mutex_lock(&lpc_enetif->TXLockMutex);
#endif

	/* Prevent LWIP from de-allocating this pbuf. The driver will
	   free it once it's been transmitted. */
	if (!notdmasafe)
		pbuf_ref(p);

	/* Setup transfers */
	q = p;
	while (dn > 0) {
		dn--;

		/* Only save pointer to free on last descriptor */
		if (dn == 0) {
			/* Save size of packet and signal it's ready */
			lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT |
				EMAC_TCTRL_LAST;
            lpc_enetif->txb[idx] = p;
		}
		else {
			/* Save size of packet, descriptor is not last */
			lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT;
			lpc_enetif->txb[idx] = NULL;
		}

		LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
			("lpc_low_level_output: pbuf packet(%p) sent, chain#=%d,"
			" size = %d (index=%d)\n", q->payload, dn, q->len, idx));

		lpc_enetif->ptxd[idx].packet = (u32_t) q->payload;

		q = q->next;

		idx++;
		if (idx >= LPC_NUM_BUFF_TXDESCS)
			idx = 0;
	}

	LPC_EMAC->TxProduceIndex = idx;

	LINK_STATS_INC(link.xmit);

#if NO_SYS == 0
	/* Restore access */
	sys_mutex_unlock(&lpc_enetif->TXLockMutex);
#endif

	return ERR_OK;
}
Exemple #8
0
THREAD_RETURN CYASSL_THREAD server_test(void* args)
{
    SOCKET_T sockfd   = 0;
    SOCKET_T clientfd = 0;

    SSL_METHOD* method = 0;
    SSL_CTX*    ctx    = 0;
    SSL*        ssl    = 0;

    char   msg[] = "I hear you fa shizzle!";
    char   input[80];
    int    idx;
    int    ch;
    int    version = SERVER_DEFAULT_VERSION;
    int    doCliCertCheck = 1;
    int    useAnyAddr = 0;
    int    port = yasslPort;
    int    usePsk = 0;
    int    doDTLS = 0;
    int    useNtruKey   = 0;
    int    nonBlocking  = 0;
    int    trackMemory  = 0;
    int    fewerPackets = 0;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)cliCert;
    char*  ourCert    = (char*)svrCert;
    char*  ourKey     = (char*)svrKey;
    int    argc = ((func_args*)args)->argc;
    char** argv = ((func_args*)args)->argv;

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)cliEccCert;
    ourCert    = (char*)eccCert;
    ourKey     = (char*)eccKey;
#endif
    (void)trackMemory;

    while ((ch = mygetopt(argc, argv, "?dbstnNufp:v:l:A:c:k:S:")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'd' :
                doCliCertCheck = 0;
                break;

            case 'b' :
                useAnyAddr = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_CYASSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'n' :
                useNtruKey = 1;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'p' :
                port = atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'N':
                nonBlocking = 1;
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = SSLv3_server_method();
            break;

    #ifndef NO_TLS
        case 1:
            method = TLSv1_server_method();
            break;


        case 2:
            method = TLSv1_1_server_method();
            break;

        #endif
#endif

#ifndef NO_TLS
        case 3:
            method = TLSv1_2_server_method();
            break;
#endif
                
#ifdef CYASSL_DTLS
        case -1:
            method = DTLSv1_server_method();
            break;

        case -2:
            method = DTLSv1_2_server_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = SSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (SSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("server can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (fewerPackets)
        CyaSSL_CTX_set_group_messages(ctx);

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!usePsk) {
        if (SSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                    " CyaSSL home dir");
    }
#endif

#ifdef HAVE_NTRU
    if (useNtruKey) {
        if (CyaSSL_CTX_use_NTRUPrivateKey_file(ctx, ourKey)
                                               != SSL_SUCCESS)
            err_sys("can't load ntru key file, "
                    "Please run from CyaSSL home dir");
    }
#endif

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!useNtruKey && !usePsk) {
        if (SSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                " CyaSSL home dir");
    }
#endif

    if (usePsk) {
#ifndef NO_PSK
        SSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb);
        SSL_CTX_use_psk_identity_hint(ctx, "cyassl server");
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (SSL_CTX_set_cipher_list(ctx, defaultCipherList) != SSL_SUCCESS)
                err_sys("server can't set cipher list 2");
        }
#endif
    }

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    /* if not using PSK, verify peer with certs */
    if (doCliCertCheck && usePsk == 0) {
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |
                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0);
        if (SSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from CyaSSL home dir");
    }
#endif

#ifdef OPENSSL_EXTRA
    SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    /* don't use EDH, can't sniff tmp keys */
    if (cipherList == NULL) {
        if (SSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS)
            err_sys("server can't set cipher list 3");
    }
#endif

#ifdef HAVE_SNI
    if (sniHostName) {
        if (CyaSSL_CTX_UseSNI(ctx, CYASSL_SNI_HOST_NAME, sniHostName,
                                           XSTRLEN(sniHostName)) != SSL_SUCCESS)
            err_sys("UseSNI failed");
        else
            CyaSSL_CTX_SNI_SetOptions(ctx, CYASSL_SNI_HOST_NAME,
                                                  CYASSL_SNI_ABORT_ON_MISMATCH);
    }
#endif

    ssl = SSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL");
    CyaSSL_set_quiet_shutdown(ssl, 1) ;
#ifdef HAVE_CRL
    CyaSSL_EnableCRL(ssl, 0);
    CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, CYASSL_CRL_MONITOR |
                                                     CYASSL_CRL_START_MON);
    CyaSSL_SetCRL_Cb(ssl, CRL_CallBack);
#endif
        osDelay(5000) ;
    tcp_accept(&sockfd, &clientfd, (func_args*)args, port, useAnyAddr, doDTLS);
    if (!doDTLS) 
        CloseSocket(sockfd);

    SSL_set_fd(ssl, clientfd);
    if (usePsk == 0) {
        #if !defined(NO_FILESYSTEM) && defined(OPENSSL_EXTRA)
            CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM);
        #elif !defined(NO_CERTS)
            SetDH(ssl);  /* repick suites with DHE, higher priority than PSK */
        #endif
    }
        osDelay(5000) ;
#ifndef CYASSL_CALLBACKS
    if (nonBlocking) {
        CyaSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&clientfd);
        NonBlockingSSL_Accept(ssl);
    } else if (SSL_accept(ssl) != SSL_SUCCESS) {
        int err = SSL_get_error(ssl, 0);
        char buffer[80];
        printf("error = %d, %s\n", err, ERR_error_string(err, buffer));
        err_sys("SSL_accept failed");
    }
#else
    NonBlockingSSL_Accept(ssl);
#endif
    showPeer(ssl);
        osDelay(5000) ;
    idx = SSL_read(ssl, input, sizeof(input)-1);
    if (idx > 0) {
        input[idx] = 0;
        printf("Client message: %s\n", input);

    }
    else if (idx < 0) {
        int readErr = SSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("SSL_read failed");
    }

    if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg))
        err_sys("SSL_write failed");
        
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
    
    CloseSocket(clientfd);
    ((func_args*)args)->return_code = 0;

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */

    return 0;
}
Exemple #9
0
void part2_main(void *ptr)
{
    uint32_t signals = 0;
    size_t len = 0;
    char *str = NULL;

    while (1) {
        signals = psa_wait_any(PSA_BLOCK);
        if (0 == (signals & (ROT_SRV_REVERSE_MSK | ROT_SRV_DB_TST_MSK))) {
            SPM_PANIC("returned from psa_wait_any without ROT_SRV_REVERSE_MSK or ROT_SRV_DB_TST_MSK bit on\n");
        }
        if (signals & ROT_SRV_REVERSE_MSK) {
            psa_get(ROT_SRV_REVERSE_MSK, &msg);
            switch (msg.type) {
                case PSA_IPC_CALL: {
                    if ((msg.in_size[0] + msg.in_size[1] + msg.in_size[2]) == 0) {
                        SPM_PANIC("got a zero message size to REVERSE ROT_SRV\n");
                    }

                    len = msg.in_size[0];
                    str = (char *)malloc(sizeof(char) * len);
                    if (NULL == str) {
                        SPM_PANIC("memory allocation failure\n");
                    }
                    psa_read(msg.handle, 0, str, len);
                    for (size_t i = 0; i < len / 2; i ++) {
                        char a = str[i];
                        str[i] = str[len - i - 1];
                        str[len - i - 1] = a;
                    }

                    psa_write(msg.handle, 0, str, len);
                    free(str);
                    str = NULL;
                    break;
                }
                case PSA_IPC_CONNECT:
                case PSA_IPC_DISCONNECT:
                    break;
                default:
                    SPM_PANIC("Unexpected message type %d!", (int)(msg.type));
                    break;
            }

            psa_reply(msg.handle, PSA_SUCCESS);
        } else { // -- Doorbell test

            psa_get(ROT_SRV_DB_TST_MSK, &msg);
            switch (msg.type) {
                case PSA_IPC_CALL: {
                    int32_t caller_part_id = psa_identity(msg.handle);
                    // Doorbell contract is valid only between secure partitions
                    if (PSA_NSPE_IDENTIFIER == caller_part_id) {
                        SPM_PANIC("Caller partition is non secure\n");
                    }
                    // In doorbell scenario the server first calls psa_reply()
                    psa_reply(msg.handle, PSA_SUCCESS);
                    // Then the servers waits to some driver making long calculations - imitate using osDelay()
                    osDelay(20);
                    // After work is done, ring the doorbell
                    psa_notify(caller_part_id);
                    break;
                }
                case PSA_IPC_CONNECT:
                case PSA_IPC_DISCONNECT:
                    psa_reply(msg.handle, PSA_SUCCESS);
                    break;
                default:
                    SPM_PANIC("Unexpected message type %d!", (int)(msg.type));
                    break;
            }
        }
    }
}
Exemple #10
0
error_t dnsResolve(NetInterface *interface,
   const char_t *name, HostType type, IpAddr *ipAddr)
{
   error_t error;
   systime_t delay;
   DnsCacheEntry *entry;

   //Debug message
   TRACE_INFO("Resolving host name %s (DNS resolver)...\r\n", name);

   //Acquire exclusive access to the DNS cache
   osMutexAcquire(dnsCacheMutex);

   //Search the DNS cache for the specified host name
   entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_DNS);

   //Check whether a matching entry has been found
   if(entry)
   {
      //Host name already resolved?
      if(entry->state == DNS_STATE_RESOLVED ||
         entry->state == DNS_STATE_PERMANENT)
      {
         //Return the corresponding IP address
         *ipAddr = entry->ipAddr;
         //Successful host name resolution
         error = NO_ERROR;
      }
      else
      {
         //Host name resolution is in progress...
         error = ERROR_IN_PROGRESS;
      }
   }
   else
   {
      //If no entry exists, then create a new one
      entry = dnsCreateEntry();

      //Record the host name whose IP address is unknown
      strcpy(entry->name, name);

      //Initialize DNS cache entry
      entry->type = type;
      entry->protocol = HOST_NAME_RESOLVER_DNS;
      entry->interface = interface;
      //Select primary DNS server
      entry->dnsServerNum = 0;
      //Get an ephemeral port number
      entry->port = socketGetEphemeralPort();

      //An identifier is used by the DNS client to match replies
      //with corresponding requests
      entry->id = tcpIpStackGetRand();

      //Callback function to be called when a DNS response is received
      error = udpAttachRxCallback(interface, entry->port, dnsProcessResponse, NULL);

      //Check status code
      if(!error)
      {
         //Initialize retransmission counter
         entry->retransmitCount = DNS_CLIENT_MAX_RETRIES;
         //Send DNS query
         error = dnsSendQuery(entry);

         //DNS message successfully sent?
         if(!error)
         {
            //Save the time at which the query message was sent
            entry->timestamp = osGetTickCount();
            //Set timeout value
            entry->timeout = DNS_CLIENT_INIT_TIMEOUT;
            entry->maxTimeout = DNS_CLIENT_MAX_TIMEOUT;
            //Decrement retransmission counter
            entry->retransmitCount--;

            //Switch state
            entry->state = DNS_STATE_IN_PROGRESS;
            //Host name resolution is in progress
            error = ERROR_IN_PROGRESS;
         }
         else
         {
            //Unregister callback function
            udpDetachRxCallback(interface, entry->port);
         }
      }
   }

   //Release exclusive access to the DNS cache
   osMutexRelease(dnsCacheMutex);

   //Set default polling interval
   delay = DNS_CACHE_INIT_POLLING_INTERVAL;

   //Wait the host name resolution to complete
   while(error == ERROR_IN_PROGRESS)
   {
      //Wait until the next polling period
      osDelay(delay);

      //Acquire exclusive access to the DNS cache
      osMutexAcquire(dnsCacheMutex);

      //Search the DNS cache for the specified host name
      entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_DNS);

      //Check whether a matching entry has been found
      if(entry)
      {
         //Host name successfully resolved?
         if(entry->state == DNS_STATE_RESOLVED)
         {
            //Return the corresponding IP address
            *ipAddr = entry->ipAddr;
            //Successful host name resolution
            error = NO_ERROR;
         }
      }
      else
      {
         //Host name resolution failed
         error = ERROR_FAILURE;
      }

      //Release exclusive access to the DNS cache
      osMutexRelease(dnsCacheMutex);

      //Backoff support for less aggressive polling
      delay = min(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
   }

   //Check status code
   if(error)
   {
      //Failed to resolve host name
      TRACE_INFO("Host name resolution failed!\r\n");
   }
   else
   {
      //Successful host name resolution
      TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
   }

   //Return status code
   return error;
}
Exemple #11
0
void led2_thread(void const *args) {
    while (true) {
        led2 = !led2;
        osDelay(1000);
    }
}
/**
* @brief  DHCP Process
* @param  argument: network interface
* @retval None
*/
void DHCP_thread(void const * argument)
{
  struct netif *netif = (struct netif *) argument;
  struct ip_addr ipaddr;
  struct ip_addr netmask;
  struct ip_addr gw;
  uint32_t IPaddress;
  
  for (;;)
  {
    switch (DHCP_state)
    {
    case DHCP_START:
      {
        netif->ip_addr.addr = 0;
        netif->netmask.addr = 0;
        netif->gw.addr = 0;
        IPaddress = 0;
        dhcp_start(netif);
        DHCP_state = DHCP_WAIT_ADDRESS;
      }
      break;
      
    case DHCP_WAIT_ADDRESS:
      {
        /* Read the new IP address */
        IPaddress = netif->ip_addr.addr;
        
        if (IPaddress!=0) 
        {
          DHCP_state = DHCP_ADDRESS_ASSIGNED;	
          
          /* Stop DHCP */
          dhcp_stop(netif); 
        }
        else
        {
          /* DHCP timeout */
          if (netif->dhcp->tries > MAX_DHCP_TRIES)
          {
            DHCP_state = DHCP_TIMEOUT;
            
            /* Stop DHCP */
            dhcp_stop(netif);
            
            /* Static address used */
            IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 );
            IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
            IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
            netif_set_addr(netif, &ipaddr , &netmask, &gw);
            
          }
        }
      }
      break;
      
    default: break;
    }
    
    /* wait 250 ms */
    osDelay(250);
  }
}
Exemple #13
0
/**
  * @brief  Start task
  * @param  argument: pointer that is passed to the thread function as start argument.
  * @retval None
  */
static void StartThread(void const * argument)
{
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  RCC_OscInitTypeDef RCC_OscInitStruct;
  uint32_t FLatency;
  SystemSettingsTypeDef settings;
  osTimerId lcd_timer;
       
  /* Initialize Joystick, Touch screen and LEDs */
  k_BspInit();
  k_LogInit();
  
  /* Initialize GUI */
  GUI_Init();
  WM_MULTIBUF_Enable(1);
  GUI_SelectLayer(1);
  
  /* Initialize RTC */
  k_CalendarBkupInit();
  
  /* Get General settings */
  settings.d32 = k_BkupRestoreParameter(CALIBRATION_GENERAL_SETTINGS_BKP);
    
  if(settings.b.use_180Mhz)
  {
    HAL_RCC_GetClockConfig(&RCC_ClkInitStruct, &FLatency);
    /* Select HSE as system clock source */
    RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK);
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE;
    HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1);

    HAL_RCC_GetOscConfig(&RCC_OscInitStruct);  
    RCC_OscInitStruct.PLL.PLLM = 8;
    RCC_OscInitStruct.PLL.PLLN = 360;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
    RCC_OscInitStruct.PLL.PLLQ = 7;
    HAL_RCC_OscConfig(&RCC_OscInitStruct);
    
    HAL_PWREx_EnableOverDrive();
    
    /* Select PLL as system clock source */
    RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK);
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5);
  }
  
  k_StartUp();
  
  /* Initialize Storage Units */
  k_StorageInit();
  
  /*Initialize memory pools */
  k_MemInit();
  
  /* Add Modules*/
  k_ModuleInit();
  
  k_ModuleAdd(&video_player);
  k_ModuleOpenLink(&video_player, "emf");
  k_ModuleOpenLink(&video_player, "EMF");
  k_ModuleAdd(&image_browser);  
  k_ModuleOpenLink(&image_browser, "jpg"); 
  k_ModuleOpenLink(&image_browser, "JPG");
  k_ModuleOpenLink(&image_browser, "bmp"); 
  k_ModuleOpenLink(&image_browser, "BMP");
  k_ModuleAdd(&system_info);
  k_ModuleAdd(&file_browser);
  k_ModuleAdd(&cpu_bench);
  k_ModuleAdd(&game_board);
  
  /* Create GUI task */
  osThreadDef(GUI_Thread, GUIThread, osPriorityHigh, 0, 15 * configMINIMAL_STACK_SIZE);
  osThreadCreate (osThread(GUI_Thread), NULL); 

  /* Create Touch screen Timer */
  osTimerDef(TS_Timer, TimerCallback);
  lcd_timer =  osTimerCreate(osTimer(TS_Timer), osTimerPeriodic, (void *)0);

  /* Start the TS Timer */
  osTimerStart(lcd_timer, 100);
  
  for( ;; )
  {
        /* Toggle LED3 and LED4 */
        BSP_LED_Toggle(LED3);
        BSP_LED_Toggle(LED4);    
        osDelay(250);
  }
}
Exemple #14
0
/********************************** 功能说明 **********************************
*	系统延时功能
*******************************************************************************/
void	delay( uint16_t	m_sec )
{
	osDelay( m_sec );
}
Exemple #15
0
/*----------------------------------------------------------------------------
 *   Thread 1: 'job1'
 *---------------------------------------------------------------------------*/
void job1 (void const *argument) {    /* higher priority to preempt job2     */
  while (1) {                         /* endless loop                        */
    counter1++;                       /* increment counter 1                 */
    osDelay(10);                      /* wait for timeout: 10ms              */
  }
}
Exemple #16
0
int main(void)
{

  /* USER CODE BEGIN 1 */
  osKernelInitialize();
  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  MX_USART2_UART_Init();
  MX_TIM4_Init();
  MX_TIM3_Init();
  MX_ADC1_Init();

  /* USER CODE BEGIN 2 */
//#ifdef  USE_FULL_ASSERT
#ifndef MAC_COORDINATOR
  // Board - Serial identification
  sprintf(Buf, "\x0cNUCLEO-F446 Debug Terminal\r\nVisible Light Communication "
      "Project\r\n---\r\nDEV_CONFIG=%d\r\n\r\n", DEV_CONFIG);
  HAL_UART_Transmit(&huart2, (uint8_t *) Buf, strlen(Buf), 0xffff);
#endif
//#endif
  // Initialize Optical Driver
  DRV_Init();
  // Initialize PHY layer
  PHY_Init();
  // Initialize MAC APP layer
  MAC_AppInit();
  
  // Create threads
#ifdef MAC_COORDINATOR
  tid_blinkLED = osThreadCreate (osThread(blinkLED), NULL);
#endif
  //tid_sendSerial = osThreadCreate (osThread(sendSerial), NULL);
  //tid_checkButton = osThreadCreate (osThread(checkButton), NULL);
  // Start thread execution
  osKernelStart();

  // Run codes
  DRV_RX_Start();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1) {
    osDelay(1000);
#ifdef MAC_COORDINATOR
    osSignalSet(tid_blinkLED, 0x0001);
#endif
  }
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

  /* USER CODE END 3 */

}
/*!
 @brief Thread that controls the LEDs along the arm. 
 @param *argument Unused
 @retval None
 */
void ledThread (void const *argument) {
	uint32_t led = 0;
	uint32_t delay = 0;
	while(1) {
		osMutexWait(receiver.mutexID, osWaitForever);
		delay = receiver.data[4];
		osMutexRelease(receiver.mutexID);
		
		if (delay==0) {
			GPIO_SetBits(GPIOD, GPIO_Pin_0);
			GPIO_SetBits(GPIOD, GPIO_Pin_1);
			GPIO_SetBits(GPIOD, GPIO_Pin_2);
			GPIO_SetBits(GPIOD, GPIO_Pin_3);
			GPIO_SetBits(GPIOD, GPIO_Pin_4);
			GPIO_SetBits(GPIOD, GPIO_Pin_5);
			GPIO_SetBits(GPIOD, GPIO_Pin_6);
		} else {
			GPIO_ResetBits(GPIOD, GPIO_Pin_0);
			GPIO_ResetBits(GPIOD, GPIO_Pin_1);
			GPIO_ResetBits(GPIOD, GPIO_Pin_2);
			GPIO_ResetBits(GPIOD, GPIO_Pin_3);
			GPIO_ResetBits(GPIOD, GPIO_Pin_4);
			GPIO_ResetBits(GPIOD, GPIO_Pin_5);
			GPIO_ResetBits(GPIOD, GPIO_Pin_6);
			switch (led) {
				case 0:
					GPIO_SetBits(GPIOD, GPIO_Pin_0);
					break;
				case 1:
					GPIO_SetBits(GPIOD, GPIO_Pin_1);
					break;
				case 2:
					GPIO_SetBits(GPIOD, GPIO_Pin_2);
					break;
				case 3:
					GPIO_SetBits(GPIOD, GPIO_Pin_3);
					break;
				case 4:
					GPIO_SetBits(GPIOD, GPIO_Pin_4);
					break;
				case 5:
					GPIO_SetBits(GPIOD, GPIO_Pin_5);
					break;
				case 7:
					GPIO_SetBits(GPIOD, GPIO_Pin_5);
					break;
				case 8:
					GPIO_SetBits(GPIOD, GPIO_Pin_4);
					break;
				case 9:
					GPIO_SetBits(GPIOD, GPIO_Pin_3);
					break;
				case 10:
					GPIO_SetBits(GPIOD, GPIO_Pin_2);
					break;
				case 11:
					GPIO_SetBits(GPIOD, GPIO_Pin_1);
					break;
				case 12:
					GPIO_SetBits(GPIOD, GPIO_Pin_0);
					break;
				default:
					GPIO_SetBits(GPIOD, GPIO_Pin_6);
					break;
			}
			led++;
			if (led == 12) {
				led = 0;
			}
		}
		if (delay==0) {
			osDelay(100);
		} else {
			osDelay(LED_FLASH_DELAY_SCALING*delay);
		}
	}
}
/**
  * @brief  USBH_MTP_Process 
  *         The function is for managing state machine for MTP data transfers 
  * @param  phost: Host handle
  * @retval USBH Status
  */
static USBH_StatusTypeDef USBH_MTP_Process (USBH_HandleTypeDef *phost)
{
  USBH_StatusTypeDef status = USBH_BUSY;
  MTP_HandleTypeDef *MTP_Handle =  phost->pActiveClass->pData;
  uint32_t idx = 0;
  
  switch(MTP_Handle->state)
  {
  case  MTP_OPENSESSION:
    
    status = USBH_PTP_OpenSession (phost, 1); /* Session '0' is not valid */
    
    if(status == USBH_OK)
    {
      USBH_UsrLog("MTP Session #0 Opened");
      MTP_Handle->state = MTP_GETDEVICEINFO; 
#if (USBH_USE_OS == 1)
    osMessagePut ( phost->os_event, USBH_STATE_CHANGED_EVENT, 0);
#endif      
    }
    break;
    
  case MTP_GETDEVICEINFO:
    status = USBH_PTP_GetDeviceInfo (phost, &(MTP_Handle->info.devinfo));
    
    if(status == USBH_OK)
    {
      USBH_DbgLog(">>>>> MTP Device Information");
      USBH_DbgLog("Standard version : %x", MTP_Handle->info.devinfo.StandardVersion);
      USBH_DbgLog("Vendor ExtID : %s", (MTP_Handle->info.devinfo.VendorExtensionID == 6)?"MTP": "NOT SUPPORTED");      
      USBH_DbgLog("Functional mode : %s", (MTP_Handle->info.devinfo.FunctionalMode == 0) ? "Standard" : "Vendor");
      USBH_DbgLog("Number of Supported Operation(s) : %d", MTP_Handle->info.devinfo.OperationsSupported_len);
      USBH_DbgLog("Number of Supported Events(s) : %d", MTP_Handle->info.devinfo.EventsSupported_len);  
      USBH_DbgLog("Number of Supported Proprieties : %d", MTP_Handle->info.devinfo.DevicePropertiesSupported_len); 
      USBH_DbgLog("Manufacturer : %s", MTP_Handle->info.devinfo.Manufacturer);
      USBH_DbgLog("Model : %s", MTP_Handle->info.devinfo.Model);       
      USBH_DbgLog("Device version : %s", MTP_Handle->info.devinfo.DeviceVersion); 
      USBH_DbgLog("Serial number : %s", MTP_Handle->info.devinfo.SerialNumber); 
      
      MTP_Handle->state = MTP_GETSTORAGEIDS; 
#if (USBH_USE_OS == 1)
    osMessagePut ( phost->os_event, USBH_STATE_CHANGED_EVENT, 0);
#endif      
    }
    break;
    
  case MTP_GETSTORAGEIDS:
    status = USBH_PTP_GetStorageIds (phost, &(MTP_Handle->info.storids));
    
    if(status == USBH_OK)
    {
      USBH_DbgLog("Number of storage ID items : %d", MTP_Handle->info.storids.n);
      for (idx  = 0; idx < MTP_Handle->info.storids.n; idx ++)
      {
        USBH_DbgLog("storage#%d ID : %x", idx, MTP_Handle->info.storids.Storage[idx]);
      }
      
      MTP_Handle->current_storage_unit = 0;
      MTP_Handle->state = MTP_GETSTORAGEINFO;
#if (USBH_USE_OS == 1)
    osMessagePut ( phost->os_event, USBH_STATE_CHANGED_EVENT, 0);
#endif      
    }
    break;
    
  case MTP_GETSTORAGEINFO:
    status = USBH_PTP_GetStorageInfo (phost, 
                                      MTP_Handle->info.storids.Storage[MTP_Handle->current_storage_unit], 
                                      &((MTP_Handle->info.storinfo)[MTP_Handle->current_storage_unit]));
    
    if(status == USBH_OK)
    {
      USBH_UsrLog("Volume#%lu: %s   [%s]", MTP_Handle->current_storage_unit,
                  MTP_Handle->info.storinfo[MTP_Handle->current_storage_unit].StorageDescription,
                  MTP_Handle->info.storinfo[MTP_Handle->current_storage_unit].VolumeLabel);
      if(++MTP_Handle->current_storage_unit >= MTP_Handle->info.storids.n)
      {
        MTP_Handle->state = MTP_IDLE;
        MTP_Handle->is_ready = 1;
        MTP_Handle->current_storage_unit = 0;
        MTP_Handle->params.CurrentStorageId = MTP_Handle->info.storids.Storage[0];
        
        USBH_UsrLog( "MTP Class initialized.");
        USBH_UsrLog("%s is default storage unit", MTP_Handle->info.storinfo[0].StorageDescription);
        phost->pUser(phost, HOST_USER_CLASS_ACTIVE);    
      }
#if (USBH_USE_OS == 1)
    osMessagePut ( phost->os_event, USBH_STATE_CHANGED_EVENT, 0);
#endif        
    }
    break;
  
  case  MTP_IDLE:
    USBH_MTP_Events(phost);
#if (USBH_USE_OS == 1)
    osDelay(10);
    osMessagePut ( phost->os_event, USBH_STATE_CHANGED_EVENT, 0);
#endif   
  default:
    status = USBH_OK;
    break;
  }
  return status;
}
Exemple #19
0
osStatus Thread::wait(uint32_t millisec) {
    return osDelay(millisec);
}
Exemple #20
0
/* StartTask02 function */
void StartTask02(void const * argument)
{
  /* USER CODE BEGIN StartTask02 */
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_13, GPIO_PIN_SET);
    uint8_t pData0[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000000, 0b00000000, // 2ème rangée de colones
                       0b00000000, 0b00000000, // 3ème rangée de colones
                       0b00000000, 0b00000000, // 4ème rangée de colones
                       0b00000000, 0b00000000, // 5ème rangée de colones
                       0b00000000, 0b00000000, // 6ème rangée de colones
                       0b00000000, 0b00000000, // 7ème rangée de colones
                       0b00000000, 0b00000000, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b00000001  // Selection plan
                      };
    uint8_t pData1[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000000, 0b00000000, // 2ème rangée de colones
                       0b00000000, 0b00000000, // 3ème rangée de colones
                       0b00000001, 0b11111111, // 4ème rangée de colones
                       0b00000001, 0b11111111, // 5ème rangée de colones
                       0b00000001, 0b11111111, // 6ème rangée de colones
                       0b00000000, 0b00000000, // 7ème rangée de colones
                       0b00000000, 0b00000000, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b00000010  // Selection plan
                      };
    uint8_t pData2[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000000, 0b00000000, // 2ème rangée de colones
                       0b00000001, 0b11111111, // 3ème rangée de colones
                       0b00000000, 0b00000000, // 4ème rangée de colones
                       0b00000000, 0b00000000, // 5ème rangée de colones
                       0b00000000, 0b00000000, // 6ème rangée de colones
                       0b00000001, 0b11111111, // 7ème rangée de colones
                       0b00000000, 0b00000000, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b00000100  // Selection plan
                      };
    uint8_t pData3[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000001, 0b11111111, // 2ème rangée de colones
                       0b00000000, 0b00000000, // 3ème rangée de colones
                       0b00000000, 0b00000000, // 4ème rangée de colones
                       0b00000000, 0b00000000, // 5ème rangée de colones
                       0b00000000, 0b00000000, // 6ème rangée de colones
                       0b00000000, 0b00000000, // 7ème rangée de colones
                       0b00000001, 0b11111111, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b00001000  // Selection plan
                      };
    uint8_t pData4[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000001, 0b11111111, // 2ème rangée de colones
                       0b00000000, 0b00000000, // 3ème rangée de colones
                       0b00000000, 0b00000000, // 4ème rangée de colones
                       0b00000000, 0b00000000, // 5ème rangée de colones
                       0b00000000, 0b00000000, // 6ème rangée de colones
                       0b00000000, 0b00000000, // 7ème rangée de colones
                       0b00000001, 0b11111111, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b00010000  // Selection plan
                      };
    uint8_t pData5[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000001, 0b11111111, // 2ème rangée de colones
                       0b00000000, 0b00000000, // 3ème rangée de colones
                       0b00000000, 0b00000000, // 4ème rangée de colones
                       0b00000000, 0b00000000, // 5ème rangée de colones
                       0b00000000, 0b00000000, // 6ème rangée de colones
                       0b00000000, 0b00000000, // 7ème rangée de colones
                       0b00000001, 0b11111111, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b00100000  // Selection plan
                      };
    uint8_t pData6[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000000, 0b00000000, // 2ème rangée de colones
                       0b00000001, 0b11111111, // 3ème rangée de colones
                       0b00000000, 0b00000000, // 4ème rangée de colones
                       0b00000000, 0b00000000, // 5ème rangée de colones
                       0b00000000, 0b00000000, // 6ème rangée de colones
                       0b00000001, 0b11111111, // 7ème rangée de colones
                       0b00000000, 0b00000000, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000000, 0b01000000  // Selection plan
                      };
    uint8_t pData7[] = {
                       0b00000000, 0b00000001, // 1ère rangée de colones
                       0b00000000, 0b00000001, // 2ème rangée de colones
                       0b00000000, 0b00000001, // 3ème rangée de colones
                       0b00000001, 0b11111111, // 4ème rangée de colones
                       0b00000001, 0b11111111, // 5ème rangée de colones
                       0b00000001, 0b11111111, // 6ème rangée de colones
                       0b00000000, 0b00000001, // 7ème rangée de colones
                       0b00000000, 0b00000001, // 8ème rangée de colones
                       0b00000000, 0b00000001, // 9ème rangée de colones
                       0b00000000, 0b10000000  // Selection plan
                      };
    uint8_t pData8[] = {
                       0b00000000, 0b00000000, // 1ère rangée de colones
                       0b00000000, 0b00000000, // 2ème rangée de colones
                       0b00000000, 0b00000000, // 3ème rangée de colones
                       0b00000001, 0b11111111, // 4ème rangée de colones
                       0b00000001, 0b11111111, // 5ème rangée de colones
                       0b00000001, 0b11111111, // 6ème rangée de colones
                       0b00000000, 0b00000000, // 7ème rangée de colones
                       0b00000000, 0b00000000, // 8ème rangée de colones
                       0b00000000, 0b00000000, // 9ème rangée de colones
                       0b00000001, 0b00000000  // Selection plan
                      };
  /* Infinite loop */
    uint8_t plan = 0;
    uint8_t* cercle[] = {pData0, pData1, pData2, pData3, pData4, pData5, pData6, pData7, pData8};
  for(;;)
  {
    HAL_StatusTypeDef status = HAL_SPI_Transmit(&hspi4, *(cercle+plan), 20, 15);
    while (status != HAL_OK)
        status = HAL_SPI_Transmit(&hspi4, *(cercle+plan), 20, 15);
    for (int i=0; i < 8000; i++) ; 
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET);
    for (int i=0; i < 8000; i++) ; // 40 tours de boucles == 3 µs
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET);
    plan = (plan + 1)%9;
    osDelay(10000);
  }
  /* USER CODE END StartTask02 */
}
Exemple #21
0
/** \brief  Low level init of the MAC and PHY.
 *
 *  \param[in]      netif  Pointer to LWIP netif structure
 */
static err_t low_level_init(struct netif *netif)
{
	struct lpc_enetdata *lpc_enetif = netif->state;
	err_t err = ERR_OK;

	/* Enable MII clocking */
	LPC_SC->PCONP |= CLKPWR_PCONP_PCENET;

#if defined(TARGET_LPC1768)
	LPC_PINCON->PINSEL2 = 0x50150105;                  /* Enable P1 Ethernet Pins. */
	LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005;
#elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM)
  LPC_IOCON->P1_0  &= ~0x07;    /*  ENET I/O config */
  LPC_IOCON->P1_0  |= 0x01;     /* ENET_TXD0 */
  LPC_IOCON->P1_1  &= ~0x07;
  LPC_IOCON->P1_1  |= 0x01;     /* ENET_TXD1 */
  LPC_IOCON->P1_4  &= ~0x07;
  LPC_IOCON->P1_4  |= 0x01;     /* ENET_TXEN */
  LPC_IOCON->P1_8  &= ~0x07;
  LPC_IOCON->P1_8  |= 0x01;     /* ENET_CRS */
  LPC_IOCON->P1_9  &= ~0x07;
  LPC_IOCON->P1_9  |= 0x01;     /* ENET_RXD0 */
  LPC_IOCON->P1_10 &= ~0x07;
  LPC_IOCON->P1_10 |= 0x01;     /* ENET_RXD1 */
  LPC_IOCON->P1_14 &= ~0x07;
  LPC_IOCON->P1_14 |= 0x01;     /* ENET_RX_ER */
  LPC_IOCON->P1_15 &= ~0x07;
  LPC_IOCON->P1_15 |= 0x01;     /* ENET_REF_CLK */
  LPC_IOCON->P1_16 &= ~0x07;    /* ENET/PHY I/O config */
  LPC_IOCON->P1_16 |= 0x01;     /* ENET_MDC */
  LPC_IOCON->P1_17 &= ~0x07;
  LPC_IOCON->P1_17 |= 0x01;     /* ENET_MDIO */
#endif

	/* Reset all MAC logic */
	LPC_EMAC->MAC1 = EMAC_MAC1_RES_TX | EMAC_MAC1_RES_MCS_TX |
		EMAC_MAC1_RES_RX | EMAC_MAC1_RES_MCS_RX | EMAC_MAC1_SIM_RES |
		EMAC_MAC1_SOFT_RES;
	LPC_EMAC->Command = EMAC_CR_REG_RES | EMAC_CR_TX_RES | EMAC_CR_RX_RES |
		EMAC_CR_PASS_RUNT_FRM;
	osDelay(10);

	/* Initial MAC initialization */
	LPC_EMAC->MAC1 = EMAC_MAC1_PASS_ALL;
	LPC_EMAC->MAC2 = EMAC_MAC2_CRC_EN | EMAC_MAC2_PAD_EN |
		EMAC_MAC2_VLAN_PAD_EN;
	LPC_EMAC->MAXF = EMAC_ETH_MAX_FLEN;

	/* Set RMII management clock rate to lowest speed */
	LPC_EMAC->MCFG = EMAC_MCFG_CLK_SEL(11) | EMAC_MCFG_RES_MII;
	LPC_EMAC->MCFG &= ~EMAC_MCFG_RES_MII;

	/* Maximum number of retries, 0x37 collision window, gap */
	LPC_EMAC->CLRT = EMAC_CLRT_DEF;
	LPC_EMAC->IPGR = EMAC_IPGR_P1_DEF | EMAC_IPGR_P2_DEF;

#if LPC_EMAC_RMII
	/* RMII setup */
	LPC_EMAC->Command = EMAC_CR_PASS_RUNT_FRM | EMAC_CR_RMII;
#else
	/* MII setup */
	LPC_EMAC->CR = EMAC_CR_PASS_RUNT_FRM;
#endif

	/* Initialize the PHY and reset */
    err = lpc_phy_init(netif, LPC_EMAC_RMII);
	if (err != ERR_OK)
 		return err;

	/* Save station address */
	LPC_EMAC->SA2 = (u32_t) netif->hwaddr[0] |
		(((u32_t) netif->hwaddr[1]) << 8);
	LPC_EMAC->SA1 = (u32_t) netif->hwaddr[2] |
		(((u32_t) netif->hwaddr[3]) << 8);
	LPC_EMAC->SA0 = (u32_t) netif->hwaddr[4] |
		(((u32_t) netif->hwaddr[5]) << 8);

	/* Setup transmit and receive descriptors */
	if (lpc_tx_setup(lpc_enetif) != ERR_OK)
		return ERR_BUF;
	if (lpc_rx_setup(lpc_enetif) != ERR_OK)
		return ERR_BUF;

	/* Enable packet reception */
#if IP_SOF_BROADCAST_RECV
	LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN | EMAC_RFC_BCAST_EN | EMAC_RFC_MCAST_EN;
#else
	LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN;
#endif

	/* Clear and enable rx/tx interrupts */
	LPC_EMAC->IntClear = 0xFFFF;
	LPC_EMAC->IntEnable = RXINTGROUP | TXINTGROUP;

	/* Enable RX and TX */
	LPC_EMAC->Command |= EMAC_CR_RX_EN | EMAC_CR_TX_EN;
	LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN;

	return err;
}
Exemple #22
0
 /*----------------------------------------------------------------------------
*      Thread  'LED_Thread': Toggles LED
 *---------------------------------------------------------------------------*/
	void Thread_LED (void const *argument) {
		while(1){
				osDelay(1000);
				HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_12);
			}
	}
Exemple #23
0
/* StartDefaultTask function */
void StartDefaultTask(void const * argument)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    uint8_t flag_buttom_press = 0;




    /* USER CODE BEGIN 5 */
    /* Infinite loop */

    /*Configure GPIO pins : PB15 PB14 */
    GPIO_InitStruct.Pin = GPIO_PIN_15|GPIO_PIN_14;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /*Configure GPIO pin : PA8 */
    GPIO_InitStruct.Pin = GPIO_PIN_8;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);

    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);//enable MMA7264


    while(1)
    {
        Work_with_ADC();
//		HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_15);
        LM75_RW();
        osDelay(100);
        l3g4200_temp = L3G4200_ReadReg(L3GD20_REG_WHO_AM_I);


        if ((HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12) == 1) && (flag_buttom_press == 0))
        {
            HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_14);
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
            flag_buttom_press = 1;
        }
        if ((HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12) == 0) && (flag_buttom_press == 1))
        {
            flag_buttom_press = 0;
            HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET);
        }
    }

//  for(;;)
//  {
//		HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_15);
//    osDelay(1000);
//
//		if ((HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12) == 1) && (flag_buttom_press == 0))
//			{
//			  HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_14);
//				flag_buttom_press = 1;
//			}
//		if ((HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12) == 0) && (flag_buttom_press == 1))
//			flag_buttom_press = 0;
//
//  }
    /* USER CODE END 5 */
}
Exemple #24
0
/**
  * @brief  DHCP Process
* @param  argument: network interface
  * @retval None
  */
void dhcp_process(void const * argument)
{
  struct netif *netif = (struct netif *) argument;
  struct ip_addr ipaddr;
  struct ip_addr netmask;
  struct ip_addr gw;
  uint32_t IPaddress = 0;
  int mscnt =0;
  netif->ip_addr.addr = 0;
  netif->netmask.addr = 0;
  netif->gw.addr = 0;
  dhcp_start(netif);
  
  DHCP_state = DHCP_WAIT_ADDRESS;

  
  // int DHCP_state = DHCP_START;
  while( 1 )
    {
      osDelay(DHCP_FINE_TIMER_MSECS);
      dhcp_fine_tmr();
      
      mscnt += DHCP_FINE_TIMER_MSECS;
      if (mscnt >= DHCP_COARSE_TIMER_SECS*1000) {
        dhcp_coarse_tmr();
        mscnt = 0;
      }
      
      switch (DHCP_state)
        {
        case DHCP_WAIT_ADDRESS:
          {        
            /* Read the new IP address */
            IPaddress = netif->ip_addr.addr;
            
            if (IPaddress!=0) 
              {
                dhcp_renew(netif);
                DHCP_state = DHCP_ADDRESS_ASSIGNED;
                
#if 1             
                uint8_t iptab[4];
                char iptxt[80];
                
                iptab[0] = (uint8_t)(IPaddress >> 24);
                iptab[1] = (uint8_t)(IPaddress >> 16);
                iptab[2] = (uint8_t)(IPaddress >> 8);
                iptab[3] = (uint8_t)(IPaddress);
                
                
                sprintf(iptxt, "IP address assigned by a DHCP server: %d.%d.%d.%d", iptab[3], iptab[2], iptab[1], iptab[0]);       
                WriteConsole ("address IP affecté\n");
#endif        
                return;
              }
            else
              {
                /* DHCP timeout */
                if (netif->dhcp->tries > MAX_DHCP_TRIES)
                  {
                    DHCP_state = DHCP_TIMEOUT;
                    
                    /* Stop DHCP */
                    dhcp_stop(netif);
                    
                    /* Static address used */
                    IP4_ADDR(&ipaddr, IP_ADDR0 ,IP_ADDR1 , IP_ADDR2 , IP_ADDR3 );
                    IP4_ADDR(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
                    IP4_ADDR(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
                    netif_set_addr(netif, &ipaddr , &netmask, &gw);
                    
                return;                    
                    
#if CONSOLE          
                    char iptxt[80];
                    sprintf((char*)iptxt, "%Static IP address  : d.%d.%d.%d", IP_ADDR0, IP_ADDR1, IP_ADDR2, IP_ADDR3);
                    WriteConsole("DHCP timeout !!\n");
                    WriteConsole(iptxt);      
#endif            
                  }
                else
                  netif->dhcp->tries++;
              }
          }
          break;
          
        default: break;
        }
Exemple #25
0
/**
  * @brief  SSL client task.
  * @param  pvParameters not used
  * @retval None
  */
void ssl_client(void const * argument)
{
  int ret, len, server_fd;
  unsigned char buf[1024];
  ssl_context ssl;
  x509_cert cacert;
  
  memset( &ssl, 0, sizeof( ssl_context ) );
  memset( &cacert, 0, sizeof( x509_cert ) );
  
  /*
  *  Initialize certificates
  */
  printf( "  . Loading the CA root certificate ..." );
  
#if defined(POLARSSL_CERTS_C)
  ret = x509parse_crt( &cacert, (const unsigned char *) test_ca_crt,
                      strlen( test_ca_crt ) );
#else
  ret = 1;
  printf("POLARSSL_CERTS_C not defined.");
#endif
  
  if( ret < 0 )
  {
    printf( " failed\n  !  x509parse_crt returned -0x%x\n\n", -ret );
    goto exit;
  }
  
  printf( " ok (%d skipped)\n", ret );
  
  /* Start the connection */
  do
  {
    printf(( "\n\rSSL : Start the connection \n\r"));
    printf("\n\rConnecting to tcp/%s/ Port:%4d...", SSL_SERVER_NAME, SSL_SERVER_PORT); 
    
    /* Bint the connection to SSL server port */
    ret = net_connect(&server_fd, SSL_SERVER_NAME, SSL_SERVER_PORT);
    if(ret != 0)
    {
      /* Connection to SSL server failed */
      printf(" failed \n\r ! net_connect returned %d\n\r", -ret);
      
      /* Wait 500 ms until next retry */
      vTaskDelay(500);
    } 
  }while(ret!=0);
  
  printf( " ok\n\r" );
  
  /*
  * 2. Setup stuff
  */
  printf( "  . Setting up the SSL/TLS structure..." );
  
  if( ( ret = ssl_init( &ssl ) ) != 0 )
  {
    printf( " failed\n  ! ssl_init returned %d\n\n\r", ret );
    goto exit;
  }
  
  printf( " ok\n\r" );
  
  ssl_set_endpoint( &ssl, SSL_IS_CLIENT );
  ssl_set_authmode( &ssl, SSL_VERIFY_OPTIONAL );
  ssl_set_ca_chain( &ssl, &cacert, NULL, "PolarSSL Server 1" );
  
  ssl_set_rng( &ssl, RandVal , NULL );
  ssl_set_dbg( &ssl, my_debug, NULL);
  ssl_set_bio( &ssl, net_recv, &server_fd,
              net_send, &server_fd );
  
  /* Set max ssl version to TLS v1.1 because TLS v1.2 needs SHA-256 for HASH
     which is not supported by STM32F417xx Hardware*/
  ssl_set_max_version( &ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_2);
  
  /*
  * Handshake
  */
  printf( "  . Performing the SSL/TLS handshake..." );
  
  while( ( ret = ssl_handshake( &ssl ) ) != 0 )
  {
    if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
    {
      printf( " failed\n  ! ssl_handshake returned -0x%x\n\n\r", -ret );
      goto exit;
    }
  }
  
  printf( " ok\n\r" );
  
  /*
  * Verify the server certificate
  */
  printf( "\n\r  . Verifying peer X.509 certificate..." );
  
  if( ( ret = ssl_get_verify_result( &ssl ) ) != 0 )
  {
    printf( " failed\n\r" );
    
    if( ( ret & BADCERT_EXPIRED ) != 0 )
      printf( "  ! server certificate has expired\n" );
    
    if( ( ret & BADCERT_REVOKED ) != 0 )
      printf( "  ! server certificate has been revoked\n" );
    
    if( ( ret & BADCERT_CN_MISMATCH ) != 0 )
      printf( "  ! CN mismatch (expected CN=%s)\n", "PolarSSL Server 1" );
    
    if( ( ret & BADCERT_NOT_TRUSTED ) != 0 )
      printf( "  ! self-signed or not signed by a trusted CA\n" );
    
    printf( "\n\r" );
  }
  else
    printf( " ok\n\r" );
  
  /*
  * Write the GET request
  */
  printf( "  > Write to server:" );
  
  len = sprintf( (char *) buf, GET_REQUEST );
  
  while( ( ret = ssl_write( &ssl, buf, len ) ) <= 0 )
  {
    if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
    {
      printf( " failed\n  ! ssl_write returned %d\n\n\r", ret );
      goto exit;
    }
  }
  
  len = ret;
  printf( " %d bytes written\n\n\r%s", len, (char *) buf );
  
  /*
  * Read the HTTP response
  */
  printf( "  < Read from server:" );
  
  do
  {
    len = sizeof( buf ) - 1;
    memset( buf, 0, sizeof( buf ) );
    ret = ssl_read( &ssl, buf, len );
    
    if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
      continue;
    
    if( ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY )
      break;
    
    if( ret < 0 )
    {
      printf( "failed\n\r  ! ssl_read returned %d\n\n\r", ret );
      break;
    }
    
    if( ret == 0 )
    {
      printf( "\n\nEOF\n\n\r" );
      break;
    }
    
    len = ret;
    printf( " %d bytes read\n\n\r%s", len, (char *) buf );
  }
  while( 1 );
  
exit:

#ifdef POLARSSL_ERROR_C
  if( ret != 0 )
  {
    char error_buf[100];
    error_strerror( ret, error_buf, 100 );
    printf("Last error was: %d - %s\n\n\r", ret, error_buf );
  }
#endif
  
  x509_free( &cacert );
  net_close( server_fd );
  ssl_free( &ssl );
  
  memset( &ssl, 0, sizeof( ssl ) );
  
  /* Infinite loop */
  for( ;; ) 
  {
    /* Toggle LED1 */
    BSP_LED_Toggle(LED1);
    
    /* Insert 400 ms delay */
    osDelay(400);
  }
}
Exemple #26
0
void delayThread(void const *argument) {
  while(1) {
    osDelay(500);
    osSemaphoreRelease(semid);
  }
}
Exemple #27
0
/*---------------------------------------------------------------------------
     TITLE	: begin
     WORK	:
     ARG	:
     RET	:
---------------------------------------------------------------------------*/
void SkyRover::delay( int32_t delay_data ) 
{
	osDelay( delay_data );
}
/**
  * @brief  Callback routine of the dialog
  * @param  pMsg: pointer to a data structure of type WM_MESSAGE
  * @retval None
  */
static void _cbDialog(WM_MESSAGE * pMsg) {
  WM_HWIN  hItem;
  int Id, NCode;

  static uint8_t sel = 0;
  
  switch (pMsg->MsgId) {
  case WM_INIT_DIALOG:

    memset(Video_Path, 0, 256);   
    
    hItem = BUTTON_CreateEx(574, 0, 65, 65, pMsg->hWin, WM_CF_SHOW, 0, ID_BUTTON_EXIT);
    WM_SetCallback(hItem, _cbButton_exit); 
    
    hItem = ST_AnimatedIconView_CreateEx(100, 
                                         70, 
                                         LCD_GetXSize() - 0, 
                                         LCD_GetYSize() - 30, 
                                         pMsg->hWin, 
                                         WM_CF_SHOW | WM_CF_HASTRANS ,
                                         0,
                                         ID_ICONVIEW_SUBMENU, 
                                         200, 
                                         250, 5, 5);    
    
    
    ST_AnimatedIconView_SetDualFont(hItem, GUI_FONT_20_1, GUI_FONT_20_1);
    
    ST_AnimatedIconView_SetSpace(hItem, GUI_COORD_Y, 5);
    ST_AnimatedIconView_SetSpace(hItem, GUI_COORD_X, 25);
    ST_AnimatedIconView_SetFrame(hItem, GUI_COORD_Y, 10);
    ST_AnimatedIconView_SetFrame(hItem, GUI_COORD_X, 5);
    
    ST_AnimatedIconView_SetSel(hItem, -1);
    
    ST_AnimatedIconView_SetTextColor(hItem, ICONVIEW_CI_UNSEL, 0x00DCA939);
    ST_AnimatedIconView_SetBkColor(hItem, ICONVIEW_CI_UNSEL, GUI_WHITE);
    ST_AnimatedIconView_SetBkColor(hItem, ICONVIEW_CI_SEL, GUI_WHITE);
    
    ST_AnimatedIconView_SetDualTextColor(hItem, ICONVIEW_CI_SEL, 0x00DCA939, 0x00522000);  
    
    ST_AnimatedIconView_AddIcon(hItem, open_file, 0, "Play video");   
    ST_AnimatedIconView_AddIcon(hItem, add_video, 0, "Add to playlist");    
    
    break;     

  case WM_PAINT: 
    GUI_SetColor(GUI_BLACK);
    GUI_DrawLine(639, 0, 639, 480);   

    break;
    
  case WM_NOTIFY_PARENT:
    Id    = WM_GetId(pMsg->hWinSrc);    /* Id of widget */
    NCode = pMsg->Data.v;               /* Notification code */   
    
    switch(Id) {
    case ID_BUTTON_EXIT: 
      switch(NCode) {
      case WM_NOTIFICATION_RELEASED:
        GUI_EndDialog(pMsg->hWin, 0);
        break;
      }
      break; 
      
      
    case ID_ICONVIEW_SUBMENU: 
      switch(NCode) {
      case WM_NOTIFICATION_RELEASED:      
        sel = ST_AnimatedIconView_GetSel(pMsg->hWinSrc);
        
        if(sel == 0)
        {

          osDelay(100);  
          /* Playlist not empty, so start play first item */
          if(VideoList.ptr > 0)
          {  
            GUI_SetLayerVisEx (1, 1);
            GUI_SelectLayer(1); 
            playbackwin = WM_CreateWindowAsChild(-1, 0, 640, 480, WM_GetDesktopWindowEx(1), WM_CF_SHOW, _cbplaybackwin , 0);
            WM_CreateWindowAsChild(0, 70, 640, 300, WM_GetDesktopWindowEx(1), WM_CF_SHOW | WM_CF_HASTRANS, _cbTouch , 0);             
            GUI_SelectLayer(0);
            _StartPlay(&hvideo, (char *)VideoList.file[0].name, &Video_File, 0, 0);
            VideoPlayer_State = VIDEO_PLAY;
            hFrame = WM_CreateWindowAsChild(-1, 0, 640, 480,pMsg->hWin, WM_CF_SHOW, _cbVideoWindow , 0);    
            GUI_SelectLayer(1);
            
          }
          else
          {/* There is no item yet in the playlist: Show hint message */
            hItem = GUI_CreateDialogBox(_aFileInfoDialogCreate, 
                                GUI_COUNTOF(_aFileInfoDialogCreate), 
                                _cbFileInfoDialog, 
                                pMsg->hWin, 
                                100, 
                                80);
            WM_MakeModal(hItem);
          }
        }
        else /* Add file to playlist icon item action */
        {
            hItem = GUI_CreateDialogBox(_aPlaylistDialogCreate, 
                                GUI_COUNTOF(_aPlaylistDialogCreate), 
                                _cbPlaylistDialog, 
                                pMsg->hWin, 
                                100, 
                                80);
            WM_MakeModal(hItem);
        }
        break;
      }
      break;
    }
    break;
  default:
    WM_DefaultProc(pMsg);
    break;
  }    
}
Exemple #29
0
netTaskErr getEpochTime(void)
{
	uint8_t count;
	netTaskErr result = errOK;
	netStatus sntpStatus,
		dnsStatus;
	osEvent statusNtpWait,
		statusDnsWait;
	
	// getting IP of NTP server
	for (count = 0; count < DNS_WAIT_TRIES; count++)
	{
		osSignalClear(netTaskId, FLAG_DNS_RESOLVED);
		dnsStatus = get_host_by_name (ntpHostName, dnsCBack);
		if (dnsStatus == netOK)
		{
			statusDnsWait = osSignalWait(FLAG_DNS_RESOLVED, DNS_TIMEOUT_MS);
			if ((statusDnsWait.status == osEventSignal) &&
				((ntpHostIP[0] != 0) ||
				(ntpHostIP[1] != 0) ||
				(ntpHostIP[2] != 0) ||
				(ntpHostIP[3] != 0))
			)
			{
				result = errOK;
				break;
			}
			else
			{
				osSignalClear(netTaskId, FLAG_DNS_RESOLVED);
				result = errDnsTOut;
			}
		}
		else
		{
			result = errDnsResolve;
		}
		osDelay(DNS_WAIT_DELAY_MS);
	}
	
	if (result != errOK)
		return result;
	
	// requesting Unix time from NTP server
	for (count = 0; count < SNTP_WAIT_TRIES; count++)
	{
		osSignalClear(netTaskId, FLAG_UDP_PACKET_RECV);
		sntpStatus = sntp_get_time (&ntpHostIP[0], sntpCBack);
		if (sntpStatus == netOK)
		{
			statusNtpWait = osSignalWait(FLAG_UDP_PACKET_RECV, UDP_TIMEOUT_MS);
			if ((statusNtpWait.status == osEventSignal) && (ntpEpochTime != 0))
			{
				result = errOK;
				break;
			}
			else
			{
				osSignalClear(netTaskId, FLAG_UDP_PACKET_RECV);
				result = errNtpCBackTOut;
			}
		}
		else
		{
			result = errNtpNotReady; // SNTP not ready or bad parameters.
		}
		osDelay(SNTP_WAIT_DELAY_MS);
	}
	
	return result;
}
Exemple #30
0
/* StartTaskFATFS function */
void StartTaskFATFS(void const * argument)
{
  /* USER CODE BEGIN StartTaskFATFS */
  /* Infinite loop */
	UINT count = 0;
uint32_t i = 1;
static	FATFS fileSystem;
static	FIL testFile;
	FRESULT res = FR_OK;
	char buf[100];
	sprintf(gbuf, "fat run");
			//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
	
	do{
	osDelay(1000);
//	sprintf(SD_Path,"0:/\0");
	res = f_mount(&fileSystem, SD_Path, 1);
		sprintf(gbuf, "fat mnt %i",res);
		
    osDelay(1000);
	//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);

	/*if(res == FR_NO_FILESYSTEM){ 
		res = f_mkfs("", 0, 0);
		sprintf(gbuf, "fat mkfs %i",res);
		
    osDelay(1000);
		//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
		
		res = f_mount(&fileSystem, SD_Path, 1);
		sprintf(gbuf, "fat mnt %i",res);
		
    osDelay(1000);
	//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
	
}*/
	}while (res!= FR_OK);
	
			HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
  res = f_open(&testFile, "testfile.txt", FA_OPEN_ALWAYS | FA_READ |FA_WRITE );
			sprintf(gbuf, "fat open %i",res);
	
    osDelay(1000);
			//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
	/*uint16_t tmp = f_size(&testFile);
	f_lseek(&testFile, tmp);
			*/
	for(;;)
  {
		//if(i > 100000) vTaskDelete(TaskFATFSHandle);
		if(i%100 == 0){
			sprintf(&gbuf[9], "fat wr %i", i);
			
    osDelay(1000);
			//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
		}
		memset(buf,0,100);
		sprintf(buf, "%lu\r\n", i++);
    res = f_write(&testFile, buf, strlen(buf), &count);
		if( res != FR_OK) break;
		f_sync(&testFile);
    //f_close(&testFile);
    osDelay(10);
  }
  /* USER CODE END StartTaskFATFS */
}