Ejemplo n.º 1
0
int main(void)
{
#ifdef NUT_OS
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE.dev_name, "w", stdout);
#endif

    puts("uHTTP form sample\nBuild " __DATE__ " " __TIME__);

#ifdef NUT_OS
    NutRegisterDevice(&DEV_ETHER, 0, 0);
    NutDhcpIfConfig(DEV_ETHER_NAME, NULL, 60000);
    NutRegisterDevice(&devUrom, 0, 0);
#endif

    StreamInit();
    MediaTypeInitDefaults();
    HttpRegisterRedir("", "/index.html", 301);
    HttpRegisterCgiFunction("getform.cgi", CgiGetForm);
    HttpRegisterCgiFunction("postform.cgi", CgiPostForm);
    HttpRegisterMediaType("cgi", NULL, NULL, HttpCgiFunctionHandler);
    StreamClientAccept(HttpdClientHandler, NULL);

    puts("Exit");
#ifdef NUT_OS
    for (;;) ;
#endif

    return 0;
}
Ejemplo n.º 2
0
/*
 * Initialize the protocol port.
 */
static void ProtocolPortInit(void)
{
#ifdef PPP_DEV
    /* Register PPP and UART device. */
    NutRegisterDevice(&PPP_DEV, 0, 0);
    NutRegisterDevice(&devPpp, 0, 0);
#else
    /* Use Ethernet. */
    NutRegisterDevice(&DEV_ETHER, 0, 0);
#endif
}
Ejemplo n.º 3
0
/*
 * Main application routine.
 */
int main(void)
{
    uint32_t baud = 115200;

    /*
     * Register the UART device, open it, assign stdout to it and set
     * the baudrate.
     */
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE.dev_name, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
    puts("\n\nNut/OS timer sample");

    /*
     * Display some general info.
     */
    printf("CPU running at %lu Hz\n", NutGetCpuClock());
    printf("%lu system ticks per second\n", NutTimerMillisToTicks(1000));

    /*
     * Run the demos.
     */
    OneShotDemo(10);
    PeriodicDemo(2);
    DelayDemo();
    SleepDemo(); /* Never returns. */

    return 0;
}
Ejemplo n.º 4
0
int initNetworkDHCP(){
	int retval;
	if (NutRegisterDevice(&DEV_ETHER, 0, 0)) {
		LogMsg_P(LOG_INFO, PSTR("Registering ethernet failed."));
		retval = 1;
    }
    else if (NutDhcpIfConfig(DEV_ETHER_NAME, NULL, 0)) {
        uint8_t initial_mac[6] = MY_MAC;
 
        if (NutDhcpIfConfig(DEV_ETHER_NAME, initial_mac, 0)) {
            u_long initial_ip_addr = inet_addr(MY_IP);
            u_long initial_ip_mask = inet_addr(MY_MASK);
            NutNetIfConfig(DEV_ETHER_NAME, initial_mac, initial_ip_addr, initial_ip_mask);
			retval = 2;
        }
    }
    if (NutRegisterDiscovery(INADDR_BROADCAST, 0, DISF_INITAL_ANN)) {
        //printf("Discover Service failed");
		LogMsg_P(LOG_INFO, PSTR("Discover Service failed"));
		retval = 3;
    } else {
		LogMsg_P(LOG_INFO, PSTR("Ethernet Startup Message: OK"));
		LogMsg_P(LOG_INFO, PSTR("IP = [%d],[%d],[%d],[%d]"));
        default_handler = NutRegisterDiscoveryCallback(MyHandler);
		retval = 4;
    }
	return retval;
}
Ejemplo n.º 5
0
/*!
 * \brief Uart0 process initialisation. Uses stdout in combination with Uart0.
 */
void Uart0DriverInit(void)
{
    stream = NULL;

    // register Uart0
    NutRegisterDevice(&devUart0, 0, 0);
}
Ejemplo n.º 6
0
bool Network_init(NH * nh) {
	int i = 0;
	for(;;) {
		i++;
		printf("Registering %s... ", DEV_ETHER_NAME);
		NutSleep(500);
		if(NutRegisterDevice(&DEV_ETHER, 0, 0) == 0) {
			printf("ok\n");
			break;
		}
		printf("Failed, retry\n");
		if ( i > 2 )
			return false;
	}

	int ip_end = rand()%128+1;
	char ip[12];
	sprintf(ip, "10.10.7.%d", ip_end);

	uint8_t mac[6] =   {0x00, 0x06, 0x98, 0x30, 0x00, ip_end};
	printf("configuring... ");
	NutNetIfConfig(DEV_ETHER_NAME, mac, inet_addr(ip), inet_addr(NMASK));
	printf("IP: %s\n\n\n", inet_ntoa(inet_addr(ip)));
	NutSleep(2000);
	printf("ok\n");
	fflush(stdout);

	printf("Creating Udp socket... ");
	if ((nh->udpSock = NutUdpCreateSocket(SNMP_PORT)) == 0)
	{
		printf("failed\n");
	}
	printf("ok\n");

	printf("Creating Udp TRAP socket... ");
	if ((nh->udpTrapSock = NutUdpCreateSocket(TRAP_PORT)) == 0)
	{
		printf("failed\n");
	}
	printf("ok\n");

	//allocate room for packets and values
	SNMP_packetPool = (snmpPacket**)malloc(PACKETPOOL_SIZE * sizeof(snmpPacket*));
	for(i = 0; i < PACKETPOOL_SIZE; i++)
		SNMP_packetPool[i] = (snmpPacket*)malloc(sizeof(snmpPacket));
	SNMP_valuePool = (uint8_t*)malloc(VALUEPOOL_SIZE * sizeof(uint8_t));
	PP_ptr = 0; VP_ptr = 0; VP_reserved = 0; PP_reserved = 0;

	SNMP_valuePool[215] = 'G'; //DEBUG
	//printf("PP_ptr: %d, valuepool[0]: %d, valuepool[215]: %c\n", PP_ptr, SNMP_valuePool[0], SNMP_valuePool[215]); //DEBUG

	NutThreadCreate("udpReceiveThread", udpReceiveThread, nh, 1024);
	NutThreadCreate("udpTrapReceiveThread", udpTrapReceiveThread, nh, 756);
	printf("ok\n");
	return true;
}
Ejemplo n.º 7
0
/*static */
void Main::init_term() {
	FILE *uart_terminal;
	u_long baud = 57600;

	btn_hardware_init();
	NutRegisterDevice(&APP_UART, 0, 0);
	uart_terminal = fopen(APP_UART.dev_name, "r+");    
	_ioctl(_fileno(uart_terminal), UART_SETSPEED, &baud);
	freopen(APP_UART.dev_name, "w", stdout);   
}
Ejemplo n.º 8
0
void alarmBeep(void)
{
	u_long baud = DBG_BAUDRATE;
	
	NutRegisterDevice(&DBG_DEVICE, 0, 0);
	freopen(DBG_DEVNAME, "w", stdout);
	_ioctl(_fileno(stdout), UART_SETSPEED, &baud);
	
	VsBeep(440,10000);
}
Ejemplo n.º 9
0
/*
 * Open serial debug port for standard output.
 */
static void DebugPortOpen(void)
{
    uint32_t baud = 115200;

    /* Register debug UART. */
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    /* Open debug device for standard output. */
    freopen(DEV_CONSOLE_NAME, "w", stdout);
    /* Set baud rate. */
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
}
Ejemplo n.º 10
0
void RegisterDevice()
{
	printf("Registering ethernet port. \n");
	if (NutRegisterDevice(&DEV_ETHER, 0, 0)) {
		printf("Registering  failed.");
	}
	else if (NutDhcpIfConfig(DEV_ETHER_NAME, NULL, 0))
	{
		printf("Connected");
	}
	printf("registering donge");
	printf("Receive time from: pool.ntp.org");
	timeserver = inet_addr("213.154.229.24");
}
int main(void)
{
	tm gmt;
	WatchDogDisable();
	NutDelay(100);
	SysInitIO();
	SPIinit();
	LedInit();
	LcdLowLevelInit();
	Uart0DriverInit();
	Uart0DriverStart();
	LogInit();
	LogMsg_P(LOG_INFO, PSTR("-----------------------------------------------------------------------------------------------"));
	CardInit();
	X12Init();
	if (X12RtcGetClock(&gmt) == 0)
	{
		LogMsg_P(LOG_INFO, PSTR("RTC time [%02d:%02d:%02d]\n"), gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
	}
	if (At45dbInit() == AT45DB041B)
	{
		
	}
	RcInit();
	KbInit();
	SysControlMainBeat(ON);             // enable 4.4 msecs hartbeat interrupt
	initMenu();
	sei();
	NutTimerInit();
	NutThreadSetPriority(1);
	int keyvalue = KbGetKey();
	int old;
	LcdBackLight(LCD_BACKLIGHT_ON);
	if(NutRegisterDevice(&DEV_ETHER, 0x8300, 5))printf("Error: No LAN device\n");
	else printf("Lan device initialized\n");
	
	for (;;)
	{
		keyvalue = KbGetKey();
		if(old != keyvalue){
			stateMenu(keyvalue);
			old = keyvalue;
		}		
		NutSleep(100);
		WatchDogRestart();
	}

	return(0);      // never reached, but 'main()' returns a non-void, so.....
}
Ejemplo n.º 12
0
int main(void)
{
    uint32_t baud = 115200;

    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE.dev_name, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
#if !defined(__GNUC__)
    puts("This program requires a compiler that supports 64-bit integers.");
#else
    puts("This program requires a configured OWIBUS.");
#endif
    for (;;);
    return 0;
}
Ejemplo n.º 13
0
/*
 * Main application routine. 
 */
int main(void)
{
    uint32_t baud = 115200;

    /*
     * Register the UART device, open it, assign stdout to it and set 
     * the baudrate.
     */
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE_NAME, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);

    /*
     * Print title.
     */
    puts("\nNut/OS Event Queue Demo");
    puts("High     Main     Low      ");

    /*
     * Post an initial event. This will put the queue into signaled 
     * state and immediately grant the next call to NutEventWait().
     */
    NutEventPost(&mutex);

    /*
     * Start two background threads.
     */
    NutThreadCreate("high", High, 0, 256);
    NutThreadCreate("low", Low, 0, 256);

    for(;;) {
        puts("         Request");
        if (NutEventWait(&mutex, 1000)) {
            puts("         Timeout");
        }
        else {
            puts("         Acquired");
            NutSleep(1500);
            puts("         Release");
            NutEventPost(&mutex);
        }
        NutSleep(1000);
    }
    return 0;
}
Ejemplo n.º 14
0
/*
 * Main application routine. 
 *
 * Nut/OS automatically calls this entry after initialization.
 */
int main(void)
{
    uint8_t my_mac[] = MY_MAC;

    /*
     * Initialize digital I/O.
     */
    init_dio();

#ifdef DEV_ETHER
    /*
     * Register Realtek controller at address 8300 hex
     * and interrupt 5.
     */
    NutRegisterDevice(&DEV_ETHER, 0x8300, 5);

    /*
     * Configure lan interface. 
     */
    if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000) && NutDhcpIfConfig("eth0", my_mac, 60000)) {
        /*
         * No DHCP server available. Use hard coded values.
         */
        uint32_t ip_addr = inet_addr(MY_IP);      /* ICCAVR fix. */
        NutNetIfConfig("eth0", my_mac, ip_addr, inet_addr(MY_MASK));
    }

    /*
     * Start another service thread to allow
     * two concurrent connections.
     */
    NutThreadCreate("sback", service_thread, 0, 1384);

    for (;;)
        service();
#endif /* DEV_ETHER */

    return 0;
}
Ejemplo n.º 15
0
int initNetworkStatic(){
	int returnmsg;
	uint8_t mac[6] = MY_MAC;
	uint32_t ip_addr = inet_addr(MY_IP);
	uint32_t ip_mask = inet_addr(MY_MASK);
	
	if (NutRegisterDevice(&DEV_ETHER, 0, 0)) {
        //Registering failed
		returnmsg = 0;
    }
    // Configure network.
    else if (NutNetIfConfig(DEV_ETHER_NAME, mac, ip_addr, ip_mask)) {
        //Configuring failed
		returnmsg = 1;
    }
    // Done.
    else {
        //OK
		returnmsg = 2;
    }

	return returnmsg;
}
Ejemplo n.º 16
0
/* Editor main routine. */
int main(void)
{
    uint32_t baud = 115200;
    char buf[32];
    uint8_t *cp;
    uint32_t addr;
    char ch;
 
    /* Assign stdin and stdout to the default UART device. */
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE_NAME, "w", stdout);
    freopen(DEV_CONSOLE_NAME, "r", stdin);    
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
    puts("\n\nNetwork Configuration Editor - Compiled " __DATE__ " - " __TIME__);
    ShowHardwareConfiguration();
 
    for (;;) {
        /* Load configuration. */
        if (NutNetLoadConfig(DEV_ETHER_NAME)) {
            puts("\nNo configuration available");
            strcpy(confnet.cd_name, DEV_ETHER_NAME);
        } else {
            puts("\nConfiguration loaded");
        }
 
        /* Edit MAC address. */
        do {
            strcpy(buf, ether_ntoa(confnet.cdn_mac));
            EditLine("MAC Address", buf, 18);
            cp = ether_aton(buf);
        } while (cp == NULL);
        memcpy(confnet.cdn_mac, cp, 6);
 
        /* Edit IP address. */
        do {
            strcpy(buf, inet_ntoa(confnet.cdn_cip_addr));
            EditLine("IP Address", buf, 16);
            addr = inet_addr(buf);
        } while (addr == -1);
        confnet.cdn_cip_addr = addr;
 
        /* Edit IP mask. */
        do {
            strcpy(buf, inet_ntoa(confnet.cdn_ip_mask));
            EditLine("IP Mask", buf, 16);
            addr = inet_addr(buf);
        } while (addr == -1);
        confnet.cdn_ip_mask = addr;
 
        /* Edit IP gate. */
        do {
            strcpy(buf, inet_ntoa(confnet.cdn_gateway));
            EditLine("IP Gate", buf, 16);
            addr = inet_addr(buf);
        } while (addr == -1);
        confnet.cdn_gateway = addr;
 
        /* Prompt for saving. */
        printf("\nPress S to save this configuration ");
 
        /* Flush input buffer and read next character. */
        while (kbhit()) {
            ch = getchar();
        }
        ch = getchar();
 
        /* Save or discard edited configuration. */
        if (ch == 's' || ch == 'S') {
            if (NutNetSaveConfig()) {
                puts("Failed");
            } else {
                puts("Saved");
            }
        } else {
            puts("Discarded");
        }
    }
    return 0;
}
Ejemplo n.º 17
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 (; ;);
}
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);
	}
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
/*
 * UART sample.
 *
 * Some functions do not work with ICCAVR.
 */
int main(void)
{
    int got;
    int userchoice;
    char *cp;
    u_long baud = 115200;

#ifdef STDIO_FLOATING_POINT
    float dval = 0.0;
#endif

    /*
     * Each device must be registered. We do this by referencing the 
     * device structure of the driver. The advantage is, that only 
     * those device drivers are included in our flash code, which we 
     * really need.
     *
     * The uart0 device is the first one on the ATmega chip. So it 
     * has no configurable base address or interrupt and we set both 
     * parameters to zero.
     */
    NutRegisterDevice(&DEV_UART, 0, 0);

    /*
     * Now, as the device is registered, we can open it. The fopen()
     * function returns a pointer to a FILE structure, which we use 
     * for subsequent reading and writing.
     */
    uart = fopen(DEV_UART_NAME, "r+");
    
    freopen("uart0", "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);

    /*
     * Before doing the first read or write, we set the baudrate.
     * This low level function doesn't know about FILE structures
     * and we use _fileno() to get the low level file descriptor
     * of the stream.
     *
     * The short sleep allows the UART to settle after the baudrate
     * change.
     */
    _ioctl(_fileno(uart), UART_SETSPEED, &baud);

    /* Initialize the LCd */
    NutRegisterDevice(&devLcd, 0, 0);
    /* Initialize UROM */
    NutRegisterDevice(&devUrom, 0, 0);
    NutRegisterDevice(&devDebug0, 0, 0);

    /*
    * Stream devices can use low level read and write functions.
    * Writing program space data is supported too.
    */
    _write(_fileno(uart), banner, strlen(banner));
    {
        lcdPrint(banner);
		
        _write_P(_fileno(uart), presskey_P, sizeof(presskey_P));
    }

    /*
     * Stream devices do buffered I/O. That means, nothing will be 
     * passed to the hardware device until either the output buffer 
     * is full or we do a flush. With stream I/O we typically use
     * fflush(), but low level writing a null pointer will also flush 
     * the output buffer.
     */
    _write(_fileno(uart), 0, 0);

    /*
     * The low level function read() will grab all available bytes 
     * from the input buffer. If the buffer is empty, the call will
     * block until something is available for reading.
     */
    got = _read(_fileno(uart), inbuf, sizeof(inbuf));
    _write(_fileno(uart), inbuf, got);
	
	/*
     * Nut/OS never expects a thread to return. So we enter an 
     * endless loop here.
     */

    do {
	fflush(uart);
	lcdPrint("Main Menu");
	userchoice = 0;
        /*
         * A bit more advanced input routine is able to read a string 
         * up to and including the first newline character or until a
         * specified maximum number of characters, whichever comes first.
         */
		puts("\n*************");
		puts("\n* Main Menu *");
		puts("\n*************\n");
		puts("\n1. Generate speech\n");
		puts("\n2. IRC\n");
		puts("\n3. Settings\n");
		puts("\n4. Help\n");
		puts("\n5. Play wav\n");
      puts("\nEnter your choice: ");
		readLine(inbuf, sizeof(inbuf));

        /*
         * Streams support formatted output as well as printing strings 
         * from program space.
         */
        if (inbuf[0]) {
		   puts("\n\n");
			userchoice = atoi(inbuf);
			switch (userchoice)
    		{
    		case 1: speechSynthesize(uart);
        		break;
    		case 2: runIRC(uart);
        		break;
    		case 3: openSettings(uart);
        		break;
    		case 4: showHelp(uart);        		
        		break;
    		case 5: playWAV(uart);
    		    break;
    		default: puts("Invalid option selected\n");
    		}
		}

        /*
         * Just to demonstrate formatted floating point output.
         * In order to use this, we need to link the application
         * with nutcrtf instead of nutcrt for pure integer.
         */
#ifdef STDIO_FLOATING_POINT
        dval += 1.0125;
        fprintf(uart, "FP %f\n", dval);
#endif
    }
	while (1);
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
0
/*
 * Main application routine. 
 *
 */
int main(void)
{
    uint32_t baud = 115200;
    UDPSOCKET *socket;

    uint32_t ip_addr;
    uint32_t ip_udp_echo;
    int    rc;
    int    error;
    int    packet_nr;
    uint16_t length;

    /*
     * Initialize the uart device.
     */
    NutRegisterDevice(&DEV_DEBUG, 0, 0);
    freopen(DEV_DEBUG_NAME, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
    puts("Demo for ICMP support in UDP sockets...\r\n");

#ifdef DEV_ETHER
#ifndef NUT_UDP_ICMP_SUPPORT
#warning ICMP support for UDP sockets not enabled in the configurator, please enable NUT_UDP_ICMP_SUPPORT
    puts("ICMP support for UDP sockets not enabled in the configurator\r\n");
    puts("Please enable NUT_UDP_ICMP_SUPPORT\r\n");
#endif    
    /*
     * Register the network device.
     */
    puts("Configuring Ethernet interface");
    NutRegisterDevice(&DEV_ETHER, 0, 0);

    ip_addr = inet_addr(MY_IP);
    NutNetIfConfig("eth0", my_mac, ip_addr, inet_addr(MY_MASK));
    NutIpRouteAdd(0, 0, inet_addr(MY_GATE), &DEV_ETHER);

    printf("%s ready\r\n", inet_ntoa(ip_addr));


    socket = NutUdpCreateSocket(UDP_ECHO_PORT);
    if (socket == 0) {
        printf("Could not create UDP socket in port '%d'\r\n", UDP_ECHO_PORT);
        puts("Demo halted...\r\n");
        while (1);
    } else {
        printf("Successfully created UDP socket on port '%d'\r\n", UDP_ECHO_PORT);
        length = UDP_BUFF_SIZE;
        if (NutUdpSetSockOpt(socket, SO_RCVBUF, &length, sizeof(length))) {;
            printf("Could not set UDP receive buffer size (%d)\r\n", length);
            puts("Demo halted...\r\n");
            while (1);
        }
    }
    
    if (NutThreadCreate("RCV", UDPReceiver, (void*)socket, 1024) == 0) {
            puts("Could not start receiver thread\r\n");
            puts("Demo halted...\r\n");
            while (1);
    } else {
        puts("Receiver thread started\r\n");
    }
    
    puts("Starting echo test (1 packet / second)\r\n");
    
    ip_udp_echo = inet_addr(UDP_ECHO_IP);
    packet_nr = 0;
    
    while (1) {
        packet_nr ++;
        sprintf(send_buffer, "Packet: %d", packet_nr);
        rc = NutUdpSendTo(socket, ip_udp_echo, UDP_ECHO_PORT, send_buffer, length);
        printf("--> Sended packet: \"%s\", to %s, rc: %d\r\n", send_buffer, inet_ntoa(ip_udp_echo), rc);
        if (rc < 0) {
            uint32_t remote_ip;
            uint16_t remote_port;
            
            error = NutUdpError(socket, &remote_ip, &remote_port);
            print_udp_icmp_error(remote_ip, remote_port, error);
            
        }
        
        NutSleep(1000);
    }
#endif /* DEV_ETHER */
    return 0;
}
Ejemplo n.º 23
0
/*
 * Main application routine.
 *
 * Nut/OS automatically calls this entry after initialization.
 */
int main(void)
{
    uint32_t baud = 115200;
    /* IP of the local network in host byte order. */
    uint32_t net_ip;
    /* Currently scanned IP in host byte order. */
    uint32_t scan_ip;
    /* Currently scanned IP in network byte order. */
    uint32_t dest;
    /* Host portion mask in host byte order. */
    uint32_t host_mask;
    /* Current echo request sequence number. */
    uint16_t seq = 0;

    /*
     * Assign stdout to the DEBUG device.
     */
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE.dev_name, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);

    /*
     * Print out our version information.
     */
    printf("\n\nNut/OS %s\n", NutVersionString());
    printf("PingNet %s " __DATE__ " " __TIME__ "\n", APP_VERSION);

    /*
     * Configure the network interface. It is assumed, that
     * we got a valid configuration in non-volatile memory.
     *
     * For alternatives see
     * http://www.ethernut.de/nutwiki/Network_Configuration
     */
    printf("Configure %s...", DEV_ETHER_NAME);
    if (NutRegisterDevice(&DEV_ETHER, 0, 0)) {
        FatalError("failed");
    }
    if (NutDhcpIfConfig("eth0", 0, 60000)) {
        FatalError("no valid network configuration");
    }
    printf("%s ready\n", inet_ntoa(confnet.cdn_ip_addr));
    /* Some Ethernet device drivers seem to return from initialization
       even if they are not fully up and running. Typically this is no
       problem, because upper layers will do retries. However, in our
       special case we'd lose some nodes during the first scan. So just
       take a short nap to give the driver some more time. */
    NutSleep(2000);

    /*
     * Register an ICMP callback function to inspect all incoming
     * ICMP packets.
     */
    if (NutRegisterIpHandler(IPPROTO_ICMP, IcmpCallback)) {
        FatalError("failed to register ICMP callback");
    }

    /*
     * Determine the host portion mask and the IP of the local
     * network from our IP configuration. Note, that Nut/Net
     * stores all IP address items in network byte order.
     */
    host_mask = ~ntohl(confnet.cdn_ip_mask);
    net_ip = ntohl(confnet.cdn_ip_addr) & ~host_mask;

    /*
     * Allocate a bit field to store the state of all possible
     * nodes of our local network. Limit this to 2^16 (class B)
     * and also reject point to point configurations.
     */
    if (host_mask > 0xFFFF || host_mask < 0x0003) {
        FatalError("Bad network size");
    }
    upnodes = calloc((host_mask + 1) / 8, 1);
    if (upnodes == NULL) {
        FatalError("out of memory");
    }

    /*
     * Scan the whole network endlessly.
     */
    for (;;) {
        int retries = 0;

        seq++;
        scan_ip = net_ip;
        /*
         * Scan node by node.
         */
        for (;;) {
            int got = 0;

            /* If this is not a retry, move to the next possible node
               address. */
            if (retries == 0) {
                scan_ip++;
            }
            /* All nodes processed if we reached the broadcast address. */
            if ((scan_ip & host_mask) == host_mask) {
                break;
            }
            /* Send an echo request to the current IP (network byte order). */
            dest = htonl(scan_ip);
            printf("\r%s ", inet_ntoa(dest));
            if (IcmpSendPing(dest, 1, seq, 32) == 0) {
                /* Wait until our ICMP handler signals new packets. */
                while (got == 0 && NutEventWait(&sign_queue, 100) == 0) {
                    /* Inspect all queued packets. */
                    while (nbuf_queue) {
                        NETBUF *nb;
                        IPHDR *ip = (IPHDR *) nbuf_queue->nb_nw.vp;

                        /* Check if this packet is from the currently scanned
                           node address. We may additionally check ID and
                           sequence number, but actually anything from that
                           interface will be just fine to mark it as up. */
                        got += (ip->ip_src == dest);
                        nb = nbuf_queue;
                        nbuf_queue = nb->nb_next;
                        NutNetBufFree(nb);
                    }
                }
                if (NODE_IS_UP(scan_ip & host_mask)) {
                    /* If the node has been up and is now down, then
                       do a few retries first to be sure that it is
                       really not responding anymore. */
                    if (got == 0) {
                        if (retries < 3) {
                            retries++;
                        } else {
                            retries = 0;
                            NODE_DOWN(scan_ip & host_mask);
                            puts("down");
                        }
                    }
                }
                else if (got) {
                    /* New node detected. */
                    NODE_UP(scan_ip & host_mask);
                    puts("up");
                }
            } else {
                /* Failed to send out the request. */
                puts("ICMP transmit error");
            }
        }
        /* Sleep one minute before scanning the network again. */
        printf("\rSleeping                ");
        NutSleep(60000);
    }
    /* Never reached, but required to suppress compiler warning. */
    return 0;
}
Ejemplo n.º 24
0
/*
 * Application entry.
 */
int main(void)
{
    uint32_t baud = 115200;
    int cmd;

    /* Use UART device for stdin and stdout. */
    NutRegisterDevice(&DEV_CONSOLE, 0, 0);
    freopen(DEV_CONSOLE.dev_name, "w", stdout);
    freopen(DEV_CONSOLE.dev_name, "r", stdin);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);
    printf("\n\nCalendar Time %s running on Nut/OS %s\n"
           , version, NutVersionString());

#ifdef USE_LINE_EDITOR
    /* Open line editor, if configured. */
    printf("Opening line editor...");
    edline = EdLineOpen(EDIT_MODE_ECHO);
    if (edline) {
        puts("OK");
    } else {
        puts("failed");
    }
#else
    puts("Note: Enable local echo!");
#endif

#if USE_TIME_ZONE
    _timezone = USE_TIME_ZONE;
#endif

#ifdef RTC_CHIP
    /* Register and query hardware RTC, if available. */
    printf("Registering RTC hardware...");
    if (NutRegisterRtc(&RTC_CHIP)) {
        puts("failed");
    } else {
        uint32_t rtc_stat;

        NutRtcGetStatus(&rtc_stat);
        if (rtc_stat & RTC_STATUS_PF) {
#if defined(USE_BUILD_TIME)
            puts("power failure, Setting Time from Build date");
            /* Initially use the compile date and time. */
            time_t now = RfcTimeParse("Unk, " __DATE__ " " __TIME__);
            stime(&now);
            puts("Built " __DATE__ " " __TIME__);
#else
            puts("power failure");
#endif
        } else {
            puts("OK");
        }
    }
#elif USE_BUILD_TIME
    {
        /* Initially use the compile date and time. */
        time_t now = RfcTimeParse("Unk, " __DATE__ " " __TIME__);
        stime(&now);
        puts("Built " __DATE__ " " __TIME__);
    }
#endif

    for (;;) {
        /* Print command menu. */
        puts("\n  0 - Display seconds counter");
        puts("  1 - Display universal time");
        puts("  2 - Display local time");
        puts("  3 - Display system uptime");
        puts("  C - Calculate weekday");
        puts("  S - Set local time");
        puts("  Y - Toggle DST calculation");
        puts("  Z - Set timezone");

        printf("What is thy bidding, my master? ");

        /* Flush input buffer. */
        while (kbhit()) {
            cmd = getchar();
        }

        /* Get the next command. */
        cmd = getchar();
        putchar('\n');

        /* Process the command. */
        switch (cmd) {
        case '0':
            DisplaySeconds();
            break;
        case '1':
            DisplayZuluTime();
            break;
        case '2':
            DisplayLocalTime();
            break;
        case '3':
            DisplayUpTime();
            break;
        case 'C':
        case 'c':
            CalcWeekDay();
            break;
        case 'S':
        case 's':
            SetLocalTime();
            break;
        case 'Y':
        case 'y':
            /* Nut/OS uses a global variable to enable/disable DST.
               Toggle the current status and display the result. */
            _daylight = _daylight == 0;
            printf("DST calculation %sabled\n", _daylight ? "en" : "dis");
            break;
        case 'Z':
        case 'z':
            SetTimeZone();
            break;
        }
    }
    return 0;
}
Ejemplo n.º 25
0
/*
 * UART sample.
 *
 */
int main(void)
{

    uint32_t baud = 115200;
    FILE *uart;
    int res, i = 0;
    uint64_t hid  = 0;
    int32_t xcelsius;
    int run =0;
    uint8_t raw[2];
    uint8_t diff;

    NutRegisterDevice(&DEV_CONSOLE, 0, 0);

    uart = fopen(DEV_CONSOLE.dev_name, "r+");

    _ioctl(_fileno(uart), UART_SETSPEED, &baud);

    freopen(DEV_CONSOLE.dev_name, "w", stdout);
    fprintf(stdout, banner);

#undef DEF_OWIBUS
#include <dev/owibus_gpio.h>
#define DEF_OWIBUS owiBus0Gpio

    res = OwiInit(&DEF_OWIBUS);
    if(res)
    {
        printf("Owi Error %d\n", res);
        while(1)
            NutSleep(10);
    }
    diff = OWI_SEARCH_FIRST;
    res = OwiRomSearch(&DEF_OWIBUS, &diff, &hid);
    if(res)
    {
        printf("OwiRomSearch failed\n");
        while(1)
            NutSleep(10);
    }
    fprintf(stdout, "Hardware ID of first device %08lx%08lx\n",
            (uint32_t)(hid>>32),
            (uint32_t)(hid &0xffffffff));
    if ((hid & 0xff) != W1_THERM_DS18B20)
    {
        fprintf(stdout, "One-wire device found, but family not handled"
                "in this example\n");
        while(1) NutSleep(10);
    }
    while(1)
    {
        res = OwiCommand(&DEF_OWIBUS, OWI_CONVERT_T, NULL);
        if (res)
            printf("OwiCommand convert_t error %d\n", res);
        NutSleep(750);
        while (!(res = OwiReadBlock(&DEF_OWIBUS, &diff, 1)) && !diff && i < 100)
        {
            NutSleep(10);
            i++;
        }
        if (i)
        {
            printf(
                "Conversion took additional %d poll cycles\n",
                i);
            i = 0;
        }
        res = OwiCommand(&DEF_OWIBUS, OWI_READ, NULL);
        if (res)
            printf("OwiCommand read error %d\n", res);
        res = OwiReadBlock(&DEF_OWIBUS, raw, 16);
        if (res)
            printf("OwiReadBlock error %d\n", res);
        xcelsius = (raw[1]<<8 | raw[0]) * (int32_t)625;
        fprintf(stdout, "Run %3d: Temp %ld.%04ld\r",
                run++, xcelsius/10000, xcelsius%10000);
    }
    return 0;
}