示例#1
0
/**
 * @brief Handle when a pattern has been detected by UART
 *
 * @param esp_dte ESP32 Modem DTE object
 */
static void esp_handle_uart_pattern(esp_modem_dte_t *esp_dte)
{
    int pos = uart_pattern_pop_pos(esp_dte->uart_port);
    int read_len = 0;
    if (pos != -1) {
        if (pos < ESP_MODEM_LINE_BUFFER_SIZE - 1) {
            /* read one line(include '\n') */
            read_len = pos + 1;
        } else {
            ESP_LOGW(MODEM_TAG, "ESP Modem Line buffer too small");
            read_len = ESP_MODEM_LINE_BUFFER_SIZE - 1;
        }
        read_len = uart_read_bytes(esp_dte->uart_port, esp_dte->buffer, read_len, pdMS_TO_TICKS(100));
        if (read_len) {
            /* make sure the line is a standard string */
            esp_dte->buffer[read_len] = '\0';
            /* Send new line to handle */
            esp_dte_handle_line(esp_dte);
        } else {
            ESP_LOGE(MODEM_TAG, "uart read bytes failed");
        }
    } else {
        ESP_LOGW(MODEM_TAG, "Pattern Queue Size too small");
        uart_flush(esp_dte->uart_port);
    }
}
示例#2
0
RET_CODE sn_client_process(void)
{
  u32 ret = 0, i = 0;
  u8 ch = 0;
  u16 code = 0xFFFF;
  u8 hkey = 0xFF;
  void * p_dev = dev_find_identifier(NULL,
                            DEV_IDT_TYPE,
                            SYS_DEV_TYPE_UIO);
  dm_read(class_get_handle_by_id(DM_CLASS_ID), FPKEY_BLOCK_ID, 0, 5, sizeof(u8), &hkey);

  uart_flush(0);
  OS_PRINTF(SN_CLIRNT_SIG);
  for(i = 0; i < SN_TIMEOUT; i++)
  {
    uio_get_code(p_dev, &code);
    if(hkey != 0xFF)
    {
      if((code & 0x100) && (hkey == (code & 0xFF)))
      {
        jump_to_usbupgrade();
        return ERR_FAILURE;
      }
    }
    ret = uart_read_byte(0, &ch, 100);
    if((ret == 0) && (ch == SN_CLIRNT_RES))
    {
      return SUCCESS;  
    }
  }
  return ERR_FAILURE;
}
示例#3
0
/**
 * @brief Change Modem's working mode
 *
 * @param dte Modem DTE object
 * @param new_mode new working mode
 * @return esp_err_t
 *      - ESP_OK on success
 *      - ESP_FAIL on error
 */
static esp_err_t esp_modem_dte_change_mode(modem_dte_t *dte, modem_mode_t new_mode)
{
    modem_dce_t *dce = dte->dce;
    MODEM_CHECK(dce, "DTE has not yet bind with DCE", err);
    esp_modem_dte_t *esp_dte = __containerof(dte, esp_modem_dte_t, parent);
    MODEM_CHECK(dce->mode != new_mode, "already in mode: %d", err, new_mode);
    switch (new_mode) {
    case MODEM_PPP_MODE:
        MODEM_CHECK(dce->set_working_mode(dce, new_mode) == ESP_OK, "set new working mode:%d failed", err, new_mode);
        uart_disable_pattern_det_intr(esp_dte->uart_port);
        uart_enable_rx_intr(esp_dte->uart_port);
        break;
    case MODEM_COMMAND_MODE:
        uart_disable_rx_intr(esp_dte->uart_port);
        uart_flush(esp_dte->uart_port);
        uart_enable_pattern_det_intr(esp_dte->uart_port, '\n', 1, MIN_PATTERN_INTERVAL, MIN_POST_IDLE, MIN_PRE_IDLE);
        uart_pattern_queue_reset(esp_dte->uart_port, CONFIG_UART_PATTERN_QUEUE_SIZE);
        MODEM_CHECK(dce->set_working_mode(dce, new_mode) == ESP_OK, "set new working mode:%d failed", err, new_mode);
        break;
    default:
        break;
    }
    return ESP_OK;
err:
    return ESP_FAIL;
}
static void handle_flush(const char *req, int *req_index)
{
    char dirstr[MAXATOMLEN];
    if (ei_decode_atom(req, req_index, dirstr) < 0) {
        send_error_response("einval");
        return;
    }

    enum uart_direction direction;
    if (strcmp(dirstr, "receive") == 0)
        direction = UART_DIRECTION_RECEIVE;
    else if (strcmp(dirstr, "transmit") == 0)
        direction = UART_DIRECTION_TRANSMIT;
    else if (strcmp(dirstr, "both") == 0)
        direction = UART_DIRECTION_BOTH;
    else {
        send_error_response("einval");
        return;
    }

    if (!uart_is_open(uart)) {
        send_error_response("ebadf");
        return;
    }

    if (uart_flush(uart, direction) >= 0)
        send_ok_response();
    else
        send_error_response(uart_last_error());
}
示例#5
0
文件: serial.c 项目: Heyvaert/ipxe-1
/**
 * Shut down serial console
 *
 * @v flags		Shutdown flags
 */
static void serial_shutdown ( int flags __unused ) {

	/* Do nothing if we have no UART */
	if ( ! serial_console.base )
		return;

	/* Flush any pending output */
	uart_flush ( &serial_console );

	/* Leave console enabled; it's still usable */
}
示例#6
0
文件: reset.c 项目: jgottula/JAMS
noreturn void reset(void) {
	uart_flush();
	
	cli();
	
	/* invoke a software reset */
	CCP = CCP_IOREG_gc;
	RST.CTRL |= RST_SWRST_bm;
	
	for ( ;; );
}
示例#7
0
BOOL ap_satcodx_recv_alloc_uart(satcodx_impl_data_t *p_satcodx_impl_data)
{
#if WIN32
    uartwin_init(1);
    return TRUE;
#else
    //close shell uart interface!!!
    //clear uart fifo
    uart_flush(UART_ID_0);
    return TRUE;
#endif
}
示例#8
0
/* DolphinDOS XZ command */
void save_dolphin(void) {
  buffer_t *buf;
  uint8_t eoi;

  /* find the already open file */
  buf = find_buffer(1);

  if (!buf)
    return;

  /* reset buffer position */
  buf->position = 2;
  buf->lastused = 2;

  /* experimental delay to avoid hangs */
  delay_us(100);

  /* handshaking */
  parallel_set_dir(PARALLEL_DIR_IN);
  set_data(0);
  parallel_clear_rxflag();
  parallel_send_handshake();
  uart_flush();

  /* receive data */
  do {
    /* flush buffer if full */
    if (buf->mustflush)
      if (buf->refill(buf))
        return; // FIXME: check error handling in Dolphin

    while (!parallel_rxflag) ;

    buf->data[buf->position] = parallel_read();
    mark_buffer_dirty(buf);

    if (buf->lastused < buf->position)
      buf->lastused = buf->position;
    buf->position++;

    /* mark for flushing on wrap */
    if (buf->position == 0)
      buf->mustflush = 1;

    eoi = !!IEC_CLOCK;

    parallel_clear_rxflag();
    parallel_send_handshake();
  } while (!eoi);

  /* the file will be closed with ATN+0xe1 by DolphinDOS */
}
示例#9
0
char handshake()
{
	uart_flush();
	_delay_ms(100);
	
	while(uart_available()==0)
	{

		PORTB |=(1<<PB5);
		_delay_ms(100);
		PORTB &=~(1<<PB5);
		_delay_ms(100);
		
	}
	
	if (uart_getc() == 'a')
	{
		PORTB |=(1<<PB5);
		_delay_ms(50);
		PORTB &=~(1<<PB5);
		_delay_ms(50);
		PORTB |=(1<<PB5);
		_delay_ms(50);
		PORTB &=~(1<<PB5);
		_delay_ms(50);
		
	}
	
	uart_putc('b');
	while(uart_available()==0)
	{
		PORTB |=(1<<PB5);
		_delay_ms(20);
		
		PORTB &= ~(1<<PB5);
		_delay_ms(20);
	}
	
	if (uart_getc() == 'c')
	{
		uart_putc('d');
		PortMode = REGULAR;
		return(0);  // handshake success
	}
	else
	{
		uart_puts_p(PSTR("\n Debug mode"));
		PortMode = DEBUG;
		return(1);  // debug mode
	}
}
示例#10
0
/*!
 * @brief flush pending data
 * @retval 0 on success
 * @retval -1 on failure
 * @param[in] obj pointer to object instance
 * @note will block until specified amount of data is received or timeout
 */
int
serial_flush(serial *obj)
{
    struct_uart *uart;
    serial_private *prv;
    prv = (serial_private *)obj->prv;
    uart = (struct_uart *)(prv->fd);

    if (prv->fd < 0) {
        return(-1);
    }

    return uart_flush(uart);
}
示例#11
0
noreturn void assert_fail(const __flash char *file, uint16_t line) {
    uart_flush(UART_PC, 1000);

    char buf[64];
    snprintf_P(buf, sizeof(buf), PSTR("\nassertion failed: %S:%" PRIu16 "\n"),
               file, line);
    uart_direct_write_str(UART_PC, UART_DIV_115200, buf);

#if ASSERT_FAIL_RESET
    reset();
#else
    die();
#endif
}
static void socket_uart_callback_data_received(lwip_if_socket_t *socket, unsigned int received)
{
	int current, length;
	uint8_t byte;
	bool strip_telnet;
	telnet_strip_state_t telnet_strip_state;

	length = string_length(&uart_socket_receive_buffer);

	strip_telnet = config_flags_match(flag_strip_telnet);
	telnet_strip_state = ts_copy;

	for(current = 0; current < length; current++)
	{
		byte = string_at(&uart_socket_receive_buffer, current);

		switch(telnet_strip_state)
		{
			case(ts_copy):
			{
				if(strip_telnet && (byte == 0xff))
					telnet_strip_state = ts_dodont;
				else
				{
					if(uart_full(0))
						stat_uart_receive_buffer_overflow++;
					else
						uart_send(0, byte);
				}

				break;
			}
			case(ts_dodont):
			{
				telnet_strip_state = ts_data;
				break;
			}
			case(ts_data):
			{
				telnet_strip_state = ts_copy;
				break;
			}
		}
	}

	string_clear(&uart_socket_receive_buffer);
	lwip_if_receive_buffer_unlock(socket);
	uart_flush(0);
}
示例#13
0
void bluetooth_configure(void)
{
	uart_flush();
	_delay_ms(500);

	hc05_send_command("AT");
	_delay_ms(500);

	hc05_send_command("AT+NAME=\"Iron Man Mark IV\"");
	hc05_send_command("AT+PSWD=1234");
	hc05_send_command("AT+UART=38400,0,0");
	hc05_send_command("AT+CMODE=1");
	hc05_send_command("AT+CLASS=800804");
	hc05_send_command("AT+RESET");
}
示例#14
0
void bluetooth_init(void)
{
	// Double transmission speed
	UCSRA = _BV(U2X);

	// Set baud rate
	UBRRL = (F_CPU / (8UL * UART_BAUD)) - 1;

	// Asynchronous mode, no parity, 8N1
	UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0);

	// Enable TX & RX, Enable RXC interrupt
	UCSRB = _BV(TXEN) | _BV(RXEN) | _BV(RXCIE);

	uart_flush();
}
示例#15
0
void resetResponse(){

      _pos = 0;
	  _response_Checksum = 0;
	  _response_Available = false;
      _response_ERROR = 0;

	  for (uint8_t i = 0; i < 32; i++){
	  // uart_putc(_response_FrameData[i]);
	  _response_FrameData[i] = 0;
	  uart_flush();////////////////////////////////////////////////////////////////////////
	  PORTA = 0x00;///////////////////////////////////////////////

	  }

}
示例#16
0
static void handle_flush(const char *req, int *req_index)
{
    // No arguments
    (void) req;
    (void) req_index;

    if (!uart_is_open(uart)) {
        send_error_response("ebadf");
        return;
    }

    if (uart_flush(uart) >= 0)
        send_ok_response();
    else
        send_error_response(uart_last_error());
}
示例#17
0
int main(void)
{
	
	init_avr();

	uart_init();

	TCCR1B=(0<<ICNC1) | (0<<ICES1) | (0<<WGM13) | (0<<WGM12) | (1<<CS12) | (0<<CS11) | (0<<CS10);
	// Timer/Counter 1 Interrupt(s) initialization
	TIMSK1=(0<<ICIE1) | (0<<OCIE1B) | (0<<OCIE1A) | (1<<TOIE1);

	sei();
	
	Task[0] = 0;
	
	while(1)
	{
		
		if(BytesRead != 0)
		{
			TCCR1B = 0x00; // stop timer1
			memcpy(data_buffer, uart_buffer, BytesRead);
			uart_flush();
			for(int i = 0; i < 16; i++)
			Task[i] = data_buffer[i];
			run_task(Task);
			for(int i = 0; i < 16; i++)
			Task[i] = 0;
			TCCR1B = 0x04; // run timer1
			TimerEvent = false;
		}
		
		if(TimerEvent)
		{
			TimerEvent = false;
			run_task(Task);
			for(int i = 0; i < 16; i++)
			Task[i] = 0;
		}
		set_sleep_mode(SLEEP_MODE_IDLE);
		sleep_mode();
	}
		
}
示例#18
0
int main(void) {

	uint8_t oldStatus = 0;

	initSysVars();
	initPorts();

	// we use RS485 here, to go with RS232 just have a look at Modbus_uart.c/.h
	// and use the rs232 init function
	rs485_init(UART_BAUD_SELECT(9600,F_CPU));
	initInterrupts();
	sei();

//	actProfileData[IDX_DW_Debug02] = 2;
	actProfileData[IDX_DW_Debug01] = 101;
	actProfileData[IDX_DW_Debug02] = 102;
	actProfileData[IDX_DW_Debug03] = 103;

	actProfileData[IDX_DW_EncSteps] = 200;
	actProfileData[IDX_DW_EncHyst] = 4;
	setBitValForSysBit(IDX_AB_EncSync, ON);


	for (;;) {


		if (oldStatus != uart0_status.status) {
			oldStatus = uart0_status.status;

			if (uart0_status.status == RS_FrameComplete) {
				if (UART_RxHead) {
					modbus_processSlaveFrame((uint8_t*) UART_RxBuf, UART_RxHead);
				}
				uart_flush();
				uart0_status.status = RS_Wait;
			}
		}

		if (changedBit.cBit != 99) {
			performBitActions();
		}
	}

}
示例#19
0
文件: main.c 项目: somanydots/dotme
int main(void)
{
    initLED();
    initDOTS();
    uart_init(UART_BAUD_SELECT(38400, F_CPU));
    sei();
    uart_flush();
    _delay_ms(100);


    uint8_t i=0;

    char c;
    memset(to_write, 0x00, sizeof(to_write));

    PORTD &=~RESETPIN;
    _delay_ms(1);
    PORTD |= RESETPIN;

    for (uint8_t i=0; i<200; i++) {
      writeCol(0xFF);
    }

    for (;;) {
      while(uart_available() == 0) {
        PORTB|=(1<<PB5);
        _delay_ms(100);
        PORTB&=~(1<<PB5);
        _delay_ms(100);
      }
      c = uart_getc();
      char c_lo = c;
      uart_putc(c);
      if (c_lo >= 0x20) {
        to_write[i++] = c_lo;
      }
      if ((c_lo < 0x20) || (i >= 12)) {
        writeArray(to_write);
        i=0;
      }
    }
    return 0;   /* never reached */
}
示例#20
0
void analog_read_fast(bool start, uint8 pin)
{
    // todo: needs more testing
    uint8 msg[] = { '\\', 'f', 0x00 };
    uint16 i;

    if (!start)
        msg[1] = 'F';			// stop command

    // fix pin mapping
    if (pin == PC5) {
        msg[2] = 5;
    } else if (pin == PC4) {
        msg[2] = 4;
    } else if (pin == PC3) {
        msg[2] = 3;
    } else {
        msg[2] = pin;
    }

    if (start) {
        // flush output buffer first
        uart_flush();
        uart_write_prio(msg, 3, NULL, 0x00);
        uart_wait_prio(2);
        // drain the remaining in-queue with dummy reads
        while((i = uart_read(NULL, 128)));
        // this would be the place to adjust the spi rate
    } else {
        uart_write_prio(msg, 2, NULL, 0x00);
        uart_wait_prio(2);
        // drain the remaining in-queue with dummy reads
        while((i = uart_read(NULL, 128)));
        // this would be the place to adjust the spi rate again
    }
}
示例#21
0
void mp_hal_debug_str(const char *str) {
    while (*str) {
        uart_tx_one_char(UART0, *str++);
    }
    uart_flush(UART0);
}
示例#22
0
static void flush_data()
{
  uart_flush(0);
}
示例#23
0
void shavs_test1(void){ /* KAT tests */
	uint32_t length=0;
	int32_t expect_input=0;

	if(!shavs_algo){
			cli_putstr("\r\nERROR: select algorithm first!");
		return;
	}
	char c;
	uint8_t diggest[shavs_algo->hashsize_b/8];
	shavs_ctx.buffersize_B=shavs_algo->blocksize_b/8;
	uint8_t buffer[shavs_ctx.buffersize_B+5];
	shavs_ctx.buffer = buffer;
	cli_putstr("\r\nbuffer_size = 0x");
	cli_hexdump_rev(&(shavs_ctx.buffersize_B), 2);
	cli_putstr(" bytes");
	for(;;){
		shavs_ctx.blocks = 0;
		memset(buffer, 0, shavs_ctx.buffersize_B);
		length = getLength();
		if((int32_t)length<0){
#if DEBUG
			cli_putstr("\r\n(x) Len == ");
			cli_hexdump_rev(&length, 4);
			uart_flush(0);
#endif
			return;
		}

#if DEBUG
		cli_putstr("\r\nLen == ");
		cli_hexdump_rev(&length, 4);
		uart_flush(0);
#endif
		if(length==0){
			expect_input=2;
		}else{
			expect_input=((length + 7) >> 2) & (~1L);
		}
#if DEBUG
		cli_putstr("\r\nexpected_input == ");
		cli_hexdump_rev(&expect_input, 4);
		if(expect_input==0)
			cli_putstr("\r\nexpected_input == 0 !!!");
#endif
		shavs_ctx.buffer_idx = 0;
		shavs_ctx.in_byte    = 0;
		shavs_ctx.blocks     = 0;
		uint8_t ret;
#if DEBUG
		cli_putstr("\r\n HFAL init");
		cli_putstr("\r\n (2) expected_input == ");
		cli_hexdump_rev(&expect_input, 4);
#endif
		ret = hfal_hash_init(shavs_algo, &(shavs_ctx.ctx));
		if(ret){
			cli_putstr("\r\n HFAL init returned with: ");
			cli_hexdump(&ret, 1);
			return;
		}
#if DEBUG
		cli_putstr("\r\n (3) expected_input == ");
		cli_hexdump_rev(&expect_input, 4);
		cli_putstr("\r\n");
#endif
		while((c=cli_getc_cecho())!='M' && c!='m'){
			if(!isblank((uint8_t)c)){
				cli_putstr("\r\nERROR: wrong input (1) [0x");
				cli_hexdump(&c, 1);
				cli_putstr("]!\r\n");
				hfal_hash_free(&(shavs_ctx.ctx));
				return;
			}
		}
		if((c=cli_getc_cecho())!='s' && c!='S'){
				cli_putstr("\r\nERROR: wrong input (2)!\r\n");
				hfal_hash_free(&(shavs_ctx.ctx));
				return;
		}
		if((c=cli_getc_cecho())!='g' && c!='G'){
				cli_putstr("\r\nERROR: wrong input (3)!\r\n");
				hfal_hash_free(&(shavs_ctx.ctx));
				return;
		}
		while((c=cli_getc_cecho())!='='){
			if(!isblank((uint8_t)c)){
				cli_putstr("\r\nERROR: wrong input (4)!\r\n");
				hfal_hash_free(&(shavs_ctx.ctx));
				return;
			}
		}
#if DEBUG
		cli_putstr("\r\nparsing started");
#endif
		shavs_ctx.buffer_idx = 0;
		shavs_ctx.in_byte    = 0;
		shavs_ctx.blocks     = 0;
		while(expect_input>0){
			c=cli_getc_cecho();
#if DEBUG
			cli_putstr("\r\n\t(");
			cli_hexdump_rev(&expect_input, 4);
			cli_putstr(") ");
#endif
			if(buffer_add(c)==0){
				--expect_input;
			}else{
				if(!isblank((uint16_t)c)){
					cli_putstr("\r\nERROR: wrong input (5) (");
					cli_putc(c);
					cli_putstr(")!\r\n");
					hfal_hash_free(&(shavs_ctx.ctx));
					return;
				}
			}
		}
#if DEBUG
		cli_putstr("\r\nBuffer-A:");
		cli_hexdump_block(buffer, shavs_ctx.buffersize_B, 5, 8);

		cli_putstr("\r\n starting finalization");
		cli_putstr("\r\n\tblocks     == ");
		cli_hexdump_rev(&(shavs_ctx.blocks),4);
		cli_putstr("\r\n\tbuffer_idx == ");
		cli_hexdump_rev(&(shavs_ctx.buffer_idx),2);
		cli_putstr("\r\n\tin_byte    == ");
		cli_hexdump_rev(&(shavs_ctx.in_byte),1);

		cli_putstr("\r\n starting last block");
		cli_putstr("\r\n\tlength       == ");
		cli_hexdump_rev(&length,4);
		cli_putstr("\r\n\tbuffersize_B == ");
		cli_hexdump_rev(&(shavs_ctx.buffersize_B),2);
		uint16_t temp=length-(shavs_ctx.blocks)*((shavs_ctx.buffersize_B)*8);
		cli_putstr("\r\n\t (temp)      == ");
		cli_hexdump_rev(&temp,2);
#else
		uint16_t temp=length-(shavs_ctx.blocks)*((shavs_ctx.buffersize_B)*8);
#endif
		hfal_hash_lastBlock( &(shavs_ctx.ctx), buffer, /* be aware of freaking compilers!!! */
		                    temp );
#if DEBUG
		cli_putstr("\r\n starting ctx2hash");
#endif
		hfal_hash_ctx2hash(diggest, &(shavs_ctx.ctx));
#if DEBUG
		cli_putstr("\r\n starting hash free");
#endif
		hfal_hash_free(&(shavs_ctx.ctx));
		cli_putstr("\r\n MD = ");
		cli_hexdump(diggest, shavs_algo->hashsize_b/8);

	}
}
示例#24
0
static void uart_task(void *pvParameters)
{
    int uart_num = UART_NUM_0;
    uart_event_t event;
    size_t buffered_size;
    uint8_t* dtmp = (uint8_t*) malloc(BUF_SIZE);
    for(;;) {
        //Waiting for UART event.
        if(xQueueReceive(uart0_queue, (void * )&event, (portTickType)portMAX_DELAY)) {
            //ESP_LOGI(TAG, "uart[%d] event:", uart_num);
            switch(event.type) {
                //Event of UART receving data
                /*We'd better handler data event fast, there would be much more data events than
                other types of events. If we take too much time on data event, the queue might
                be full.
                in this example, we don't process data in event, but read data outside.*/
                case UART_DATA:
                    uart_get_buffered_data_len(uart_num, &buffered_size);
                    //ESP_LOGI(TAG, "data, len: %d; buffered len: %d", event.size, buffered_size);
                    break;
                //Event of HW FIFO overflow detected
                case UART_FIFO_OVF:
                    ESP_LOGI(TAG, "hw fifo overflow\n");
                    //If fifo overflow happened, you should consider adding flow control for your application.
                    //We can read data out out the buffer, or directly flush the rx buffer.
                    uart_flush(uart_num);
                    break;
                //Event of UART ring buffer full
                case UART_BUFFER_FULL:
                    ESP_LOGI(TAG, "ring buffer full\n");
                    //If buffer full happened, you should consider encreasing your buffer size
                    //We can read data out out the buffer, or directly flush the rx buffer.
                    uart_flush(uart_num);
                    break;
                //Event of UART RX break detected
                case UART_BREAK:
                    ESP_LOGI(TAG, "uart rx break\n");
                    break;
                //Event of UART parity check error
                case UART_PARITY_ERR:
                    ESP_LOGI(TAG, "uart parity error\n");
                    break;
                //Event of UART frame error
                case UART_FRAME_ERR:
                    ESP_LOGI(TAG, "uart frame error\n");
                    break;
                //UART_PATTERN_DET
                case UART_PATTERN_DET:
                    ESP_LOGI(TAG, "uart pattern detected\n");
                    break;
                //Others
                default:
                    ESP_LOGI(TAG, "uart event type: %d\n", event.type);
                    break;
            }
        }
    }
    free(dtmp);
    dtmp = NULL;
    vTaskDelete(NULL);
}
void HardwareSerial::flush()
{
  uart_flush(_uart);
}
示例#26
0
void menu_browse_files(void) {
  buffer_t *buf;
  buffer_t *buf_tbl;
  buffer_t *buf_cur;
  buffer_t *first_buf;
  path_t path;
  cbmdirent_t dent;
  uint16_t entries;
  uint8_t entry_num;
  bool fat_filesystem;
  uint8_t i;
  uint8_t my;
  uint16_t mp;
  bool action;
  uint16_t stack_mp[MAX_LASTPOS];
  uint8_t stack_my[MAX_LASTPOS];
  uint8_t pos_stack;
  uint8_t save_active_buffers;

  pos_stack = 0;
  memset(stack_mp, 0, sizeof(stack_mp));
  memset(stack_my, 0, sizeof(stack_my));
  save_active_buffers = active_buffers;

start:
  lcd_clear();
  lcd_puts_P(PSTR("Reading..."));

  buf = buf_tbl = buf_cur = first_buf = NULL;
  entries = entry_num = mp = 0;
  fat_filesystem = false;

  // Allocate one buffer, used to read a single directory entry
  if ((buf = alloc_system_buffer()) == NULL) return;

  // Allocate buffers with continuous data segments
  // Stores pointers to directory entries for qsort
  if ((buf_tbl = alloc_linked_buffers(CONFIG_DIR_BUFFERS)) == NULL) return;

  // Buffers to store the actual diretory entries.
  // Whilst the directory grows, new buffers get allocated and linked
  if ((buf_cur = alloc_system_buffer()) == NULL) return;
  first_buf = buf_cur;

  // Allocating buffers affects the LEDs
  set_busy_led(false); set_dirty_led(true);

  path.part = current_part;
  path.dir  = partition[path.part].current_dir;
  uart_trace(&path.dir, 0, sizeof(dir_t));
  uart_putcrlf();
  uart_flush();
  if (opendir(&buf->pvt.dir.dh, &path)) return;

  for (;;) {
    if (next_match(&buf->pvt.dir.dh,
                    buf->pvt.dir.matchstr,
                    buf->pvt.dir.match_start,
                    buf->pvt.dir.match_end,
                    buf->pvt.dir.filetype,
                    &dent) == 0)
    {
      uint8_t e_flags = 0;
      if (dent.opstype == OPSTYPE_FAT) {
        fat_filesystem = true;
        if (check_imageext(dent.pvt.fat.realname) != IMG_UNKNOWN)
          e_flags |= E_IMAGE;
      }
      // Current block full?
      if (entry_num == ENTRIES_PER_BLOCK) {
        entry_num = 0;
        buffer_t *old_buf = buf_cur;
        if ((buf_cur = alloc_system_buffer()) == NULL) {
          printf("alloc buf_cur failed, %d entries", entries);
          goto cleanup;
        }
        set_busy_led(false); set_dirty_led(true);
        buf_cur->pvt.buffer.next = NULL;
        old_buf->pvt.buffer.next = buf_cur;
      }

      // Store entry
      ep[entries] = (entry_t *) (buf_cur->data + entry_num * sizeof(entry_t));
      ustrncpy(ep[entries]->filename, dent.name, 16);
      ep[entries]->filesize = dent.blocksize;
      if ((dent.typeflags & EXT_TYPE_MASK) == TYPE_DIR)
        e_flags |= E_DIR;
      ep[entries]->flags = e_flags;
      entries++;
      entry_num++;
    } else {
      // No more directory entries to read
      break;
    }
  }
  printf("%d entries\r\n", entries);

  if (fat_filesystem)
    qsort(ep, entries, sizeof(entry_t*), compare);

  for (uint16_t i = 0; i < entries; i++) {
    printf("%3u: ", i);
    if (ep[i]->flags & E_DIR)
      uart_puts_P(PSTR(" DIR "));
    else if (ep[i]->flags & E_IMAGE)
      uart_puts_P(PSTR(" IMG "));
    else
      printf("%4u ", ep[i]->filesize);
    uint8_t filename[16 + 1];
    ustrncpy(filename, ep[i]->filename, 16);
    filename[16] = '\0';
    pet2asc(filename);
    printf("%s\r\n", filename);
    uart_flush();
  }
  uart_putcrlf();

#define DIRNAV_OFFSET   2
#define NAV_ABORT       0
#define NAV_PARENT      1

  mp = stack_mp[pos_stack];
  my = stack_my[pos_stack];
  printf("mp set to %d\r\n", mp);
  if (mp < (LCD_LINES - 1))
    my = mp;
  else
    my = 0;
  action = false;

  for (i=0; i < MAX_LASTPOS; i++) {
    if (pos_stack == i) uart_putc('>');
    printf("%d ", stack_mp[i]);
  }
  uart_putcrlf();

  for (;;) {
    lcd_clear();
    for (i = 0; i < LCD_LINES; i++) {
      lcd_locate(0, i);
      int8_t y = mp - my + i;
      if (y < 0) return; // should not happen!
      if (y < DIRNAV_OFFSET) {
        rom_menu_browse(y);
      } else {
        y -= DIRNAV_OFFSET;
        if (y >= entries) {
          lcd_puts_P(PSTR("-- End of dir --"));
          break;
        } else {
          lcd_print_dir_entry(y);
        }
      }
    }

    lcd_cursor(true);
    for (;;) {
      lcd_locate(0, my);
      //printf("mp: %u   my: %u\r\n", mp, my);
      //while (!get_key_state(KEY_ANY));
      if (get_key_autorepeat(KEY_PREV)) {
        if (mp > 0) {
          --mp;
          if (my > 0) --my;
          else {
            my = LCD_LINES - 1;
            if (mp < LCD_LINES) {
              while ((mp - my) >= DIRNAV_OFFSET) {
                --my;
                // TODO: is this really necessary?
                uart_puts_P(PSTR("my fixed\r\n"));
              }
            }
            break;
          }
        } else {
          my = LCD_LINES - 2;
          mp = entries + DIRNAV_OFFSET - 1;
          break;
        }
      }
      if (get_key_autorepeat(KEY_NEXT)) {
        if (mp < (entries -1 + DIRNAV_OFFSET)) {
          ++mp;
          if (my < (LCD_LINES - 1))  ++my;
          else {
            my = 0;
            break;
          }
        } else {
          mp = 0;
          my = 0;
          break;
        }
      }
      if (get_key_press(KEY_SEL)) {
        action = true;
        break;
      }
    }
    lcd_cursor(false);
    if (!action) continue;
    if (mp == NAV_ABORT) goto cleanup;
    if (mp == NAV_PARENT) {
      uart_puts_P(PSTR("CD_\r\n"));
      ustrcpy_P(command_buffer, PSTR("CD_"));
      command_length = 3;
      parse_doscommand();
      clear_command_buffer();
      stack_mp[pos_stack] = 0;
      stack_my[pos_stack] = 0;
      if (pos_stack > 0) --pos_stack;
      printf("pos_stack set to %d\r\n", pos_stack);
      if (current_error != ERROR_OK) goto cleanup;
      goto reread;
    }
    if (ep[mp - DIRNAV_OFFSET]->flags & E_DIR ||
        ep[mp - DIRNAV_OFFSET]->flags & E_IMAGE)
    {
      clear_command_buffer();
      ustrcpy_P(command_buffer, PSTR("CD:"));
      ustrncpy(command_buffer + 3, ep[mp - DIRNAV_OFFSET]->filename, 16);
      command_length = ustrlen(command_buffer);
      parse_doscommand();
      clear_command_buffer();
      if (current_error != ERROR_OK) goto cleanup;
      if (pos_stack < MAX_LASTPOS) {
        stack_mp[pos_stack]   = mp;
        stack_my[pos_stack++] = my;
        printf("pos_stack set to %d\r\n", pos_stack);
      }
      goto reread;
    }
  }

reread:
  free_buffer(buf);

  buffer_t *p = buf_tbl;
  do {
    p->allocated = 0;
    p = p->pvt.buffer.next;
  } while (p != NULL);

  p = first_buf;
  if (p != NULL) do {
    p->allocated = 0;
    p = p->pvt.buffer.next;
  } while (p != NULL);

  set_busy_led(false); set_dirty_led(true);
  active_buffers = save_active_buffers;
  if (mp == NAV_ABORT) return;
  goto start;

cleanup:
  mp = NAV_ABORT;
  goto reread;
}
示例#27
0
/***************************************************************************//**
*
* uart_update - 从串口进行升级
*
* @param void
*
* @retval true  成功
* @retval false 失败
*
*******************************************************************************/
STATUS uart_update(void)
{
    uint32 i, startAddress, transferSize = 0;
    uint8 size;
    uint8 status;
    uint8 cmd, data[MAX_BUF_SIZE];

    uart_printf("Press ESC to upgrade from serial port ");

    // 检测是否要从串口进行升级
    if (!escKeyDetect()) return (OK);

    uart_printf("Receiving data ..");

    // 过滤多余按键或串口切换产生的错误字节
    while (!packet_hello())
    {
    }

    startAddress = 0xffffffff;

    status = COMMAND_RET_SUCCESS;
    while (true)
    {
        // 如果未正确接收报文,放弃处理
        if (!packet_receive(&cmd, data, &size))
        {
            packet_nak();
            continue;
        }

        // 根据命令字进行处理
        switch(cmd)
        {
        case COMMAND_PING: // 测试连接
            status = COMMAND_RET_SUCCESS;

            // 返回确认包
            packet_ack();

            break;

        case COMMAND_DOWNLOAD: // 开始下载
            status = COMMAND_RET_SUCCESS;
            do
            {
                // 检查报文长度
                if (size != 8)
                {
                    status = COMMAND_RET_INVALID_CMD;

                    break;
                }

                // 起始地址
                startAddress = (data[0] << 24)
                               | (data[1] << 16)
                               | (data[2] <<  8)
                               |  data[3];
                /* 起始地址必须为0,由各BootLoader自行决定写入位置 */
                if (startAddress != 0u)
                {
                    status = COMMAND_RET_INVALID_CMD;
                    break;
                }
                startAddress = APP_START_ADDRESS;
                // 下载字节数
                transferSize = (data[4] << 24)
                               | (data[5] << 16)
                               | (data[6] <<  8)
                               |  data[7];

                // 检查写入空间
                if (!iflash_spaceCheck(startAddress, transferSize))
                {
                    status = COMMAND_RET_INVALID_PARA;

                    break;
                }

                // 清除中断状态
                iflash_errorClear();

                // 按块擦除将要更新的地址区间
                for (i = startAddress; i < startAddress + transferSize; i += FLASH_PAGE_SIZE)
                    iflash_erase(i);

                // 检查中断状态,如果出现错误,则设置对应状态
                if (iflash_errorCheck())
                    status = COMMAND_RET_FLASH_FAIL;
            }
            while(false);

            if (status != COMMAND_RET_SUCCESS)
                transferSize = 0;

            // 确认报文已得到处理
            packet_ack();

            break;

        case COMMAND_GET_STATUS: // 获取状态
            // 返回确认包
            packet_ack();

            // 返回当前状态
            packet_status(status);

            break;

        case COMMAND_SEND_DATA: // 数据
            status = COMMAND_RET_SUCCESS;

            // 注意:后台程序应保证size按字对齐,否则写入结果无法预料
            // 检查是否还有数据未写入
            if (transferSize >= size)
            {
                iflash_write(startAddress, data, size);
                if (iflash_errorCheck())
                    status = COMMAND_RET_FLASH_FAIL;
                else
                {
                    transferSize -= size;
                    startAddress += size;
                }
            }
            else status = COMMAND_RET_INVALID_PARA;

            // 返回确认包
            packet_ack();

            break;

        case COMMAND_RESET: // 复位
            // 返回确认包
            packet_ack();

            // 等待UART完成发送
            uart_flush();

            delay(524288);

            // 写入注册码及复位请求
            HWREG(NVIC_APINT) = (NVIC_APINT_VECTKEY | NVIC_APINT_SYSRESETREQ);

            // 死循环
            while(true)
            {
            }
        default: // 未知命令
            // 返回确认包
            packet_ack();

            // 状态设为未知命令
            status = COMMAND_RET_UNKNOWN_CMD;
        }
    }
}
示例#28
0
int main(void)
{
	ansi_init();
	uart_init();// Initialize UART Peripheral
	IntializeTimer();
  
	// Clear the Screen of the hyper terminal <send clear code>
  
	spi_init();// Initialize SPI

	w5100_init();// Initial the W5100 Ethernet
  
	if(S0_initialize_socket(MR_TCP,30000))
	{
		printf("INIT DONE 2\n");
		//S0_connect(dest_ip,dest_port);
	}	
	
	printf("%x\n",get_socket0_status());
	uart_putch('\0',&uart_str);
	uart_flush();
	
	host= http_extract_host(url);
	relativeAddress = http_extract_relativeAddress(url,strlen(host));
	request= http_create_request(method,relativeAddress,httpV,host);
	;//="GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nUser-Agent: Mozilla/5.0 (windows NT 6.1; wow64) Applewebkit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 safari/537.11\r\nAccept: text/html\r\nAccept-Encoding: gzip, deflate\r\n";
	//printf("%s",request);
	S0_connect(dest_ip,dest_port);
	
	if(get_socket0_status() == SOCK_ESTABLISHED)
	{
		printf("Connected\n");
		uart_putch('\0',&uart_str);
	}
	
  // Loop forever
  int loop = 1, counter = 0;
  //sei();
  while(loop)
  {
	  // keep reading the socket zero status
	  // and handle at least socket closed and socket established
	  
	uint8_t sockstat=get_socket0_status();

	switch(sockstat/*Handle all possible socket status here*/) 
	{
	case SOCK_CLOSED:
		//printf("ERROR1\n");
		//uart_putch('\0',&uart_str);
		//S0_connect(dest_ip,dest_port);
		printf("%x\n",get_socket0_status());
		uart_putch('\0',&uart_str);
		loop = 0;
		break;
	case SOCK_ESTABLISHED:
		printf("SOCK_ESTABLISHED\n");
		uart_putch('\0',&uart_str);
		// Get the client request size
		// And read the client Request in temp buffer
		// make sure the temp buffer is sending GET request
		S0_send((uint8_t*)request,strlen(request));
		printf("Request Sent\n");
		uart_putch('\0',&uart_str);
		uart_flush();
		_delay_ms(2000);
		if(S0_RX_getReceivedSize() != 0)
		{
			counter++;
			S0_recv(buf,S0_RX_getReceivedSize());
			printf("RECV Response\n");
			uart_putch('\0',&uart_str);
			printf("%s",(char*)buf);
			uart_putch('\0',&uart_str);
			//loop =0;
		}
		// create a buffer that will hold the response and send it
		// if the GET request has an option to turn on/off a LED Carry that now.
		// finally disconnect the socket with the client.
		break;
      case SOCK_FIN_WAIT:
      case SOCK_CLOSING:
      case SOCK_TIME_WAIT:
      case SOCK_CLOSE_WAIT:
      case SOCK_LAST_ACK:
		
		loop = 0;
		printf("Recevied %d\n",counter);
		uart_putch('\0',&uart_str);
		close(0);
		// force the socket to be closed
		break;
	//default:	
		//printf("nothing\n");	
	}		
  }
  return 0;
}
示例#29
0
文件: fl-gijoe.c 项目: j0ju/sd2iec
void load_gijoe(UNUSED_PARAMETER) {
  buffer_t *buf;

  set_data(1);
  set_clock(1);
  set_atn_irq(0);

  /* Wait until the bus has settled */
  delay_ms(10);
  while (!IEC_DATA || !IEC_CLOCK) ;

  while (1) {
    /* Handshake */
    set_clock(0);

    while (IEC_DATA)
      if (check_keys())
        return;

    set_clock(1);
    uart_flush();

    /* First byte is ignored */
    if (gijoe_read_byte() < 0)
      return;

    /* Read two file name characters */
    command_buffer[0] = gijoe_read_byte();
    command_buffer[1] = gijoe_read_byte();

    set_clock(0);

    command_buffer[2] = '*';
    command_buffer[3] = 0;
    command_length = 3;

    /* Open the file */
    file_open(0);
    uart_flush();
    buf = find_buffer(0);
    if (!buf) {
      set_clock(1);
      gijoe_send_byte(0xfe);
      gijoe_send_byte(0xfe);
      gijoe_send_byte(0xac);
      gijoe_send_byte(0xf7);
      continue;
    }

    /* file is open, transfer */
    while (1) {
      uint8_t i = buf->position;

      set_clock(1);
      delay_us(2);

      do {
        if (buf->data[i] == 0xac)
          gijoe_send_byte(0xac);

        gijoe_send_byte(buf->data[i]);
      } while (i++ < buf->lastused);

      /* Send end marker and wait for the next name */
      if (buf->sendeoi) {
        gijoe_send_byte(0xac);
        gijoe_send_byte(0xff);

        cleanup_and_free_buffer(buf);
        break;
      }

      /* Send "another sector following" marker */
      gijoe_send_byte(0xac);
      gijoe_send_byte(0xc3);
      delay_us(50);
      set_clock(0);

      /* Read next block */
      if (buf->refill(buf)) {
        /* Send error marker */
        gijoe_send_byte(0xfe);
        gijoe_send_byte(0xfe);
        gijoe_send_byte(0xac);
        gijoe_send_byte(0xf7);

        cleanup_and_free_buffer(buf);
        break;
      }
    }
  }
}
示例#30
0
void cmd_flush(void)
{
	uart_write( (uint8_t*)cmd_line, strlen(cmd_line) );
	uart_flush();
}