Beispiel #1
0
// ============================================================================================
// KEY INPUT PROCESS
// ============================================================================================
void key_input()
{
	char input_char = 0;
	
	if (usart.available()) input_char = usart.get();
	
	if(input_char == 0x1b) xboot_reset(); //reboot the board

	if(input_char == 'Z')	//Reboot whole system
	{
		send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "Z");
		temp_time = jiffies + 3000;
		while(jiffies < temp_time)
		{
			LED_PORT.OUTTGL = LED_USR_1_PIN_bm; _delay_ms(100);
		}
		xboot_reset();
	}


    // print version number
	if(input_char == 'v')
		fprintf_P(&usart_stream, PSTR("build number = %ld\r\n"), (unsigned long) &__BUILD_NUMBER);

	if(input_char == 'd')
	{
		if(display) display = false;
		else		display = true;
	}

	if(input_char == 'r')	//set sec_counter as 0
	{
		send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "r");	
		sec_counter = 0;
	}

    
    // ============================================================================================
    /// updateRate commands 
    // ============================================================================================

	// Hold Current Servo Position
    if(input_char == 'n'){
        fprintf_P(&usart_stream, PSTR("setting updateRate to NONE\n"));
        updateRate = NONE;
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "n");
    }
    if(input_char == 's'){
        fprintf_P(&usart_stream, PSTR("setting updateRate to 10ms\n"));
        updateRate = SMOOTH;
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "s");	
    }
    if(input_char == 'h'){
        fprintf_P(&usart_stream, PSTR("setting updateRate to 200ms\n"));
        updateRate = TWO_HUNDRED;
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "h");	
    }
    
    // ============================================================================================
    /// currentMode commands
    // ============================================================================================
    if(input_char == 'p'){
        fprintf_P(&usart_stream, PSTR("'p' - etting currentMode to PERIODIC\n"));
        currentMode = PERIODIC;
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "p");
    }
    if(input_char == 'V'){
        fprintf_P(&usart_stream, PSTR("'V' - setting currentMode to AVERAGE\n"));
        currentMode = AVERAGE;
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "V");
    }
    if(input_char == 'w'){
        fprintf_P(&usart_stream, PSTR("'w' - setting currentMode to SWEEP\n"));
        currentMode = SWEEP;
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "w");
    }
    
    if(input_char == 'c'){
        cycleOn = !cycleOn;
        fprintf_P(&usart_stream, PSTR("'c' - cycle all modes\n"));
        send_message(MESSAGE_COMMAND, ALL_DIRECTION, ALL, "c");

    }
    
    // ============================================================================================
    /// toggle debug print
    // ============================================================================================
    if(input_char == 'P'){
        fprintf_P(&usart_stream, PSTR("'P' - toggling debug printf on/off \n"));
        debugPrint = !debugPrint;
    }
    if(input_char == 'c'){
        printKeyCommands();
    }

}
Beispiel #2
0
// ============================================================================================
// MAIN FUNCTION
// ============================================================================================
int main(void)
{      
	char input_char;	
	int end_time;
	
	_delay_ms(50);
       
    init();

    xgrid.rx_pkt = &rx_pkt;

    LED_PORT.OUT = LED_USR_0_PIN_bm;
	fprintf_P(&usart_stream, PSTR("avr-xgrid build %ld\r\n"), (unsigned long) &__BUILD_NUMBER);

	swarm_initialization1();
	// ##### Initialization of swarm dynamics #####
	//switch(program_num){
	//	case 1: swarm_initialization1(); break;
	//	case 2: swarm_initialization2(); break;
	//	case 3: swarm_initialization3(); break;
	//}
	// ############################################

	while (1){		

		//end_time = jiffies + 200;

		if (usart.available()) input_char = usart.get();
							
		// main loop
		if (input_char == 0x1b) xboot_reset();

		else if(input_char != 0x00){
			fprintf_P(&usart_stream, PSTR("CPU: %c\r\n"), input_char);
			external_command(input_char);
			input_char = 0x00;	// clear the most recent computer input
		}

		if(communication_on){
			communication();		// send position data to neighbors
			communication_on = false;
		}

		if(calculation_on){
			swarm_calculation1();
			calculation_on = false;
		}

		//LED_PORT.OUTTGL = LED_USR_1_PIN_bm;		// toggle yellow LED
		// ##### Processing for swarm dynamics #####
		//switch(program_num){	// select program
		//	case 1: swarm_calculation1(); break;	// Ken's swarm dynamics
		//	case 2: swarm_calculation2(); break;	// two rythms
		//	case 3: swarm_calculation3(); break;	// Van der Pol Oscillator
		//	default: no_movement();
		//}
		// #########################################

		if(servo_motor_on){
			servo_motor_control();	// servo control
			servo_motor_on = false;
		}

		//if(jiffies>end_time){
		//	LED_PORT.OUT = LED_USR_1_PIN_bm;		// turn on yellow LED
		//}
		
		//while(jiffies<end_time);

		//if(jiffies>60000) jiffies = 0;	//reset jiffies in every 60 sec
	}
	return 0;
}
/*
 * \return 0 on success or 2 in case of an I/O error.
 */
static int NutChatSendString(int fd, char *str)
{
    int rc = 0;
    u_char eol = 1;
    u_char 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;
}
Beispiel #4
0
void pan1322::SetDiscoverable(bool discoverable)
{
	fprintf_P(bt_pan1322_out, PSTR("AT+JDIS=%i\r\n"), (discoverable) ? 3 : 0);
	this->WaitForOK();
}
Beispiel #5
0
void pan1322::StreamTail()
{
	fprintf_P(bt_pan1322_out, PSTR("\r\n"));
	this->usart->FlushTxBuffer();
}
Beispiel #6
0
static stat_t _dispatch()
{
	uint8_t status;

	// read input line or return if not a completed line
	// xio_gets() is a non-blocking workalike of fgets()
	while (true) {
		if ((status = xio_gets(tg.primary_src, tg.in_buf, sizeof(tg.in_buf))) == STAT_OK) {
			tg.bufp = tg.in_buf;
			break;
		}
		// handle end-of-file from file devices
		if (status == STAT_EOF) {					// EOF can come from file devices only
			if (cfg.comm_mode == TEXT_MODE) {
				fprintf_P(stderr, PSTR("End of command file\n"));
			} else {
				rpt_exception(STAT_EOF, 0);		// not really an exception
			}
			tg_reset_source();					// reset to default source
		}
		return (status);						// Note: STAT_EAGAIN, errors, etc. will drop through
	}
	tg.linelen = strlen(tg.in_buf)+1;					// linelen only tracks primary input
	strncpy(tg.saved_buf, tg.bufp, SAVED_BUFFER_LEN-1);	// save input buffer for reporting

	// dispatch the new text line
	switch (toupper(*tg.bufp)) {				// first char

//		case '!': { cm_request_feedhold(); break; }		// include for diagnostics
//		case '@': { cm_request_queue_flush(); break; }
//		case '~': { cm_request_cycle_start(); break; }

		case NUL: { 							// blank line (just a CR)
			if (cfg.comm_mode != JSON_MODE) {
				tg_text_response(STAT_OK, tg.saved_buf);
			}
			break;
		}
		case 'H': { 							// intercept help screens
			cfg.comm_mode = TEXT_MODE;
			print_general_help();
			tg_text_response(STAT_OK, tg.bufp);
			break;
		}
		case '$': case '?':{ 					// text-mode configs
			cfg.comm_mode = TEXT_MODE;
			tg_text_response(cfg_text_parser(tg.bufp), tg.saved_buf);
			break;
		}
		case '{': { 							// JSON input
			cfg.comm_mode = JSON_MODE;
			js_json_parser(tg.bufp);
			break;
		}
		default: {								// anything else must be Gcode
			if (cfg.comm_mode == JSON_MODE) {
				strncpy(tg.out_buf, tg.bufp, INPUT_BUFFER_LEN -8);	// use out_buf as temp
				sprintf(tg.bufp,"{\"gc\":\"%s\"}\n", tg.out_buf);
				js_json_parser(tg.bufp);
			} else {
				tg_text_response(gc_gcode_parser(tg.bufp), tg.saved_buf);
			}
		}
	}
	return (STAT_OK);
}
Beispiel #7
0
void print_adc_calibration() {
	fprintf_P(stderr,PSTR("\n[debug] ADC OFFSETS: "));
	for (uint8_t chan=0;chan<CHANNEL_AMT;chan++) 
		fprintf(stderr," [ %d : %d ] ", chan, adc_offset[chan]);
}
Beispiel #8
0
void cmd_err(void) { fprintf_P(&debug, PSTR("Command error\r\n")); }
Beispiel #9
0
void check_debug_uart(void) {
	static uint8_t inputbuf[RX_LINE_SIZE], inputptr = 0;
	uint8_t i, recv;
	int16_t ticks;
	
	while(uart_available(DEBUG)) {
		recv = uart_get(DEBUG);
		
		if(recv == '\r') {
			fprintf(&debug, "\r\n");
			
			if(inputptr) {
				switch(inputbuf[0]) {
					case '?': // print drive command list
					fprintf_P(&debug, PSTR("stop() ........................ | p00\r\n"));
					fprintf_P(&debug, PSTR("fwd_both(speed) ............... | p0300, p0400, p15 u8\r\n"));
					fprintf_P(&debug, PSTR("rev_both(speed) ............... | p0301, p0401, p15 u8\r\n"));
					fprintf_P(&debug, PSTR("forward(Lspeed, Rspeed) ....... | p0300, p0400, p11 u8, p12 u8\r\n"));
					fprintf_P(&debug, PSTR("reverse(Lspeed, Rspeed) ....... | p0301, p0401, p11 u8, p12 u8\r\n"));
					fprintf_P(&debug, PSTR("turnCCW(Lspeed, Rspeed) ....... | p0301, p0400, p11 u8, p12 u8\r\n"));
					fprintf_P(&debug, PSTR("turnCW (Lspeed, Rspeed) ....... | p0300, p0401, p11 u8, p12 u8\r\n"));
					fprintf_P(&debug, PSTR("set_abs_pos(pos) .............. | p1a s16\r\n"));
					fprintf_P(&debug, PSTR("set_rel_pos(sect, pos) ........ | p1b u8 u8\r\n"));
					fprintf_P(&debug, PSTR("pos_corr_on() ................. | p1f01\r\n"));
					fprintf_P(&debug, PSTR("pos_corr_off() ................ | p1f00\r\n"));
					fprintf_P(&debug, PSTR("nav_abs_pos(speed, pos) ....... | p31 u8 s16\r\n"));
					fprintf_P(&debug, PSTR("nav_rel_pos(speed, sect, pos) . | p32 u8 u8 u8\r\n"));
					break;
					
					case 'p': // passthrough to DRIVE MCU
					for(i = 1; i < inputptr; i++) { uart_put(DRIVE, inputbuf[i]); }
					uart_put(DRIVE, '\r');
					break;
					
					case 'r': // toggle reverse passthrough from DRIVE MCU
					rev_passthru ^= 1;
					break;
					
					case 'd': // local dump on/off
					local_dump ^= 1;
					break;
					
					case 's': // start/stop main thread
					run_main ^= 1;
					if(run_main) { fprintf_P(&debug, PSTR("Main thread started!\r\n")); }
					else         { fprintf_P(&debug, PSTR("Main thread stopped!\r\n")); stop(); }
					break;
					
					case 't': // start/stop test thread
					if(inputptr != 2) { cmd_err(); break; }
					run_test = htoa(0, inputbuf[1]);
					if(!run_test) { fprintf_P(&debug, PSTR("All test sequences stopped!\r\n")); stop(); }
					else { fprintf_P(&debug, PSTR("Started test sequence %u!\r\n"), run_test); }
					break;
					
					case ' ': // stop all motors
					run_main = 0;
					run_test = 0;
					pid_on = 0;
					stop();
					set_speed_3(0);
					set_speed_4(0);
					break;
					
					case 'u':
					fprintf_P(&debug, PSTR("%lu\r\n"), uptime());
					break;
					
					case 'b':
					#define VBAT_FACTOR 0.0044336
					fprintf_P(&debug, PSTR("4 x %1.2fV\r\n"), (float)read_adc(VSENS) * VBAT_FACTOR);
					break;
                    
					case 'm': // servo power
					if(inputptr != 2 || (inputbuf[1] & ~1) != '0') { cmd_err(); break; }
					inputbuf[1] == '0' ? clr_bit(SPWR) : set_bit(SPWR);
					break;
					
					case '9': // magnets
					if(inputptr != 2 || (inputbuf[1] & ~1) != '0') { cmd_err(); break; }
					if(inputbuf[1] == '0') { clr_bit(FET1); clr_bit(FET2); fprintf_P(&debug, PSTR("Magnets off!\r\n")); }
					else                   { set_bit(FET1); set_bit(FET2); fprintf_P(&debug, PSTR("Magnets on!\r\n"));  }
					break;
					
					case '1': // PID on/off
					if(inputptr != 2 || (inputbuf[1] & ~1) != '0') { cmd_err(); break; }
					if(inputbuf[1] == '0') { pid_on = 0; fprintf_P(&debug, PSTR("PID off!\r\n")); }
					else                   { pid_on = 1; fprintf_P(&debug, PSTR("PID on!\r\n")); reset_pid(); }
					break;
					
					case '3': // turn motor commands
					if(!isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					switch(inputbuf[1]) {
						case '0': // forward (uint8_t speed)
						if(inputptr != 4) { cmd_err(); break; }
						motor3_fwd();
						set_speed_3(htoa(inputbuf[2], inputbuf[3]) * 40);
						break;
						
						case '1': // reverse (uint8_t speed)
						if(inputptr != 4) { cmd_err(); break; }
						motor3_rev();
						set_speed_3(htoa(inputbuf[2], inputbuf[3]) * 40);
						break;
						
						case '2': // set reference target (int16_t ticks)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						pid_target[MOTOR3] = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '3': // set reference speed (int16_t ticks)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						pid_speed[MOTOR3] = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '4': // set P (int16_t factor)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ENC3_P = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '5': // set I (int16_t factor)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ENC3_I = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '6': // set D (int16_t factor)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ENC3_D = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '7': // set noise gate (int16_t level)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ENC3_NOISE_GATE = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case 'f': // set reference angle
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						ticks = deg2ticks(htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]));
						cli();
						V_encoder = ticks;
						sei();
						reset_pid();
						break;
						
						default:
						cmd_err();
					}
					break;
					
					case '4': // lift motor commands
					if(!isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					switch(inputbuf[1]) {
						case '0': // up (uint8_t speed)
						if(inputptr != 4) { cmd_err(); break; }
						motor4_fwd();
						set_speed_4(htoa(inputbuf[2], inputbuf[3]) * 40);
						break;
						
						case '1': // down (uint8_t speed)
						if(inputptr != 4) { cmd_err(); break; }
						motor4_rev();
						set_speed_4(htoa(inputbuf[2], inputbuf[3]) * 40);
						break;
						
						case '2': // set reference target (int16_t ticks)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						pid_target[MOTOR4] = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '3': // set reference speed (int16_t ticks)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						pid_speed[MOTOR4] = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '4': // set P (int16_t factor)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ACTU_P = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '5': // set I (int16_t factor)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ACTU_I = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '6': // set D (int16_t factor)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ACTU_D = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						case '7': // set noise gate (int16_t level)
						if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
						//ACTU_NOISE_GATE = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
						break;
						
						default:
						cmd_err();
					}
					break;
					
					case '5': // servo5 commands
					if(inputptr != 4 || !isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					servo5(htoa(inputbuf[2], inputbuf[3]));
					//OCR0A = htoa(inputbuf[1], inputbuf[2]);
					break;
					
					case '6': // servo6 commands
					if(inputptr != 4 || !isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					servo6(htoa(inputbuf[2], inputbuf[3]));
					//OCR0B = htoa(inputbuf[1], inputbuf[2]);
					break;
					
					case '7': // servo7 commands
					if(inputptr != 4 || !isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					servo7(htoa(inputbuf[2], inputbuf[3]));
					//OCR2A = htoa(inputbuf[1], inputbuf[2]);
					break;
					
					case '8': // servo8 commands
					if(inputptr != 4 || !isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					servo8(htoa(inputbuf[2], inputbuf[3]));
					//OCR2B = htoa(inputbuf[1], inputbuf[2]);
					break;
					
					case 'x':
					if(!isHex(inputbuf[2]) || !isHex(inputbuf[3])) { cmd_err(); break; }
					switch(inputbuf[1]) {					
						case '1': // set reference angle
							if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
							param1 = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
							break;
						case '2': // set reference angle
							if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
							param2 = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
							break;
						case '3': // set reference angle
							if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
							param3 = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
							break;
						case '4': // set reference angle
							if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
							param4 = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
							break;
						case '5': // set reference angle
							if(inputptr != 6 || !isHex(inputbuf[4]) || !isHex(inputbuf[5])) { cmd_err(); break; }
							param5 = htoa(inputbuf[2], inputbuf[3]) << 8 | htoa(inputbuf[4], inputbuf[5]);
							break;
					}
					break;
					
					default:
					cmd_err();
				}
				
				inputptr = 0;
			}
		}
		else if(recv == 0x7f) {
			if(!inputptr) { uart_put(DEBUG, '\a'); }
			else {
				fprintf(&debug, "\b\e[K");
				inputptr--;
			}
		}
		else {
			if(inputptr == RX_LINE_SIZE) { uart_put(DEBUG, '\a'); }
			else {
				uart_put(DEBUG, recv);
				inputbuf[inputptr] = recv;
				inputptr++;
			}
		}
	}
static void put_addr_row( FILE * stream, char *n1, char *n2, uint32_t addr )
{
    static prog_char tfmt[] = "<TR><TD>&nbsp;%s&nbsp;</TD><TD>&nbsp;%s&nbsp;</TD><TD>&nbsp;%s&nbsp;</TD></TR>\r\n";
    if( n1 == 0 ) n1 = "IP Address";
    fprintf_P( stream, tfmt, n1, n2, inet_ntoa(addr) );
}
int CgiNetIO( FILE * stream, REQUEST * req )
{
    char *name = 0;
    char *value = 0;

    char tmp[100] = "";

    if (req->req_query)
    {
        char *pname;
        char *pvalue;
        int i;
        int count;

        strncpy( tmp, req->req_query, sizeof(tmp)-1 );

        count = NutHttpGetParameterCount(req);
        /* Extract count parameters. */
        for (i = 0; i < count; i++)
        {
            pname = NutHttpGetParameterName(req, i);
            pvalue = NutHttpGetParameterValue(req, i);

            /* Send the parameters back to the client. */
//            fprintf_P(stream, PSTR("%s: %s<BR>\r\n"), pname, pvalue);

            if( 0 == strcmp( pname, "name" ) )		name = pvalue;
            if( 0 == strcmp( pname, "item" ) )		name = pvalue;
            if( 0 == strcmp( pname, "val" ) )		value = pvalue;
            if( 0 == strcmp( pname, "value" ) )		value = pvalue;
        }
    }


    if( name == 0 )
    {
        //httpSendString( stream, "Error: must be 'name' and, possibly, 'value' parameters" );
//    errmsg:
        //NutHttpSendHeaderTop(stream, req, 500, "Must have ?name= or ?name=&value=, name: adc{0-7}, dig{0-63}, temp{0-7}");
        web_header_200(stream, req);
        static prog_char h1[] = "<HTML><body> Must have ?name= or ?name=&value=, name: adc{0-7}, temp{0-7}, q='%s' </body></HTML>";
        fprintf_P( stream, h1, tmp );
        return 0;
    }

    if( value )
    {
        // Write
        int rc = setNamedParameter( name, value );

        if( rc )
        {
            web_header_200(stream, req);
            static prog_char h1[] = "<HTML><body>set %s rc=%d</body></HTML>";
            fprintf_P(stream, h1, name, rc );
            return 0;
        }

        httpSendString( stream, req, "Ok" );
        notice_activity();
    }
    else
    {
        char *data = getNamedParameter( name );
        if( data == 0 )
        {
            //        goto errmsg;
            web_header_200(stream, req);
            static prog_char h1[] = "<HTML><body>no data for %s</body></HTML>";
            fprintf_P(stream, h1, name );
            return 0;
        }

        httpSendString( stream, req, data );
        notice_activity();
    }
    return 0;
}
Beispiel #12
0
int main(void)
{
        //char old_btn = 0;
        //char btn;
        uint32_t j = 0;
        
		char input_char, first_char;
		
        _delay_ms(50);
        
        init();
        
        xgrid.rx_pkt = &rx_pkt;
        
        LED_PORT.OUT = LED_USR_0_PIN_bm;
        
        fprintf_P(&usart_stream, PSTR("avr-xgrid build %ld\r\n"), (unsigned long) &__BUILD_NUMBER);
        
		/*
		char str[] = "boot up";
		Xgrid::Packet pkt;
		pkt.type = 0;
		pkt.flags = 0;
		pkt.radius = 1;
		pkt.data = (uint8_t *)str;
		pkt.data_len = 4;
                        
		xgrid.send_packet(&pkt);
		*/
		
		if (usart.available())
		{
			first_char = usart.get();
		}	
		
        while (1)
        {
                if (usart.available())
				{
					input_char = usart.get();
				}	
							
				// main loop
                if (input_char == 0x1b)
                        xboot_reset();
						
				else if(input_char == 0x00)
				{
					//fprintf_P(&usart_stream, PSTR("received: first char (%i)**\r\n"),first_char);
					
				}
				
				else
				{
					fprintf_P(&usart_stream, PSTR("CPU: %c**\r\n"), input_char);
					
					if (input_char == 'a')
					{
						char str[] = "A";
                        Xgrid::Packet pkt;		// Packet is defined onl line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 4;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if(input_char == 'y')
					{
						LED_PORT.OUTTGL = LED_USR_1_PIN_bm;
					}
					
					else if (input_char == '1')
					{
						char str[] = "1";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 1;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '2')
					{
						char str[] = "22";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 2;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '3')
					{
						char str[] = "333";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 3;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '4')
					{
						char str[] = "4444";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 4;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '5')
					{
						char str[] = "55555";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 5;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '6')
					{
						char str[] = "666666";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 6;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '7')
					{
						char str[] = "7777777";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 7;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '8')
					{
						char str[] = "88888888";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 8;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '9')
					{
						char str[] = "999999999";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 9;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '0')
					{
						char str[] = "1010101010";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 10;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '-')
					{
						char str[] = "11111111111";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 11;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '=')
					{
						char str[] = "121212121212";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 12;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == '[')
					{
						char str[] = "1313131313131";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 13;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if (input_char == ']')
					{
						char str[] = "14141414141414";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 14;
                        
                        xgrid.send_packet(&pkt);
					}
					
					
					
					input_char = 0x00;	
				}
				
				j = jiffies + 10;
				               
                while (j > jiffies) { };
        }  
}
Beispiel #13
0
enum pop_process_result pop_process(void) {
	enum popstate psn = ps;
	enum pop_process_result result = pp_continue;
	enum popreply preply;
	char * line = NULL;

	if (ps == pstart) {
		mail_using_modem = true;
		uart0_flush();
		wifi_connectgpio();
		// 10 seconden timeout voor het leggen van de verbinding
		ptrycounter = 10;
		psn = pconnectioninitiated;
	} else if (ps == pconnectioninitiated) {
		// verbonden?
		if (wifi_isconnectedgpio()) {
			psn = pconnected;
		} else {
			if (ptrycounter == 0) {
				psn = pfinished;
				fprintf_P(pcout, PSTR("P connection failed\r\n"));
				result = pp_connectionfailed;
			}
		}
	} else if (ps == pconnected) {
		// Verbonden!, login sturen
		if (uart0_havenewline()) {
			line = uart0_readline();
			preply = pop_read_reply(line);
			if (preply == pok) {
				printf_P(PSTR("USER %s\r\n"), currentsettings.username);
				psn = ploginsent;
			} else if (preply == perr) {
				fprintf_P(pcout, PSTR("P Connect error %s\r\n"), line);
				psn = pfinished;
			}
		}
	} else if (ps == ploginsent) {
		if(uart0_havenewline()) {
			line = uart0_readline();
			fprintf_P(pcout, PSTR("L %s\r\n"),line);
			preply = pop_read_reply(line);
			if (preply == pok) {
				fprintf_P(pcout, PSTR("P login ok\r\n"));
				psn = ploginok;
			} else if (preply == perr) {
				fprintf_P(pcout, PSTR("P error sending username %s\r\n"),line);
				psn = ploginerr;
			}
		}
	} else if (ps == ploginerr) {
		psn = pfinished;
	} else if (ps == ploginok) {
		printf_P(PSTR("PASS %s\r\n"), currentsettings.password);
		psn = ppassent;
	} else if (ps == ppassent) {
		if(uart0_havenewline()) {
			line = uart0_readline();
			fprintf_P(pcout, PSTR("L %s\r\n"),line);
			preply = pop_read_reply(line);
			if (preply == pok) {
				psn = ppassok;
			} else if (preply == perr) {
				fprintf_P(pcout, PSTR("P error sending password %s\r\n"),line);
				psn = ppasserr;
			}
		}
	} else if (ps == ppasserr) {
		psn = pfinished;
	} else if (ps == ppassok) {
		psn = ploggedin;
	} else if (ps == ploggedin) {
		printf_P(PSTR("STAT\r\n"));
		psn = pstatsent;
	} else if (ps == pstatsent) {
		if (uart0_havenewline()) {
			line = uart0_readline();
			fprintf_P(pcout, PSTR("L %s\r\n"),line);
			preply = pop_read_reply(line);
			if (preply == pok) {
				preply = pop_read_num_messages(line);
				if (pmailcount > MAXMESSAGES) {
					currentmailno = pmailcount;
					lastmsgtoreceive = pmailcount - MAXMESSAGES+1;;
					receivingpos = 0;
					psn = pquerymsgtop;
				} else if (pmailcount == 0){
					mails.fillcount = 0;
					psn = pquit;
				} else {
					currentmailno = pmailcount;
					lastmsgtoreceive = 1;
					receivingpos = 0;
					psn = pquerymsgtop;
				}
			} else if (preply == perr) {
				fprintf_P(pcout, PSTR("P error in STAT %d, %s\r\n"),preply,line);
				psn = pfinished;
			}
		}
	} else if (ps == pquerymsgtop) {
		printf_P(PSTR("TOP %lu 0\r\n"),currentmailno);
		psn = pmsgtopok;
	} else if (ps == pmsgtopok) {
		if (uart0_havenewline()) {
			line = uart0_readline();
			preply = pop_read_reply(line);
			if (preply == pok) {
				psn = preceivemsgtop;
				mails.m[receivingpos].sender[0] = '\0';
				mails.m[receivingpos].title[0] = '\0';
				mails.m[receivingpos].time[0] = '\0';
			} else if (preply == perr){
				fprintf_P(pcout, PSTR("P error in TOP %s\r\n"),line);
				psn = pfinished;
			}
		}
	} else if (ps == preceivemsgtop) {
		if (uart0_havenewline()) {
			line = uart0_readline();
			if (read_field(strFROMUCASE,line,mails.m[receivingpos].sender, MAXSENDERLENGHT)==ifound) {
				fprintf_P(pcout, PSTR("P read sender %s\r\n"),mails.m[receivingpos].sender);
			} else if (read_field(strSUBJECTUCASE,line,mails.m[receivingpos].title, MAXTITLELENGHT)==ifound) {
				fprintf_P(pcout, PSTR("P read subject %s\r\n"),mails.m[receivingpos].title);
			} else if (read_field(strDATEUCASE,line,mails.m[receivingpos].time, MAXTIMELENGHT)==ifound) {
				fprintf_P(pcout, PSTR("P read date %s\r\n"),mails.m[receivingpos].time);
			} else if (line[0] == '.') {
				// einde van de headers
				currentmailno--;
				receivingpos++;
				// klopt nog niet!!
				if (currentmailno >= lastmsgtoreceive) {
					psn = pquerymsgtop;
				} else {
					mails.fillcount=min(pmailcount,MAXMESSAGES);
					psn = pquit;
				}
			}
		}
	} else if (ps == pquit) {
		printf_P(PSTR("QUIT\r\n"));
		psn = pfinished;
	} else if (ps == pfinished) {
		wifi_disconnectgpio();
		mails.filling = false;
		mail_using_modem = false;
		result = pp_done;
		psn = pstart;
	}


	if (ps!=psn) {
		fprintf_P(pcout, PSTR("P State: %s %s\r\n"),popstateinfo[ps],popstateinfo[psn]);
		// max 30 sec in dezelfde state
		pcurrentstatecounter = 30;
	} else {
		if (pcurrentstatecounter == 0) {
			mails.filling = false;
			fprintf_P(pcout, PSTR("# fsm frozen\r\n"));
			wifi_disconnectgpio();
			result = pp_fsmfrozen;
			psn = pstart;
		}
	}
	ps = psn;
	return result;
}
Beispiel #14
0
/*----------------------------------------------*/
VOID event_loop( VOID )
{
	T_SYS_EVENT t_sys_event = E_EVENT_IDLE;
	T_SYS_EVENT_TBL *pt_sys_event_tbl;
	UINT ui_loopnum;

#ifdef CO_ENABLE_EVENT_TRACE_LOG
	Usart_Set_Stderr();
#endif

	while( 1 ) {
//#ifdef CO_ENABLE_EVENT_TRACE_LOG
//	fprintf_P( stderr, PSTR( "wait next event\n") );
//#endif

#ifdef CO_ENABLE_I2C_SLAVE_READ
	if( t_sys_event == E_EVENT_I2C_SLAVE_READ ) {
		i2c_slave_read_event_finish();
	}
#endif

#ifdef CO_SLEEP_ENABLE
		sleep_cpu();
#endif

		t_sys_event = get_event();

//#ifdef CO_ENABLE_EVENT_TRACE_LOG
//		fprintf_P( stderr, PSTR( "recv event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
//#endif

#ifdef CO_SLEEP_ENABLE
		// すべての割り込みハンドラ内でsleep_disable()を実施している。
		// そうすることで、ループ先頭のsleep_enable()~ループ終端のsleep()までの間に割り込みが
		// 発生してもsleep()しなくなる。
		// sleep()するのは、sleep_enable()~sleep()までの間に割り込みが一度も発生しない場合のみとなる。
		cli();
		sleep_enable();
		sei();
#endif

#ifdef CO_ENABLE_EVENT_TRACE_LOG
		if( t_sys_event != E_EVENT_IDLE ) {
			fprintf_P( stderr, PSTR( "begin event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
		}
#endif

		/* TODO:ステータスチェンジはgo_sys_stat()でやれば良い */
		pt_sys_event_tbl = NULL;
		for( ui_loopnum = 0; gt_sys_stat_tbl[ui_loopnum].pt_sys_event_tbl != NULL; ui_loopnum++ ) {
			if( gt_sys_stat_tbl[ui_loopnum].t_sys_stat == _gt_sys_stat ) {
				pt_sys_event_tbl = gt_sys_stat_tbl[ui_loopnum].pt_sys_event_tbl;
				break;
			}
		}
		if( pt_sys_event_tbl == NULL ) {
#ifdef CO_ENABLE_EVENT_TRACE_LOG
			fprintf_P( stderr, PSTR("unknown sys stat event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
#endif
			continue;
		}


		for( ui_loopnum = 0; pt_sys_event_tbl[ui_loopnum].fn_hdl != NULL; ui_loopnum++ ) {
			if( pt_sys_event_tbl[ui_loopnum].t_sys_event == t_sys_event ) {
#ifdef CO_ENABLE_EVENT_TRACE_LOG
				int i_ret = pt_sys_event_tbl[ui_loopnum].fn_hdl();
				if( i_ret != 0 ) {
					fprintf_P( stderr, PSTR("event handler error returned, ret=%d\n"), i_ret );
				}
#else
				(VOID)pt_sys_event_tbl[ui_loopnum].fn_hdl();
#endif
				break;
			}
		}
		if( pt_sys_event_tbl[ui_loopnum].fn_hdl == NULL ) {
#ifdef CO_ENABLE_EVENT_TRACE_LOG
			fprintf_P( stderr, PSTR("unknown sys event event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
#endif
			continue;
		}


#ifdef CO_ENABLE_EVENT_TRACE_LOG
		if( t_sys_event != E_EVENT_IDLE ) {
			fprintf_P( stderr, PSTR("return event loop stat=%u\n\n"), _gt_sys_stat );
		}
#endif
	}
}
Beispiel #15
0
stat_t _command_dispatch()
{
#ifdef __AVR
	stat_t status;

	// read input line or return if not a completed line
	// xio_gets() is a non-blocking workalike of fgets()
	while (true) {
		if ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {
			cs.bufp = cs.in_buf;
			break;
		}
		// handle end-of-file from file devices
		if (status == STAT_EOF) {						// EOF can come from file devices only
			if (cfg.comm_mode == TEXT_MODE) {
				fprintf_P(stderr, PSTR("End of command file\n"));
			} else {
				rpt_exception(STAT_EOF);				// not really an exception
			}
			tg_reset_source();							// reset to default source
		}
		return (status);								// Note: STAT_EAGAIN, errors, etc. will drop through
	}
#endif // __AVR
#ifdef __ARM
	// detect USB connection and transition to disconnected state if it disconnected
	if (SerialUSB.isConnected() == false) cs.state = CONTROLLER_NOT_CONNECTED;

	// read input line and return if not a completed line
	if (cs.state == CONTROLLER_READY) {
		if (read_line(cs.in_buf, &cs.read_index, sizeof(cs.in_buf)) != STAT_OK) {
			cs.bufp = cs.in_buf;
			return (STAT_OK);	// This is an exception: returns OK for anything NOT OK, so the idler always runs
		}
	} else if (cs.state == CONTROLLER_NOT_CONNECTED) {
		if (SerialUSB.isConnected() == false) return (STAT_OK);
		cm_request_queue_flush();
		rpt_print_system_ready_message();
		cs.state = CONTROLLER_STARTUP;

	} else if (cs.state == CONTROLLER_STARTUP) {		// run startup code
		cs.state = CONTROLLER_READY;

	} else {
		return (STAT_OK);
	}
	cs.read_index = 0;
#endif // __ARM
#ifdef __RX
	stat_t status;
	parse_gcode_func_selection(CODE_PARSER);
	// read input line or return if not a completed line
	// xio_gets() is a non-blocking workalike of fgets()
	while (true) {
		if ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {
			cs.bufp = cs.in_buf;
			break;
		}
		// handle end-of-file from file devices
		if (status == STAT_EOF) {						// EOF can come from file devices only
			//gfilerunning = false;
			xio_close(cs.primary_src);
//			macro_func_ptr = command_idle;
			if (cfg.comm_mode == TEXT_MODE) {
				fprintf_P(stderr, PSTR("End of command file\n"));
			} else {
				rpt_exception(STAT_EOF);				// not really an exception
			}
			tg_reset_source();							// reset to default source
		}
		return (status);								// Note: STAT_EAGAIN, errors, etc. will drop through
	}
#endif // __AVR
	// set up the buffers
	cs.linelen = strlen(cs.in_buf)+1;					// linelen only tracks primary input
	strncpy(cs.saved_buf, cs.bufp, SAVED_BUFFER_LEN-1);	// save input buffer for reporting

	// dispatch the new text line
	switch (toupper(*cs.bufp)) {						// first char

		case '!': { cm_request_feedhold(); break; }		// include for AVR diagnostics and ARM serial
		case '%': { cm_request_queue_flush(); break; }
		case '~': { cm_request_cycle_start(); break; }

		case NUL: { 									// blank line (just a CR)
			if (cfg.comm_mode != JSON_MODE) {
				text_response(STAT_OK, cs.saved_buf);
			}
			break;
		}
		case '$': case '?': case 'H': { 				// text mode input
			cfg.comm_mode = TEXT_MODE;
			text_response(text_parser(cs.bufp), cs.saved_buf);
			break;
		}
		case '{': { 									// JSON input
			cfg.comm_mode = JSON_MODE;
			json_parser(cs.bufp);
			break;
		}
		default: {										// anything else must be Gcode
			if (cfg.comm_mode == JSON_MODE) {			// run it as JSON...
				strncpy(cs.out_buf, cs.bufp, INPUT_BUFFER_LEN -8);					// use out_buf as temp
				sprintf((char *)cs.bufp,"{\"gc\":\"%s\"}\n", (char *)cs.out_buf);	// '-8' is used for JSON chars
				json_parser(cs.bufp);
			} else {									//...or run it as text
				text_response(gc_gcode_parser(cs.bufp), cs.saved_buf);
			}
		}
	}
	return (STAT_OK);
}
Beispiel #16
0
void gui_dialog_loop()
{
	if (gui_dialog_style & GUI_STYLE_NO_TITLE)
	{
		//no title mode (GUI_STYLE_NO_TITLE is set)
		disp.DrawRectangle(0, 0, GUI_DISP_WIDTH - 2, GUI_DISP_HEIGHT - 2, 1, false);
	}
	else
	{
		//normal mode
		gui_dialog(gui_dialog_msg_line0);
	}

	disp.LoadFont(F_TEXT_M);
	uint8_t f_h = disp.GetTextHeight();

	if ((gui_dialog_style & GUI_STYLE_MASK) == GUI_STYLE_STATS)
	{
		//if new flight has begin exit the stat screen
		if (fc.flight.state != FLIGHT_LAND)
		{
			gui_dialog_cb(1);
		}

		uint32_t diff = fc.flight.timer / 1000;
		uint8_t hour, min;

		hour = diff / 3600;
		diff %= 3600;

		min = diff / 60;
		diff %= 60;

		char tmp[32];

		disp.GotoXY(GUI_DIALOG_LEFT, GUI_DIALOG_TOP + f_h * 0);
		if (hour > 0)
			fprintf_P(lcd_out, PSTR("%02d:%02d"), hour, min);
		else
			fprintf_P(lcd_out, PSTR("%02d.%02d"), min, diff);

		strcpy_P(tmp, PSTR("Alt"));
		gui_raligh_text(tmp, (GUI_DIALOG_WIDTH * 2) / 3 - 2, GUI_DIALOG_TOP + f_h * 0);
		strcpy_P(tmp, PSTR("Vario"));
		gui_raligh_text(tmp, GUI_DIALOG_RIGHT + 1, GUI_DIALOG_TOP + f_h * 0);

		sprintf_P(tmp, PSTR("%dm"), fc.flight.stats.max_alt);
		gui_raligh_text(tmp, (GUI_DIALOG_WIDTH * 2) / 3 - 2, GUI_DIALOG_TOP + f_h * 1);
		sprintf_P(tmp, PSTR("%dm"), fc.flight.stats.min_alt);
		gui_raligh_text(tmp, (GUI_DIALOG_WIDTH * 2) / 3 - 2, GUI_DIALOG_TOP + f_h * 2);

		sprintf_P(tmp, PSTR("%0.1fm"), (float)fc.flight.stats.max_climb / 100.0);
		gui_raligh_text(tmp, GUI_DIALOG_RIGHT + 1, GUI_DIALOG_TOP + f_h * 1);
		sprintf_P(tmp, PSTR("%0.1fm"), (float)fc.flight.stats.max_sink / 100.0);
		gui_raligh_text(tmp, GUI_DIALOG_RIGHT + 1, GUI_DIALOG_TOP + f_h * 2);

		disp.LoadFont(F_TEXT_S);
		disp.GotoXY(GUI_DIALOG_LEFT, GUI_DIALOG_TOP + f_h * 1 + 2);
		fprintf_P(lcd_out, PSTR("max"));
		disp.GotoXY(GUI_DIALOG_LEFT, GUI_DIALOG_TOP + f_h * 2 + 2);
		fprintf_P(lcd_out, PSTR("min"));
	}
	else
	{
		uint8_t top;

		if (gui_dialog_style & GUI_STYLE_NO_TITLE)
		{
			//no title mode (GUI_STYLE_NO_TITLE is set)
			top = 3;

			disp.GotoXY(GUI_DIALOG_LEFT, top + f_h * 0);
			fprintf_P(lcd_out, PSTR("%s"), gui_dialog_msg_line0);
		}
		else
		{
			//normal mode
			top = GUI_DIALOG_TOP - f_h;
		}

		disp.GotoXY(GUI_DIALOG_LEFT, top + f_h * 1);
		fprintf_P(lcd_out, PSTR("%s"), gui_dialog_msg_line1);

		disp.GotoXY(GUI_DIALOG_LEFT, top + f_h * 2);
		fprintf_P(lcd_out, PSTR("%s"), gui_dialog_msg_line2);

		disp.GotoXY(GUI_DIALOG_LEFT, top + f_h * 3);
		fprintf_P(lcd_out, PSTR("%s"), gui_dialog_msg_line3);
	}

	disp.LoadFont(F_TEXT_S);
	f_h = disp.GetAHeight();

	switch (gui_dialog_style & GUI_STYLE_MASK)
	{
		case(GUI_STYLE_OK):
		case(GUI_STYLE_STATS):
			gui_caligh_text_P(PSTR("OK"), GUI_DIALOG_LEFT + GUI_DIALOG_WIDTH / 2, GUI_DIALOG_BOTTOM - f_h);
		break;

		case(GUI_STYLE_OKCANCEL):
			gui_caligh_text_P(PSTR("OK"), GUI_DIALOG_LEFT + GUI_DIALOG_WIDTH / 2, GUI_DIALOG_BOTTOM - f_h);
			gui_raligh_text_P(PSTR("Cancel"), GUI_DIALOG_RIGHT - 1, GUI_DIALOG_BOTTOM - f_h);
		break;

		case(GUI_STYLE_YESNO):
			gui_caligh_text_P(PSTR("Yes"), GUI_DIALOG_LEFT + GUI_DIALOG_WIDTH / 2, GUI_DIALOG_BOTTOM - f_h);
			gui_raligh_text_P(PSTR("No"), GUI_DIALOG_RIGHT - 1, GUI_DIALOG_BOTTOM - f_h);
		break;

		case(GUI_STYLE_TIMESET):
			gui_caligh_text_P(PSTR("GPS"), GUI_DIALOG_LEFT + GUI_DIALOG_WIDTH / 2, GUI_DIALOG_BOTTOM - f_h);
			gui_raligh_text_P(PSTR("Manual"), GUI_DIALOG_RIGHT - 1, GUI_DIALOG_BOTTOM - f_h);
		break;

		case(GUI_STYLE_FORMAT):
			gui_caligh_text_P(PSTR("No"), GUI_DIALOG_LEFT + GUI_DIALOG_WIDTH / 2, GUI_DIALOG_BOTTOM - f_h);
			gui_raligh_text_P(PSTR("Yes"), GUI_DIALOG_RIGHT - 1, GUI_DIALOG_BOTTOM - f_h);
		break;
	}
}
Beispiel #17
0
void gui_list_draw()
{
	char tmp_text[64];
	char tmp_sub_text[32];

	uint8_t flags;

	disp.LoadFont(F_TEXT_M);
	uint8_t t_h = disp.GetTextHeight();

	int16_t y = gui_list_y_offset;
	int8_t height;
	int16_t total_height = 0;
	uint8_t sub_height;

	//emulate middle click
	if (button_in_reset(B_MIDDLE))
	{
		if (task_get_ms_tick() - gui_list_middle_hold > BUTTON_LONG)
		{
			gui_switch_task(gui_list_back);
			if ((config.gui.menu_audio_flags & CFG_AUDIO_MENU_BUTTONS) && gui_buttons_override == false)
				seq_start(&snd_menu_exit, config.gui.menu_volume);
		}
	}
	else
		gui_list_middle_hold = task_get_ms_tick();

	for (uint8_t i = 0; i < gui_list_size; i++)
	{

		flags = 0;
		if (i < gui_list_size - 1)
		{
			gui_list_gen_f(i, tmp_text, &flags, tmp_sub_text);
		}
		else
		{
			strcpy_P(tmp_text, PSTR("back"));
			flags = GUI_LIST_BACK;
		}

		uint8_t x_val = 5;

		switch(flags & GUI_LIST_T_MASK)
		{
			case(GUI_LIST_FOLDER):
				x_val = 5;
			break;

			case(GUI_LIST_BACK):
				x_val = 2;
			break;

			case(GUI_LIST_TITLE):
				x_val = 1;
				disp.LoadFont(F_TEXT_S);
				t_h = disp.GetTextHeight();
			break;

		}

		height = 1 + t_h;

		if ((flags & GUI_LIST_T_MASK) == GUI_LIST_SUB_TEXT)
		{
			sub_height = disp.GetTextHeight();
			height += sub_height;
		}

		if (gui_list_index[gui_task] == i)
		{
			if (y < 0)
				gui_list_y_offset = -total_height;

			if (y > GUI_DISP_HEIGHT - height)
				gui_list_y_offset = -total_height + GUI_DISP_HEIGHT - height;
		}

		if (y > GUI_DISP_HEIGHT)
			continue;

		disp.GotoXY(x_val, y + 1);
		fprintf_P(lcd_out, PSTR("%s"), tmp_text);

		//sub text
		if ((flags & GUI_LIST_T_MASK) == GUI_LIST_SUB_TEXT)
			gui_raligh_text(tmp_sub_text, GUI_DISP_WIDTH - 3, y + t_h + 1);

		//tick
		if ((flags & GUI_LIST_T_MASK) == GUI_LIST_CHECK_OFF || (flags & GUI_LIST_T_MASK) == GUI_LIST_CHECK_ON)
		{
			disp.DrawRectangle(GUI_DISP_WIDTH - 9, y + 1, GUI_DISP_WIDTH - 3, y + 7, 1, 0);
			if ((flags & GUI_LIST_T_MASK) == GUI_LIST_CHECK_ON)
			{
				disp.DrawLine(GUI_DISP_WIDTH - 8, y + 5, GUI_DISP_WIDTH - 7, y + 6, 1);
				disp.DrawLine(GUI_DISP_WIDTH - 6, y + 5, GUI_DISP_WIDTH - 4, y + 3, 1);
			}
		}

		//disabled entry
		if (flags & GUI_LIST_DISABLED)
		{
			for (uint8_t cx = 0; cx < GUI_DISP_WIDTH - 1; cx++)
				for (uint8_t cy = y + cx % 2 + 1; cy < y + t_h; cy += 2)
					disp.PutPixel(cx, cy, 0);
		}

		//selector
		if (gui_list_index[gui_task] == i)
		{
			disp.Invert(0, y, GUI_DISP_WIDTH - 1, y + height - 1);
			disp.PutPixel(0, y, 0);
			disp.PutPixel(GUI_DISP_WIDTH - 1, y, 0);
			disp.PutPixel(GUI_DISP_WIDTH - 1, y + height - 1, 0);
			disp.PutPixel(0, y + height - 1, 0);
		}

		if ((flags & GUI_LIST_T_MASK) == GUI_LIST_TITLE)
		{
			//restore font
			disp.LoadFont(F_TEXT_M);
			t_h = disp.GetTextHeight();
		}

		y += height;
		total_height += height;
	}
}
Beispiel #18
0
// ============================================================================================
// switches between all the sensor modes
// if  behavior has been altered by sensor interaction returns true (except RATE)
// ============================================================================================
bool sensorBehavior(){
    bool updated = false;
    
    if (presMode != lastPresMode){
        if (presenceDetected && !ignorePresence){
            // smooth transition when changing presence modes
            fprintf_P(&usart_stream, PSTR("changePresMode\r\n"));
            startXFade(0.01);
        }
        
        switch(presMode){
            case POINT:
                presenceTimeOut = 6; // in seconds
                neighborPresenceTimeOut = presenceTimeOut;
                usingNeighborPresence = true;
                break;
        
            case RANDOM:
                presenceTimeOut = 8;
                neighborPresenceTimeOut = presenceTimeOut;
                usingNeighborPresence = false;
                break;
        
            case RATE:
                presenceTimeOut = 20;
                neighborPresenceTimeOut = presenceTimeOut;
                usingNeighborPresence = false;
                break;
        
            case SHAKE:
                presenceTimeOut = 8;
                neighborPresenceTimeOut = presenceTimeOut;
                usingNeighborPresence = false;
                break;
        
            case WAVE:
                presenceTimeOut = 4;
                neighborPresenceTimeOut = presenceTimeOut;
                usingNeighborPresence = true;
                break;
        
            case RHYTHM:
                presenceTimeOut = 40;
                neighborPresenceTimeOut = presenceTimeOut;
                usingNeighborPresence = false;
                break;
        }
    }
    
    // because for rate there is no change of angle just update rate so don't need to transition
    if(newPresence && presMode != RATE && presMode != IGNORE){
        fprintf_P(&usart_stream, PSTR("newPres\r\n"));
        startXFade(0.1);
    }
    
    if (newNeighborPresence && usingNeighborPresence){
        newNeighborPresence = false;
        switch(presMode){
            case POINT:
                fprintf_P(&usart_stream, PSTR("new neighbor\r\n"));
                if (neighborPresenceDetected)
                    startXFade(0.05);
                else
                    startXFade(0.01);
                break;
                
        }
    }
    
    switch(presMode)
    {
        case POINT:
            updated = point();
            break;
            
        case SHAKE:
            updated = presenceWave(false);
            break;
            
        case WAVE:
            updated = presenceWave(true);
            break;
            
        case RANDOM:
            updated = randomAngle();
            break;
            
        case RATE:
            updated = randomUpdateRate();
            break;
            
        case RHYTHM:
            updated = toFro();
            
        case IGNORE: // do nothing
            break;
    }
    
    return updated;
}
int main(void)
{
        //char old_btn = 0;
        //char btn;
        uint32_t j = 0;
        
		char input_char, first_char;
		
        _delay_ms(50);
        
        init();
        
        xgrid.rx_pkt = &rx_pkt;
        
        LED_PORT.OUT = LED_USR_0_PIN_bm;
        
        fprintf_P(&usart_stream, PSTR("avr-xgrid build %ld\r\n"), (unsigned long) &__BUILD_NUMBER);
        
		/*
		char str[] = "boot up";
		Xgrid::Packet pkt;
		pkt.type = 0;
		pkt.flags = 0;
		pkt.radius = 1;
		pkt.data = (uint8_t *)str;
		pkt.data_len = 4;
                        
		xgrid.send_packet(&pkt);
		*/
		
		// KEN'S CODE 
		
		swarm_initialization();
		
		int16_t servo_position_deg = 0;	// servo position in degrees
		
		// END KEN'S CODE
		
		if (usart.available())
		{
			first_char = usart.get();
		}	
		
        while (1)
        {
                j = jiffies + 10;	// from here, you have 10 ms to reach the bottom of this loop
				
				if (usart.available())
				{
					input_char = usart.get();
				}	
							
				// main loop
                if (input_char == 0x1b)
                        xboot_reset();
				
				else if(input_char != 0x00)
				{
					fprintf_P(&usart_stream, PSTR("CPU: %c**\r\n"), input_char);
					
					if (input_char == 'a')
					{
						char str[] = "A";
                        Xgrid::Packet pkt;		// Packet is defined on line 72 of xgrid.h
                        pkt.type = 0;
                        pkt.flags = 0;
                        pkt.radius = 1;
                        pkt.data = (uint8_t *)str;
                        pkt.data_len = 4;
                        
                        xgrid.send_packet(&pkt);
					}
					
					else if(input_char == 'y')
					{
						LED_PORT.OUTTGL = LED_USR_1_PIN_bm;
					}
					
					input_char = 0x00;	// clear the most recent computer input
				}
				
				// KEN'S CODE:
				
				//swarm_communication();
				//swarm_calculation();
				servo_motor_control();
				
		
                // END KEN'S CODE
				
				if(jiffies > j)	// if TRUE, then we took too long to get here, halt program
				{
					cli();	//disable_interrupts
					LED_PORT.OUTSET = LED_USR_0_PIN_bm;		// turn red light on and keep it on
					LED_PORT.OUTSET = LED_USR_1_PIN_bm;		// turn yellow light on and keep it on
					while(1==1)
					{};
				}					
				
                while (j > jiffies) { };
        }  
}
Beispiel #20
0
void wifi_request_ntp(uint32_t *time_val, Wifi_Error *error) {
  const int char_timeout_ms = 500;

  NTP_Packet packet = {0};
  packet.li_version_mode = (3 << 0) | (4 << 2) | (3 << 5);
  // TODO: More here...

  printf_P(PSTR("[WIFI] Sending NTP request...\n"));

  char cmd[64];
  sprintf_P(cmd, AT_CIPSTART_UDP, NTP_IP, NTP_PORT);
  wifi_repeat_until_ok(cmd);

  fprintf_P(serial_output, AT_CIPSEND, sizeof(NTP_Packet));
  print_response();

  while(serial_available()) fgetc(serial_input);

  const char *message_chars = (char*)&packet;
  for(int i = 0; i < sizeof(NTP_Packet); ++i) {
    fputc(message_chars[i], serial_output);
  }

  _delay_ms(1000);

  // "Received data" marker
  const char* marker = "\n+IPD,";
  int marker_pos = 1;

  // Wait for response
  while(marker_pos < strlen(marker)) {
    char c;
    if(!serial_getc_timeout(&c, char_timeout_ms)) {
      if(error != NULL) *error = Wifi_Error_Timeout;
      return;
    }
    if(c == marker[marker_pos]) {
      ++marker_pos;
    } else {
      marker_pos = 0;
    }
  }

  char response_len_str[16];

  for(int i = 0; true; ++i) {
    char c;
    if(!serial_getc_timeout(&c, char_timeout_ms)) {
      if(error != NULL) *error = Wifi_Error_Timeout;
      return;
    }
    if(c >= '0' && c <= '9') {
      response_len_str[i] = c;
    } else if(c == ':') {
      response_len_str[i] = '\0';
      break;
    } else {
      if(error != NULL) *error = Wifi_Error_Unknown;
      return;
    }
  }

  int response_len = atoi(response_len_str);

  if(response_len != sizeof(NTP_Packet)) {
    if(error != NULL) *error = Wifi_Error_Unknown;
    return;
  }

  char* packet_bytes = (char*)&packet;
  for(int i = 0; i < response_len; ++i) {
    char c;
    if(!serial_getc_timeout(&c, char_timeout_ms)) {
      if(error != NULL) *error = Wifi_Error_Timeout;
      return;
    }
    packet_bytes[i] = c;
  }

  while(serial_available()) fgetc(serial_input);

  // Will error if remote closed connection already, that's fine
  fprintf_P(serial_output, AT_CIPCLOSE);
  _delay_ms(100);
  print_response();

  // TODO: Use other data in some way
  *time_val = swap_endian(packet.transmit_time);
  //*time_val -= 3155673600ul; // Y2K time
  *time_val -= 0x83AA7E80; // Unix time

  if(error != NULL) *error = Wifi_Error_None;
}
Beispiel #21
0
void adc_calibrate_store() {
	fprintf_P(stderr,PSTR("\n[debug] Warning: unimplimented function adc_calibrate_store called"));
}
Beispiel #22
0
void ui_loop(void) {
	_ui_init_lcd();
	
	/*alarm_set(1000);*/
	
	char obd_buf[64];
	uint8_t obd_idx = 0;
	
	bool do_cmd = true;
	for ( ; ; ) {
		int c;
		
		/*bool do_cmd = false;
		ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
			if (timer0_count >= 1000) {
				do_cmd = true;
				timer0_count -= 1000;
			}
		}*/
		
		if (do_cmd) {
			// get throttle position
			fputs_P(PSTR("0111\n"), stn1110);
			obd_idx = 0;
			do_cmd = false;
		}
		
		/* repeatedly receive and transmit data until neither are available */
		bool got_data;
		do {
			got_data = false;
			
			/* tx */
			/*if (uart_avail(UART_PC) && (c = fgetc(stdin)) != EOF) {
				fputc(c, stn1110);
				
				if (!tx) {
					tx = true;
					rx = false;
					
					lcd_clear();
					lcd_goto_xy(0, 0);
					fputs_P(PSTR(">>\r\n>>\r\n<<\r\n<<"), lcd);
					lcd_goto_xy(3, 0);
				}
				
				if (c != '\n') {
					fputc(c, lcd);
				}
				
				got_data = true;
			}*/
			
			/* rx */
			if (uart_avail(UART_STN1110) && (c = fgetc(stn1110)) != EOF) {
				fputc(c, stdout);
				
				if (c != '\n') {
					obd_buf[obd_idx++] = c;
				} else {
					obd_buf[obd_idx] = '\0';
					
					/*// REMOVE ME
					strcpy_P(obd_buf, PSTR("10 41 e8"));*/
					
					lcd_clear();
					// TODO: just overwrite
					
					/*static uint8_t counter = 0;*/
					
					uint8_t discard, accel;
					if (sscanf_P(obd_buf, PSTR("%hhx %hhx %hhx"),
						&discard, &discard, &accel)== 3) {
						/*accel = counter++;*/
						
						int16_t accel_i = (int16_t)accel - 40;
						accel_i *= 100;
						accel_i /= (205 - 40);
						
						int16_t accel_b = (accel_i * 4) / 5;
						if (accel_b < 0) accel_b = 0;
						if (accel_b > 100) accel_b = 100;
						
						fprintf_P(lcd, PSTR("%3d"), accel_i);
						fputc(' ', lcd);
						
						while (accel_b >= 5) {
							lcd_write(0xff);
							accel_b -= 5;
						}
						if (accel_b > 0) {
							lcd_write(accel_b - 1);
						}
					} else {
						fprintf_P(lcd, PSTR("error:\r\n%s"), obd_buf);
					}
					
					do_cmd = true;
					
					/*_delay_ms(100);*/
				}
				
				got_data = true;
			}
		} while (got_data);
		
		// TODO: go to sleep instead
		_delay_us(10);
	}
}
Beispiel #23
0
void pan1322::AcceptConnection()
{
	fprintf_P(bt_pan1322_out, PSTR("AT+JACR=1\r\n"));
}
Beispiel #24
0
/*
 * CGI Sample: Show request parameters.
 *
 * See httpd.h for REQUEST structure.
 *
 * This routine must have been registered by NutRegisterCgi() and is
 * automatically called by NutHttpProcessRequest() when the client
 * request the URL 'cgi-bin/test.cgi'.
 */
static int ShowQuery(FILE * stream, REQUEST * req)
{
    char *cp;
    /*
     * This may look a little bit weird if you are not used to C programming
     * for flash microcontrollers. The special type 'prog_char' forces the
     * string literals to be placed in flash ROM. This saves us a lot of
     * precious RAM.
     */
    static prog_char head[] = "<HTML><HEAD><TITLE>Parameters</TITLE></HEAD><BODY><H1>Parameters</H1>";
    static prog_char foot[] = "</BODY></HTML>";
    static prog_char req_fmt[] = "Method: %s<BR>\r\nVersion: HTTP/%d.%d<BR>\r\nContent length: %ld<BR>\r\n";
    static prog_char url_fmt[] = "URL: %s<BR>\r\n";
    static prog_char query_fmt[] = "Argument: %s<BR>\r\n";
    static prog_char type_fmt[] = "Content type: %s<BR>\r\n";
    static prog_char cookie_fmt[] = "Cookie: %s<BR>\r\n";
    static prog_char auth_fmt[] = "Auth info: %s<BR>\r\n";
    static prog_char agent_fmt[] = "User agent: %s<BR>\r\n";

    /* These useful API calls create a HTTP response for us. */
    NutHttpSendHeaderTop(stream, req, 200, "Ok");
    NutHttpSendHeaderBottom(stream, req, html_mt, -1);

    /* Send HTML header. */
    fputs_P(head, stream);

    /*
     * Send request parameters.
     */
    switch (req->req_method) {
    case METHOD_GET:
        cp = "GET";
        break;
    case METHOD_POST:
        cp = "POST";
        break;
    case METHOD_HEAD:
        cp = "HEAD";
        break;
    default:
        cp = "UNKNOWN";
        break;
    }
    fprintf_P(stream, req_fmt, cp, req->req_version / 10, req->req_version % 10, req->req_length);
    if (req->req_url)
        fprintf_P(stream, url_fmt, req->req_url);
    if (req->req_query)
        fprintf_P(stream, query_fmt, req->req_query);
    if (req->req_type)
        fprintf_P(stream, type_fmt, req->req_type);
    if (req->req_cookie)
        fprintf_P(stream, cookie_fmt, req->req_cookie);
    if (req->req_auth)
        fprintf_P(stream, auth_fmt, req->req_auth);
    if (req->req_agent)
        fprintf_P(stream, agent_fmt, req->req_agent);

    /* Send HTML footer and flush output buffer. */
    fputs_P(foot, stream);
    fflush(stream);

    return 0;
}
Beispiel #25
0
void print_scalar(char *label, double value)
{
	fprintf_P(stderr,PSTR("%S %8.4f\n"),label,value); 
}
Beispiel #26
0
/*
 * CGI Sample: Show list of sockets.
 *
 * This routine must have been registered by NutRegisterCgi() and is
 * automatically called by NutHttpProcessRequest() when the client
 * request the URL 'cgi-bin/sockets.cgi'.
 */
static int ShowSockets(FILE * stream, REQUEST * req)
{
    /* String literals are kept in flash ROM. */
    static prog_char head[] = "<HTML><HEAD><TITLE>Sockets</TITLE></HEAD>"
        "<BODY><H1>Sockets</H1>\r\n"
        "<TABLE BORDER><TR><TH>Handle</TH><TH>Type</TH><TH>Local</TH><TH>Remote</TH><TH>Status</TH></TR>\r\n";
#if defined(__AVR__)
    static prog_char tfmt1[] = "<TR><TD>%04X</TD><TD>TCP</TD><TD>%s:%u</TD>";
#else
    static prog_char tfmt1[] = "<TR><TD>%08lX</TD><TD>TCP</TD><TD>%s:%u</TD>";
#endif
    static prog_char tfmt2[] = "<TD>%s:%u</TD><TD>";
    static prog_char foot[] = "</TABLE></BODY></HTML>";
    static prog_char st_listen[] = "LISTEN";
    static prog_char st_synsent[] = "SYNSENT";
    static prog_char st_synrcvd[] = "SYNRCVD";
    static prog_char st_estab[] = "<FONT COLOR=#CC0000>ESTABL</FONT>";
    static prog_char st_finwait1[] = "FINWAIT1";
    static prog_char st_finwait2[] = "FINWAIT2";
    static prog_char st_closewait[] = "CLOSEWAIT";
    static prog_char st_closing[] = "CLOSING";
    static prog_char st_lastack[] = "LASTACK";
    static prog_char st_timewait[] = "TIMEWAIT";
    static prog_char st_closed[] = "CLOSED";
    static prog_char st_unknown[] = "UNKNOWN";
    prog_char *st_P;
    extern TCPSOCKET *tcpSocketList;
    TCPSOCKET *ts;

    NutHttpSendHeaderTop(stream, req, 200, "Ok");
    NutHttpSendHeaderBottom(stream, req, html_mt, -1);

    /* Send HTML header. */
    fputs_P(head, stream);
    for (ts = tcpSocketList; ts; ts = ts->so_next) {
        switch (ts->so_state) {
        case TCPS_LISTEN:
            st_P = (prog_char *) st_listen;
            break;
        case TCPS_SYN_SENT:
            st_P = (prog_char *) st_synsent;
            break;
        case TCPS_SYN_RECEIVED:
            st_P = (prog_char *) st_synrcvd;
            break;
        case TCPS_ESTABLISHED:
            st_P = (prog_char *) st_estab;
            break;
        case TCPS_FIN_WAIT_1:
            st_P = (prog_char *) st_finwait1;
            break;
        case TCPS_FIN_WAIT_2:
            st_P = (prog_char *) st_finwait2;
            break;
        case TCPS_CLOSE_WAIT:
            st_P = (prog_char *) st_closewait;
            break;
        case TCPS_CLOSING:
            st_P = (prog_char *) st_closing;
            break;
        case TCPS_LAST_ACK:
            st_P = (prog_char *) st_lastack;
            break;
        case TCPS_TIME_WAIT:
            st_P = (prog_char *) st_timewait;
            break;
        case TCPS_CLOSED:
            st_P = (prog_char *) st_closed;
            break;
        default:
            st_P = (prog_char *) st_unknown;
            break;
        }
        /*
         * Fixed a bug reported by Zhao Weigang.
         */
        fprintf_P(stream, tfmt1, (uintptr_t) ts, inet_ntoa(ts->so_local_addr), ntohs(ts->so_local_port));
        fprintf_P(stream, tfmt2, inet_ntoa(ts->so_remote_addr), ntohs(ts->so_remote_port));
        fputs_P(st_P, stream);
        fputs("</TD></TR>\r\n", stream);
        fflush(stream);
    }

    fputs_P(foot, stream);
    fflush(stream);

    return 0;
}
/*!
 * \brief Wait for a specific string to appear.
 *
 * \param ci  Pointer to a NUTCHAT structure, which must have been 
 *            created by NutChatCreate().
 * \param str Expected string. May be empty if nothing is expected.
 *
 * \return 0 on success, 3 in case of a timeout error while waiting
 *         for an expected string, or the index of an abort string 
 *         plus 4, if one has been received. 
 */
int NutChatExpectString(NUTCHAT * ci, char *str)
{
    char ch;
    u_char m;
    u_char i;
    char *cp = str;

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

    while (*cp) {

        /*
         * Read the next character. Return on timeout.
         */
        if (_read(ci->chat_fd, &ch, 1) != 1) {
#ifdef NUTDEBUG
            if (__chat_trf) {
                static prog_char dbgmsg[] = "' TIMEOUT\n";
                fputs_P(dbgmsg, __chat_trs);
            }
#endif
            return 3;
        }
#ifdef NUTDEBUG
        if (__chat_trf) {
            if (ch > 31 && ch < 127) {
                fputc(ch, __chat_trs);
            } else {
                fprintf(__chat_trs, "\\x%02X", ch);
            }
        }
#endif
        /*
         * If the character doesn't match the next expected one,
         * then restart from the beginning of the expected string.
         */
        if (ch != *cp) {
            cp = str;
        }

        /*
         * If the character matched, advance the pointer into
         * the expected string.
         */
        if (ch == *cp) {
            cp++;
        }

        /*
         * Check for abort strings.
         */
        for (i = 0; i < ci->chat_aborts; i++) {
            m = ci->chat_abomat[i];
            if (ch == ci->chat_abort[i][m]) {
                if (ci->chat_abort[i][++m] == 0) {
#ifdef NUTDEBUG
                    if (__chat_trf) {
                        static prog_char dbgmsg[] = "' ABORT\n";
                        fputs_P(dbgmsg, __chat_trs);
                    }
#endif
                    return i + 4;
                }
            } else
                m = (ch == ci->chat_abort[i][0]);
            ci->chat_abomat[i] = m;
        }

        /*
         * Check for report strings.
         */
        if (ci->chat_report_state > 0) {
            m = ci->chat_repmat;
            if (ci->chat_report_state == 2) {
                chat_report[m++] = ch;
            } else if (ch == ci->chat_report_search[m]) {
                chat_report[m++] = ch;
                if (ci->chat_report_search[m] == 0) {
                    ci->chat_report_state = 2;
                }
            } else {
                m = (ch == ci->chat_report_search[0]);
            }
            ci->chat_repmat = m;
        }
    }

    /*
     * Read the remainder of the string before NutChatSendString clears it
     */
    if (ci->chat_report_state == 2) {
        m = ci->chat_repmat;    /* not needed... (but not nice to remove it) */
        while (m < CHAT_MAX_REPORT_SIZE) {
            if (_read(ci->chat_fd, &ch, 1) != 1 || ch < ' ') {
                break;
            }
            chat_report[m++] = ch;

#ifdef NUTDEBUG
            if (__chat_trf) {
                if (ch > 31 && ch < 127) {
                    fputc(ch, __chat_trs);
                } else {
                    fprintf(__chat_trs, "\\x%02X", ch);
                }
            }
#endif
        }
        ci->chat_report_state = 0;      /* Only find first occurence */
        chat_report[m] = 0;
    }
#ifdef NUTDEBUG
    if (__chat_trf) {
        static prog_char dbgmsg[] = "'\n";
        fputs_P(dbgmsg, __chat_trs);
    }
#endif

    return 0;
}
Beispiel #28
0
static void _prompt_error(uint8_t status, char *buf)
{
	fprintf_P(stderr, PSTR("error: %S: %s \n"),(PGM_P)pgm_read_word(&msgStatusMessage[status]),buf);
}
Beispiel #29
0
static void JSONSettings(const KVPairs & key_value_pairs, FILE * stream_file)
{
	ServeHeader(stream_file, 200, "OK", false, "text/plain");
	IPAddress ip;
	fprintf(stream_file, "{\n");
#ifdef ARDUINO
	ip = GetIP();
	fprintf_P(stream_file, PSTR("\t\"ip\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]);
	ip = GetNetmask();
	fprintf_P(stream_file, PSTR("\t\"netmask\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]);
	ip = GetGateway();
	fprintf_P(stream_file, PSTR("\t\"gateway\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]);
	ip = GetNTPIP();
	fprintf_P(stream_file, PSTR("\t\"NTPip\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]);
	fprintf_P(stream_file, PSTR("\t\"NTPoffset\" : \"%d\",\n"), GetNTPOffset());
#endif
	fprintf_P(stream_file, PSTR("\t\"webport\" : \"%u\",\n"), GetWebPort());
	fprintf_P(stream_file, PSTR("\t\"ot\" : \"%d\",\n"), GetOT());
	ip = GetWUIP();
	fprintf_P(stream_file, PSTR("\t\"wuip\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]);
	fprintf_P(stream_file, PSTR("\t\"wutype\" : \"%s\",\n"), GetUsePWS() ? "pws" : "zip");
	fprintf_P(stream_file, PSTR("\t\"zip\" : \"%ld\",\n"), (long) GetZip());
	fprintf_P(stream_file, PSTR("\t\"sadj\" : \"%ld\",\n"), (long) GetSeasonalAdjust());
	char ak[17];
	GetApiKey(ak);
	fprintf_P(stream_file, PSTR("\t\"apikey\" : \"%s\",\n"), ak);
	GetPWS(ak);
	ak[11] = 0;
	fprintf_P(stream_file, PSTR("\t\"pws\" : \"%s\"\n"), ak);
	fprintf(stream_file, "}");
}
Beispiel #30
0
void poll(){
  // Main polling loop
  
  // Check for a character from the USART
  // See if there is a command comming in
  if (uart_char_is_waiting()) {
    char c = uart_read();
    
    // Update the command state-machine
    if (c == '\n' || c == '\r' ) {
      // End of a command, process it and reset the command string
      if (current_command == COMMAND_NONE) {
      } else if (current_command == COMMAND_INFLATE) {
	syringe_inflate();
	current_state = STATE_INFLATE;
      } else if (current_command == COMMAND_DEFLATE) {
	syringe_deflate();
	current_state = STATE_DEFLATE;
      } else if (current_command == COMMAND_SET_PRESSURE) {
	int ret = sscanf_P(value_str, PSTR("%d"), &target_pressure);
	//	printf_P(PSTR("1 = %d\r\n"), ret );  
	//	printf_P(PSTR("2 = %d\r\n"), target_pressure );
      }
      value_str_i = 0;
      current_command = COMMAND_NONE;
      current_command_state = CMD_STATE_COMMAND;
    } else {
      // In a command string
      if (current_command_state == CMD_STATE_COMMAND) {
	// Command character
	if (c == 'i') {
	  // Inflate
	  current_command = COMMAND_INFLATE;
	} else if (c == 'd') {
	  // Deflate
	  current_command = COMMAND_DEFLATE;
	} else if (c == 'p') {
	  // Set pressure point
	  current_command = COMMAND_SET_PRESSURE;
	} else {
	  current_command = COMMAND_NONE;
	}
	current_command_state = CMD_STATE_EQUAL;
      } else if (current_command_state == CMD_STATE_EQUAL) {
	// Assume the second char is always '='
	current_command_state = CMD_STATE_VALUE;
      } else if (current_command_state == CMD_STATE_VALUE) {
	// In value part of command
	value_str[value_str_i++] = c;
	if (value_str_i >= MAX_VALUE_LENGTH) {
	  value_str_i = MAX_VALUE_LENGTH-1;
	}
	value_str[value_str_i] = 0; // Write NULL terminator
      }
    }
  }
  
  // Check the current pressure
  // take 100 samples and average them!
  // holder variables for temperature data
  uint16_t last_sample = 0;
  double this_temp;
  double pres_avg = 0.0;
  uint8_t i;
  
  for(i=0; i<100; i++) {
    last_sample = adc_read();
    //this_temp = sampleTokPi(last_sample);
    this_temp = last_sample;
    
    // add this contribution to the average
    pres_avg = pres_avg + this_temp/100.0;
  }

  // Check to see if we hit the target presure
  if ( current_state == STATE_INFLATE ) {
    if ( pres_avg >= target_pressure ) {
      // Stop Inflating
      syringe_off();
      current_state = STATE_IDLE;
    }
  } else if ( current_state == STATE_DEFLATE ) {
    if ( pres_avg <= target_pressure ) {
      // Stop Deflating
      syringe_off();
      current_state = STATE_IDLE;      
    }
  }   

  // write message to LCD
  lcd_home();
  lcd_write_string(PSTR("ADC: "));
  lcd_write_int16(last_sample);
  lcd_write_string(PSTR(" of 1024   "));
  lcd_line_two();
  if ( current_state == STATE_IDLE ) {
    fprintf_P(&lcd_stream, PSTR("State: Idle      "));
  } else if ( current_state == STATE_RECV ) {
    fprintf_P(&lcd_stream, PSTR("State: Recv      "));
  } else if ( current_state == STATE_INFLATE ) {
    fprintf_P(&lcd_stream, PSTR("State: Inflate   "));
  } else if ( current_state == STATE_DEFLATE ) {
    fprintf_P(&lcd_stream, PSTR("State: Deflate   "));
  }
  lcd_line_three();
  fprintf_P(&lcd_stream, PSTR("Target Pres: %d"), target_pressure );
  // write message to serial port
  //printf_P(PSTR("%.2f degrees F\r\n"), temp_avg);
  //printf_P(PSTR("Pres = %d\r\n"), target_pressure );
  //printf_P(PSTR("Value = %s\r\n"), value_str );

}