Exemple #1
0
/*
 * Display the coordinated universal time.
 *
 * The value is constantly updated until the user presses a key.
 */
static void DisplayZuluTime(void)
{
    time_t secs;
    struct _tm *gmt;
    uint_fast8_t i = 0;

    while (!kbhit()) {
        secs = time(NULL);
        gmt = gmtime(&secs);
        printf(" [%c] Universal time: ", rotor[++i & 3]);
        PrintDateTime(gmt);
        printf("    \r");
        NutSleep(500);
    }
    putchar('\n');
}
void lcd_q_put( uint16_t data )
{
    cli();

    // Wait for output to drain
    while( lcd_q_full() )
    {
        sei();
        NutSleep(1);
        cli();
    }

    lcd_queue[ lcd_q_put_pos++ ] = data;

    sei();
}
Exemple #3
0
THREAD(sensorsReader, arg) {
    struct sensorNode* list = (struct sensorNode*) arg;
    struct sensorNode* current;
    NutThreadSetPriority(70);
    
    for (;;) {
        current = list;

        while (current != NULL) {
            current->data.value = current->data.read(current->data.params);
            current = current->next;
            NutThreadYield();
        }

        NutSleep(5000);
    }
}
Exemple #4
0
void RetrieveTime()
{
	tm test;
	for (;;) {
		if (NutSNTPGetTime(&timeserver, &ntp_time) == 0) {
			break;
		} else {
			NutSleep(200);
			puts("Time Error");
		}
	}
	ntp_datetime = localtime(&ntp_time);
	tm RTCdate={ntp_datetime->tm_sec,  ntp_datetime->tm_min,  ntp_datetime->tm_hour, ntp_datetime->tm_mday,  ntp_datetime->tm_mon,  ntp_datetime->tm_year,1,1,1};

	setDateTime(&RTCdate);
	isSynchronizedTimer = 60;
	getDateTime(&test);

	printf(" RTC time check = %d : %d : %d \n ",  test.tm_hour, test.tm_min, test.tm_sec);
}
Exemple #5
0
/*
 * Display system up time.
 *
 * The value is constantly updated until the user presses a key.
 */
static void DisplayUpTime(void)
{
    uint32_t hours;
    uint32_t minutes;
    uint32_t seconds;
    uint_fast8_t i = 0;

    while (!kbhit()) {
        seconds = NutGetSeconds();
        minutes = seconds / 60UL;
        hours = minutes / 60UL;
        minutes %= 60UL;
        seconds %= 60UL;
        printf(" [%c] System is running %lu hours"
               ", %lu minutes and %lu seconds   \r"
               , rotor[++i & 3], hours, minutes, seconds);
        NutSleep(500);
    }
    putchar('\n');
}
/*
 * PPP client application entry.
 */
int main(void)
{
    int pppcom;

    /* Initialize a debug port for standard output and display a banner. */
    DebugPortOpen();
    printf("\n\nPPP Client Sample - Nut/OS %s\n", NutVersionString());

    /* Initialize the network interface. */
    ProtocolPortInit();
    /* This loop runs once per hour. */
    for (;;) {
        /* Open the network interface. */
        pppcom = ProtocolPortOpen();
        if (pppcom == -1) {
            /* If this fails, we are busted. */
            break;
        }
        /* Establish the modem connection. */
        if (ProtocolPortConnect(pppcom) == 0) {
            /* Configure the network interface. */
            if (ProtocolPortConfigure() == 0) {
                /* Talk to the Internet. */
                QueryDateAndTime();
            }
        }
        /* Hang up. */
        ProtocolPortClose(pppcom);

        /* Sleep 1 hour. */
        puts("I'll be back in 1 hour.");
        NutSleep(3600000);
    }
    /* Ouch... */
    puts("Good bye cruel world");

    return 0;
}
Exemple #7
0
int NtpSync(void){
    /* Ophalen van pool.ntp.org */
    isSyncing = true;
    setTimeZone(50);
    httpGet("/gettimezone.php", parsetimezone);
    _daylight = 0;
    printf("Timezone is: %d", TIME_ZONE);
    if(TIME_ZONE == 50)
    {
        return 0;
    }
    NutDelay(100);
    //puts("Tijd ophalen van pool.ntp.org (213.154.229.24)");
    timeserver = inet_addr("213.154.229.24");

    for (;;) {
        if (NutSNTPGetTime(&timeserver, &ntp_time) == 0) {
            break;
        } else {
            NutSleep(400);
            puts("Fout bij het ontvangen van de tijd");
        }
    }
    //puts("Opgehaald.\n");

    ntp_datetime = localtime(&ntp_time);

    printf("NTP time is: %02d:%02d:%02d\n", ntp_datetime->tm_hour, ntp_datetime->tm_min, ntp_datetime->tm_sec);
    printf("NTP date is: %02d.%02d.%02d\n\n", ntp_datetime->tm_mday, (ntp_datetime->tm_mon + 1), (ntp_datetime->tm_year + 1900));

    X12RtcSetClock(ntp_datetime);
    NtpWriteTimeToEeprom(*ntp_datetime);

    isSyncing = false;
    validTime = true;
    return 1;
}
Exemple #8
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;
}
void delay_halfsec(void)
{
    NutSleep(500);
}
Exemple #10
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;
}
Exemple #11
0
	int main(void) {
		//audioInit();
		//setVolume(254);
		WatchDogDisable();		//disable watchdog
		NutDelay(100);			//wait for it to disable
		SysInitIO();			//initialise input and output
		SPIinit();				//initialise SPI-registers (speed, mode)
		LedInit();				//initialise led
		initLCD();				//initialise lcd
		Uart0DriverInit();		//initialise Universal asynchronous receiver/transmitter  
		Uart0DriverStart();		//start Uart
		printf("\n\n\n\nHardware initialization done\n\n");
		LogInit();				//initialise ability to log
		CardInit();				//initialise cardreader
		printf("\n----------------------------------------------START OF PROGRAM------------------------------------------------------------\n");

		if (NutSegBufInit(8192) == 0) {
			puts("NutSegBufInit: Fatal error");
		}
		
		/*
		* Initialize the MP3 decoder hardware.
		*/
		if (VsPlayerInit() || VsPlayerReset(0)) {
			puts("VsPlayer: Fatal error");
		}
		
		if(X12Init() == -1){
			printf("error initializing RTC");	//initialise X12RTC 
		}				
		tm gmt;
		if (X12RtcGetClock(&gmt) == 0) {
			LogMsg_P(LOG_INFO, PSTR("local storage time [%02d:%02d:%02d] (in RTC)\n"), gmt.tm_hour, gmt.tm_min, gmt.tm_sec);
		}

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

		RcInit();					//Initialise the Remote Control module
		KbInit();					//Initialise keyboard
		initMenu();					//Initialise menu
		NutThreadCreate("Bh", ButtonHandlerThread, NULL, 512);	//create thread to handle button presses
		printf("\nInitialization done.\n");
		initAlarms();
		SysControlMainBeat(ON); 	//enable 4.4 msecs heartbeat interrupt
		printf("Heartbeat on.\n");
		NutThreadSetPriority(1);	//Increase our priority so we can feed the watchdog.
		sei();						//enable global interrupts
		NutThreadCreate("Bg", TimeSyncThread, NULL, 512);
		NutThreadCreate("Bq", RefreshSceenThread, NULL, 512);
		NutThreadCreate("Bl", AlarmCheckerThread, NULL, 512);
		printf("\nEntering main loop.\n");
		LcdBackLight(LCD_BACKLIGHT_ON);
		for(;;){
			NutSleep(100);
			WatchDogRestart();			//restart watchdog
		}
		
		return(0);
	}
Exemple #12
0
    /*
 * \brief Play MP3 stream.
 *
 * \param stream Socket stream to read MP3 data from.
 */
    void PlayMp3Stream(FILE *stream, u_long metaint) {
        size_t rbytes;
        u_char *mp3buf;
        u_char ief;
        int got = 0;
        u_long last;
        u_long mp3left = metaint;

        /*
         * Initialize the MP3 buffer. The NutSegBuf routines provide a global
         * system buffer, which works with banked and non-banked systems.
         */
        if (NutSegBufInit(8192) == 0) {
            puts("Error: MP3 buffer init failed");
            return;
        }

        /*
         * Initialize the MP3 decoder hardware.
         */
        if (VsPlayerInit() || VsPlayerReset(0)) {
            puts("Error: MP3 hardware init failed");
            return;
        }
        VsSetVolume(0, 0);

        /*
         * Reset the MP3 buffer.
         */
        ief = VsPlayerInterrupts(0);
        NutSegBufReset();
        VsPlayerInterrupts(ief);
        last = NutGetSeconds();

        for (; ;) {

            if(STOP_THREAD){
                STOP_THREAD = 0;
                return;
            }

            /*
             * Query number of byte available in MP3 buffer.
             */
            ief = VsPlayerInterrupts(0);
            mp3buf = NutSegBufWriteRequest(&rbytes);
            VsPlayerInterrupts(ief);

            /*
             * If the player is not running, kick it.
             */
            if (VsGetStatus() != VS_STATUS_RUNNING) {
                if (rbytes < 1024 || NutGetSeconds() - last > 4UL) {
                    last = NutGetSeconds();
                    puts("Kick player");
                    VsPlayerKick();
                }
            }

            /*
             * Do not read pass metadata.
             */
            if (metaint && rbytes > mp3left) {
                rbytes = mp3left;
            }

            /*
             * Read data directly into the MP3 buffer.
             */
            while (rbytes) {
                if ((got = fread(mp3buf, 1, rbytes, stream)) > 0) {
                    ief = VsPlayerInterrupts(0);
                    mp3buf = NutSegBufWriteCommit(got);
                    VsPlayerInterrupts(ief);

                    if (metaint) {
                        mp3left -= got;
                        if (mp3left == 0) {
                            ProcessMetaData(stream);
                            mp3left = metaint;
                        }
                    }

                    if (got < rbytes && got < 512) {
                        printf("%lu buffered\n", NutSegBufUsed());
                        NutSleep(250);
                    }
                    else {
                        NutThreadYield();
                    }
                } else {
                    break;
                }
                rbytes -= got;
            }

            if (got <= 0) {
                break;
            }

            NutSleep(100);
        }
    }
/*! \fn AhdlcRx(void *arg)
 * \brief Asynchronous HDLC receiver thread.
 *
 *
 * Running at high priority.
 */
THREAD(AhdlcRx, arg)
{
    NUTDEVICE *dev = arg;
    NUTDEVICE *netdev;
    AHDLCDCB *dcb = dev->dev_dcb;
    IFNET *ifn;
    NETBUF *nb;
    uint8_t *rxbuf;
    uint8_t *rxptr;
    uint16_t rxcnt;
    uint8_t ch;
    uint16_t tbx;
    uint8_t inframe;
    uint8_t escaped;
    uint16_t rxfcs;

    NutThreadSetPriority(9);
    for (;;) {
        /*
         * Reset variables to their initial state
         */
        rxptr = 0;
        rxcnt = 0;
        escaped = 0;
        rxfcs = AHDLC_INITFCS;
        inframe = 0;

        for (;;) {
            /*
             * Wait until the network interface has been attached.
             * This will be initiated by the application calling
             * NutNetIfConfig(), which in turn calls a HDLC_SETIFNET
             * ioctl() to store the NUTDEVICE pointer of the network
             * device in dev_icb and trigger an event on dcb_mf_evt.
             */
            while ((netdev = dev->dev_icb) == 0) {
                if (NutEventWait(&dcb->dcb_mf_evt, 1000) == 0) {
                    NutSleep(100);
                }
            }
            ifn = netdev->dev_icb;
            dcb->dcb_rtimeout = 1000;
            inframe = 0;

            /*
             * Allocate the receive buffer, if this fails, we are in a
             * low memory situation. Take a nap and see, if the
             * situation improved.
             */
            if ((rxbuf = NutHeapAlloc(dcb->dcb_rx_mru)) != 0) {
                break;
            }
            NutSleep(1000);
        }

        /*
         * Signal the link driver that we are up.
         */
        ifn->if_send = AhdlcOutput;
        netdev->dev_ioctl(netdev, LCP_LOWERUP, 0);

        for (;;) {
            /*
             * If we are still connected to a network, fetch the next
             * character from the buffer.
             */
            while (dcb->dcb_rd_idx == dcb->dcb_rx_idx) {
                if (dev->dev_icb == 0)
                    break;
                // TODO: Check for idle timeout. 
                if (NutEventWait(&dcb->dcb_rx_rdy, dcb->dcb_rtimeout)) {
                    continue;
                }
            }

            /*
             * Leave loop if network interface is detached
             */
            if (dev->dev_icb == 0)
                break;

            /*
             * If RAW mode is active, we are not allowing any data encapsulation
             * processing. So we just sleep for a while.
             */
            if (dcb->dcb_modeflags & UART_MF_RAWMODE) {
                /*
                 * It is a must to sleep here, because if we just yield it could create
                 * too much processing in here and stall processing elsewhere. This gives
                 * opportunity to other threads to process incoming data from USART.
                 */
                NutSleep(100);
                continue;
            }

            /*
             * Read next character from input buffer
             */
            ch = dcb->dcb_rx_buf[dcb->dcb_rd_idx++];

            if (inframe) {
                if (ch != AHDLC_FLAG) {
                    if (ch == AHDLC_ESCAPE) {
                        escaped = 1;
                        continue;
                    }
                    if (escaped) {
                        ch ^= AHDLC_TRANS;
                        escaped = 0;
                    }

                    /*
                     * Unless the peer lied to us about the negotiated MRU,
                     * we should never get a frame which is too long. If it
                     * happens, toss it away and grab the next incoming one.
                     */
                    if (rxcnt++ < dcb->dcb_rx_mru) {
                        /* Update calculated checksum and store character in buffer. */
                        tbx = (uint16_t) ((uint8_t) rxfcs ^ ch) << 1;
                        rxfcs >>= 8;
                        rxfcs ^= ((uint16_t) PRG_RDB(fcstab + tbx) << 8) | PRG_RDB(fcstab + tbx + 1);
                        *rxptr++ = ch;
                    } else
                        inframe = 0;
                    continue;
                }

                if (rxcnt > 6 && rxfcs == AHDLC_GOODFCS) {
                    /*
                       * If the frame checksum is valid, create a NETBUF
                       * and pass it to the network specific receive handler.
                     */
                    rxcnt -= 2;
                    if ((nb = NutNetBufAlloc(0, NBAF_DATALINK, rxcnt)) != 0) {
                        memcpy(nb->nb_dl.vp, rxbuf, rxcnt);
                        (*ifn->if_recv) (netdev, nb);
                    }
                }
            }

            /*
             * If frame flag is received, resync frame processing
             */
            if (ch == AHDLC_FLAG) {
                inframe = 1;
                escaped = 0;
                rxptr = rxbuf;
                rxcnt = 0;
                rxfcs = AHDLC_INITFCS;
            }
        }
Exemple #14
0
// ~1/16 sec
void delay_thsec(void)
{
    NutSleep(62);
}
/*!
 * \brief Configure the internal PHY.
 *
 * Reset the PHY and initiate auto-negotiation.
 */
static int NicPhyConfig(phantom_device_t * dev)
{
    u_int16_t phy_sor;
    u_int16_t phy_sr;
    u_int16_t phy_to;
    u_int16_t mode;

    /* 
     * Reset the PHY and wait until this self clearing bit
     * becomes zero. We sleep 63 ms before each poll and
     * give up after 3 retries. 
     */
    //printf("Reset PHY..");
    NicPhyWrite(dev, NIC_PHYCR, PHYCR_RST);
    for (phy_to = 0;; phy_to++) {
        NutSleep(63);
        if ((NicPhyRead(dev, NIC_PHYCR) & PHYCR_RST) == 0)
            break;
        if (phy_to > 3)
            return -1;
    }
    //printf("OK\n");

    /* Store PHY status output. */
    phy_sor = NicPhyRead(dev, NIC_PHYSOR);

    /* Enable PHY interrupts. */
    NicPhyWrite(dev, NIC_PHYMSK, PHYMSK_MLOSSSYN | PHYMSK_MCWRD | PHYMSK_MSSD |
                PHYMSK_MESD | PHYMSK_MRPOL | PHYMSK_MJAB | PHYMSK_MSPDDT | PHYMSK_MDPLDT);

    /* Set RPC register. */
    mode = RPCR_ANEG | RPCR_LEDA_PAT | RPCR_LEDB_PAT;
    nic_bs(0);
    nic_outw(NIC_RPCR, mode);

#ifdef NIC_FIXED
    /* Disable link. */
    phy_sr = NicPhyRead(NIC_PHYCFR1);
    NicPhyWrite(NIC_PHYCFR1, phy_sr | 0x8000);
    NutSleep(63);

    /* Set fixed capabilities. */
    NicPhyWrite(NIC_PHYCR, NIC_FIXED);
    nic_bs(0);
    nic_outw(NIC_RPCR, mode);

    /* Enable link. */
    phy_sr = NicPhyRead(NIC_PHYCFR1);
    NicPhyWrite(NIC_PHYCFR1, phy_sr & ~0x8000);
    phy_sr = NicPhyRead(NIC_PHYCFR1);

#else
    /*
     * Advertise our capabilities, initiate auto negotiation
     * and wait until this has been completed.
     */
    //printf("Negotiate..");
    NicPhyWrite(dev, NIC_PHYANAD, PHYANAD_TX_FDX | PHYANAD_TX_HDX | PHYANAD_10FDX | PHYANAD_10_HDX | PHYANAD_CSMA);
    NutSleep(63);
    for (phy_to = 0, phy_sr = 0;; phy_to++) {
        /* Give up after 10 seconds. */
        if (phy_to >= 1024)
            return -1;
        /* Restart auto negotiation every 4 seconds or on failures. */
        if ((phy_to & 127) == 0 /* || (phy_sr & PHYSR_REM_FLT) != 0 */ ) {
            NicPhyWrite(dev, NIC_PHYCR, PHYCR_ANEG_EN | PHYCR_ANEG_RST);
            //printf("Restart..");
            NutSleep(63);
        }
        /* Check if we are done. */
        phy_sr = NicPhyRead(dev, NIC_PHYSR);
        //printf("[SR %04X]", phy_sr);
        if (phy_sr & PHYSR_ANEG_ACK)
            break;
        NutSleep(63);
    }
    //printf("OK\n");
#endif

    return 0;
}
Exemple #16
0
// 1/4 sec
void delay_qsec(void)
{
    NutSleep(250);
}
static int LcdInit(NUTDEVICE * dev)
{
#if defined(PMC_PCER)
    outr(PMC_PCER, _BV(LCD_RS_PIO_ID) | _BV(LCD_EN_PIO_ID));
#endif

    /* Initialize GPIO lines. */
#ifdef LCD_RW_BIT
    outr(PMC_PCER, _BV(LCD_RW_PIO_ID));
    LCD_RW_CLR();
#endif

#ifdef LCD_EN2_BIT
    outr(PMC_PCER, _BV(LCD_EN2_PIO_ID));
    LCD_EN2_CLR();
#endif

#ifdef LCD_RST_BIT
    outr(PMC_PCER, _BV(LCD_RST_PIO_ID));
    LCD_RST_CLR();
#endif

    LCD_RS_CLR();
    LCD_RW_CLR();
    LcdClrBits(LCD_DATA);
    NutMicroDelay(30);
    LCD_EN_CLR();
    NutMicroDelay(30);

    /* Initial delay. Actually only required after power on. */
    NutSleep(16);

    /* This initialization will make sure, that the LCD is switched
     * to 8-bit mode, no matter which mode we start from or we finally
     * need.
     */
    LcdWriteNibble((_BV(LCD_FUNCTION) | _BV(LCD_FUNCTION_8BIT)) >> 4);
    NutSleep(15);
    LcdWriteNibble((_BV(LCD_FUNCTION) | _BV(LCD_FUNCTION_8BIT)) >> 4);
    NutSleep(4);
    LcdWriteNibble((_BV(LCD_FUNCTION) | _BV(LCD_FUNCTION_8BIT)) >> 4);
    NutSleep(2);

#ifdef LCD_IF_4BIT
    /* We now switch to 4-bit mode */
    LcdWriteNibble(_BV(LCD_FUNCTION) >> 4);
    NutSleep(2);

    // TODO: Add support for large font in single line displays
    /* Set number of lines and font. Can't be changed later. */
#if (LCD_ROWS == 2) || (LCD_ROWS==4)
    LcdWriteNibble((_BV(LCD_FUNCTION) | _BV(LCD_FUNCTION_2LINES)) >> 4);
    LcdWriteNibble(_BV(LCD_FUNCTION) | _BV(LCD_FUNCTION_2LINES));
#else
    LcdWriteNibble(_BV(LCD_FUNCTION) >> 4);
    LcdWriteNibble(_BV(LCD_FUNCTION) );
#endif
#else /* LCD_IF_4BIT */
    LcdWriteCmd(_BV(LCD_FUNCTION) | _BV(LCD_FUNCTION_8BIT));
#endif /* LCD_IF_4BIT */
    NutSleep(2);

    /* Switch display and cursor off. */
    LcdWriteNibble(_BV(LCD_ON_CTRL) >> 4);
    LcdWriteNibble(_BV(LCD_ON_CTRL));
    NutSleep(2);

    /* Clear display. */
    LcdClear();

    /* Set entry mode. */
    LcdWriteCmd(_BV(LCD_ENTRY_MODE) | _BV(LCD_ENTRY_INC));
    /* Switch display on. */
    LcdWriteCmd(_BV(LCD_ON_CTRL) | _BV(LCD_ON_DISPLAY));
    /* Move cursor home. */
    LcdCursorHome();
    /* Set data address to zero. */
    LcdWriteCmd(_BV(LCD_DDRAM));

    return 0;
}
Exemple #18
0
THREAD(SoundRecord, arg)
{

	printf("SoundAnalyzer started\n");
	fflush(stdout);
	VsTest();
	NutSleep(200);

	SoundStruct* ss = arg;

	int i;
	int recording = -1;

	ResetDevice();

	unsigned int samplecount = 0;
	short sample;

	short * recordBuffer = malloc( RECORD_BUFFER_SIZE * sizeof(short) );
	for(i = 0; i < RECORD_BUFFER_SIZE; i++)
		recordBuffer[i] = 0;

	i = 0;

	int absolute = 0;		 	//sum of the absolute values of samples
	short absoluteCount = 0; 	//number of recorded samples up to ABSOLUTE_COUNT
	bool readyToBegin = false;

	bool lastWindow = false;

	RecordDeviceInit(8000, 1, 0, 20);

	for(;;)
	{
		NutSleep(3);

		samplecount = VsRegRead(VS_HDAT1_REG);

		// spec page 54: if sci_hdat1 >= 896 may be better not
		// to read and wait for overflow
		while ( (samplecount > 0 && samplecount < 896 )) {

			samplecount--;
			sample = VsRegRead(VS_HDAT0_REG);

			recordBuffer[i] = sample;

			absolute += abs(sample);
			if( absoluteCount < ABSOLUTE_COUNT)
				absoluteCount++;

			else //the oldest sample must be deducted from the sum variable (absolute)
			{
				if ( i - ABSOLUTE_COUNT < 0)
					absolute -= abs(recordBuffer[RECORD_BUFFER_SIZE+i-ABSOLUTE_COUNT]);
				else
					absolute -= abs(recordBuffer[i-ABSOLUTE_COUNT]);
			}

			i++;
			if ( i == RECORD_BUFFER_SIZE )
			{
				i=0;
				readyToBegin = true;
				//printf("%d, ", absolute/ABSOLUTE_COUNT); //DEBUG
			}

			if( absoluteCount < ABSOLUTE_COUNT)
				continue; //recording does not begin until the averaging window has been fully covered

			//start recording, if the treshold is exceeded
			//if (readyToBegin && (absolute/ABSOLUTE_COUNT > RECORD_START) && recording == -1)
			if(readyToBegin && sample > RECORD_START && recording == -1)
			{
				setLedOn(_BV(_LED_1));

				recording = 0;

				/*
				if ( i < BACKTRACE )
				{
					memcpy(ss->buffer, recordBuffer+i-BACKTRACE, BACKTRACE-i);
					memcpy(ss->buffer+(BACKTRACE-i), recordBuffer, i);
				}
				else
					memcpy(ss->buffer, recordBuffer+i, BACKTRACE);
				*/

			}

			//if we are recording, save sample
			if ( recording != -1)
			{
				ss->buffer[BACKTRACE+recording] = sample;
				recording++;
			}

			if (recording >= 0 && ( (BACKTRACE+recording == WIN_SIZE* CEPS_COUNT) || (absolute/ABSOLUTE_COUNT < RECORD_STOP) ) )
				lastWindow = true; //-2 means that recording should be stopped whenever the last window is filled
			if( lastWindow && ((BACKTRACE + recording) % WIN_SIZE == 0) ) //dynamic length
			{
			//if ( ABSOLUTE_COUNT+recording == WIN_SIZE* CEPS_COUNT && recording != -1) {  //fixed length
				ss->ceps_count = (BACKTRACE + recording) / WIN_SIZE;
				lastWindow = false;
				if(ss->ceps_count < 5) continue;

				setLedOff(_BV(_LED_1));
				recording = -1;

				if(ss->ceps_count < MIN_CEPS_COUNT) continue;
				if(ss->ceps_count != CEPS_COUNT && ss->ceps_count > 3) ss->ceps_count -= 3;



				//WAWISETTI
//				printf("\n\n");
//				int j;
//				for(j = 0; j < 44; j++)
//					printf("%02x ", wavheader[j]);
//
//				printf("\n\n\n");
//				for(j = 0; j < ss->ceps_count*WIN_SIZE; j++)
//					printf("%02x ", recordBuffer[j]);
//
//				printf("\n\n\n");
//				for(;;)
//					NutThreadYield();

				NutEventPost( &recordBufferReadyRead );

				//for(;;)
				//	NutThreadYield();

				//break; //mihi tätä breakkii tarvitaan??
			}

		}
	}
}
Exemple #19
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);      
}
/*! \fn NicRxLanc(void *arg)
 * \brief NIC receiver thread.
 *
 */
THREAD(NicRxLanc, arg)
{
    NUTDEVICE *dev;
    IFNET *ifn;
    lanc111_nic_t *ni;
    NETBUF *nb;
    uint8_t imsk;

    dev = arg;
    ifn = (IFNET *) dev->dev_icb;
    ni = (lanc111_nic_t *) dev->dev_dcb;

    /*
     * This is a temporary hack. Due to a change in initialization,
     * we may not have got a MAC address yet. Wait until a valid one
     * has been set.
     */
    while (!ETHER_IS_UNICAST(ifn->if_mac)) {
        NutSleep(10);
    }

    /*
     * Do not continue unless we managed to start the NIC. We are
     * trapped here if the Ethernet link cannot be established.
     * This happens, for example, if no Ethernet cable is plugged
     * in.
     */
    while(NicStart(ifn->if_mac)) {
        NutSleep(1000);
    }

    //LANC111_SIGNAL_MODE();

    // Enable IRQs. Enabled on irq allocation.
    //sbi(EIMSK, LANC111_SIGNAL_IRQ);

    NutEventPost(&nic->ni_tx_rdy);

    /* Run at high priority. */
    NutThreadSetPriority(9);

    for (;;) {

        /*
         * Wait for the arrival of new packets or
         * check the receiver every two second.
         */
        NutEventWait(&ni->ni_rx_rdy, 2000);

        /*
         * Fetch all packets from the NIC's internal
         * buffer and pass them to the registered handler.
         */
        imsk = nic_inlb(NIC_MSK);
        nic_outlb(NIC_MSK, 0);
        while ((nb = NicGetPacket()) != 0) {
            if (nb != (NETBUF *) 0xFFFF) {
                ni->ni_rx_packets++;
                (*ifn->if_recv) (dev, nb);
            }
        }
        nic_outlb(NIC_MSK, imsk | INT_RCV | INT_ERCV);
    }
}
Exemple #21
0
// 1/8 sec
void delay_esec(void)
{
    NutSleep(125);
}
Exemple #22
0
static void LcdCursorHome(void)
{
    LcdWriteCmd(1 << LCD_HOME);
    NutSleep(2);
}
Exemple #23
0
static void playWAV(FILE *uart) {
    printf("\n\nTest wav decoding with UROM\n");
    NutSleep(100);
    //init_localaudio(8000, "UROM:testi.wav", 1);
    playWaveFile();
}
Exemple #24
0
static void LcdClear(void)
{
    LcdWriteCmd(_BV(LCD_CLR));
    NutSleep(2);
}
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);
	}
}
/*!
 * \brief Discover available cards.
 *
 * Currently this has been tested for SanDisk SD Cards and several
 * MultiMedia Cards. It doesn't seem to work with RS-MMC, though.
 *
 * \param ifc Specifies the hardware interface.
 *
 * \return 0 on success, -1 otherwise.
 */
static int At91MciDiscover(MCIFC * ifc)
{
    uint32_t sr;
    uint32_t clk = MCI_MMC_BITRATE;
    uint32_t opd = 0;
    int tmo;

    At91MciEnablePins();

    /* Put all cards in idle state. */
    At91MciTxCmd(ifc, MCICMD_GO_IDLE_STATE | MCI_SPCMD_INIT, 0);
    At91MciTxCmd(ifc, MCICMD_GO_IDLE_STATE, 0);

    /* Poll SDC operating conditions. */
    for (tmo = 1000; --tmo;) {
        sr = At91MciTxCmd(ifc, MCICMD_SEND_APP_CMD, 0);
        if ((ifc->ifc_resp[0] & (1 << 8)) != 0 && (sr & MCICMD_IERROR) == 0) {
            sr = At91MciTxCmd(ifc, MCICMD_SEND_APP_OP_COND, MMCARD_VRANGE);
            if ((sr & MCICMD_IERROR) == 0) {
                ifc->ifc_opcond = ifc->ifc_resp[0];
                if (ifc->ifc_resp[0] & MMCOP_NBUSY) {
                    ifc->ifc_config |= MCIFLG_SDCARD;
                    break;
                }
            }
        }
        NutSleep(1);
    }

    if (tmo == 0) {
        /* No SDC. Put all cards back in idle state and try MMC. */
        opd = MCI_OPDCMD;
        At91MciTxCmd(ifc, MCICMD_GO_IDLE_STATE, 0);

        /* Poll MMC operating conditions. */
        for (tmo = 100; --tmo;) {
            sr = At91MciTxCmd(ifc, MCICMD_SEND_OP_COND | opd, MMCARD_VRANGE);
            ifc->ifc_opcond = ifc->ifc_resp[0];
            if (ifc->ifc_resp[0] & MMCOP_NBUSY) {
                break;
            }
            NutSleep(1);
        }
    }

    if (tmo == 0) {
        /* No valid card. */
        At91MciDisablePins();
        return -1;
    }

    /* Discover cards. */
    ifc->ifc_reladdr = 0;
    for (tmo = 50; --tmo;) {
        sr = At91MciTxCmd(ifc, MCICMD_ALL_SEND_CID | opd, 0);
        memcpy(ifc->ifc_cid, ifc->ifc_resp, sizeof(ifc->ifc_cid));
        if (sr & MCI_RTOE) {
            /* No more cards. */
            break;
        }
        if (ifc->ifc_config & MCIFLG_SDCARD) {
            /* SD Card will send an address. */
            ifc->ifc_reladdr = 0;
        } else {
            /* MultiMedia Card will receive an address. */
            ifc->ifc_reladdr++;
        }
        At91MciTxCmd(ifc, MCICMD_SEND_RELATIVE_ADDR | opd, ifc->ifc_reladdr << 16);
        if (ifc->ifc_config & MCIFLG_SDCARD) {
            /* Store SD Card address. */
            ifc->ifc_reladdr = ifc->ifc_resp[0] >> 16;
            /* SD Cards can run at higher clock rates. */
            clk = MCI_SDC_BITRATE;
        }
    }
Exemple #27
0
/*
 * \return 0 on success or 2 in case of an I/O error.
 */
static int NutChatSendString(int fd, char *str)
{
    int rc = 0;
    uint8_t eol = 1;
    uint8_t skip;
    char ch;

#ifdef NUTDEBUG
    if (__chat_trf) {
        static prog_char dbgfmt[] = "Send '%s'\n";
        fprintf_P(__chat_trs, dbgfmt, str);
    }
#endif

    /* Flush input buffer. */
    _read(fd, 0, 0);
    while (*str && eol && rc == 0) {
        ch = *str++;
        skip = 0;
        if (ch == '^') {
            ch = *str++;
            ch &= 0x1f;
        } else if (ch == '\\') {
            ch = *str++;
            switch (ch) {
            case 'b':
                ch = '\b';
                break;
            case 'c':
                eol = 0;
                skip = 1;
                break;
            case 'd':
                NutSleep(1000);
                skip = 1;
                break;
            case 'n':
                ch = '\n';
                break;
            case 'N':
                ch = 0;
                break;
            case 'p':
                NutDelay(100);
                skip = 1;
                break;
            case 'r':
                ch = '\r';
                break;
            case 's':
                ch = ' ';
                break;
            case 't':
                ch = '\t';
                break;
            default:
                if (ch >= '0' && ch <= '7') {
                    ch &= 0x07;
                    if (*str >= '0' && *str <= '7') {
                        ch <<= 3;
                        ch |= *str++ & 0x07;
                        if (*str >= '0' && *str <= '7') {
                            ch <<= 3;
                            ch |= *str++ & 0x07;
                        }
                    }
                }
                break;
            }
        }
        if (skip)
            skip = 0;
        else {
            NutDelay(10);
            if (_write(fd, &ch, 1) != 1)
                rc = 2;
            else
                _write(fd, 0, 0);
        }
    }
    if (eol && rc == 0 && _write(fd, "\r", 1) != 1)
        rc = 2;
    else
        _write(fd, 0, 0);

    return rc;
}
/*! \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);
    }
}
Exemple #29
0
THREAD(AlarmPollingThread, arg)
{
    static u_int button_cooldown_counter = 0;
    static bool button_cooldown = true;
    u_long alarm_a;
    u_long alarm_b; 
    short snooze_time;
    tm snooze;
    tm alarm_a_backup;
    
    for(;;)
    {      
        X12RtcGetStatus(&alarm_a);
        alarm_b = alarm_a;
        alarm_a &= 0b00100000;

        alarm_b &= 0b01000000;

        if(alarm_a!=0 && alarm_a_on)
        {
            VsBeep((u_char)500, 1000);              //BeepBoop, beeps with (frequency, duration)
            VsSetVolume(0,0);
            puts("Volume on");
        }

        if(alarm_b!=0 && alarm_b_on)
        {
            VsBeep((u_char)1000, 1000);              //BeepBoop, beeps with (frequency, duration)
            VsSetVolume(0,0);
            puts("Volume on");
        }

        if(button_cooldown_counter >= 2)
        {
            button_cooldown = false;
            button_cooldown_counter = 0;
        }
    
        if(kb_button_is_pressed(KEY_ALT) && alarm_a!=0)
        {
            At45dbPageRead(2, &snooze_time, 2);
            X12RtcClearStatus(0b00100000);
            get_alarm_a(&snooze);
            snooze.tm_min+=snooze_time;
            set_alarm_a(&snooze);
        }
        
        if(!button_cooldown)
        {
            switch(kb_button_pressed())
            {
                case KEY_ESC:
                    puts("escape pressed");
                    if(VsGetVolume() != 0)
                    {
                        puts("volume on");
                        VsSetVolume(0, 0);
                    }
                    else if(VsGetVolume() == 0)  
                    {
                        puts("volume off");
                        VsSetVolume(100, 100);
                    } 
                    if(alarm_a != 0)
                    {
                        X12RtcClearStatus(0b00100000);
                        At45dbPageRead(3, &alarm_a_backup, sizeof(tm));
                        set_alarm_a(&alarm_a_backup);
                    }
                    if(alarm_b != 0)
                    {
                        X12RtcClearStatus(0b01000000);
                        disable_alarm_b();
                        alarm_b_on = false;
                    }
                    break;

                case KEY_01:
                    alarm_a_on = !alarm_a_on;
                    alarmstatus_changed = true;
                    break;

                case KEY_02:
                    alarm_b_on = !alarm_b_on;
                    alarmstatus_changed = true;
                    break;

                default:
                    break;
            }
            button_cooldown = true;
        }
        if(button_cooldown)
                button_cooldown_counter++; 
        NutSleep(100);
    }
}
void playTone(int tone, int time)
{
	VsBeepStart(tone);
	NutSleep(10);
}