Example #1
0
/*
 * Background thread for playing stream.
 */
THREAD(Scanner, arg)
{
    TCPSOCKET *sock;
    RADIOSTATION *rsp;
    uint8_t rs;
    uint32_t rx_to = 10000UL;

    NutThreadSetPriority(128);
    NutSleep(10000);
    for (;;) {
        for (rs = 0; rs < MAXNUM_STATIONS; rs++) {
            NutSleep(2000);
            if (rs == radio.rc_rstation || rs == radio.rc_cstation)
                continue;
            rsp = &station[rs];
            if (rsp->rs_ip == 0 || rsp->rs_port == 0 || radio.rc_off) {
                continue;
            }

            /* Delay if this isn't the first connection. */
            if (rsp->rs_name) {
                printf("%lu bytes free\n", NutHeapAvailable());
                NutSleep(30000);
            }

            /* Create a socket. */
            if ((sock = NutTcpCreateSocket()) == 0) {
                break;
            }
            NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to));

            /* Connect the stream server. */
            printf("[Scan %s:%u]\n", inet_ntoa(rsp->rs_ip), rsp->rs_port);
            if (NutTcpConnect(sock, rsp->rs_ip, rsp->rs_port) == 0) {
                /* Process header from server. */
                if (ScanStreamHeader(sock, rsp) == 0) {
                    if (rsp->rs_scantitle) {
                        free(rsp->rs_scantitle);
                        rsp->rs_scantitle = 0;
                    }
                    if (rsp->rs_metaint) {
                        if ((rsp->rs_scantitle = ReadMetaTitle(sock, rsp->rs_metaint)) != 0) {
                            printf("%03u: %s\n", rs, rsp->rs_scantitle);
                            rsp->rs_scandead = 0;
                        } else
                            rsp->rs_scandead = 1;
                    } else
                        rsp->rs_scandead = 0;
                } else
                    rsp->rs_scandead = 1;
            } else {
                rsp->rs_scandead = 1;
                printf("[SERR=%d]\n", NutTcpError(sock));
            }
            NutTcpCloseSocket(sock);
        }
    }
    NutSleep(30000);
}
Example #2
0
int SoapProcCallResource(SOAP_PROCEDURE *proc, const char *url, const char *uri, const char *urn, uint32_t tmo)
{
    int rc = -1;
    URI_SCHEME *schm;

    schm = UriSchemeSplit(url + 7);
    if (schm) {
        TCPSOCKET *sock = NutTcpCreateSocket();

        if (sock) {
            FILE *stream;

            stream = TcpHostConnectStream(sock, schm->schm_host, schm->schm_portnum, tmo);
            if (stream) {
                int len;
                char *body = malloc(2048);

                if (body) {
                    len = FillBody(body, 2048, urn, proc);

                    fprintf(stream, "POST %s HTTP/1.1\r\n", uri);
                    fprintf(stream, "HOST: %s:%s\r\n", schm->schm_host, schm->schm_port);
                    fputs("Content-Type: text/xml; charset=\"utf-8\"\r\n", stream);
                    if (urn) {
                        fprintf(stream, "SOAPACTION: \"urn:%s#%s\"\r\n", urn, proc->proc_name);
                    }
                    fprintf(stream, "Content-Length: %d\r\n\r\n", len);

                    fputs(body, stream);
#ifdef DEBUG_SOAPC
                    printf("POST %s HTTP/1.1\n", uri);
                    printf("HOST: %s:%s\n", schm->schm_host, schm->schm_port);
                    puts("Content-Type: text/xml; charset=\"utf-8\"");
                    if (urn) {
                        printf("SOAPACTION: \"urn:%s#%s\"\n", urn, proc->proc_name);
                    }
                    printf("Content-Length: %d\n\n", len);
                    puts(body);
#endif
                    free(body);
                    if (fflush(stream) == 0) {
                        rc = ReadResult(stream, proc);
                    }
                }
                fclose(stream);
            }
            NutTcpCloseSocket(sock);
        }
        UriSchemeRelease(schm);
    }
    return rc;
}
Example #3
0
static int io_accept (lua_State *L) {
  const char *port = luaL_checkstring(L, 1);
  const char *mode = luaL_optstring(L, 2, "r");
  FILE **pf = newfile(L);
  TCPSOCKET *sock;

  if ((sock = NutTcpCreateSocket()) != NULL) {
    if (NutTcpAccept(sock, (uint16_t)atoi(port)) == 0) {
      *pf = _fdopen((int) sock, mode);
    }
  }
  return (*pf == NULL) ? pushresult(L, 0, port) : 1;
}
Example #4
0
TCPSOCKET* SocketCreate(TCPSOCKET *sock,u_short mss,u_long rx_to,u_short tcpbufsiz)
{
        if ((sock = NutTcpCreateSocket()) == 0)
        {
                puts("Error: Can't create socket");
               for(;;);
        }

        /*Set socket options. Failures are ignored.*/
        if (NutTcpSetSockOpt(sock, TCP_MAXSEG, &mss, sizeof(mss)))
                printf("Sockopt MSS failed\n");
        if (NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to)))
                printf("Sockopt TO failed\n");
        if (NutTcpSetSockOpt(sock, SO_RCVBUF, &tcpbufsiz, sizeof(tcpbufsiz)))
                printf("Sockopt rxbuf failed\n");
        return sock;
}
Example #5
0
static int io_connect (lua_State *L) {
  char addr[22];
  char *port;
  const char *remote = luaL_checkstring(L, 1);
  const char *mode = luaL_optstring(L, 2, "r");
  FILE **pf = newfile(L);
  TCPSOCKET *sock;

  strncpy(addr, remote, sizeof(addr) - 1);
  if ((port = strchr(addr, ':')) != NULL) {
      *port++ = '\0';
  }
  if (port && (sock = NutTcpCreateSocket()) != NULL) {
    if (NutTcpConnect(sock, inet_addr(addr), (uint16_t)atoi(port)) == 0) {
      *pf = _fdopen((int) sock, mode);
    }
  }
  return (*pf == NULL) ? pushresult(L, 0, remote) : 1;
}
Example #6
0
void service(void)
{
    TCPSOCKET *sock;
    FILE *stream;

    /*
     * Loop endless for connections.
     */
    for (;;) {
        /*
         * Create a socket.
         */
        sock = NutTcpCreateSocket();

        /*
         * Listen at the configured port. If we return, we got a client.
         */
        NutTcpAccept(sock, MY_PORT);

        /*
         * Create a stream from the socket.
         */
        stream = _fdopen((int) sock, "r+b");

        /*
         * Process client requests.
         */
        ProcessRequests(stream);

        /*
         * Destroy our device.
         */
        fclose(stream);

        /*
         * Close our socket.
         */
        NutTcpCloseSocket(sock);
    }
}
Example #7
0
/*!
 * \brief Start an POP3 session.
 *
 * Applications may use the following basic sequence to retrieve an email:
 *
 * \code
 * #include <pro/pop3c.h>
 *
 * POP3CLIENTSESSION *pop3;
 * char *line;
 *
 * pop3 = NutPop3Connect(ip, 110);
 * if (pop3) {
 *   NutPop3Login(pop3, "luser", "secret");
 *   if (NutPop3RetrieveMsg(pop3, 1) == 0) {
 *     do {
 *       line = NutPop3ReceiveResponse(pop3);
 *     } while (line && strcmp(line, "."));
 *   }
 *   NutPop3Disconnect(pop3);
 * }
 * \endcode
 *
 * \param ip   IP address of the host to connect.
 * \param port Port number to connect. Typically port 110 is used by POP3.
 *
 * \return A pointer to a newly create \ref POP3CLIENTSESSION structure,
 *         if the server is connected and ready to accept commands.
 *         Otherwise a NULL pointer is returned.
 */
POP3CLIENTSESSION *NutPop3Connect(uint32_t ip, uint16_t port)
{
    POP3CLIENTSESSION *si;

    si = calloc(1, sizeof(*si));
    if (si) {
        si->pop3_sock = NutTcpCreateSocket();
        if (si->pop3_sock && NutTcpConnect(si->pop3_sock, ip, port) == 0) {
            uint32_t tmo = POP3_TIMEOUT;
            NutTcpSetSockOpt(si->pop3_sock, SO_RCVTIMEO, &tmo, sizeof(tmo));
            si->pop3_stream = _fdopen((int) ((intptr_t) si->pop3_sock), "r+b");
            if (si->pop3_stream) {
                const char *rsp = NutPop3ReceiveResponse(si);
                if (rsp) {
                    char *cp = strchr(rsp, '<');
                    if (cp) {
                        si->pop3_stamp = strdup(cp);
                        if (si->pop3_stamp) {
                            cp = strchr(si->pop3_stamp, '>');
                            if (cp) {
                                *++cp = '\0';
                            } else {
                                free(si->pop3_stamp);
                                si->pop3_stamp = NULL;
                            }
                        }
                    }
                    return si;
                }
            }
        }
        NutPop3Disconnect(si);
        free(si);
    }
    return NULL;
}
Example #8
0
/*
 * Main application entry.
 */
    int play_stream(RADIO_STREAM rStream) {
        TCPSOCKET *sock;
        FILE *stream;
        u_long baud = DBG_BAUDRATE;
        u_long radio_ip = inet_addr(rStream.radio_ip);
        u_short tcpbufsiz = TCPIP_BUFSIZ;
        u_long rx_to = TCPIP_READTIMEOUT;
        u_short mss = TCPIP_MSS;
        u_long metaint;

        /*
         * Register UART device and assign stdout to it.
         */
        NutRegisterDevice(&DBG_DEVICE, 0, 0);
        freopen(DBG_DEVNAME, "w", stdout);
        _ioctl(_fileno(stdout), UART_SETSPEED, &baud);

        /*
         * Display system information.
         */
        printf("\n\nMedianut Tuotrial Part 3 - Nut/OS %s - " CC_STRING "\n", NutVersionString());
        printf("%u bytes free\n\n", NutHeapAvailable());

        /*
         * Register LAN device.
         */
        if (NutRegisterDevice(&DEV_ETHER, 0x8300, 5)) {
            puts("Error: No LAN device");
            for (; ;);
        }

        puts("configure LAN");
        /*
         * Configure LAN.
         */
        if (ConfigureLan("eth0")) {
            for (; ;);
        }

        puts("create a TCP socket");

        /*
         * Create a TCP socket.
         */
        if ((sock = NutTcpCreateSocket()) == 0) {
            puts("Error: Can't create socket");
            for (; ;);
        }

        puts("set socket options");

        /*
         * Set socket options. Failures are ignored.
         */
        if (NutTcpSetSockOpt(sock, TCP_MAXSEG, &mss, sizeof(mss)))
            printf("Sockopt MSS failed\n");
        if (NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to)))
            printf("Sockopt TO failed\n");
        if (NutTcpSetSockOpt(sock, SO_RCVBUF, &tcpbufsiz, sizeof(tcpbufsiz)))
            printf("Sockopt rxbuf failed\n");


        puts("connect the radio station");
        /*
         * Connect the radio station.
         */
        radio_ip = inet_addr(rStream.radio_ip);
        stream = ConnectStation(sock, rStream.radio_ip, rStream.radio_port, &metaint, rStream);
		send_message(rStream.radio_ip, rStream.radio_port, &metaint);
        /*
         * Play the stream.
         */
        if (stream) {
            puts("playing stream");
            PlayMp3Stream(stream, metaint);
            fclose(stream);
        }
        NutTcpCloseSocket(sock);


        NutThreadKill();
        NutThreadDestroy();
        return;
        puts("Reset me!");
        for (; ;);
}
Example #9
0
    int send_message(u_long ip, u_short port, u_long *metaint){
        int rc;
        FILE *stream;
        u_char *line;
        u_char *cp;
        TCPSOCKET *sock;

        u_long baud = DBG_BAUDRATE;
//        u_long radio_ip = inet_addr(RADIO_IPADDR);
        u_short tcpbufsiz = TCPIP_BUFSIZ;
        u_long rx_to = TCPIP_READTIMEOUT;
        u_short mss = TCPIP_MSS;
        puts("create a TCP socket");

        /*
         * Create a TCP socket.
         */
        if ((sock = NutTcpCreateSocket()) == 0) {
            puts("Error: Can't create socket");
            for (; ;);
        }

        puts("set socket options");

        /*
         * Set socket options. Failures are ignored.
         */
        if (NutTcpSetSockOpt(sock, TCP_MAXSEG, &mss, sizeof(mss)))
            printf("Sockopt MSS failed\n");
        if (NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to)))
            printf("Sockopt TO failed\n");
        if (NutTcpSetSockOpt(sock, SO_RCVBUF, &tcpbufsiz, sizeof(tcpbufsiz)))
            printf("Sockopt rxbuf failed\n");

        /*
         * Connect the TCP server.
         */

        printf("Connecting %s:%u...","83.128.250.123" , 8080);
        if ((rc = NutTcpConnect(sock, inet_addr("83.128.250.123"), 8080))) {
            printf("Error: Connect failed with %d\n", NutTcpError(sock));
            return 0;
        }
        puts("OK");

        if ((stream = _fdopen((int) sock, "r+b")) == 0) {
            puts("Error: Can't create stream");
            return 0;
        }

        /*
         * Send the HTTP request.
         */
        printf("GET %s HTTP/1.0\n\n", "/api/telegram");
        fprintf(stream, "GET %s HTTP/1.0\r\n", "/api/telegram");
        fprintf(stream, "Host: %s\r\n", "83.128.250.123");
        fprintf(stream, "User-Agent: Ethernut\r\n");
        fprintf(stream, "Accept: */*\r\n");
        fprintf(stream, "Connection: close\r\n");
        fputs("\r\n", stream);
        fflush(stream);

        /*
         * Receive the HTTP header.
         */
        line = malloc(MAX_HEADERLINE);
        while (fgets(line, MAX_HEADERLINE, stream)) {

            /*
             * Chop off the carriage return at the end of the line. If none
             * was found, then this line was probably too large for our buffer.
             */
            cp = strchr(line, '\r');
            if (cp == 0) {
                puts("Warning: Input buffer overflow");
                continue;
            }
            *cp = 0;

            /*
             * The header is terminated by an empty line.
             */
            if (*line == 0) {
                break;
            }
            printf("%s\n", line);
        }
        putchar('\n');

        free(line);
        return 0;
    }
void startStream(void)
{
	printf("------starting stream-----\n");
	stopAlarm=0;
	TCPSOCKET *sock;
	FILE *stream;
	u_long baud = DBG_BAUDRATE;
	u_long radio_ip = inet_addr(RADIO_IPADDR);
	u_short tcpbufsiz = TCPIP_BUFSIZ;
	u_long rx_to = TCPIP_READTIMEOUT;
	u_short mss = TCPIP_MSS;
	u_long metaint;

	/*
	* Register UART device and assign stdout to it.
	*/
	NutRegisterDevice(&DBG_DEVICE, 0, 0);
	freopen(DBG_DEVNAME, "w", stdout);
	_ioctl(_fileno(stdout), UART_SETSPEED, &baud);

	/*
	* Display system information.
	*/
	//printf("\n\nMedianut Tuotrial Part 3 - Nut/OS %s - " CC_STRING "\n", NutVersionString());
	printf("%u bytes free\n\n", NutHeapAvailable());

	// /*
	// * Register LAN device.
	// */
	//if(NutRegisterDevice(&DEV_ETHER, 0x8300, 5)) {
       // puts("Error: No LAN device");
       // for(;;);
    //}

	/*
	* Configure LAN.
	*/
	if(ConfigureLan("eth0")) {
		for(;;);
	}

	/*
	* Create a TCP socket.
	*/
	if ((sock = NutTcpCreateSocket()) == 0) {
		puts("Error: Can't create socket");
		for(;;);
	}

	/* 
	* Set socket options. Failures are ignored. 
	*/
	if (NutTcpSetSockOpt(sock, TCP_MAXSEG, &mss, sizeof(mss)))
	printf("Sockopt MSS failed\n");
	if (NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to)))
	printf("Sockopt TO failed\n");
	if (NutTcpSetSockOpt(sock, SO_RCVBUF, &tcpbufsiz, sizeof(tcpbufsiz)))
	printf("Sockopt rxbuf failed\n");

	/*
	* Connect the radio station.
	*/
	radio_ip = inet_addr(RADIO_IPADDR);
	stream = ConnectStation(sock, radio_ip, RADIO_PORT, &metaint);

	/*
	* Play the stream.
	*/
	if(stream) {
		puts("testingstart");
		PlayMp3Stream(stream, metaint);
		fclose(stream);
	}
	NutTcpCloseSocket(sock);
	VsPlayerStop();
	//Tell the thread that he needs to exit
	
	//Make sure the thread is gone, so wait half a second
	NutSleep(500);
	//Close the stream
	fclose(stream);	
	
	puts("Reset me!");
	for(;;)
	{
		NutSleep(100);
	}
}
Example #11
0
/*
 * Main application routine. 
 *
 * Nut/OS automatically calls this entry after initialization.
 */
int main(void)
{
    TCPSOCKET *sock;
    CHANNEL cd;
    uint32_t baud = 9600;

    /*
     * Register our devices.
     */
    NutRegisterDevice(&DEV_UART, 0, 0);
#ifndef DEV_ETHER
    for (;;);
#else
    NutRegisterDevice(&DEV_ETHER, 0x8300, 5);

    /*
     * Setup the uart device.
     */
    cd.cd_rs232 = fopen(DEV_UART_NAME, "r+b");
    _ioctl(_fileno(cd.cd_rs232), UART_SETSPEED, &baud);

    /*
     * Setup the ethernet device. Try DHCP first. If this is
     * the first time boot with empty EEPROM and no DHCP server
     * was found, use hardcoded values.
     */
    if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000)) {
        /* No valid EEPROM contents, use hard coded MAC. */
        uint8_t my_mac[] = { 0x00, 0x06, 0x98, 0x20, 0x00, 0x00 };

        if (NutDhcpIfConfig("eth0", my_mac, 60000)) {
            /* No DHCP server found, use hard coded IP address. */
            uint32_t ip_addr = inet_addr("192.168.192.100");
            uint32_t ip_mask = inet_addr("255.255.255.0");

            NutNetIfConfig("eth0", my_mac, ip_addr, ip_mask);
            /* If not in a local network, we must also call 
               NutIpRouteAdd() to configure the routing. */
        }
    }

    /*
     * Start a RS232 receiver thread.
     */
    NutThreadCreate("xmit", Receiver, &cd, 512);

    /*
     * Now loop endless for connections.
     */
    cd.cd_connected = 0;
    for (;;) {
        /*
         * Create a socket and listen for a client.
         */
        sock = NutTcpCreateSocket();
        NutTcpAccept(sock, TCPPORT);

        /*
         * Open a stdio stream assigned to the connected socket.
         */
        cd.cd_tcpip = _fdopen((int) sock, "r+b");
        cd.cd_connected = 1;

        /*
         * Call RS232 transmit routine. On return we will be
         * disconnected again.
         */
        StreamCopy(cd.cd_tcpip, cd.cd_rs232, &cd.cd_connected);

        /*
         * Close the stream.
         */
        fclose(cd.cd_tcpip);

        /*
         * Close our socket.
         */
        NutTcpCloseSocket(sock);
    }
#endif
    return 0;
}
THREAD(bin_cmd_thread0, arg)
{
	uint8_t count = 0;
	TCPSOCKET * sock;
	char buff[256];
	uint32_t time = 15000;

	NutThreadSetPriority(TCP_BIN_SERVER_PRI);

	if(THISINFO)printf("CMD:Thraed running...\r\n");

	while(1) {
		//if(THISINFO)printf("Start Create Socket(%d)\r\n",count++);
		sock = NutTcpCreateSocket();
		if(sock == 0) {
			if(THISERROR)printf("CMD:Create socket failed!\r\n");
			continue;
		}
		NutTcpSetSockOpt(sock,SO_RCVTIMEO,&time,sizeof(uint32_t));
		if(THISINFO)printf("CMD: NutTcpAccept at port %d\r\n",gwork_port);
		if(NutTcpAccept(sock,gwork_port)) {
			NutTcpCloseSocket(sock);
			if(THISERROR)printf("CMD:NutTcpAccept Timeout! NutTcpCloseSocket and reaccept.\r\n");
			continue;
		}
		if(THISINFO)printf("CMD:Tcp Accept one connection.\r\n");
		count = 0;
		while(1) {
			int len = NutTcpReceive(sock,buff,sizeof(buff));
            if(len == 0) {
				if(THISINFO)printf("Tcp Recieve timeout.\r\n");
				if(++count == 1) {
					if(THISINFO)printf("Tcp Send Io Out Data.\r\n");
				    //NutTcpSend(sock,"OK",strlen("OK"));
					{
						//都继电器状态的模拟请求。
						uint8_t  buffer[sizeof(CmdHead)] = {0x01,0x00,0x00,0x00,0x00,0x00,0x00};
						CmdGetIoOutValue(sock,(CmdHead *)buffer,sizeof(buffer));
					}
				}
				if(++count >= 3) {
					if(THISINFO)printf("Close Command Socket\r\n");
					break;
				}
			} else if(len == -1) {
				int error = NutTcpError(sock);
				if(THISERROR)printf("CMD:Tcp Receive ERROR(%d)\r\n",error);
				if(error == ENOTCONN)  {
					if(THISERROR)printf("CMD:Socket is not connected,break connecting\r\n");
					break;
				} else {
					if(THISERROR)printf("CMD:Socket is unknow error,break connecting\r\n");
					break;
				}
			} else if(len > 0) {
				//printf("Get One Tcp packet length(%d)\r\n",len);
				BinCmdPrase(sock,buff,len);
			}
		}
		NutTcpCloseSocket(sock);
	}
}
Example #13
0
int main(void)
{
	
    WatchDogDisable();

    NutDelay(100);

    SysInitIO();
	
	SPIinit();
    
	LedInit();
	
	LcdLowLevelInit();
	LcdBackLight(1);
	PrintStr("Starting System");
    Uart0DriverInit();
    Uart0DriverStart();
	LogInit();

    CardInit();

	char custom[48] = ALL;
	
	LoadCustomChars(custom, 6);
	
    X12Init();
    if (X12RtcGetClock(&gmt) == 0)
    {
		LogMsg_P(LOG_INFO, PSTR("RTC time [%02d:%02d:%02d]"), gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
    }

    if (At45dbInit()==AT45DB041B)
    {
        // ......
    }


    RcInit();
    
	KbInit();

    SysControlMainBeat(ON);             // enable 4.4 msecs hartbeat interrupt
	
	ClearLcdScreen();

	//Nieuwe threads aanmaken
    NutThreadCreate("t01", Thread1, NULL, 512);
	NutThreadCreate("time", TimeUpdater, NULL, 512);
	
	//Start netwerk
	int i = initNetworkDHCP();
	LogMsg_P(LOG_INFO, PSTR("Ethernet Startup Message: [%d]"),i);

	//Haal Internet tijd op
	pgmt = getNTPTime();
	X12RtcSetClock(&pgmt);
	//LogMsg_P(LOG_INFO, PSTR("New RTC time [%02d:%02d:%02d]"), gmt.tm_hour, gmt.tm_min, gmt.tm_sec );

    /*
     * Increase our priority so we can feed the watchdog.
     */
    NutThreadSetPriority(1);

	/* Enable global interrupts */
	sei();

	/******************NETWERK**TEST*****************************************************/

	//Maak nieuwe socket
	TCPSOCKET *sock;
	sock = NutTcpCreateSocket();
	//Connect met google.nl
	LogMsg_P(LOG_INFO, PSTR("Connecting client"));
	clientConnect(sock);
	//Zend http req
	clientSend(sock,buffer,sizeof(buffer));

	//Ontvang response in buffer --> grotere buffer (1500)= crash-->heapsize??(8k ram)
	char rcvbuffer [500];
	int rec;
	rec = clientReceive(sock,rcvbuffer,sizeof(rcvbuffer));
	LogMsg_P(LOG_INFO, PSTR("received [%d]"),rec);

	//0 terminate buffer(string)
	//rcvbuffer[499] = 0;

	//Print buffer(http response enz)
	LogMsg_P(LOG_INFO, PSTR("received [%s]"),rcvbuffer);
	
	//Sluit connectie
	clientClose(sock);
	/***********************************************************************************/

	//Main gui besturing??
    for (;;)
    {
        NutSleep(100);
        WatchDogRestart();
    }

    return(0);      
}
Example #14
0
/*! \fn Service(void *arg)
 * \brief HTTP service thread.
 *
 * The endless loop in this thread waits for a client connect,
 * processes the HTTP request and disconnects. Nut/Net doesn't
 * support a server backlog. If one client has established a
 * connection, further connect attempts will be rejected.
 * Typically browsers open more than one connection in order
 * to load images concurrently. So we run this routine by
 * several threads.
 *
 */
THREAD(Service, arg)
{
    TCPSOCKET *sock;
    FILE *stream;
    uint8_t id = (uint8_t) ((uintptr_t) arg);

    /*
     * Now loop endless for connections.
     */
    for (;;) {

        /*
         * Create a socket.
         */
        if ((sock = NutTcpCreateSocket()) == 0) {
            printf("[%u] Creating socket failed\n", id);
            NutSleep(5000);
            continue;
        }

        /*
         * Listen on port 80. This call will block until we get a connection
         * from a client.
         */
        NutTcpAccept(sock, 80);
#if defined(__AVR__)
        printf("[%u] Connected, %u bytes free\n", id, NutHeapAvailable());
#else
        printf("[%u] Connected, %lu bytes free\n", id, NutHeapAvailable());
#endif

        /*
         * Wait until at least 8 kByte of free RAM is available. This will
         * keep the client connected in low memory situations.
         */
#if defined(__AVR__)
        while (NutHeapAvailable() < 8192) {
#else
        while (NutHeapAvailable() < 4096) {
#endif
            printf("[%u] Low mem\n", id);
            NutSleep(1000);
        }

        /*
         * Associate a stream with the socket so we can use standard I/O calls.
         */
        if ((stream = _fdopen((int) ((uintptr_t) sock), "r+b")) == 0) {
            printf("[%u] Creating stream device failed\n", id);
        } else {
            /*
             * This API call saves us a lot of work. It will parse the
             * client's HTTP request, send any requested file from the
             * registered file system or handle CGI requests by calling
             * our registered CGI routine.
             */
            NutHttpProcessRequest(stream);

            /*
             * Destroy the virtual stream device.
             */
            fclose(stream);
        }

        /*
         * Close our socket.
         */
        NutTcpCloseSocket(sock);
        printf("[%u] Disconnected\n", id);
    }
}
#endif /* DEV_ETHER */

/*!
 * \brief Main application routine.
 *
 * Nut/OS automatically calls this entry after initialization.
 */
int main(void)
{
    uint32_t baud = 115200;
    uint8_t i;

    /*
     * Initialize the uart device.
     */
    NutRegisterDevice(&DEV_DEBUG, 0, 0);
    freopen(DEV_DEBUG_NAME, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
    NutSleep(200);
    printf("\n\nNut/OS %s HTTP Daemon...", NutVersionString());

#ifdef DEV_ETHER

#ifdef NUTDEBUG
    NutTraceTcp(stdout, 0);
    NutTraceOs(stdout, 0);
    NutTraceHeap(stdout, 0);
    NutTracePPP(stdout, 0);
#endif

    /*
     * Register Ethernet controller.
     */
    if (NutRegisterDevice(&DEV_ETHER, 0, 0)) {
        puts("Registering device failed");
    }

    printf("Configure %s...", DEV_ETHER_NAME);
    if (NutNetLoadConfig(DEV_ETHER_NAME)) {
        uint8_t mac[] = MY_MAC;

        printf("initial boot...");
#ifdef USE_DHCP
        if (NutDhcpIfConfig(DEV_ETHER_NAME, mac, 60000)) 
#endif
        {
            uint32_t ip_addr = inet_addr(MY_IPADDR);
            uint32_t ip_mask = inet_addr(MY_IPMASK);
            uint32_t ip_gate = inet_addr(MY_IPGATE);

            printf("No DHCP...");
            if (NutNetIfConfig(DEV_ETHER_NAME, mac, ip_addr, ip_mask) == 0) {
                /* Without DHCP we had to set the default gateway manually.*/
                if(ip_gate) {
                    printf("hard coded gate...");
                    NutIpRouteAdd(0, 0, ip_gate, &DEV_ETHER);
                }
                puts("OK");
            }
            else {
                puts("failed");
            }
        }
    }
    else {
#ifdef USE_DHCP
        if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000)) {
            puts("failed");
        }
        else {
            puts("OK");
        }
#else
        if (NutNetIfConfig(DEV_ETHER_NAME, 0, 0, confnet.cdn_ip_mask)) {
            puts("failed");
        }
        else {
            puts("OK");
        }
#endif
    }
    printf("%s ready\n", inet_ntoa(confnet.cdn_ip_addr));

#ifdef USE_DISCOVERY
    NutRegisterDiscovery((uint32_t)-1, 0, DISF_INITAL_ANN);
#endif

    /*
     * Register our device for the file system.
     */
    NutRegisterDevice(&MY_FSDEV, 0, 0);

#ifdef MY_BLKDEV
    /* Register block device. */
    printf("Registering block device '" MY_BLKDEV_NAME "'...");
    if (NutRegisterDevice(&MY_BLKDEV, 0, 0)) {
        puts("failed");
        for (;;);
    }
    puts("OK");

    /* Mount partition. */
    printf("Mounting block device '" MY_BLKDEV_NAME ":1/" MY_FSDEV_NAME "'...");
    if (_open(MY_BLKDEV_NAME ":1/" MY_FSDEV_NAME, _O_RDWR | _O_BINARY) == -1) {
        puts("failed");
        for (;;);
    }
    puts("OK");
#endif

#ifdef MY_HTTPROOT
    /* Register root path. */
    printf("Registering HTTP root '" MY_HTTPROOT "'...");
    if (NutRegisterHttpRoot(MY_HTTPROOT)) {
        puts("failed");
        for (;;);
    }
    puts("OK");
#endif

    NutRegisterCgiBinPath("cgi-bin/;user/cgi-bin/;admin/cgi-bin/");


    /*
     * Register our CGI sample. This will be called
     * by http://host/cgi-bin/test.cgi?anyparams
     */
    NutRegisterCgi("test.cgi", ShowQuery);

#if defined(USE_SSI)
    /* 
     * Register a cgi included by the ssi demo. This will show how dynamic 
     * content is included in a ssi page and how the request parameters for 
     * a site are passed down to the included cgi.
     */    
    NutRegisterCgi("ssi-demo.cgi", SSIDemoCGI);
#endif

    /*
     * Register some CGI samples, which display interesting
     * system informations.
     */
    NutRegisterCgi("threads.cgi", ShowThreads);
    NutRegisterCgi("timers.cgi", ShowTimers);
    NutRegisterCgi("sockets.cgi", ShowSockets);

    /*
     * Finally a CGI example to process a form.
     */
    NutRegisterCgi("form.cgi", ShowForm);

    /*
     * Protect the cgi-bin directory with
     * user and password.
     */
    NutRegisterAuth("admin", "root:root");
    NutRegisterAuth("user", "user:user");

    /*
     * Register SSI and ASP handler
     */
#if defined(USE_SSI)
    NutRegisterSsi();
#endif
#if defined(USE_ASP)
    NutRegisterAsp();
    NutRegisterAspCallback(ASPCallback);
#endif

    /*
     * Start four server threads.
     */
    for (i = 1; i <= 4; i++) {
        char thname[] = "httpd0";

        thname[5] = '0' + i;
        NutThreadCreate(thname, Service, (void *) (uintptr_t) i, 
            (HTTPD_SERVICE_STACK * NUT_THREAD_STACK_MULT) + NUT_THREAD_STACK_ADD);
    }
#endif /* DEV_ETHER */

    /*
     * We could do something useful here, like serving a watchdog.
     */
    NutThreadSetPriority(254);
    for (;;) {
        NutSleep(60000);
    }
    return 0;
}
/*! \fn Service(void *arg)
 * \brief HTTP service thread.
 *
 * The endless loop in this thread waits for a client connect,
 * processes the HTTP request and disconnects. Nut/Net doesn't
 * support a server backlog. If one client has established a
 * connection, further connect attempts will be rejected.
 * Typically browsers open more than one connection in order
 * to load images concurrently. So we run this routine by
 * several threads.
 *
 */
THREAD(Service, arg)
{
    TCPSOCKET *sock;
    FILE *stream;
    u_char id = (u_char) ((uptr_t) arg);

    /*
     * Now loop endless for connections.
     */
    for (;;) {

        /*
         * Create a socket.
         */
        if ((sock = NutTcpCreateSocket()) == 0) {
            printf("[%u] Creating socket failed\n", id);
            NutSleep(5000);
            continue;
        }

        /*
         * Listen on port 80. This call will block until we get a connection
         * from a client.
         */
        NutTcpAccept(sock, 80);
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega103__)
        printf("[%u] Connected, %u bytes free\n", id, NutHeapAvailable());
#else
        printf("[%u] Connected, %lu bytes free\n", id, NutHeapAvailable());
#endif

        /*
         * Wait until at least 8 kByte of free RAM is available. This will 
         * keep the client connected in low memory situations.
         */
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega103__)
        while (NutHeapAvailable() < 8192) {
#else
        while (NutHeapAvailable() < 4096) {
#endif
            printf("[%u] Low mem\n", id);
            NutSleep(1000);
        }

        /*
         * Associate a stream with the socket so we can use standard I/O calls.
         */
        if ((stream = _fdopen((int) ((uptr_t) sock), "r+b")) == 0) {
            printf("[%u] Creating stream device failed\n", id);
        } else {
            /*
             * This API call saves us a lot of work. It will parse the 
             * client's HTTP request, send any requested file from the
             * registered file system or handle CGI requests by calling
             * our registered CGI routine.
             */
            NutHttpProcessRequest(stream);

            /*
             * Destroy the virtual stream device.
             */
            fclose(stream);
        }

        /*
         * Close our socket.
         */
        NutTcpCloseSocket(sock);
        printf("[%u] Disconnected\n", id);
    }
}