Esempio n. 1
0
/* Public Functions */
int MqttClientNet_Init(MqttNet* net)
{
#ifdef USE_WINDOWS_API
    WSADATA wsd;
    WSAStartup(0x0002, &wsd);
#endif

#ifdef MICROCHIP_MPLAB_HARMONY
    static IPV4_ADDR    dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    int Dummy;
    int nNets;
    int i;
    SYS_STATUS          stat;
    TCPIP_NET_HANDLE    netH;

    stat = TCPIP_STACK_Status(sysObj.tcpip);
    if (stat < 0) {
        return MQTT_CODE_CONTINUE;
    }

    nNets = TCPIP_STACK_NumberOfNetworksGet();
    for (i = 0; i < nNets; i++) {
        netH = TCPIP_STACK_IndexToNet(i);
        ipAddr.Val = TCPIP_STACK_NetAddress(netH);
        if (ipAddr.v[0] == 0) {
            return MQTT_CODE_CONTINUE;
        }
        if (dwLastIP[i].Val != ipAddr.Val) {
            dwLastIP[i].Val = ipAddr.Val;
            PRINTF("%s", TCPIP_STACK_NetNameGet(netH));
            PRINTF(" IP Address: ");
            PRINTF("%d.%d.%d.%d\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
        }
    }
#endif /* MICROCHIP_MPLAB_HARMONY */

    if (net) {
        XMEMSET(net, 0, sizeof(MqttNet));
        net->connect = NetConnect;
        net->read = NetRead;
        net->write = NetWrite;
        net->disconnect = NetDisconnect;
        net->context = (SocketContext *)WOLFMQTT_MALLOC(sizeof(SocketContext));
        if (net->context == NULL) {
            return MQTT_CODE_ERROR_MEMORY;
        }
        XMEMSET(net->context, 0, sizeof(SocketContext));

        ((SocketContext*)(net->context))->stat = SOCK_BEGIN;
    }

    return MQTT_CODE_SUCCESS;
}
Esempio n. 2
0
void APP_Tasks( void )
{
    static SYS_TICK startTick = 0;
    static IPV4_ADDR dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    int i;

    switch(appData.state)
    {
        case APP_MOUNT_DISK:
            if(SYS_FS_Mount(SYS_FS_NVM_VOL, LOCAL_WEBSITE_PATH_FS, MPFS2, 0, NULL)  == 0)
            {
                SYS_CONSOLE_PRINT("SYS_Initialize: The %s File System is mounted.\r\n", SYS_FS_MPFS_STRING);
                appData.state = APP_TCPIP_TRANSACT;
            }
            else
            {
                //SYS_CONSOLE_Print("SYS_Initialize: Failed to mount the %s File System! \r\n", SYS_FS_MPFS_STRING);
                appData.state = APP_MOUNT_DISK;
            }
            break;

        case APP_TCPIP_TRANSACT:

            if (SYS_TICK_Get() - startTick >= SYS_TICK_TicksPerSecondGet() / 2ul)
            {
                startTick = SYS_TICK_Get();
                LEDstate ^= APP_USERIO_LED_ASSERTED;
                SYS_USERIO_SetLED(SYS_USERIO_LED_0, LEDstate);
            }

            // if the IP address of an interface has changed
            // display the new value on the system console
            nNets = TCPIP_STACK_NumberOfNetworksGet();

            for (i = 0; i < nNets; i++)
            {
                netH = TCPIP_STACK_IndexToNet(i);
                ipAddr.Val = TCPIP_STACK_NetAddress(netH);
                if(dwLastIP[i].Val != ipAddr.Val)
                {
                    dwLastIP[i].Val = ipAddr.Val;

                    SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                    SYS_CONSOLE_MESSAGE(" IP Address: ");
                    SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
                }
            }
            break;

         default:
            break;
    }
}
Esempio n. 3
0
File: app.c Progetto: ctapang/v0_70b
void APP_Initialize( void )
{
    int i;
    const char          *netName, *netBiosName;


#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
    char mDNSServiceName[] = "MyWebServiceNameX ";     // base name of the service Must not exceed 16 bytes long
                                                       // the last digit will be incremented by interface
#endif  // defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)

    appData.state = APP_TCPIP_WAIT_FOR_IP;

    nNets = TCPIP_STACK_NumberOfNetworksGet();

    for(i = 0; i < nNets; i++)
    {

        netH = TCPIP_STACK_IndexToNet(i);
        netName = TCPIP_STACK_NetNameGet(netH);
        netBiosName = TCPIP_STACK_NetBIOSName(netH);

#if defined(TCPIP_STACK_USE_NBNS)
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS enabled\r\n", netName, netBiosName);
#else
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS disabled\r\n", netName, netBiosName);
#endif  // defined(TCPIP_STACK_USE_NBNS)

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
        mDNSServiceName[sizeof(mDNSServiceName) - 2] = '1' + i;
        TCPIP_MDNS_ServiceRegister( netH
                , mDNSServiceName                   // name of the service
                ,"_http._tcp.local"                 // type of the service
                ,80                                 // TCP or UDP port, at which this service is available
                ,((const uint8_t *)"path=/index.htm")  // TXT info
                ,1                                  // auto rename the service when if needed
                ,NULL                               // no callback function
                ,NULL);                             // no application context
#endif //TCPIP_STACK_USE_ZEROCONF_MDNS_SD

    }

    /* Intialize the app state to wait for
     * media attach. */

    APP_Commands_Init();

}
Esempio n. 4
0
void APP_Tasks( void )
{
    static IPV4_ADDR dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    int i;

    switch(appData.state)
    {

        case APP_TCPIP_WAIT_FOR_IP:

            // if the IP address of an interface has changed
            // display the new value on the system console
            nNets = TCPIP_STACK_NumberOfNetworksGet();

            for (i = 0; i < nNets; i++)
            {
                netH = TCPIP_STACK_IndexToNet(i);
                ipAddr.Val = TCPIP_STACK_NetAddress(netH);
                if(dwLastIP[i].Val != ipAddr.Val)
                {
                    dwLastIP[i].Val = ipAddr.Val;

                    SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                    SYS_CONSOLE_MESSAGE(" IP Address: ");
                    SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
                    if (ipAddr.v[0] != 0 && ipAddr.v[0] != 169) // Wait for a Valid IP
                    {
                        appData.state = APP_TCPIP_OPENING_SERVER;
                    }
                }
            }
            break;
        case APP_TCPIP_OPENING_SERVER:
        {
            SYS_CONSOLE_PRINT("Waiting for Client Connection on port: %d\r\n", SERVER_PORT);
            appData.socket = TCPIP_UDP_ServerOpen(IP_ADDRESS_TYPE_IPV4, SERVER_PORT, 0);
            if (appData.socket == INVALID_SOCKET)
            {
                SYS_CONSOLE_MESSAGE("Couldn't open server socket\r\n");
                break;
            }
            appData.state = APP_TCPIP_WAIT_FOR_CONNECTION;
        }
        break;

        case APP_TCPIP_WAIT_FOR_CONNECTION:
        {
            if (!TCPIP_UDP_IsConnected(appData.socket))
            {
                return;
            }
            else
            {
                // We got a connection
                appData.state = APP_TCPIP_SERVING_CONNECTION;
                SYS_CONSOLE_MESSAGE("Received a connection\r\n");
            }
        }
        break;

        case APP_TCPIP_SERVING_CONNECTION:
        {
            if (!TCPIP_UDP_IsConnected(appData.socket))
            {
                appData.state = APP_TCPIP_CLOSING_CONNECTION;
                SYS_CONSOLE_MESSAGE("Connection was closed\r\n");
                break;
            }
            int16_t wMaxGet, wMaxPut, wCurrentChunk;
            uint16_t w, w2;
            uint8_t AppBuffer[32];
            // Figure out how many bytes have been received and how many we can transmit.
            wMaxGet = TCPIP_UDP_GetIsReady(appData.socket);	// Get UDP RX FIFO byte count
            wMaxPut = UDPIsPutReady(appData.socket);

            //SYS_CONSOLE_PRINT("\t%d bytes are available.\r\n", wMaxGet);
            if (wMaxGet == 0)
            {
                break;
            }

            if (wMaxPut < wMaxGet)
            {
                wMaxGet = wMaxPut;
            }

            // Process all bytes that we can
            // This is implemented as a loop, processing up to sizeof(AppBuffer) bytes at a time.
            // This limits memory usage while maximizing performance.  Single byte Gets and Puts are a lot slower than multibyte GetArrays and PutArrays.
            wCurrentChunk = sizeof(AppBuffer);
            for(w = 0; w < wMaxGet; w += sizeof(AppBuffer))
            {
                // Make sure the last chunk, which will likely be smaller than sizeof(AppBuffer), is treated correctly.
                if(w + sizeof(AppBuffer) > wMaxGet)
                    wCurrentChunk = wMaxGet - w;

                // Transfer the data out of the TCP RX FIFO and into our local processing buffer.
                TCPIP_UDP_ArrayGet(appData.socket, AppBuffer, wCurrentChunk);

                SYS_CONSOLE_PRINT("\tReceived a message of '%s'\r\n", AppBuffer);

                // Perform the "ToUpper" operation on each data byte
                for(w2 = 0; w2 < wCurrentChunk; w2++)
                {
                    i = AppBuffer[w2];
                    if(i >= 'a' && i <= 'z')
                    {
                            i -= ('a' - 'A');
                            AppBuffer[w2] = i;
                    }
                    else if(i == '\e')   //escape
                    {
                        SYS_CONSOLE_MESSAGE("Connection was closed\r\n");
                    }
                }

                SYS_CONSOLE_PRINT("\tSending a messages '%s'\r\n", AppBuffer);

                // Transfer the data out of our local processing buffer and into the TCP TX FIFO.
                TCPIP_UDP_ArrayPut(appData.socket, AppBuffer, wCurrentChunk);

                TCPIP_UDP_Flush(appData.socket);

                appData.state = APP_TCPIP_CLOSING_CONNECTION;
            }
        }
        break;
        case APP_TCPIP_CLOSING_CONNECTION:
        {
            			// Close the socket connection.
            TCPIP_UDP_Close(appData.socket);

            appData.state = APP_TCPIP_OPENING_SERVER;

        }
        break;
        default:
            break;
    }
}
Esempio n. 5
0
static void TCPIP_ZCLL_Process(void)
{
    int netIx;
    ZCLL_NET_HANDLE *hZcll;
    TCPIP_NET_IF*   pNetIf;
    int     zgzc_action;
    IPV4_ADDR zeroAdd = {0};
#if defined(TCPIP_ZC_INFO_ZCLL) || defined(TCPIP_ZC_DEBUG_ZCLL)
    char zeroconf_dbg_msg[256];
#endif

    for(netIx = 0; netIx < TCPIP_STACK_NumberOfNetworksGet(); netIx++)
    {

        hZcll = phZCLL + netIx;
        pNetIf = (TCPIP_NET_IF*)TCPIP_STACK_IndexToNet(netIx);


        if(hZcll->zcll_state == SM_INIT)
        {   // nothing to do in this state
            continue;
        }

        if(!TCPIP_STACK_NetworkIsLinked(pNetIf))
        {   // lost connection; re-start
            hZcll->zcll_state = SM_ADDR_INIT;
            TCPIP_STACK_AddressServiceEvent(pNetIf, TCPIP_STACK_ADDRESS_SERVICE_ZCLL, TCPIP_STACK_ADDRESS_SERVICE_EVENT_CONN_LOST);
        }

        switch(hZcll->zcll_state)
        {
            case SM_ADDR_INIT:
                /* Not yet seeded in init routine */
                /* setup random number generator
                 * we key this off the MAC-48 HW identifier
                 * the first 3 octets are the manufacturer
                 * the next 3 the serial number
                 * we'll use the last four for the largest variety
                 */

                hZcll->conflict_count = 0;
                _TCPIPStackSetConfigAddress(pNetIf, &zeroAdd, &zeroAdd, true);
                hZcll->probe_count = 0;

                hZcll->zcll_state = SM_ADDR_PROBE;
                INFO_ZCLL_PRINT("ADDR_INIT --> ADDR_PROBE \r\n");

                // No break. Fall through

            case SM_ADDR_PROBE:

                zgzc_action = zgzc_wait_for(&hZcll->random_delay, &hZcll->event_time, &hZcll->time_recorded);

                if(zgzc_action == ZGZC_STARTED_WAITING)
                {

                    if (hZcll->probe_count == 0)
                    {
                        // First probe. Wait for [0 ~ PROBE_WAIT] seconds before sending the probe.

                        hZcll->random_delay = (_zcll_rand() % (PROBE_WAIT * SYS_TMR_TickCounterFrequencyGet()));
                        DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"PROBE_WAIT Random Delay [%d]: %ld secs \r\n",
                                hZcll->probe_count,
                                hZcll->random_delay);
                    }
                    else if (hZcll->probe_count < PROBE_NUM)
                    {
                        // Subsequent probes. Wait for [PROBE_MIN ~ PROBE_MAX] seconds before sending the probe.

                        hZcll->random_delay = ( (_zcll_rand() % ((PROBE_MAX-PROBE_MIN) * SYS_TMR_TickCounterFrequencyGet()) ) +
                                (PROBE_MIN * SYS_TMR_TickCounterFrequencyGet()) );

                        DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"PROBE Random Delay [%d]: %ld ticks \r\n",
                                hZcll->probe_count,
                                hZcll->random_delay);
                    }
                    else
                    {
                        // Completed PROBE_NUM of probes. Now wait for ANNOUNCE_WAIT seconds to determine if
                        // we can claim it.

                        hZcll->random_delay = (ANNOUNCE_WAIT * SYS_TMR_TickCounterFrequencyGet());
                        DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"ANNOUNCE_WAIT delay [%d]: %ld ticks\r\n",
                                hZcll->probe_count,
                                hZcll->random_delay /*SYS_TMR_TickCounterFrequencyGet() */);
                    }

                    DEBUG0_ZCLL_PRINT((char*)zeroconf_dbg_msg);
                    break;
                }
                else if(zgzc_action == ZGZC_STARTED_WAITING)
                {   // Not Completed the delay proposed
                    break;
                }

                // Completed the delay required

                DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"   delay: %ld ticks " \
                        "completed \r\n", hZcll->random_delay);
                DEBUG0_ZCLL_PRINT((char *)zeroconf_dbg_msg);

                if(hZcll->zcll_flags.probe_conflict)
                {
                    /* Conflict with selected address */
                    INFO_ZCLL_PRINT("Probe Conflict-1 Detected. Need to select diff addr \r\n");
                    hZcll->temp_IP_addr.Val = 0x0;

                    hZcll->conflict_count++;
                    _TCPIPStackSetConfigAddress(pNetIf, &zeroAdd, &zeroAdd, true);
                }
                else if((hZcll->conflict_count == 0) &&
                        hZcll->temp_IP_addr.Val      &&
                        pNetIf->netIPAddr.Val != 0x0 &&
                        (TCPIP_ARP_IsResolved(pNetIf,&hZcll->temp_IP_addr, &hZcll->temp_MAC_addr)) )
                {
                    if(!memcmp (&hZcll->temp_MAC_addr, &pNetIf->netMACAddr, 6) )
                    {
                        DEBUG0_ZCLL_PRINT("SM_ADDR_PROBE: Resolved with our address only. " \
                                "Rare Case !!!! \r\n");
                    }
                    else
                    {
                        /* Conflict with selected address */
                        INFO_ZCLL_PRINT("Probe Conflict-2 Detected. Need to select diff addr \r\n");
                        hZcll->temp_IP_addr.Val = 0x0;

                        hZcll->conflict_count++;
                        _TCPIPStackSetConfigAddress(pNetIf, &zeroAdd, &zeroAdd, true);
                    }
                }

                if ((hZcll->zcll_flags.probe_conflict == 1) ||
                        (!hZcll->bDefaultIPTried))
                {
                    /*
                     * Pick random IP address in IPv4 link-local range
                     * 169.254.1.0/16 is the allowed address range however
                     * 169.254.0.0/24 and 169.254.255.0/24 must be excluded,
                     * which removes 512 address from our 65535 candidates.
                     * That leaves us with 65023 (0xfdff).
                     * The link-local address must start with 169.254.#.#
                     * If it does not then assign it the default value of
                     169.254.1.2 and send out probe.
                     */
                    hZcll->probe_count = 0;

                    if(!hZcll->bDefaultIPTried)
                    {
                        // First probe, and the default IP is a valid IPV4_SOFTAP_LLBASE address.
                        if (((!hZcll->bDefaultIPTried)          &&
                                    (pNetIf->DefaultIPAddr.v[0] != 169)) ||
                                ((pNetIf->DefaultIPAddr.v[1] != 254) &&
                                 (pNetIf->DefaultIPAddr.v[2] != 0)   &&
                                 (pNetIf->DefaultIPAddr.v[3] != 255)))
                        {

                            WARN_ZCLL_MESG(zeroconf_dbg_msg,"\r\n%d.%d.%d.%d not a valid link local addess. "
                                    "Autogenerating address.\r\n"
                                    ,pNetIf->DefaultIPAddr.v[0],pNetIf->DefaultIPAddr.v[1]
                                    ,pNetIf->DefaultIPAddr.v[2],pNetIf->DefaultIPAddr.v[3]);
                            WARN_ZCLL_PRINT((char *)zeroconf_dbg_msg);
                            // First probe, if the default IP is a valid IPv4 LL then use it.
                            hZcll->temp_IP_addr.Val = (IPV4_LLBASE | ((abs(_zcll_rand()) % 0xfdff) ));
                            hZcll->bDefaultIPTried = 1;
                        }
                        else
                        {
                            hZcll->temp_IP_addr.Val = TCPIP_Helper_ntohl(pNetIf->DefaultIPAddr.Val);
                        }

                        hZcll->bDefaultIPTried = 1;
                    }
                    else
                    {
                        hZcll->temp_IP_addr.Val = (IPV4_LLBASE | ((abs(_zcll_rand()) % 0xfdff) ));
                    }

                    INFO_ZCLL_MESG(zeroconf_dbg_msg,"Picked IP-Addr [%d]: %d.%d.%d.%d \r\n",
                            hZcll->probe_count,
                            hZcll->temp_IP_addr.v[3],hZcll->temp_IP_addr.v[2],
                            hZcll->temp_IP_addr.v[1],hZcll->temp_IP_addr.v[0]);
                    INFO_ZCLL_PRINT((char *)zeroconf_dbg_msg);

                    hZcll->temp_IP_addr.Val = TCPIP_Helper_ntohl((uint32_t) hZcll->temp_IP_addr.Val);
                }

                if((hZcll->zcll_flags.probe_conflict == 1) || (hZcll->probe_count < PROBE_NUM))
                {

                    hZcll->zcll_flags.probe_conflict = 0;

                    TCPIP_ZCLL_ARPAction( pNetIf
                            , &pNetIf->netIPAddr
                            , &hZcll->temp_IP_addr
                            , ARP_OPERATION_REQ | ARP_OPERATION_CONFIGURE
                            , ZCLL_ARP_PROBE);
                    hZcll->probe_count++;

                    DEBUG0_ZCLL_MESG(zeroconf_dbg_msg, "Sending ARP [%d]\r\n", hZcll->probe_count);
                    DEBUG0_ZCLL_PRINT((char *)zeroconf_dbg_msg);

                    break;
                }

                // No conflict detected ...

                if(hZcll->probe_count >= PROBE_NUM)
                {
                    hZcll->zcll_state = SM_ADDR_CLAIM;
                    hZcll->bDefaultIPTried = 0;

                    INFO_ZCLL_PRINT("ADDR_PROBE --> ADDR_CLAIM \r\n");
                }

                break;

            case SM_ADDR_CLAIM:

                zgzc_action = zgzc_wait_for( &hZcll->random_delay, &hZcll->event_time, &hZcll->time_recorded);

                if(zgzc_action == ZGZC_STARTED_WAITING)
                {
                    if (hZcll->bDefaultIPTried == 0)
                    {
                        // First announcement is immediate. We have passed the ANNOUNCE_WAIT in
                        // PROBE state already.

                        hZcll->random_delay = 0;
                    }
                    else
                    {
                        // Subsequent announcements need to wait ANNOUNCE_INTERVAL seconds
                        // before sending the announcement.

                        hZcll->random_delay = (ANNOUNCE_INTERVAL * SYS_TMR_TickCounterFrequencyGet());
                    }
                    break;
                }
                else if(zgzc_action == ZGZC_KEEP_WAITING)
                {   // Not Completed the delay proposed
                    break;
                }

                // Completed the delay required

                DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"ANNOUNCE delay: %ld ticks completed \r\n", hZcll->random_delay);
                DEBUG0_ZCLL_PRINT((char *)zeroconf_dbg_msg);

                if ( hZcll->bDefaultIPTried < ANNOUNCE_NUM )
                {
                    TCPIP_ZCLL_ARPAction(pNetIf,&hZcll->temp_IP_addr,&hZcll->temp_IP_addr, ARP_OPERATION_REQ | ARP_OPERATION_CONFIGURE, ZCLL_ARP_CLAIM);
                    (hZcll->bDefaultIPTried)++;

                    DEBUG0_ZCLL_MESG(zeroconf_dbg_msg, "Sending ANNOUNCEMENT [%d]\r\n", hZcll->bDefaultIPTried);
                    DEBUG0_ZCLL_PRINT((char *)zeroconf_dbg_msg);
                }
                else
                {
                    // Claim it. Goto DEFEND state
                    IPV4_ADDR   zcllMask;
                    zcllMask.Val = IPV4_LLBASE_MASK;
                    _TCPIPStackSetConfigAddress(pNetIf, &hZcll->temp_IP_addr, &zcllMask, false);
                    hZcll->zcll_state = SM_ADDR_DEFEND;
                    INFO_ZCLL_MESG(zeroconf_dbg_msg,"\r\n******** Taken IP-Addr: " \
                            "%d.%d.%d.%d ******** \r\n",
                            pNetIf->netIPAddr.v[0],pNetIf->netIPAddr.v[1],
                            pNetIf->netIPAddr.v[2],pNetIf->netIPAddr.v[3]);
                    INFO_ZCLL_PRINT((char *)zeroconf_dbg_msg);
                    INFO_ZCLL_PRINT("ADDR_CLAIM --> ADDR_DEFEND \r\n");
                }

                break;

            case SM_ADDR_DEFEND:

                if( hZcll->zcll_flags.late_conflict)
                {
                    if (!hZcll->zcll_flags.defended)
                    {
                        hZcll->zcll_flags.late_conflict = 0;
                        INFO_ZCLL_PRINT("CONFLICT DETECTED !!! \r\n");

                        INFO_ZCLL_PRINT("Defending the Self Address once \r\n");
                        TCPIP_ZCLL_ARPAction( pNetIf
                                ,&pNetIf->netIPAddr
                                ,&pNetIf->netIPAddr
                                ,ARP_OPERATION_RESP | ARP_OPERATION_CONFIGURE
                                ,ZCLL_ARP_DEFEND);

                        hZcll->zcll_flags.defended = true;
                    }
                    else
                    {
                        // We are not allowed to defend another conflict during an active defended period

                        INFO_ZCLL_PRINT("Releasing the IP-Address because of multiple Conflicts \r\n");

                        hZcll->zcll_state = SM_ADDR_RELEASE;

                        hZcll->zcll_flags.defended = false;
                        hZcll->event_time = false;
                        hZcll->random_delay = false;

                        INFO_ZCLL_PRINT("ADDR_DEFEND --> ADDR_RELEASE \r\n");
                        break;
                    }
                }

                if (hZcll->zcll_flags.defended)
                {
                    zgzc_action = zgzc_wait_for(&hZcll->random_delay, &hZcll->event_time, &hZcll->time_recorded);

                    if(zgzc_action == ZGZC_STARTED_WAITING)
                    {
                        hZcll->random_delay = (DEFEND_INTERVAL * SYS_TMR_TickCounterFrequencyGet());
                        DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"DEFEND_INTERVAL Delay : %ld ticks\r\n",
                                hZcll->random_delay/*SYS_TMR_TickCounterFrequencyGet() */);
                        DEBUG0_ZCLL_PRINT((char *)zeroconf_dbg_msg);

                        break; 
                    }
                    else if(zgzc_action == ZGZC_KEEP_WAITING)
                    {   // Not Completed the delay proposed
                        break;
                    }

                    // Completed the delay required

                    DEBUG0_ZCLL_MESG(zeroconf_dbg_msg,"ANNOUNCE delay: %ld ticks " \
                            "completed \r\n", hZcll->random_delay);
                    DEBUG0_ZCLL_PRINT((char *)zeroconf_dbg_msg);

                    hZcll->zcll_flags.defended = false;
                }

                break;

            case SM_ADDR_RELEASE:

                INFO_ZCLL_PRINT("ADDR_RELEASE --> ADDR_INIT\r\n");

                _TCPIPStackSetConfigAddress(pNetIf, &zeroAdd, &zeroAdd, true);

                // Need New Addr
                hZcll->temp_IP_addr.Val = (IPV4_LLBASE | ((abs(_zcll_rand()) % 0xfdff) ));
                hZcll->temp_IP_addr.Val = TCPIP_Helper_ntohl((uint32_t) hZcll->temp_IP_addr.Val);

                hZcll->zcll_state = SM_ADDR_INIT;
                hZcll->time_recorded = false;
                hZcll->zcll_flags.defended      = false;
                hZcll->event_time    = false;
                break;

            default:
                break;
        }

    }

}
Esempio n. 6
0
void APP_Tasks( void )
{
    static IPV4_ADDR dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    int i;

    switch(appData.state)
    {

        case APP_TCPIP_WAIT_FOR_IP:

            // if the IP address of an interface has changed
            // display the new value on the system console
            nNets = TCPIP_STACK_NumberOfNetworksGet();

            for (i = 0; i < nNets; i++)
            {
                netH = TCPIP_STACK_IndexToNet(i);
                ipAddr.Val = TCPIP_STACK_NetAddress(netH);
                if(dwLastIP[i].Val != ipAddr.Val)
                {
                    dwLastIP[i].Val = ipAddr.Val;

                    SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                    SYS_CONSOLE_MESSAGE(" IP Address: ");
                    SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
                    if (ipAddr.v[0] != 0 && ipAddr.v[0] != 169) // Wait for a Valid IP
                    {
                        appData.state = APP_BSD_CREATE_SOCKET;
                    }
                }
            }
            break;
       case APP_BSD_CREATE_SOCKET:
            {
            SOCKET udpSkt = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
            if(udpSkt == SOCKET_ERROR)
            {
                appData.state = APP_TCPIP_WAIT_FOR_IP;
                return;
            }
            else
            {
                appData.socket = (SOCKET)udpSkt;
                appData.state = APP_BSD_BIND;
            }
        }
       break;

        case APP_BSD_BIND:
        {
            struct sockaddr_in addr;
            int addrlen = sizeof(struct sockaddr_in);
            addr.sin_port = SERVER_PORT;
            addr.sin_addr.S_un.S_addr = IP_ADDR_ANY;
            if( bind(appData.socket, (struct sockaddr*)&addr, addrlen) == SOCKET_ERROR )
            {
                closesocket(appData.socket);
                appData.state = APP_TCPIP_SERVING_CONNECTION;
            }
            else
            {
                appData.state = APP_TCPIP_SERVING_CONNECTION;
            }
        }
        break;

        case APP_TCPIP_SERVING_CONNECTION:
        {
            uint8_t AppBuffer[32];

            struct sockaddr_in clientaddr;
            int len;

            // Figure out how many bytes have been received and how many we can transmit.
            int i = recvfrom(appData.socket, (char*)AppBuffer, sizeof(AppBuffer), 0, (struct sockaddr *)&clientaddr,&len);

            if (i <= 0)
            {
                break;
            }

            SYS_CONSOLE_PRINT("Recieved '%s'\r\n", AppBuffer);

            sendto(appData.socket, (char *)AppBuffer, i, 0, (struct sockaddr *)&clientaddr, len);

            appData.state = APP_TCPIP_CLOSING_CONNECTION;
        }
        break;
        case APP_TCPIP_CLOSING_CONNECTION:
        {
            closesocket(appData.socket);

            appData.state = APP_BSD_CREATE_SOCKET;

        }
        break;
        default:
            break;
    }
}
void AppConfig_NetworkInitialise(void)
{
    bool configDefault = false;
    bool logSettingsDefault = false;
    bool deviceServerConfig = false;

    //Unfortunately defaults to connected
    DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT *event = DRV_WIFI_SoftApEventInfoGet();
    if (event)
    {
        event->event = -1;
    }

    ConfigStore_Initialize();
    // TODO - remove debug
//   	CreatorConsole_Printf("DeviceConfig size = %d, LogConfig size = %d\r\n", sizeof(ConfigStruct), sizeof(LoggingSettingsStruct));
//   	CreatorConsole_Printf("LOGGINGSETTINGS_PAGEOFFSET = %d\r\n", LOGGINGSETTINGS_PAGEOFFSET);
//   	CreatorConsole_Printf("DRV_NVM_PAGE_SIZE  = %d\r\n", DRV_NVM_PAGE_SIZE);

    if (!ConfigStore_Config_Read())
        CreatorConsole_Puts("ERROR: Could not read config_store memory.\r\n");

    if (!ConfigStore_Config_IsValid())
    {
        if (!ConfigStore_Config_IsMagicValid())
            CreatorConsole_Puts("\r\nWriting default device configuration for first-time use...");
        else
            CreatorConsole_Puts("\r\nDevice configuration invalid. Re-writing default configuration...");

        configDefault = true;
        if (!ConfigStore_Config_ResetToDefaults())
            CreatorConsole_Puts("ERROR: Could not reset config to defaults\r\n");

        if (!ConfigStore_Config_Write())
            CreatorConsole_Puts("ERROR: Could not write default config\r\n");

        CreatorConsole_Puts(" Done\r\n");
    }

    if (!ConfigStore_LoggingSettings_Read())
        CreatorConsole_Puts("ERROR: Could not read loggingSettings.\r\n");

    if (!ConfigStore_LoggingSettings_IsValid())
    {
        if (!ConfigStore_LoggingSettings_IsMagicValid())
            CreatorConsole_Puts("\r\nWriting default device logging-settings for first-time use...");
        else
            CreatorConsole_Puts("\r\nDevice logging-settings invalid. Re-writing defaults...");

        logSettingsDefault = true;
        if (!ConfigStore_LoggingSettings_ResetToDefaults())
            CreatorConsole_Puts("ERROR: Could not reset config to defaults\r\n");

        if (!ConfigStore_LoggingSettings_Write())
            CreatorConsole_Puts("ERROR: Could not write default config\r\n");

        CreatorConsole_Puts(" Done\r\n");
    }

    CreatorLogLevel level = ConfigStore_GetLoggingLevel();
    CreatorLog_SetLevel(level);
    Client_SetLogLevel(level);

    if (!ConfigStore_DeviceServerConfig_Read())
        CreatorConsole_Puts("ERROR: Could not read device server settings.\r\n");

    if (!ConfigStore_DeviceServerConfig_IsValid())
    {
        if (!ConfigStore_DeviceServerConfig_IsMagicValid())
            CreatorConsole_Puts("\r\nWriting default device server settings for first-time use...");
        else
            CreatorConsole_Puts("\r\nDevice server settings invalid. Re-writing defaults...");

        deviceServerConfig = true;
        if (!ConfigStore_DeviceServerConfig_ResetToDefaults())
            CreatorConsole_Puts("ERROR: Could not reset device server config to defaults\r\n");

        if (!ConfigStore_DeviceServerConfig_Write())
            CreatorConsole_Puts("ERROR: Could not write default device server config\r\n");

        CreatorConsole_Puts(" Done\r\n");
    }

    CreatorTimer_SetTicksPerSecond(1000);

    // Check date/time has valid minimum value
    // TODO - could use NTP to get time (in app mode), or mobile app could set time (in config mode)
    time_t time = Creator_GetTime(NULL);
    if (time < DATETIME_MINIMUM_VALUE)
    {
        Creator_SetTime(DATETIME_MINIMUM_VALUE);
    }
    else
    {
        Creator_SetTime(time);	// Kick start the date/time support
    }
    
    // Add initial activity log entries (Note: must be after date/time and logging settings initialised)
    if (configDefault && logSettingsDefault && deviceServerConfig)
    {
        Creator_Log(CreatorLogLevel_Warning, "Default configuration settings set for first-time use");
    }
    else
    {
        if (configDefault)
            Creator_Log(CreatorLogLevel_Error, "Creator configuration lost, default values set");
        if (logSettingsDefault)
            Creator_Log(CreatorLogLevel_Error, "Logging settings lost, default values set");
        if (deviceServerConfig)
            Creator_Log(CreatorLogLevel_Error, "Device server configuration lost, default values set");
    }

    if ((BSP_SwitchStateGet(BSP_SWITCH_1) == BSP_SWITCH_STATE_PRESSED) && (BSP_SwitchStateGet(BSP_SWITCH_2) == BSP_SWITCH_STATE_PRESSED))
        _RunningInConfigurationMode = true;

    // Only run in application mode if device has valid configuration
    if (!_RunningInConfigurationMode && (!ConfigStore_Config_IsValid() || ConfigStore_StartInConfigMode() || !AppConfig_CheckValidAppConfig(false)))
        _RunningInConfigurationMode = true;

    int numberOfNetworkInterfaces = TCPIP_STACK_NumberOfNetworksGet();
    int index;
    TCPIP_NET_HANDLE networkHandle = 0;
    do
    {
        CreatorThread_SleepMilliseconds(NULL, 500);
        for (index = 0; index < numberOfNetworkInterfaces; index++)
        {
            networkHandle = TCPIP_STACK_IndexToNet(index);
            if (TCPIP_STACK_NetIsUp(networkHandle))
            {
                break;
            }
        }
    } while (index == numberOfNetworkInterfaces);

    CreatorConsole_Puts("Done\r\n");

    TCPIP_DHCP_Disable(networkHandle);
    TCPIP_DNS_Disable(networkHandle, true);
    TCPIP_DHCPS_Disable(networkHandle);
    TCPIP_DNSS_Disable(networkHandle);

    if (!ConfigStore_SoftAPSSIDValid())
    {
        const unsigned int MAC_ADDRESS_UNIQUE_PORTION_LENGTH = 6;
        char *softAPSSID = (char *) ConfigStore_GetSoftAPSSID();
        unsigned int baseStrLen = strlen(WF_DEFAULT_SSID_NAME_PREFIX) * sizeof(char);
        memset(softAPSSID, 0, CONFIG_STORE_DEFAULT_FIELD_LENGTH);
        memcpy(softAPSSID, WF_DEFAULT_SSID_NAME_PREFIX, baseStrLen);
        char macStr[MAC_ADDRESS_LENGTH];
        memset(macStr, 0, sizeof(macStr));
        uint8_t mac[MAC_ADDRESS_LENGTH / 2];
        DRV_WIFI_MacAddressGet(mac);
        unsigned int i = 0;
        for (i = 0; i < MAC_ADDRESS_LENGTH / 2; i++)
            sprintf(macStr + (i * 2 * sizeof(char)), "%02X", mac[i]);
        // Store device MAC Address so it doesn't need to be retrieved more than once
        ConfigStore_SetMacAddress(macStr);
        // Use unique portion of mac address to build SSID (last three bytes)
        strncpy((char*) softAPSSID + baseStrLen, macStr + MAC_ADDRESS_LENGTH - MAC_ADDRESS_UNIQUE_PORTION_LENGTH, MAC_ADDRESS_UNIQUE_PORTION_LENGTH);

        // Set the device's name to the same as the SoftAP SSID if it is still the blank value
        if (strcmp(ConfigStore_GetDeviceName(), CREATOR_BLANK_DEVICE_NAME) == 0)
            ConfigStore_SetDeviceName(softAPSSID);

        // Update the Device's configuration information
        ConfigStore_Config_UpdateCheckbyte();
        if (!ConfigStore_Config_Write())
            CreatorConsole_Puts("ERROR: Could not write default config");
    }

    uint8_t networkType;
    uint8_t securityType = 0;
    uint8_t connectionState;
    DRV_WIFI_NetworkTypeGet(&networkType);

    if (networkType == DRV_WIFI_NETWORK_TYPE_ADHOC)
    {
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);
        } while ((connectionState == DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS) || (connectionState == DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS));
    }
    else if (networkType == DRV_WIFI_NETWORK_TYPE_SOFT_AP)
    {
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);
        } while ((connectionState != DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS) && (connectionState == DRV_WIFI_CSTATE_CONNECTION_PERMANENTLY_LOST));
    }

    DRV_WIFI_ReconnectModeSet(0, DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT, 40, DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT);

    DRV_WIFI_Disconnect();

    do
    {
        CreatorThread_SleepMilliseconds(NULL, 100);
        DRV_WIFI_ConnectionStateGet(&connectionState);
    } while (connectionState != DRV_WIFI_CSTATE_NOT_CONNECTED);

    if (_AppInfo)
    {
        CreatorConsole_Puts("\r\n --- ");
        CreatorConsole_Puts(_AppInfo->ApplicationName);
        CreatorConsole_Puts(" v");
        CreatorConsole_Puts(_AppInfo->ApplicationVersion);
        CreatorConsole_Puts(" ---\r\n");
    }
    const char *networkSSID;
    const char *softAPPPassword = NULL;
    if (_RunningInConfigurationMode)
    {
        networkType = DRV_WIFI_NETWORK_TYPE_SOFT_AP;
        CreatorConsole_Puts("              [Configuration Mode]\r\n\r\n\r\n");
        networkSSID = ConfigStore_GetSoftAPSSID();
        const char *mac = ConfigStore_GetSoftAPSSID();
        int networkSSIDLength = strlen(networkSSID);
        DRV_WIFI_SsidSet((uint8_t *) networkSSID, networkSSIDLength);
        softAPPPassword = ConfigStore_GetSoftAPPassword();
        securityType = SetWEPKey(softAPPPassword);
        DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_SOFT_AP);

        while (DRV_WIFI_ContextLoad() == TCPIP_MAC_RES_PENDING)
        {
            CreatorThread_SleepMilliseconds(NULL, 50);
        }
    }
    else
    {
        networkType = DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE;
        UIControl_SetUIState(AppUIState_AppInitConnectingToNetwork);
        CreatorConsole_Puts("               [Application Mode]\r\n\r\n\r\n");

        uint8_t channelList[] = { };
        DRV_WIFI_ChannelListSet(channelList, sizeof(channelList));

        DRV_WIFI_ReconnectModeSet(DRV_WIFI_RETRY_FOREVER,         // retry forever to connect to Wi-Fi network
                DRV_WIFI_ATTEMPT_TO_RECONNECT,  // reconnect on deauth from AP
                40,                             // beacon timeout is 40 beacon periods
                DRV_WIFI_ATTEMPT_TO_RECONNECT); // reconnect on beacon timeout

        networkSSID = ConfigStore_GetNetworkSSID();
        int networkSSIDLength = strlen(networkSSID);
        DRV_WIFI_SsidSet((uint8_t *) networkSSID, networkSSIDLength);

        WiFiEncryptionType encryptionType = ConfigStore_GetEncryptionType();
        switch (encryptionType) {
            case WiFiEncryptionType_WEP:
            {
                const char *wepKey = ConfigStore_GetNetworkPassword();
                securityType = SetWEPKey(wepKey);
            }
                break;
            case WiFiEncryptionType_Open:
                DRV_WIFI_SecurityOpenSet();
                securityType = DRV_WIFI_SECURITY_OPEN;
                break;
            case WiFiEncryptionType_WPA:
            case WiFiEncryptionType_WPA2:
            default:
            {
                DRV_WIFI_WPA_CONTEXT context;
                if (encryptionType == WiFiEncryptionType_WPA)
                    context.wpaSecurityType = DRV_WIFI_SECURITY_WPA_WITH_KEY; // DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE;
                else
                    context.wpaSecurityType = DRV_WIFI_SECURITY_WPA2_WITH_KEY; //DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE;
                const char *passPhrase = ConfigStore_GetNetworkPassword();
                int keyLength = strlen(passPhrase);
                memcpy(context.keyInfo.key, passPhrase, keyLength);
                context.keyInfo.keyLength = keyLength;

                while (TCPIP_MAC_RES_OK != DRV_WIFI_KeyDerive(keyLength, context.keyInfo.key, networkSSIDLength, networkSSID))
                    ;
                context.keyInfo.keyLength = 32;

                DRV_WIFI_SecurityWpaSet(&context);
                securityType = context.wpaSecurityType;
            }
                break;
        }
        DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE);
    }

    CreatorConsole_Puts("==========================\r\n");
    CreatorConsole_Puts("*** WiFi Configuration ***\r\n");
    CreatorConsole_Puts("==========================\r\n");
    CreatorConsole_Puts("MAC:\t\t");
    CreatorConsole_Puts(ConfigStore_GetMacAddress());
    CreatorConsole_Puts("\r\nSSID:\t\t");
    CreatorConsole_Puts(networkSSID);
    if (softAPPPassword)
    {
        CreatorConsole_Puts("\r\nPassword:\t");
        CreatorConsole_Puts(softAPPPassword);

    }
    CreatorConsole_Puts("\r\nNetwork Type:\t");

    switch (networkType) {
        case DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE:
            CreatorConsole_Puts("Infrastructure");
            break;
        case DRV_WIFI_NETWORK_TYPE_ADHOC:
            CreatorConsole_Puts("AdHoc");
            break;
        case DRV_WIFI_NETWORK_TYPE_SOFT_AP:
            CreatorConsole_Puts("SoftAP");
            break;
    }
    CreatorConsole_Puts("\r\nSecurity:\t");

    switch (securityType) {
        case DRV_WIFI_SECURITY_OPEN:
            CreatorConsole_Puts("Open");
            break;
        case DRV_WIFI_SECURITY_WEP_40:
            CreatorConsole_Puts("WEP40");
            break;
        case DRV_WIFI_SECURITY_WEP_104:
            CreatorConsole_Puts("WEP104");
            break;
        case DRV_WIFI_SECURITY_WPA_WITH_KEY:
        case DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE:
            CreatorConsole_Puts("WPA");
            break;
        case DRV_WIFI_SECURITY_WPA2_WITH_KEY:
        case DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE:
            CreatorConsole_Puts("WPA2");
            break;
        case DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY:
        case DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:
            CreatorConsole_Puts("WPA AUTO");
            break;
    }

    DRV_WIFI_PsPollDisable();
    DRV_WIFI_Connect();

    CreatorConsole_Puts("\r\n\r\n");

    if (_RunningInConfigurationMode)
    {
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);
        } while ((connectionState != DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS) && (connectionState != DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS));
        TCPIP_DHCPS_Enable(networkHandle);
        TCPIP_DNSS_Enable(networkHandle);
        UIControl_SetUIState(AppUIState_SoftApNotConnected);
        IPV4_ADDR ipAdd;
        ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
        CreatorConsole_Puts(TCPIP_STACK_NetNameGet(networkHandle));
        CreatorConsole_Puts(" IP Address: ");
        CreatorConsole_Printf("%d.%d.%d.%d \r\n", ipAdd.v[0], ipAdd.v[1], ipAdd.v[2], ipAdd.v[3]);
    }
    else
    {
        CreatorConsole_Printf("\n\rConnecting to WiFi network...\n\r");
        bool displayedConnectionWarningToUser = false;
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);

            if (!displayedConnectionWarningToUser)
            {
                SYS_UPTIME uptime;
                AppConfig_Uptime(&uptime);
                if (uptime.Seconds >= 30 && !AppConfig_IsDeviceOnline())
                {
                    CreatorConsole_Printf("\n\r\n\r");
                    CreatorConsole_Printf("\n\r**********************************************************************");
                    CreatorConsole_Printf("\n\r* Your WiFire is taking a long time to connect to your WiFi network. *");
                    CreatorConsole_Printf("\n\r* Please check your network settings are correctly configured.       *");
                    CreatorConsole_Printf("\n\r*                                                                    *");
                    CreatorConsole_Printf("\n\r* Hold BTN1 and BTN2 whilst pressing the RESET button on your WiFire *");
                    CreatorConsole_Printf("\n\r* to restart it in Configuration mode.                               *");
                    CreatorConsole_Printf("\n\r*                                                                    *");
                    CreatorConsole_Printf("\n\r* You can then review and change your settings if required.          *");
                    CreatorConsole_Printf("\n\r**********************************************************************");
                    CreatorConsole_Printf("\n\r\n\r");
                    displayedConnectionWarningToUser = true;
                }
            }

        } while ((connectionState != DRV_WIFI_CSTATE_CONNECTED_INFRASTRUCTURE));
        TCPIP_DHCP_Enable(networkHandle);
        IPV4_ADDR ipAdd;
        ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
        while (ipAdd.Val == 0x1901A8C0)
        {
            CreatorThread_SleepMilliseconds(NULL, 500);
            ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
        }
        CreatorConsole_Puts(TCPIP_STACK_NetNameGet(networkHandle));
        CreatorConsole_Puts(" IP Address: ");
        CreatorConsole_Printf("%d.%d.%d.%d \r\n", ipAdd.v[0], ipAdd.v[1], ipAdd.v[2], ipAdd.v[3]);
        TCPIP_DNS_Enable(networkHandle, TCPIP_DNS_ENABLE_PREFERRED);
        UIControl_SetUIState(AppUIState_AppInitConnectedToNetwork);
    }
    CreatorConsole_Puts("\r\nConnected\r\n");

    //	IPV4_ADDR ipAdd;
    //	ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
    //	CreatorConsole_Puts(TCPIP_STACK_NetNameGet(networkHandle));
    //	CreatorConsole_Puts(" IP Address: ");
    //	CreatorConsole_Printf("%d.%d.%d.%d \r\n", ipAdd.v[0], ipAdd.v[1], ipAdd.v[2], ipAdd.v[3]);

}
Esempio n. 8
0
void APP_Tasks ( void )
{
    SYS_STATUS          tcpipStat;
    const char          *netName, *netBiosName;
    static IPV4_ADDR    dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    TCPIP_NET_HANDLE    netH;
    int                 i, nNets;

    PubnubStaticDemoProcess();

    /* Check the application's current state. */
    switch ( appData.state )
    {
        /* Application's initial state. */
        case APP_STATE_INIT:
        {
            tcpipStat = TCPIP_STACK_Status(sysObj.tcpip);
            if(tcpipStat < 0)
            {   // some error occurred
                SYS_CONSOLE_MESSAGE(" APP: TCP/IP stack initialization failed!\r\n");
                appData.state = APP_TCPIP_ERROR;
            }
            else if(tcpipStat == SYS_STATUS_READY)
            {
                // now that the stack is ready we can check the
                // available interfaces
                nNets = TCPIP_STACK_NumberOfNetworksGet();
                for(i = 0; i < nNets; i++)
                {

                    netH = TCPIP_STACK_IndexToNet(i);
                    netName = TCPIP_STACK_NetNameGet(netH);
                    netBiosName = TCPIP_STACK_NetBIOSName(netH);

#if defined(TCPIP_STACK_USE_NBNS)
                    SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS enabled\r\n", netName, netBiosName);
#else
                    SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS disabled\r\n", netName, netBiosName);
#endif  // defined(TCPIP_STACK_USE_NBNS)

                }
                appData.state = APP_TCPIP_WAIT_FOR_IP;

            }
            break;
        }
        case APP_TCPIP_WAIT_FOR_IP:

            // if the IP address of an interface has changed
            // display the new value on the system console
            nNets = TCPIP_STACK_NumberOfNetworksGet();

            for (i = 0; i < nNets; i++)
            {
                netH = TCPIP_STACK_IndexToNet(i);
                ipAddr.Val = TCPIP_STACK_NetAddress(netH);
                if(dwLastIP[i].Val != ipAddr.Val)
                {
                    dwLastIP[i].Val = ipAddr.Val;

                    SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                    SYS_CONSOLE_MESSAGE(" IP Address: ");
                    SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
                    if (ipAddr.v[0] != 0 && ipAddr.v[0] != 169) // Wait for a Valid IP
                    {
                        appData.state = APP_TCPIP_WAITING_FOR_INIT;
                    }
                }
            }
            break;

        case APP_TCPIP_WAITING_FOR_INIT:
        {
            PubnubStaticDemoInit();
            appData.state =  APP_TCPIP_PUBNUB;
        }
        break;

        default:
        {
            break;
        }
    }
}
Esempio n. 9
0
//
// Main application entry point.
//
int main(void)
{
    static SYS_TICK startTick = 0;
    static IPV4_ADDR dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;

    SYS_USERIO_LED_STATE LEDstate = SYS_USERIO_LED_DEASSERTED;
    int                 i, nNets;
    TCPIP_NET_HANDLE    netH;
    const char          *netName, *netBiosName;

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
    char mDNSServiceName[] = "MyWebServiceNameX ";     // base name of the service Must not exceed 16 bytes long
                                                       // the last digit will be incremented by interface
#endif  // defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)


    // perform system initialization
    SYS_Initialize(0);

    SYS_CONSOLE_MESSAGE("\r\n\n\n ---  TCPIP Demo Starts!  --- \r\n");
    SYS_OUT_MESSAGE("TCPIPStack " TCPIP_STACK_VERSION "  ""                ");

        // Display the names associated with each interface
    nNets = TCPIP_STACK_NumberOfNetworksGet();
    for(i = 0; i < nNets; i++)
    {

        netH = TCPIP_STACK_IndexToNet(i);
        netName = TCPIP_STACK_NetNameGet(netH);
        netBiosName = TCPIP_STACK_NetBIOSName(netH);

#if defined(TCPIP_STACK_USE_NBNS)
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS enabled\r\n", netName, netBiosName);
#else
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS disabled\r\n", netName, netBiosName);
#endif  // defined(TCPIP_STACK_USE_NBNS)

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
        mDNSServiceName[sizeof(mDNSServiceName) - 2] = '1' + i;
        TCPIP_MDNS_ServiceRegister( netH
                , mDNSServiceName                   // name of the service
                ,"_http._tcp.local"                 // type of the service
                ,80                                 // TCP or UDP port, at which this service is available
                ,((const uint8_t *)"path=/index.htm")  // TXT info
                ,1                                  // auto rename the service when if needed
                ,NULL                               // no callback function
                ,NULL);                             // no application context
#endif //TCPIP_STACK_USE_ZEROCONF_MDNS_SD
    }

#if defined(WF_UPDATE_FIRMWARE_UART_24G)
    extern bool    WF_FirmwareUpdate_Uart_24G(void);
    WF_FirmwareUpdate_Uart_24G();
#endif

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while (1)
    {
        SYS_Tasks();

        // Blink LED0 every second.
        if (SYS_TICK_Get() - startTick >= SYS_TICK_TicksPerSecondGet() / 2ul)
        {
            startTick = SYS_TICK_Get();
            LEDstate ^= SYS_USERIO_LED_ASSERTED;
            SYS_USERIO_SetLED(SYS_USERIO_LED_0, LEDstate);
        }

        // if the IP address of an interface has changed
        // display the new value on the system console
        nNets = TCPIP_STACK_NumberOfNetworksGet();
        for (i = 0; i < nNets; i++)
        {
            netH = TCPIP_STACK_IndexToNet(i);
            ipAddr.Val = TCPIP_STACK_NetAddress(netH);
            if(dwLastIP[i].Val != ipAddr.Val)
            {
                dwLastIP[i].Val = ipAddr.Val;

                SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                SYS_CONSOLE_MESSAGE(" IP Address: ");
                SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
            }
        }

#if (WF_DEFAULT_NETWORK_TYPE == WF_NETWORK_TYPE_SOFT_AP)

        if (g_scan_done) {
           if (g_prescan_waiting) {
               SYS_CONSOLE_MESSAGE((const char*)"\n SoftAP prescan results ........ \r\n\n");
               SCANCXT.displayIdx = 0;
               extern void WFDisplayScanMgr(void);
               while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                   WFDisplayScanMgr();
               }
               SYS_CONSOLE_MESSAGE((const char*)"\r\n ");

       #if defined(WF_CS_TRIS)
                Demo_Wifi_Connect();
       #endif
               g_scan_done = 0;
               g_prescan_waiting = 0;
           }
        }
#endif // (WF_DEFAULT_NETWORK_TYPE == WF_NETWORK_TYPE_SOFT_AP)

#if defined(WF_UPDATE_FIRMWARE_UART_24G)
    WF_FirmwareUpdate_Uart_24G();
#endif

#if defined(WF_UPDATE_FIRMWARE_TCPCLIENT_24G)
    WF_FirmwareUpdate_TcpClient_24G();
#endif

    }
}
Esempio n. 10
0
void APP_Tasks ( void )
{
    SYS_STATUS          tcpipStat;
    const char          *netName, *netBiosName;
    static IPV4_ADDR    dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    TCPIP_NET_HANDLE    netH;
    int                 i, nNets;

    /* Check the application's current state. */
    switch ( appData.state )
    {
        /* Application's initial state. */
        case APP_STATE_INIT:
        {
            tcpipStat = TCPIP_STACK_Status(sysObj.tcpip);
            if(tcpipStat < 0)
            {   // some error occurred
                SYS_CONSOLE_MESSAGE(" APP: TCP/IP stack initialization failed!\r\n");
                appData.state = APP_DONE;
            }
            else if(tcpipStat == SYS_STATUS_READY)
            {
                // now that the stack is ready we can check the
                // available interfaces
                nNets = TCPIP_STACK_NumberOfNetworksGet();
                for(i = 0; i < nNets; i++)
                {

                    netH = TCPIP_STACK_IndexToNet(i);
                    netName = TCPIP_STACK_NetNameGet(netH);
                    netBiosName = TCPIP_STACK_NetBIOSName(netH);

#if defined(TCPIP_STACK_USE_NBNS)
                    SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS enabled\r\n", netName, netBiosName);
#else
                    SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS disabled\r\n", netName, netBiosName);
#endif  // defined(TCPIP_STACK_USE_NBNS)

                }
                appData.state = APP_TCPIP_WAIT_FOR_IP;

            }
            break;
        }
        case APP_TCPIP_WAIT_FOR_IP:

            // if the IP address of an interface has changed
            // display the new value on the system console
            nNets = TCPIP_STACK_NumberOfNetworksGet();

            for (i = 0; i < nNets; i++)
            {
                netH = TCPIP_STACK_IndexToNet(i);
                ipAddr.Val = TCPIP_STACK_NetAddress(netH);
                if(dwLastIP[i].Val != ipAddr.Val)
                {
                    dwLastIP[i].Val = ipAddr.Val;

                    SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                    SYS_CONSOLE_MESSAGE(" IP Address: ");
                    SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
                    if (ipAddr.v[0] != 0 && ipAddr.v[0] != 169) // Wait for a Valid IP
                    {
                        appData.state = APP_START_LISTENING;
                    }
                }
            }
            break;
        case APP_START_LISTENING:
        {
            SYS_CONSOLE_PRINT("Starting listening on port 8000\r\n");
            struct mg_connection *nc = mg_bind(&mgr, "8000", ev_handler);  // Create listening connection and add it to the event manager
            if (nc == NULL) {
              SYS_CONSOLE_PRINT("Failed to create listener\n\r");
              appData.state = APP_DONE;
              break;
            }
            mg_set_protocol_http_websocket(nc);
            SYS_CONSOLE_PRINT("Listener started\r\n");

            appData.state = APP_POLL;
            break;
        }
        case APP_POLL:
        {
            mg_mgr_poll(&mgr, 1000);
            break;
        }
        case APP_DONE:
        {
            SYS_CONSOLE_PRINT("Server stopped\n\r");
            appData.state = APP_EMPTY;
            break;
        }
        case APP_EMPTY:
        {
            break;
        }
        /* The default state should never be executed. */
        default:
        {
            /* TODO: Handle error in application's state machine. */
            break;
        }
    }
}
Esempio n. 11
0
File: app.c Progetto: ctapang/v0_70b
void APP_Tasks( void )
{
    static IPV4_ADDR dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;
    int i;

    switch(appData.state)
    {

        case APP_TCPIP_WAIT_FOR_IP:

            // if the IP address of an interface has changed
            // display the new value on the system console
            nNets = TCPIP_STACK_NumberOfNetworksGet();

            for (i = 0; i < nNets; i++)
            {
                netH = TCPIP_STACK_IndexToNet(i);
                ipAddr.Val = TCPIP_STACK_NetAddress(netH);
                if(dwLastIP[i].Val != ipAddr.Val)
                {
                    dwLastIP[i].Val = ipAddr.Val;

                    SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                    SYS_CONSOLE_MESSAGE(" IP Address: ");
                    SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
                    if (ipAddr.v[0] != 0 && ipAddr.v[0] != 169) // Wait for a Valid IP
                    {
                        appData.state = APP_TCPIP_WAITING_FOR_COMMAND;
                        SYS_CONSOLE_MESSAGE("Waiting for command type: sendudppacket\r\n");
                    }
                }
            }
            break;
        case APP_TCPIP_WAITING_FOR_COMMAND:
        {
            if (APP_Send_Packet)
            {
                APP_Send_Packet = false;
                DNS_RESULT result = TCPIP_DNS_UsageBegin(0);
                if (result != DNS_RES_OK)
                {
                    SYS_CONSOLE_MESSAGE("Error in DNS aborting 1\r\n");
                    break;
                }
                result = TCPIP_DNS_Resolve(APP_Hostname_Buffer, DNS_TYPE_A);
                if (result != DNS_RES_OK)
                {
                    SYS_CONSOLE_MESSAGE("Error in DNS aborting 2\r\n");
                    TCPIP_DNS_UsageEnd(0);
                    break;
                }
                appData.state = APP_TCPIP_WAIT_ON_DNS;
            }
        }
        break;

        case APP_TCPIP_WAIT_ON_DNS:
        {
            IPV4_ADDR addr;
            switch (_APP_PumpDNS(APP_Hostname_Buffer, &addr))
            {
                case -1:
                {
                    // Some sort of error, already reported
                    appData.state = APP_TCPIP_WAITING_FOR_COMMAND;
                }
                break;
                case 0:
                {
                    // Still waiting
                }
                break;
                case 1:
                {
                    uint16_t port = atoi(APP_Port_Buffer);
                    appData.socket = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_IPV4,
                                                          port,
                                                          (IP_MULTI_ADDRESS*) &addr);
                    if (appData.socket == INVALID_SOCKET)
                    {
                        SYS_CONSOLE_MESSAGE("Could not start connection\r\n");
                        appData.state = APP_TCPIP_WAITING_FOR_COMMAND;
                    }
                    SYS_CONSOLE_MESSAGE("Starting connection\r\n");
                    appData.state = APP_TCPIP_WAIT_FOR_CONNECTION;
                }
                break;
            }
        }
        break;

        case APP_TCPIP_WAIT_FOR_CONNECTION:
        {
            if (!TCPIP_UDP_IsConnected(appData.socket))
            {
                break;
            }
            if(UDPIsPutReady(appData.socket) == 0)
            {
                break;
            }
            TCPIP_UDP_ArrayPut(appData.socket, (uint8_t*)APP_Message_Buffer, strlen(APP_Message_Buffer));
            TCPIP_UDP_Flush(appData.socket);
            appData.state = APP_TCPIP_WAIT_FOR_RESPONSE;
        }
        break;

        case APP_TCPIP_WAIT_FOR_RESPONSE:
        {
            char buffer[180];
            memset(buffer, 0, sizeof(buffer));
            if (!TCPIP_UDP_IsConnected(appData.socket))
            {
                SYS_CONSOLE_MESSAGE("\r\nConnection Closed\r\n");
                appData.state = APP_TCPIP_WAITING_FOR_COMMAND;
                break;
            }
            if (TCPIP_UDP_GetIsReady(appData.socket))
            {
                TCPIP_UDP_ArrayGet(appData.socket, (uint8_t*)buffer, sizeof(buffer) - 1);
                SYS_CONSOLE_MESSAGE(buffer);
                appData.state = APP_TCPIP_WAITING_FOR_COMMAND;

            }
        }
        break;
        default:
            break;
    }
}