예제 #1
0
static int StartSerialSock(unsigned short port, unsigned int slot)
{
    if(!IS_IP_ACQUIRED(wifi_state.status)) {RETURN_ERROR(ERROR_UNKNOWN, "Uninit fail");}
    if(IS_SOCK_STARTED(slot)) {RETURN_ERROR(ERROR_UNKNOWN, "Uninit fail");}

    LOG(LOG_VERBOSE, "Starting socket %d on port %d...", slot, port);

    int retval;

    socket_state[slot].addr_local.sin_family = SL_AF_INET;
    socket_state[slot].addr_local.sin_port = sl_Htons(port);
    socket_state[slot].addr_local.sin_addr.s_addr = 0;

    socket_state[slot].parent_id = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0);
    if(socket_state[slot].parent_id < 0) {RETURN_ERROR(socket_state[slot].parent_id, "Socket create fail");}

    retval = sl_Bind(socket_state[slot].parent_id, (SlSockAddr_t*)&(socket_state[slot].addr_local), sizeof(SlSockAddrIn_t));
    if(retval < 0){
        sl_Close(socket_state[slot].parent_id);
        RETURN_ERROR(retval, "Socket bind fail");
    }

    retval = ListenSerialSock(slot);

    LOG(LOG_VERBOSE, "Socket started.");

    socket_state[slot].status = SOCKET_STARTED;
    return RET_SUCCESS;
}
예제 #2
0
static bool telnet_create_socket (void) {
    SlSockNonblocking_t nonBlockingOption;
    sockaddr_in         sServerAddress;
    _i16 result;

    // Open a socket for telnet
    ASSERT ((telnet_data.sd = sl_Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) > 0);
    if (telnet_data.sd > 0) {
        // add the socket to the network administration
        modusocket_socket_add(telnet_data.sd, false);

        // Enable non-blocking mode
        nonBlockingOption.NonblockingEnabled = 1;
        ASSERT ((result = sl_SetSockOpt(telnet_data.sd, SOL_SOCKET, SL_SO_NONBLOCKING, &nonBlockingOption, sizeof(nonBlockingOption))) == SL_SOC_OK);

        // Bind the socket to a port number
        sServerAddress.sin_family = AF_INET;
        sServerAddress.sin_addr.s_addr = INADDR_ANY;
        sServerAddress.sin_port = htons(TELNET_PORT);

        ASSERT ((result |= sl_Bind(telnet_data.sd, (const SlSockAddr_t *)&sServerAddress, sizeof(sServerAddress))) == SL_SOC_OK);

        // Start listening
        ASSERT ((result |= sl_Listen (telnet_data.sd, TELNET_MAX_CLIENTS)) == SL_SOC_OK);

        if (result == SL_SOC_OK) {
            return true;
        }
        servers_close_socket(&telnet_data.sd);
    }

    return false;
}
예제 #3
0
파일: starter1.c 프로젝트: manavm/Classes
  // "Embedded Systems: Real Time Interfacing to ARM Cortex M Microcontrollers",
  // ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2014, Volume 2, Program 11.3
int main3(void){
  UINT8             IsDHCP = 0;
  _NetCfgIpV4Args_t ipV4;
  SlSockAddrIn_t    Addr, LocalAddr;
  UINT16            AddrSize = 0;
  INT16             SockID = 0;
  INT16             Status = 1;  // ok
  UINT32            data;
  unsigned char     len = sizeof(_NetCfgIpV4Args_t);
  initClk();        // PLL 50 MHz, ADC needs PPL active           16
  ST7735_InitR(INITR_REDTAB);                  // Initialize      17
  ST7735_OutString("Internet of Things\n");    //                 18
  ST7735_OutString("Embedded Systems\n");      //                 19
  ST7735_OutString("Vol. 2, Valvano");         //                 20
  ST7735_PlotClear(0,4095);  // range from 0 to 4095              21
  sl_Start(0, 0, 0); // Initializing the CC3100 device            22
  WlanConnect();     // connect to AP                             23
  sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len,   //     24
               (unsigned char *)&ipV4);                    //     25
  LocalAddr.sin_family = SL_AF_INET;                       //     26
  LocalAddr.sin_port = sl_Htons((UINT16)PORT_NUM);         //     27
  LocalAddr.sin_addr.s_addr = 0;                           //     28
  AddrSize = sizeof(SlSockAddrIn_t);                       //     29
  while(1){
    SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);       //     31   
    Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr,   //     32
                       AddrSize);                          //     33
    Status = sl_RecvFrom(SockID, uBuf, BUF_SIZE, 0,        //     34
          (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize );//     35
    if((uBuf[0]==ATYPE)&&(uBuf[1]== '=')){                 //     36
      int i,bOk; uint32_t place;                           //     37
      data = 0; bOk = 1;                                   //     38
      i=4;  // ignore possible negative sign                      39
      for(place = 1000; place; place = place/10){          //     40
        if((uBuf[i]&0xF0)==0x30){ // ignore spaces                41
          data += place*(uBuf[i]-0x30);                    //     42
        }else{                                             //     43
          if((uBuf[i]&0xF0)!= ' '){                        //     44
            bOk = 0;                                       //     45
          }                                                //     46
        }                                                  //     47
        i++;                                               //     48
      }                                                    //     49
      if(bOk){                                             //     50
        ST7735_PlotLine(data);                             //     51
        ST7735_PlotNextErase();                            //     51
      }
    }
  }
}
예제 #4
0
//--tested, working--//
uint8_t WiFiUDP::begin(uint16_t port)
{
    
    //
    //get a socket from the WiFiClass (convoluted method from the arduino library)
    //
    int socketIndex = WiFiClass::getSocket();
    if (socketIndex == NO_SOCKET_AVAIL) {
        return 0;
    }
    
    //
    //get a socket handle from the simplelink api and make sure it's valid
    //
    int socketHandle = sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, SL_IPPROTO_UDP);
    if (socketHandle < 0) {
        return 0;
    }
    
    //
    //bind the socket to the requested port and check for success
    //if failure, gracefully close the socket and return
    //
    SlSockAddrIn_t portAddress;
    portAddress.sin_family = SL_AF_INET;
    portAddress.sin_port = sl_Htons(port);
    portAddress.sin_addr.s_addr = 0;
    int iRet = sl_Bind(socketHandle, (SlSockAddr_t*)&portAddress, sizeof(portAddress));
    if (iRet < 0) {
        sl_Close(socketHandle);
        return 0;
    }
    
    //
    //now that simplelink api calls are done, set the object's variables
    //
    _socketIndex = socketIndex;
    WiFiClass::_handleArray[socketIndex] = socketHandle;
    WiFiClass::_portArray[socketIndex] = port;
    WiFiClass::_typeArray[socketIndex] = TYPE_UDP_PORT;
    return 1;
}
예제 #5
0
/*
 * ::bind()
 */
int bind(int s, const struct sockaddr *address, socklen_t address_len)
{
    SlSockAddr_t sl_address;
    switch (address->sa_family)
    {
        case AF_INET:
            sl_address.sa_family = SL_AF_INET;
            break;
        case AF_INET6:
            sl_address.sa_family = SL_AF_INET6;
            break;
        case AF_PACKET:
            sl_address.sa_family = SL_AF_PACKET;
            break;
        default:
            errno = EAFNOSUPPORT;
            return -1;
    }

    memcpy(sl_address.sa_data, address->sa_data, sizeof(sl_address.sa_data));

    int result = sl_Bind(s, &sl_address, address_len);

    if (result < 0)
    {
        switch (result)
        {
            default:
                errno = EINVAL;
                break;
            case SL_POOL_IS_EMPTY:
                errno = ENOMEM;
        }
        return -1;
    }
 
    return 0;  
}
예제 #6
0
/*
 * ::bind()
 */
int bind(int socket, const struct sockaddr *address, socklen_t address_len)
{
    SlSockAddr_t sl_address;
    sl_address.sa_family = address->sa_family;
    memcpy(sl_address.sa_data, address->sa_data, sizeof(sl_address.sa_data));

    int result = sl_Bind(socket, &sl_address, address_len);

    if (result < 0)
    {
        switch (result)
        {
            default:
                errno = EINVAL;
                break;
            case SL_POOL_IS_EMPTY:
                errno = ENOMEM;
        }
        return -1;
    }
 
    return 0;  
}
예제 #7
0
파일: main.c 프로젝트: dlugaz/All
//****************************************************************************
//
//! \brief Opening a server side socket and receiving data
//!
//! This function opens a TCP socket in Listen mode and waits for an incoming
//! TCP connection. If a socket connection is established then the function
//! will try to read 1000 TCP packets from the connected client.
//!
//! \param[in]      port number on which the server will be listening on
//!
//! \return         0 on success, -1 on Error.
//!
//! \note           This function will wait for an incoming connection till one
//!                 is established
//
//****************************************************************************
static int BsdTcpServer(unsigned short Port)
{
    SlSockAddrIn_t  Addr;
    SlSockAddrIn_t  LocalAddr;

    int             idx;
    int             AddrSize;
    int             SockID;
    int             Status;
    int             newSockID;
    long            LoopCount = 0;
    long            nonBlocking = 1;

    for (idx=0 ; idx<BUF_SIZE ; idx++)
    {
        uBuf.BsdBuf[idx] = (char)(idx % 10);
    }

    LocalAddr.sin_family = SL_AF_INET;
    LocalAddr.sin_port = sl_Htons((unsigned short)Port);
    LocalAddr.sin_addr.s_addr = 0;

    SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    ASSERT_ON_ERROR(SockID);

    AddrSize = sizeof(SlSockAddrIn_t);
    Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize);
    if( Status < 0 )
    {
        /* error */
        sl_Close(SockID);
        ASSERT_ON_ERROR(Status);
    }

    Status = sl_Listen(SockID, 0);
    if( Status < 0 )
    {
        sl_Close(SockID);
        ASSERT_ON_ERROR(Status);
    }

    Status = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING,
                           &nonBlocking, sizeof(nonBlocking));
    ASSERT_ON_ERROR(Status);

    newSockID = SL_EAGAIN;

    while( newSockID < 0 &&  IS_IP_ACQUIRED(g_ulStatus))
    {
        newSockID = sl_Accept(SockID, ( struct SlSockAddr_t *)&Addr,
                              (SlSocklen_t*)&AddrSize);
        if( newSockID == SL_EAGAIN )
        {
            /* Wait for 1 ms */
            Delay(1);
        }
        else if( newSockID < 0 )
        {
            sl_Close(SockID);
            ASSERT_ON_ERROR(newSockID);
        }
    }

    if(! IS_IP_ACQUIRED(g_ulStatus))
    {
        return CLIENT_DISCONNECTED;
    }
    // run 'iperf -c <device IP> -i 1 -t 10000'  command on PC/Smartphone
    while (LoopCount < TCP_PACKET_COUNT)
    {
        Status = sl_Recv(newSockID, uBuf.BsdBuf, BUF_SIZE, 0);
        if( Status <= 0 )
        {
            /* error */
            ASSERT_ON_ERROR(sl_Close(newSockID));
            ASSERT_ON_ERROR(sl_Close(SockID));
            ASSERT_ON_ERROR(Status);
        }
        LoopCount++;
    }
    GPIO_IF_LedOn(MCU_EXECUTE_SUCCESS_IND);
    ASSERT_ON_ERROR(sl_Close(newSockID));
    ASSERT_ON_ERROR(sl_Close(SockID));

    return SUCCESS;
}
예제 #8
0
파일: main.c 프로젝트: Mecabot/IoT
//*****************************************************************************
//
//! Gets the current time from the selected SNTP server
//!
//! \brief  This function obtains the NTP time from the server.
//!
//! \param  GmtDiffHr is the GMT Time Zone difference in hours
//! \param  GmtDiffMins is the GMT Time Zone difference in minutes
//!
//! \return 0 : success, -ve : failure
//!
//*****************************************************************************
long GetSNTPTime(unsigned char ucGmtDiffHr, unsigned char ucGmtDiffMins)
{

/*
                            NTP Packet Header:

       0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9  0  1
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |LI | VN  |Mode |    Stratum    |     Poll      |   Precision    |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                          Root  Delay                           |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                       Root  Dispersion                         |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                     Reference Identifier                       |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                    Reference Timestamp (64)                    |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                    Originate Timestamp (64)                    |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                     Receive Timestamp (64)                     |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                     Transmit Timestamp (64)                    |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                 Key Identifier (optional) (32)                 |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                                                                |
      |                 Message Digest (optional) (128)                |
      |                                                                |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

*/
    char cDataBuf[48];
    long lRetVal = 0;
    int iAddrSize;

    //
    // Send a query to the NTP server to get the NTP time
    //
    memset(cDataBuf, 0, sizeof(cDataBuf));
    cDataBuf[0] = '\x1b';

    sAddr.sa_family = AF_INET;
    // the source port
    sAddr.sa_data[0] = 0x00;
    sAddr.sa_data[1] = 0x7B;    // UDP port number for NTP is 123
    sAddr.sa_data[2] = (char)((g_sAppData.ulDestinationIP>>24)&0xff);
    sAddr.sa_data[3] = (char)((g_sAppData.ulDestinationIP>>16)&0xff);
    sAddr.sa_data[4] = (char)((g_sAppData.ulDestinationIP>>8)&0xff);
    sAddr.sa_data[5] = (char)(g_sAppData.ulDestinationIP&0xff);

    lRetVal = sl_SendTo(g_sAppData.iSockID, cDataBuf, sizeof(cDataBuf), 0, &sAddr, sizeof(sAddr));
    if (lRetVal != sizeof(cDataBuf))
    {
        // could not send SNTP request
        hourSet = 25; // This will ensure we try to fetch time again
        //ASSERT_ON_ERROR(SERVER_GET_TIME_FAILED);
    }

    //
    // Wait to receive the NTP time from the server
    //
    sLocalAddr.sin_family = SL_AF_INET;
    sLocalAddr.sin_port = 0;
    sLocalAddr.sin_addr.s_addr = 0;
    if(g_sAppData.ulElapsedSec == 0)
    {
        lRetVal = sl_Bind(g_sAppData.iSockID, (SlSockAddr_t *)&sLocalAddr, sizeof(SlSockAddrIn_t));
    }

    iAddrSize = sizeof(SlSockAddrIn_t);

    lRetVal = sl_RecvFrom(g_sAppData.iSockID, cDataBuf, sizeof(cDataBuf), 0, (SlSockAddr_t *)&sLocalAddr, (SlSocklen_t*)&iAddrSize);
    ASSERT_ON_ERROR(lRetVal);

    //
    // Confirm that the MODE is 4 --> server
    //
    if ((cDataBuf[0] & 0x7) != 4)    // expect only server response
    {
        hourSet = 25; // This will ensure we try to fetch time again
        //ASSERT_ON_ERROR(SERVER_GET_TIME_FAILED);  // MODE is not server, abort
    }
    else
    {
        unsigned char iIndex;

        //
        // Getting the data from the Transmit Timestamp (seconds) field
        // This is the time at which the reply departed the
        // server for the client
        //
        g_sAppData.ulElapsedSec = cDataBuf[40];
        g_sAppData.ulElapsedSec <<= 8;
        g_sAppData.ulElapsedSec += cDataBuf[41];
        g_sAppData.ulElapsedSec <<= 8;
        g_sAppData.ulElapsedSec += cDataBuf[42];
        g_sAppData.ulElapsedSec <<= 8;
        g_sAppData.ulElapsedSec += cDataBuf[43];

        //
        // seconds are relative to 0h on 1 January 1900
        //
        g_sAppData.ulElapsedSec -= TIME2013;

        //
        // in order to correct the timezone
        //
        g_sAppData.ulElapsedSec += (ucGmtDiffHr * SEC_IN_HOUR);
        g_sAppData.ulElapsedSec += (ucGmtDiffMins * SEC_IN_MIN);

        g_sAppData.pcCCPtr = &g_sAppData.acTimeStore[0];

        //
        // day, number of days since beginning of 2013
        //
        g_sAppData.isGeneralVar = g_sAppData.ulElapsedSec/SEC_IN_DAY;
        memcpy(g_sAppData.pcCCPtr, g_acDaysOfWeek2013[g_sAppData.isGeneralVar%7], 3);
        g_sAppData.pcCCPtr += 3;
        *g_sAppData.pcCCPtr++ = '\x20';

        //
        // month
        //
        g_sAppData.isGeneralVar %= 365;
        for (iIndex = 0; iIndex < 12; iIndex++)
        {
            g_sAppData.isGeneralVar -= g_acNumOfDaysPerMonth[iIndex];
            if (g_sAppData.isGeneralVar < 0)
                    break;
        }
        if(iIndex == 12)
        {
            iIndex = 0;
        }
        memcpy(g_sAppData.pcCCPtr, g_acMonthOfYear[iIndex], 3);
        g_sAppData.pcCCPtr += 3;
        *g_sAppData.pcCCPtr++ = '\x20';

        // Set the Month Value
        dateTime.sl_tm_mon = iIndex + 1;

        //
        // date
        // restore the day in current month
        //
        g_sAppData.isGeneralVar += g_acNumOfDaysPerMonth[iIndex];
        g_sAppData.uisCCLen = itoa(g_sAppData.isGeneralVar + 1, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = '\x20';

        // Set the Date
        dateTime.sl_tm_day = g_sAppData.isGeneralVar + 1;

        //
        // time
        //
        g_sAppData.ulGeneralVar = g_sAppData.ulElapsedSec%SEC_IN_DAY;

        // number of seconds per hour
        g_sAppData.ulGeneralVar1 = g_sAppData.ulGeneralVar%SEC_IN_HOUR;

        // number of hours
        g_sAppData.ulGeneralVar /= SEC_IN_HOUR;
        g_sAppData.uisCCLen = itoa(g_sAppData.ulGeneralVar, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = ':';

        // Set the hour
        dateTime.sl_tm_hour = g_sAppData.ulGeneralVar;

        // number of minutes per hour
        g_sAppData.ulGeneralVar = g_sAppData.ulGeneralVar1/SEC_IN_MIN;

        // Set the minutes
        dateTime.sl_tm_min = g_sAppData.ulGeneralVar;

        // number of seconds per minute
        g_sAppData.ulGeneralVar1 %= SEC_IN_MIN;
        g_sAppData.uisCCLen = itoa(g_sAppData.ulGeneralVar, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = ':';
        g_sAppData.uisCCLen = itoa(g_sAppData.ulGeneralVar1, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = '\x20';

        //Set the seconds
        dateTime.sl_tm_sec = g_sAppData.ulGeneralVar1;

        //
        // year
        // number of days since beginning of 2013
        //
        g_sAppData.ulGeneralVar = g_sAppData.ulElapsedSec/SEC_IN_DAY;
        g_sAppData.ulGeneralVar /= 365;
        g_sAppData.uisCCLen = itoa(YEAR2013 + g_sAppData.ulGeneralVar, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;

        *g_sAppData.pcCCPtr++ = '\0';

        //Set the year
        dateTime.sl_tm_year = 2013 + g_sAppData.ulGeneralVar;

        CLI_Write("Response from server: ");
        CLI_Write((unsigned char *)g_acSNTPserver);
        CLI_Write("\n\r");
        CLI_Write((unsigned char *)g_sAppData.acTimeStore);
        CLI_Write("\n\r\n\r");

        //Set time of the device for certificate verification.
        lRetVal = setDeviceTimeDate();
        if(lRetVal < 0)
        {
            CLI_Write("Unable to set time in the device.\n\r");
            return lRetVal;
        }
    }

    return SUCCESS;
}
예제 #9
0
파일: starter1.c 프로젝트: manavm/Classes
int main(void){
  UINT8             IsDHCP = 0;
  _NetCfgIpV4Args_t ipV4;
  SlSockAddrIn_t    Addr;
  SlSockAddrIn_t    LocalAddr;
  UINT16            AddrSize = 0;
  INT16             SockID = 0;
  INT16             Status = 1;  // ok
  UINT32            data;
  unsigned char     len = sizeof(_NetCfgIpV4Args_t);
  stopWDT();        // Stop WDT 
  initClk();        // PLL 50 MHz, ADC needs PPL active
  Board_Init();     // initialize LaunchPad I/O 
  ConfigureUART();  // Initialize the UART.
  UARTprintf("Section 11.4 IoT example, Volume 2 Real-time interfacing\n");
  UARTprintf("This node is configured to receive UDP packets\n");
  UARTprintf("This node should be at IP: %d.%d.%d.%d  Port: %d\n\n",
      SL_IPV4_BYTE(IP_ADDR,3), SL_IPV4_BYTE(IP_ADDR,2), 
      SL_IPV4_BYTE(IP_ADDR,1), SL_IPV4_BYTE(IP_ADDR,0),PORT_NUM);
  ST7735_InitR(INITR_REDTAB);
  ST7735_OutString("Internet of Things\n");
  ST7735_OutString("Embedded Systems\n");
  ST7735_OutString("Vol. 2, Valvano");
  ST7735_PlotClear(0,4095);  // range from 0 to 4095
  while(1){
    sl_Start(0, 0, 0); /* Initializing the CC3100 device */
    /* Connecting to WLAN AP - Set with static parameters defined at the top
       After this call we will be connected and have IP address */
    WlanConnect();   // connect to AP
    /* Read the IP parameter */
    sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len,(unsigned char *)&ipV4);
    UARTprintf("This node is at IP: %d.%d.%d.%d\n", SL_IPV4_BYTE(ipV4.ipV4,3), SL_IPV4_BYTE(ipV4.ipV4,2), SL_IPV4_BYTE(ipV4.ipV4,1), SL_IPV4_BYTE(ipV4.ipV4,0));
    while(Status > 0){
      UARTprintf("\nReceiving a UDP packet ...");

      LocalAddr.sin_family = SL_AF_INET;
      LocalAddr.sin_port = sl_Htons((UINT16)PORT_NUM);
      LocalAddr.sin_addr.s_addr = 0;
      AddrSize = sizeof(SlSockAddrIn_t);
      SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);     
      if( SockID < 0 ){
        UARTprintf("SockIDerror\n");
        Status = -1; // error
      }else{
        Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize);
        if( Status < 0 ){
          sl_Close(SockID); 
          UARTprintf("Sock Bind error\n");
        }else{
          Status = sl_RecvFrom(SockID, uBuf, BUF_SIZE, 0,
                  (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize );
          if( Status <= 0 ){
            sl_Close(SockID);
            UARTprintf("Receive error %d ",Status);
          }else{
            LED_Toggle();
            sl_Close(SockID);
            UARTprintf("ok %s ",uBuf);
            if((uBuf[0]==ATYPE)&&(uBuf[1]== '=')){ int i,bOk; uint32_t place;
              data = 0; bOk = 1;
              i=4;  // ignore possible negative sign
              for(place = 1000; place; place = place/10){
                if((uBuf[i]&0xF0)==0x30){ // ignore spaces
                  data += place*(uBuf[i]-0x30);
                }else{
                  if((uBuf[i]&0xF0)!= ' '){
                    bOk = 0;
                  }
                }
                i++;
              }
              if(bOk){
                ST7735_PlotLine(data);
                ST7735_PlotNextErase(); 
              }
            }
          }
        }
      }
      ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 120ms
    }
  }
}
예제 #10
0
    s->sock_base.sd = sd;
    return 0;
}

STATIC void wlan_socket_close(mod_network_socket_obj_t *s) {
    // this is to prevent the finalizer to close a socket that failed when being created
    if (s->sock_base.sd >= 0) {
        modusocket_socket_delete(s->sock_base.sd);
        sl_Close(s->sock_base.sd);
        s->sock_base.sd = -1;
    }
}

STATIC int wlan_socket_bind(mod_network_socket_obj_t *s, byte *ip, mp_uint_t port, int *_errno) {
    MAKE_SOCKADDR(addr, ip, port)
    int ret = sl_Bind(s->sock_base.sd, &addr, sizeof(addr));
    if (ret != 0) {
        *_errno = ret;
        return -1;
    }
    return 0;
}

STATIC int wlan_socket_listen(mod_network_socket_obj_t *s, mp_int_t backlog, int *_errno) {
    int ret = sl_Listen(s->sock_base.sd, backlog);
    if (ret != 0) {
        *_errno = ret;
        return -1;
    }
    return 0;
}
int BsdTcpServer(unsigned short usPort)
{
  
    UART_PRINT("BsdTcpServer\r\n"); 
    while( wlanConnectStatus == 0);
  
  
  
    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    int             iNewSockID;
    unsigned long            lLoopCount = 0;
    long            lBytesSent = 0;
    long            lNonBlocking = 0;                   //0 :non-blocking,
    int             iTestBufLen;

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10) + '0';
    }

    iTestBufLen  = BUF_SIZE;

    //filling the TCP server socket address
    sLocalAddr.sin_family = SL_AF_INET;
   sLocalAddr.sin_port = sl_Htons((unsigned short)usPort);
   sLocalAddr.sin_addr.s_addr = 0;
   
//	sLocalAddr.sin_port = usPort;
//	sLocalAddr.sin_addr.s_addr = SL_IPV4_VAL(192,168,1,101);
    

   

   
    // creating a TCP socket
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    if( iSockID < 0 )
    {
      
      // UART_PRINT("error at creating a TCP socket ! \n\r"); 
       
        // error
        return -1;
    }
    
 //   UART_PRINT("iSockID :"); 
 //   Z_NumDispaly(iSockID, 2);
        

    iAddrSize = sizeof(SlSockAddrIn_t);

    // binding the TCP socket to the TCP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
    
 //   UART_PRINT("error at binding the TCP socket to the TCP server address ! \n\r"); 
     
      // error
    	return -1;
    }
    
    
//	UART_PRINT("binding the TCP socket to the TCP server address ok! \n\r"); 
        
        

    // putting the socket for listening to the incoming TCP connection
    iStatus = sl_Listen(iSockID, 0);
    if( iStatus < 0 )
    {
      
 //     UART_PRINT("error at putting the socket for listening to the incoming TCP connection ! \n\r"); 
    	return -1;
    }

//	UART_PRINT("listen end! \n\r"); 

    // setting socket option to make the socket as non blocking
    iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking));
    iNewSockID = SL_EAGAIN;

    char uttMessage[50]={0};
       snprintf(uttMessage,sizeof(uttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
       UART_PRINT(uttMessage); 
 
 serverCreatOK = 1;
 
UART_PRINT(" waiting for an incoming TCP connection! \n\r"); 



    // waiting for an incoming TCP connection
    while( iNewSockID < 0 )
    {
    	// accepts a connection form a TCP client, if there is any
    	// otherwise returns SL_EAGAIN
       iNewSockID = sl_Accept(iSockID, ( struct SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize);
       if( iNewSockID == SL_EAGAIN )
       {
         UtilsDelay(10000);
         
             char uttMessage[50]={0};
       snprintf(uttMessage,sizeof(uttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
       UART_PRINT(uttMessage); 
       
 //      vTaskResume((xTaskHandle)&clientTaskHandle);
       vTaskSuspend((xTaskHandle)&ServerTaskHandle);
       
//	  UART_PRINT(" iNewSockID == SL_EAGAIN! \n\r"); 
       }
       /*
       else if( iNewSockID < 0 )
       {
    	  // error
    	   UART_PRINT(" iNewSockID < 0! \n\r"); 
    	   return -1;
       }*/
    }
    
                 char utttMessage[50]={0};
       snprintf(utttMessage,sizeof(utttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
       UART_PRINT(utttMessage); 


	    UART_PRINT("connect succeed the new iSockID :"); 
    		Z_NumDispaly(iSockID, 5);

	unsigned long the_client_ip = sl_BIGtoLITTLE_l( (unsigned long)sAddr.sin_addr.s_addr );


	UART_PRINT("the client ip is :"); 
	Z_IPDispaly(&the_client_ip);


	unsigned short the_client_port = sl_BIGtoLITTLE_S( (unsigned short)sAddr.sin_port );
        


	UART_PRINT("the client port is :"); 
	Z_NumDispaly( (unsigned long)the_client_port,5);
	


/*
UART_PRINT(" waits for 1000 packets from the connected TCP client! \n\r"); 

    // waits for 1000 packets from the connected TCP client
    while (lLoopCount < 1000)
    {
        iStatus = sl_Recv(iNewSockID, g_cBsdBuf, iTestBufLen, 0);
        if( iStatus <= 0 )
		{
			// error
        	return -1;
		}

		lLoopCount++;
		lBytesSent += iStatus;
    }
  */

/*

    // sending 3 packets to the TCP server
    while (lLoopCount < 3)
    {
    	// sending packet
 //       iStatus = sl_Send(iNewSockID, g_cBsdBuf, iTestBufLen, 0 );

	char *send_buffer = "hellow i am cc3200 , welcome to wifi world !\n\r";

	 iStatus = sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
        if( iStatus <= 0 )
        {
        	UART_PRINT("error at sending packet\n\r"); 
		 Z_NumDispaly(lLoopCount,5);
            // error
        	return -1;
        }

        lLoopCount++;
        lBytesSent += iStatus;




    }

/*
//#define SL_POLICY_CONNECTION    (0x10)
//#define SL_POLICY_SCAN          (0x20)
//#define SL_POLICY_PM            (0x30)    
    
    
//    while(1){
//   Z_DelayS(1);
//    char OutMessage[50]={0};
//    snprintf(OutMessage,sizeof(OutMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
//    sl_Send(iNewSockID, OutMessage, strlen(OutMessage), 0 );        
//    }   
    
    
 
    
    char *setbuffer= "\n set policy \n\r";
sl_Send(iNewSockID, setbuffer, strlen(setbuffer), 0 );

char recBuffer[2] = {0};
char numBuffer[15]={0};

while(1){
  
char sl_policy = '0';
char set_prar = '0';
char OutMessage[50] = {0};
char num = 0;
                
                
                
                while(1){
                  
                  char temp_num = sl_Recv(iNewSockID, recBuffer, sizeof(recBuffer), 0);                 
                 
                  if(temp_num>0)
                    num += temp_num;
                  
                  if(num == 1)
                      sl_policy = recBuffer[0]-'0';
                      
                  
                  if(num == 3)
                    set_prar = recBuffer[0]-'0';
                  
                  if(num>3 && (recBuffer[0]=='\r' || recBuffer[0]=='\n'))
                    break;
                    
                  
                  if(num>3){
                    num = 0;
                  
                  char *send_buffer= "\nplease input again!!!\n\r";
                    sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );}
                  
                  
                  snprintf(numBuffer,sizeof(numBuffer),"num:%d\n\r",num);
                  UART_PRINT(numBuffer);
                   
                }
                
                char *send_buffer= "\nfinished input!\n\r";
                sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
                
                



                switch(sl_policy*16){
                    case SL_POLICY_CONNECTION://1 x 
                          snprintf(OutMessage,sizeof(OutMessage),"CONN= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          UART_PRINT(OutMessage);
                          break;
                          
                    case SL_POLICY_SCAN://2 x 
                          snprintf(OutMessage,sizeof(OutMessage),"SCAN= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          if(set_prar == 0)
                                  sl_WlanPolicySet(SL_POLICY_SCAN,0,0,0);
                          else
                                  sl_WlanPolicySet(SL_POLICY_SCAN,1,(unsigned char *)&set_prar,sizeof(set_prar));
                          
                          UART_PRINT(OutMessage);
                          break;
                          
                case SL_POLICY_PM://3 x : x=0(normal),x=1(latency),x=2(low),x=3(always on),
                          snprintf(OutMessage,sizeof(OutMessage),"PM= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          UART_PRINT(OutMessage);
                          sl_WlanPolicySet(SL_POLICY_PM , set_prar, NULL,0);
                          break;
                                                   
                case 0x00://0 x :finished set 
                          break;
                          
                case 0x40:{//4xx: hibernate
                                  char *send_buffer= "\nsl_hibernate!\n\r";
                sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
                   sl_Stop(0);
                   break;}
                   
                case 0x50:{//4xx: hibernate
                                  char *send_buffer= "\ndevice_hibernate!\n\r";
                sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
                   PRCMHibernateEnter();
                   break;}
                          
                    default:
                          snprintf(OutMessage,sizeof(OutMessage),"Error= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          UART_PRINT(OutMessage);
                          break;
                            
                }
                
                
                if(sl_policy == 0)
                  break;

}





  
  
Sl_WlanNetworkEntry_t netEntries[20];
 char message[80];




/****no scan*********/
 /* 
#define SL_SCAN_DISABLE  0
sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_DISABLE,0,0);

while(1);
return 0;







    
 UINT8  intervalInSeconds=1;  
    

 while(1){
        Z_DelayS(1); 
        sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_POLICY_EN(1), (unsigned char *)&intervalInSeconds,sizeof(intervalInSeconds));
 }
    
    
     
*/ 
 
 /*
char *noticebuffer= "\n set send message time \n\r";
sl_Send(iNewSockID, noticebuffer, strlen(noticebuffer), 0 );

 
while(1){
                  
                  char temp_num = sl_Recv(iNewSockID, recBuffer, sizeof(recBuffer), 0);                 
                 
                  if(temp_num>0)
                    break;                  
                   
}
                
    

 while(1){  
    
   

    //Get Scan Result
   UINT8 Index = sl_WlanGetNetworkList(0,20,&netEntries[0]);

  
    for(UINT8 i=0; i< Index; i++)
    {
         snprintf(message, 60, "%d) SSID %s  RSSI %d \n\r",i,netEntries[i].ssid,netEntries[i].rssi);
	//UART_PRINT(message); 
        sl_Send(iNewSockID, message, strlen(message), 0 );
        
        
        
        
    }  
    
  Z_DelayS(recBuffer[0]-'0');  

  }    
    









    // close the connected socket after receiving from connected TCP client
    sl_Close(iNewSockID);

    // close the listening socket
    sl_Close(iSockID);

    return 0;
    
    */
}
예제 #12
0
void ControlServer(void *pvParameters) {

	char ServerBuffer[CONFIG_SERVER_BUFFER];
	char MsgBuffer[100];
	char *pMsgBuffer;

	SlSockAddrIn_t sAddr;
	SlSockAddrIn_t sLocalAddr;
	int32_t i32SockID;
	int32_t i32NewSockID;
	int32_t i32DataSize;
	int32_t i32NonBlocking = 1;
	SlSocklen_t i32AddrSize;
	int32_t retval;

	pMsgBuffer = &MsgBuffer[0];

	InitVariables();
	retval = ResetSimpleLink();
	if (retval < 0)
		while (1)
			;

	WlanConnect();

	sprintf(MsgBuffer, "Connectado a rede: %s\n\r"
			"IP: %d.%d.%d.%d\n\r"
			"Gateway: %d.%d.%d.%d\n\r", SL_IPV4_BYTE(g_sSLCon.DeviceIP, 3),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 2),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 1),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 0),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 3),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 2),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 1),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 0));

	osi_MsgQWrite(&g_sUartQuee, &pMsgBuffer, OSI_NO_WAIT);

	sLocalAddr.sin_family = SL_AF_INET;
	sLocalAddr.sin_port = sl_Htons((unsigned short) g_sSLCon.PortNumber);
	sLocalAddr.sin_addr.s_addr = 0;

	i32SockID = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0);
	sl_Bind(i32SockID, (SlSockAddr_t *) &sLocalAddr, sizeof(SlSockAddrIn_t));
	sl_Listen(i32SockID, 0);
	sl_SetSockOpt(i32SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &i32NonBlocking,
			sizeof(i32NonBlocking));

	while (1) {
		i32NewSockID = SL_EAGAIN;

		while (i32NewSockID < 0) {
			i32NewSockID = sl_Accept(i32SockID, (struct SlSockAddr_t *) &sAddr,
					(SlSocklen_t*) &i32AddrSize);
			if (i32NewSockID == SL_EAGAIN) {
				osi_Sleep(100);
			} else if (i32NewSockID < 0) {
				while (1) {
				}
			}
		}

		i32DataSize = sl_Recv(i32NewSockID, ServerBuffer, CONFIG_SERVER_BUFFER,
				0);

		if (strcmp(ServerBuffer, "Led On") == 0) {
			Led_Green(LED_ON);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Led Off") == 0) {
			Led_Green(LED_OFF);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Lamp On") == 0) {
			MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, GPIO_PIN_6);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Lamp Off") == 0) {
			MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, 0);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		}

		sl_Send(i32NewSockID, ServerBuffer, i32DataSize, 0);
		sl_Close(i32NewSockID);
	}

}
예제 #13
0
파일: main.c 프로젝트: gale320/cc3200
//****************************************************************************
//
//! \brief Opening a UDP server side socket and receiving data
//!
//! This function opens a UDP socket in Listen mode and waits for an incoming
//! UDP connection.
//!    If a socket connection is established then the function will try to
//!    read 1000 UDP packets from the connected client.
//!
//! \param[in]          port number on which the server will be listening on
//!
//! \return             0 on success, Negative value on Error.
//
//****************************************************************************
int BsdUdpServer(unsigned short usPort)
{
    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    long            lLoopCount = 0;
    short           sTestBufLen;

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10);
    }

    sTestBufLen  = BUF_SIZE;
    //filling the UDP server socket address
    sLocalAddr.sin_family = SL_AF_INET;
    sLocalAddr.sin_port = sl_Htons((unsigned short)usPort);
    sLocalAddr.sin_addr.s_addr = 0;

    iAddrSize = sizeof(SlSockAddrIn_t);

    // creating a UDP socket
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);
    if( iSockID < 0 )
    {
        // error
        ASSERT_ON_ERROR(UCP_SERVER_FAILED);
    }

    // binding the UDP socket to the UDP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
        // error
        sl_Close(iSockID);
        ASSERT_ON_ERROR(UCP_SERVER_FAILED);
    }

    // no listen or accept is required as UDP is connectionless protocol
    /// waits for 1000 packets from a UDP client
    while (lLoopCount < g_ulPacketCount)
    {
        iStatus = sl_RecvFrom(iSockID, g_cBsdBuf, sTestBufLen, 0,
                     ( SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize );

    if( iStatus < 0 )
    {
        // error
        sl_Close(iSockID);
        ASSERT_ON_ERROR(UCP_SERVER_FAILED);
    }
    lLoopCount++;
    }

    UART_PRINT("Recieved %u packets successfully\n\r",g_ulPacketCount);

    //closing the socket after receiving 1000 packets
    sl_Close(iSockID);

    return SUCCESS;
}
예제 #14
0
//****************************************************************************
//                            MAIN FUNCTION
//****************************************************************************
int main(void)
{
    long lRetVal;
	char cCmdBuff[20];
	signed char cCmd = APP_SLEEP;

    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    SlSockAddrIn_t  sBrdAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    long            lLoopCount = 0;
    short           sTestBufLen;
    struct SlTimeval_t timeVal;

    //
    // Board Initialization
    //
    BoardInit();
    
    //
	// uDMA Initialization
	//
	UDMAInit();
    
    //
    // Configure the pinmux settings for the peripherals exercised
    // Note: pinmux has been modified after the output from pin mux tools
    // to enable sleep clk for the peripherals exercised
    //
    PinMuxConfig();

    //
	// Initialize the platform
	//
	platform_init();

    //
    // Initialise the UART terminal
    //
    InitTerm();

    //
	// Display banner
	//
    DisplayBanner();
    
	//
    // starting the simplelink
    //
	lRetVal = sl_Start(NULL, NULL, NULL);
	if (lRetVal < 0)
	{
		UART_PRINT("Failed to start the device \n\r");
		LOOP_FOREVER();
	}

    //
    // Swtich to STA mode if device is not
    //
    SwitchToStaMode(lRetVal);
    
    //
    // set connection policy
    //
    sl_WlanPolicySet(SL_POLICY_CONNECTION, 
                                SL_CONNECTION_POLICY(0, 0, 0, 0, 0), NULL, 0);
	//
	// Set the power management policy of NWP
	//
	lRetVal = sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0);

    UART_PRINT("Trying to Connect to AP: %s ...\r\n",SSID_NAME);

    //
    //Connecting to WLAN AP
    //
    lRetVal = WlanConnect();
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to establish connection w/ an AP \n\r");
        LOOP_FOREVER();
    }

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10);
    }
    
	sTestBufLen  = BUF_SIZE;
	//filling the UDP server socket address
	sLocalAddr.sin_family = SL_AF_INET;
	sLocalAddr.sin_port = sl_Htons((unsigned short)PORT_NUM);
	sLocalAddr.sin_addr.s_addr = 0;

	//filling the UDP server socket address
	sBrdAddr.sin_family = SL_AF_INET;
	sBrdAddr.sin_port = sl_Htons((unsigned short)PORT_NUM);
	sBrdAddr.sin_addr.s_addr = sl_Htonl((unsigned int)g_ulDestinationIp);

	iAddrSize = sizeof(SlSockAddrIn_t);

	// creating a UDP socket
	iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);

    /* setting time out for socket recv */
    timeVal.tv_sec =  5;             // Seconds
    timeVal.tv_usec = 0;             // Microseconds. 10000 microseconds resolution
    sl_SetSockOpt(iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (_u8 *)&timeVal, sizeof(timeVal));

    // binding the UDP socket to the UDP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
        // error
        sl_Close(iSockID);
        ASSERT_ON_ERROR(iStatus);
    }

	//
	// setting Apps power policy
	//
	lp3p0_setup_power_policy(POWER_POLICY_STANDBY);
    
    UART_PRINT("enter one of the following command:\n\r");
    UART_PRINT("sleep - for putting the system into LPDS mode\n\r");
    UART_PRINT("        GPIO 13 and timer(5 sec) are the wk source configured\n\r");
    UART_PRINT("recv  - for receiving 1000 UDP packets\n\r");
    UART_PRINT("send  - for broadcasting 1000 UDP packets\n\r");
	
    do{
        
		UART_PRINT("cmd#");
		//
		// get cmd over UART
		//
		GetCmd(cCmdBuff, 20);

		//
		// parse the command
		//
		ParseCmd(cCmdBuff, &cCmd);

		if(cCmd == APP_SLEEP)
		{
			//
			// set timer and gpio as wake src
			//
			set_rtc_as_wk_src(WK_LPDS, LPDS_DUR_SEC, false);
			set_gpio_as_wk_src(WK_LPDS, GPIO_SRC_WKUP, PRCM_LPDS_FALL_EDGE);
			cc_idle_task_pm();
		}
		else if(cCmd == APP_RECV)
		{
			lLoopCount = 0;
		    /// waits for 1000 packets from a UDP client
		    while (lLoopCount < g_ulPacketCount)
		    {
		        iStatus = sl_RecvFrom(iSockID, g_cBsdBuf, sTestBufLen, 0,
		                     ( SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize );

				if( iStatus < 0 )
				{
					//error
					break;
				}
				lLoopCount++;
		    }
		    UART_PRINT("Recieved %u packets successfully \n\r",lLoopCount);
		    if(lLoopCount != g_ulPacketCount)
		    {
                if(iStatus == SL_EAGAIN)
                {
                    UART_PRINT("timed out\n\r");
                }
                else
                {
                    UART_PRINT("recv error: %d\n\r", iStatus);
                }
		    }
		}
		else if(cCmd == APP_SEND)
		{
			lLoopCount = 0;
		    // sending 1000 packets to the UDP server
		    while (lLoopCount < g_ulPacketCount)
		    {
		        // sending packet
		        iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0,
		                                (SlSockAddr_t *)&sBrdAddr, iAddrSize);
		        if( iStatus <= 0 )
		        {
		            // error
		            UART_PRINT("send error\n\r");
                    break;
		        }
		        lLoopCount++;
		    }
		    UART_PRINT("Sent %u packets successfully\n\r",lLoopCount);
		}
	}while(FOREVER);
}
예제 #15
0
파일: main.c 프로젝트: Balu1991/Wifly_Light
//****************************************************************************
//
//! \brief Opening a server side socket and receiving data
//!
//! This function opens a TCP socket in Listen mode and waits for an incoming
//! TCP connection. If a socket connection is established then the function
//! will try to read 1000 TCP packets from the connected client.
//!
//! \param[in]      port number on which the server will be listening on
//!
//! \return         0 on success, -1 on Error.
//!
//! \note           This function will wait for an incoming connection till one
//!                 is established
//
//****************************************************************************
static int BsdTcpServer(UINT16 Port)
{
    SlSockAddrIn_t  Addr;
    SlSockAddrIn_t  LocalAddr;

    int             idx;
    int             AddrSize;
    int             SockID;
    int             Status;
    int             newSockID;
    long            LoopCount = 0;
    long            nonBlocking = 1;

    for (idx=0 ; idx<BUF_SIZE ; idx++)
    {
        uBuf.BsdBuf[idx] = (char)(idx % 10);
    }

    LocalAddr.sin_family = SL_AF_INET;
    LocalAddr.sin_port = sl_Htons((UINT16)Port);
    LocalAddr.sin_addr.s_addr = 0;

    SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    if( SockID < 0 )
    {
        /* error */
        return -1;
    }

    AddrSize = sizeof(SlSockAddrIn_t);
    Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize);
    if( Status < 0 )
    {
        /* error */
        sl_Close(SockID);
        return -1;
    }

    Status = sl_Listen(SockID, 0);
    if( Status < 0 )
    {
        sl_Close(SockID);
        return -1;
    }

    Status = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING,
                           &nonBlocking, sizeof(nonBlocking));
    if( Status < 0 )
    {
        return -1;
    }
    newSockID = SL_EAGAIN;

    while( newSockID < 0 )
    {
        newSockID = sl_Accept(SockID, ( struct SlSockAddr_t *)&Addr,
                              (SlSocklen_t*)&AddrSize);
        if( newSockID == SL_EAGAIN )
        {
            /* Wait for 1 ms */
            Delay(1);
        }
        else if( newSockID < 0 )
        {
            sl_Close(SockID);
            return -1;
        }
    }

    while (LoopCount < TCP_PACKET_COUNT)
    {
        Status = sl_Recv(newSockID, uBuf.BsdBuf, BUF_SIZE, 0);
        if( Status <= 0 )
        {
            /* error */
            sl_Close(newSockID);
            sl_Close(SockID);
            return -1;
        }
        LoopCount++;
    }
    GPIO_IF_LedOn(MCU_EXECUTE_SUCCESS_IND);
    sl_Close(newSockID);
    sl_Close(SockID);

    return 0;
}
예제 #16
0
파일: NTPTime.c 프로젝트: nlbutts/TempWifi
//*****************************************************************************
//
//! \brief     Get the NTP time
//!
//! \param    none
//!
//! \return void
//! \note
//! \warning
//
//*****************************************************************************
uint8_t GetTime(struct tm * decodedTime)
{
    const char * g_acSNTPserver = "wwv.nist.gov"; //Add any one of the above servers
    unsigned long ulDestinationIP;
    int iSocketDesc;
    long lRetVal;
    char cDataBuf[48];
    int iAddrSize;
    SlSockAddr_t sAddr;
    SlSockAddrIn_t sLocalAddr;

    //
    // Create UDP socket
    //
    iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(iSocketDesc < 0)
    {
        ERR_PRINT(iSocketDesc);
        return 0;
    }
    //g_sAppData.iSockID = iSocketDesc;

    UART_PRINT("Socket created\n\r");

    //
    // Get the NTP server host IP address using the DNS lookup
    //
    lRetVal = Network_IF_GetHostIP((char*)g_acSNTPserver, &ulDestinationIP);

    if( lRetVal >= 0)
    {

        struct SlTimeval_t timeVal;
        timeVal.tv_sec =  SERVER_RESPONSE_TIMEOUT;    // Seconds
        timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
        lRetVal = sl_SetSockOpt(iSocketDesc,SL_SOL_SOCKET,SL_SO_RCVTIMEO,\
                        (unsigned char*)&timeVal, sizeof(timeVal));
        if(lRetVal < 0)
        {
            ERR_PRINT(lRetVal);
            //
            // Close the socket
            //
            close(iSocketDesc);
            UART_PRINT("Socket closed\n\r");
            return 0;
        }

        //
        // Send a query ? to the NTP server to get the NTP time
        //
        memset(cDataBuf, 0, sizeof(cDataBuf));
        cDataBuf[0] = '\x1b';

        sAddr.sa_family = AF_INET;
        // the source port
        sAddr.sa_data[0] = 0x00;
        sAddr.sa_data[1] = 0x7B;    // UDP port number for NTP is 123
        sAddr.sa_data[2] = (char)((ulDestinationIP>>24)&0xff);
        sAddr.sa_data[3] = (char)((ulDestinationIP>>16)&0xff);
        sAddr.sa_data[4] = (char)((ulDestinationIP>>8)&0xff);
        sAddr.sa_data[5] = (char)(ulDestinationIP&0xff);

        lRetVal = sl_SendTo(iSocketDesc,
                         cDataBuf,
                         sizeof(cDataBuf), 0,
                         &sAddr, sizeof(sAddr));
        if (lRetVal != sizeof(cDataBuf))
        {
            // could not send SNTP request
            //ASSERT_ON_ERROR(SERVER_GET_TIME_FAILED);
            return 0;
        }

        //
        // Wait to receive the NTP time from the server
        //
        sLocalAddr.sin_family = SL_AF_INET;
        sLocalAddr.sin_port = 0;
        sLocalAddr.sin_addr.s_addr = 0;
        lRetVal = sl_Bind(iSocketDesc,
                (SlSockAddr_t *)&sLocalAddr,
                sizeof(SlSockAddrIn_t));

        iAddrSize = sizeof(SlSockAddrIn_t);

        lRetVal = sl_RecvFrom(iSocketDesc,
                           cDataBuf, sizeof(cDataBuf), 0,
                           (SlSockAddr_t *)&sLocalAddr,
                           (SlSocklen_t*)&iAddrSize);
        //ASSERT_ON_ERROR(lRetVal);

        if(lRetVal < 0)
        {
            UART_PRINT("Server Get Time failed\n\r");
            //
            // Close the socket
            //
            close(iSocketDesc);
            UART_PRINT("Socket closed\n\r");
            return 0;
        }

        // We received the time
        DecodeSNTPTime(cDataBuf, decodedTime);
    }
    else
    {
예제 #17
0
파일: main.c 프로젝트: gale320/cc3200
//*****************************************************************************
//
//! This function opens a TCP socket in Listen mode and waits for an incoming 
//! TCP connection.. If a socket connection is established then the function 
//! will try to read 1000 TCP packets from the connected client.
//!
//! \param port number on which the server will be listening on
//!
//! \return  0 on success, -ve on Error.
//!
//*****************************************************************************
static long BsdTcpServer(unsigned short Port)
{
    SlSockAddrIn_t  Addr;
    SlSockAddrIn_t  LocalAddr;
    int             indexCount,iAddrSize,SockID,iStatus,newSockID;
    long            LoopCount = 0;
    long            nonBlocking = 1;
    SlTimeval_t     timeVal;

    for (indexCount=0 ; indexCount<BUF_SIZE ; indexCount++)
    {
        g_uBuf.cBsdBuf[indexCount] = (char)(indexCount % 10);
    }

    LocalAddr.sin_family = SL_AF_INET;
    LocalAddr.sin_port = sl_Htons((unsigned short)Port);
    LocalAddr.sin_addr.s_addr = 0;
    SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    ASSERT_ON_ERROR(SockID);

    iAddrSize = sizeof(SlSockAddrIn_t);
    iStatus = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, iAddrSize);

    if( iStatus < 0 )
    {
        // error
        ASSERT_ON_ERROR(sl_Close(SockID));
        ASSERT_ON_ERROR(iStatus);
    }

    iStatus = sl_Listen(SockID, 0);
    if( iStatus < 0 )
    {
        sl_Close(SockID);
        ASSERT_ON_ERROR(iStatus);
    }

    iStatus = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, \
                            &nonBlocking,
                            sizeof(nonBlocking));
    newSockID = SL_EAGAIN;
    while( newSockID < 0 )
    {
        newSockID = sl_Accept(SockID, ( struct SlSockAddr_t *)&Addr, 
                                        (SlSocklen_t*)&iAddrSize);
        if( newSockID == SL_EAGAIN )
        {
                MAP_UtilsDelay(80000);
        }
        else if( newSockID < 0 )
        {
            ASSERT_ON_ERROR(sl_Close(SockID));
            // error
            ASSERT_ON_ERROR(newSockID);
        }
    }
    timeVal.tv_sec = 1;
    timeVal.tv_usec = 0;
    if( newSockID >= 0 )
    {
        iStatus = sl_SetSockOpt(newSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO,
                                &timeVal, sizeof(timeVal));
        ASSERT_ON_ERROR(iStatus);
    }

    while (LoopCount < PACKET_COUNT)
    {
        iStatus = sl_Recv(newSockID, g_uBuf.cBsdBuf, BUF_SIZE, 0);
        if( iStatus <= 0 )
        {
            // error
            ASSERT_ON_ERROR(sl_Close(newSockID));
            ASSERT_ON_ERROR(sl_Close(SockID));
            ASSERT_ON_ERROR(iStatus);
        }

        LoopCount++;
    }

    ASSERT_ON_ERROR(sl_Close(newSockID));
    ASSERT_ON_ERROR(sl_Close(SockID));
    return 0;
}
예제 #18
0
//--tested, working--//
void WiFiServer::begin()
{
    //
    //Stop the port 80 internal http server if running a server on port 80
    //
    if (_port == 80) {
        sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
    }
    
    //
    //get a socket from the WiFiClass (convoluted method from the arduino library)
    //
    int socketIndex = WiFiClass::getSocket();
    if (socketIndex == NO_SOCKET_AVAIL) {
        return;
    }
    
    //
    //get a socket handle from the simplelink api and make sure it's valid
    //
    int socketHandle = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_IPPROTO_TCP);
    if (socketHandle < 0) {
        return;
    }
    //
    //bind the socket to the requested port and check for success
    //if failure, gracefully close the socket and return failure
    //
    SlSockAddrIn_t portAddress;
    portAddress.sin_family = SL_AF_INET;
    portAddress.sin_port = sl_Htons(_port);
    portAddress.sin_addr.s_addr = 0;
    int enableOption = 1;

    sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &enableOption, sizeof(enableOption));
    sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_KEEPALIVE, &enableOption, sizeof(enableOption));

    int iRet = sl_Bind(socketHandle, (SlSockAddr_t*)&portAddress, sizeof(SlSockAddrIn_t));
    if (iRet < 0) {
        sl_Close(socketHandle);
        return;
    }
    
    //
    //Make the socket start listening for incoming tcp connections
    //(backlog of length 0)
    //
    iRet = sl_Listen(socketHandle, 0);
    if (iRet < 0) {
        sl_Close(socketHandle);
        return;
    }
    
    //
    //set socket operation to be non blocking
    //
    long NonBlocking = true;
    iRet = sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &NonBlocking, sizeof(NonBlocking));
    if (iRet < 0) {
        sl_Close(socketHandle);
        return;
    }
    
    //
    //Simplelink api calls are done, so set the object's variables
    //
    _socketIndex = socketIndex;
    WiFiClass::_handleArray[socketIndex] = socketHandle;
    WiFiClass::_portArray[socketIndex] = _port;
    WiFiClass::_typeArray[socketIndex] = TYPE_TCP_SERVER;
}
예제 #19
0
파일: main.c 프로젝트: bigcat26/cc3200-sdk
//*****************************************************************************
//
//! \brief Task Created by main fucntion. This task creates a udp server and
//!        wait for packets. Upon receiving the packet, signals the other task.
//!
//! \param pvParameters is a general void pointer (not used here).
//!
//! \return none
//
//*****************************************************************************
void UDPServerTask(void *pvParameters)
{
    unsigned char ucSyncMsg;
    unsigned char ucQueueMsg = 3;
    int iSockDesc = 0;
    int iRetVal = 0;
    sockaddr_in sLocalAddr;
    sockaddr_in sClientAddr;
    unsigned int iAddrSize = 0;
       
    //
    // waiting for the other task to start simplelink and connection to the AP
    //
    osi_MsgQRead(&g_tConnectionFlag, &ucSyncMsg, OSI_WAIT_FOREVER);
    osi_MsgQDelete(&g_tConnectionFlag);
    
    //
    // configure the Server
    //
    sLocalAddr.sin_family = SL_AF_INET;
    sLocalAddr.sin_port = sl_Htons((unsigned short)APP_UDP_PORT);
    sLocalAddr.sin_addr.s_addr = 0;
    
    iAddrSize = sizeof(sockaddr_in);
    
    //
    // creating a UDP socket
    //
    iSockDesc = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);

    if(iSockDesc < 0)
    {
        UART_PRINT("sock error\n\r");
        LOOP_FOREVER();
    }
    
    //
    // binding the socket
    //
    iRetVal = sl_Bind(iSockDesc, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if(iRetVal < 0)
    {
        UART_PRINT("bind error\n\r");
        LOOP_FOREVER();
    }
    
    while(FOREVER)
    {
        //
        // waiting on a UDP packet
        //
        iRetVal = sl_RecvFrom(iSockDesc, g_cBuffer, BUFF_SIZE, 0,
                              ( SlSockAddr_t *)&sClientAddr,
                              (SlSocklen_t*)&iAddrSize );
        if(iRetVal > 0)
        {
            //
            // signal the other task about receiving the UDP packet
            //
            osi_MsgQWrite(&g_tWkupSignalQueue, &ucQueueMsg, OSI_WAIT_FOREVER);
        }
        else
        {
            UART_PRINT("recv error\n\r");
            LOOP_FOREVER();
        }
    }  
}
//****************************************************************************
//
//!	\brief Opening a TCP server side socket and receiving data
//!
//!	This function opens a TCP socket in Listen mode and waits for an incoming
//!	TCP connection.
//! If a socket connection is established then the function will try to read
//!	1000 TCP packets from the connected client.
//!
//! \param[in] 		 port number on which the server will be listening on
//!
//! \return	         0 on success, -1 on error.
//!
//!	\note            This function will wait for an incoming connection till
//!					 one is established
//
//****************************************************************************
int BsdTcpServer(unsigned short usPort)
{
    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    int             iNewSockID;
    unsigned long            lLoopCount = 0;
    long            lBytesSent = 0;
    long            lNonBlocking = 1;
    int             iTestBufLen;

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10) + '0';
    }

    iTestBufLen  = BUF_SIZE;

    //filling the TCP server socket address
    sLocalAddr.sin_family = SL_AF_INET;
   sLocalAddr.sin_port = sl_Htons((unsigned short)usPort);
   sLocalAddr.sin_addr.s_addr = 0;
   
//	sLocalAddr.sin_port = usPort;
//	sLocalAddr.sin_addr.s_addr = SL_IPV4_VAL(192,168,1,101);
    

    // creating a TCP socket
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    if( iSockID < 0 )
    {
      
       UART_PRINT("error at creating a TCP socket ! \n\r"); 
       
        // error
        return -1;
    }
    
    UART_PRINT("iSockID :"); 
    Z_NumDispaly(iSockID, 2);
        

    iAddrSize = sizeof(SlSockAddrIn_t);

    // binding the TCP socket to the TCP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
    
    UART_PRINT("error at binding the TCP socket to the TCP server address ! \n\r"); 
     
      // error
    	return -1;
    }
    
    
	UART_PRINT("binding the TCP socket to the TCP server address ok! \n\r"); 
        
        

    // putting the socket for listening to the incoming TCP connection
    iStatus = sl_Listen(iSockID, 0);
    if( iStatus < 0 )
    {
      
      UART_PRINT("error at putting the socket for listening to the incoming TCP connection ! \n\r"); 
    	return -1;
    }

	UART_PRINT("listen end! \n\r"); 

    // setting socket option to make the socket as non blocking
    iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking));
    iNewSockID = SL_EAGAIN;

UART_PRINT(" waiting for an incoming TCP connection! \n\r"); 

    // waiting for an incoming TCP connection
    while( iNewSockID < 0 )
    {
    	// accepts a connection form a TCP client, if there is any
    	// otherwise returns SL_EAGAIN
       iNewSockID = sl_Accept(iSockID, ( struct SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize);
       if( iNewSockID == SL_EAGAIN )
       {
         UtilsDelay(10000);
//	  UART_PRINT(" iNewSockID == SL_EAGAIN! \n\r"); 
       }
       else if( iNewSockID < 0 )
       {
    	  // error
    	   UART_PRINT(" iNewSockID < 0! \n\r"); 
    	   return -1;
       }
    }


	    UART_PRINT("connect succeed the new iSockID :"); 
    		Z_NumDispaly(iSockID, 5);

	unsigned long the_client_ip = sl_BIGtoLITTLE_l( (unsigned long)sAddr.sin_addr.s_addr );


	UART_PRINT("the client ip is :"); 
	Z_IPDispaly(&the_client_ip);


	unsigned short the_client_port = sl_BIGtoLITTLE_S( (unsigned short)sAddr.sin_port );
        


	UART_PRINT("the client port is :"); 
	Z_NumDispaly( (unsigned long)the_client_port,5);
	


/*
UART_PRINT(" waits for 1000 packets from the connected TCP client! \n\r"); 

    // waits for 1000 packets from the connected TCP client
    while (lLoopCount < 1000)
    {
        iStatus = sl_Recv(iNewSockID, g_cBsdBuf, iTestBufLen, 0);
        if( iStatus <= 0 )
		{
			// error
        	return -1;
		}

		lLoopCount++;
		lBytesSent += iStatus;
    }
  */



    // sending 3 packets to the TCP server
    while (lLoopCount < 3)
    {
    	// sending packet
 //       iStatus = sl_Send(iNewSockID, g_cBsdBuf, iTestBufLen, 0 );

	char *send_buffer = "hellow i am cc3200 , welcome to wifi world !\n\r";

	 iStatus = sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
        if( iStatus <= 0 )
        {
        	UART_PRINT("error at sending packet\n\r"); 
		 Z_NumDispaly(lLoopCount,5);
            // error
        	return -1;
        }

        lLoopCount++;
        lBytesSent += iStatus;




    }





  
  
Sl_WlanNetworkEntry_t netEntries[20];
 char message[80];
 
 
     unsigned long intervalInSeconds = 10;
    sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_POLICY_EN(1), (unsigned char *)&intervalInSeconds,sizeof(intervalInSeconds));
 
 
 while(1){  
    

    //Get Scan Result
   UINT8 Index = sl_WlanGetNetworkList(0,20,&netEntries[0]);


    for(UINT8 i=0; i< Index; i++)
    {
         snprintf(message, 60, "%d) SSID %s  RSSI %d \n\r",i,netEntries[i].ssid,netEntries[i].rssi);
	UART_PRINT(message); 
        
        
        sl_Send(iNewSockID, message, strlen(message), 0 );
        
    }  
    
  Z_DelayS(3);  

  }    
    









    // close the connected socket after receiving from connected TCP client
    sl_Close(iNewSockID);

    // close the listening socket
    sl_Close(iSockID);

    return 0;
}