Пример #1
0
void USART0_IRQHandler(void)
{
	Chip_UART0_IRQRBHandler(LPC_USART0, &rxring, &txring);
	if (RingBuffer_IsEmpty(&txring)) {
		xSemaphoreGiveFromISR(sem_uart_ready, NULL);
	}
	if (!RingBuffer_IsEmpty(&rxring)) {
		xSemaphoreGiveFromISR(sem_uart_read_ready, NULL);
	}
}
Пример #2
0
/* Pop multiple items from Ring buffer */
int RingBuffer_PopMult(RINGBUFF_T *RingBuff, void *data, int num)
{
	uint8_t *ptr = RingBuff->data;
	int cnt1, cnt2;

	/* We cannot insert when queue is empty */
	if (RingBuffer_IsEmpty(RingBuff))
		return 0;

	/* Calculate the segment lengths */
	cnt1 = cnt2 = RingBuffer_GetCount(RingBuff);
	if (RB_INDT(RingBuff) + cnt1 >= RingBuff->count)
		cnt1 = RingBuff->count - RB_INDT(RingBuff);
	cnt2 -= cnt1;

	cnt1 = MIN(cnt1, num);
	num -= cnt1;

	cnt2 = MIN(cnt2, num);
	num -= cnt2;

	/* Write segment 1 */
	ptr += RB_INDT(RingBuff) * RingBuff->itemSz;
	memcpy(data, ptr, cnt1 * RingBuff->itemSz);
	RingBuff->tail += cnt1;

	/* Write segment 2 */
	ptr = (uint8_t *) RingBuff->data + RB_INDT(RingBuff) * RingBuff->itemSz;
	data = (uint8_t *) data + cnt1 * RingBuff->itemSz;
	memcpy(data, ptr, cnt2 * RingBuff->itemSz);
	RingBuff->tail += cnt2;

	return cnt1 + cnt2;
}
Пример #3
0
int main(void) {
    chip_startup_routine();

    configure_can_reads();
    statep = DSM_Init();
    set_state_machine_configs();

	while (1) {
		if (!RingBuffer_IsEmpty(&CAN_rx_buffer)) {
			CCAN_MSG_OBJ_T temp_msg;
			RingBuffer_Pop(&CAN_rx_buffer, &temp_msg);
			Board_UART_Print("Received Message ID: 0x");
			itoa(temp_msg.mode_id, str, 16);
			Board_UART_Println(str);
		}	
        
        read_input_requests(inputp);
        // MODE_REQUEST mode_request = get_mode_request(inputp);

        DI_ERROR step_error;
        // step_error = DSM_Step(inputp, statep, outputp, mode_request, msTicks);
        handle_error(step_error);

        demo_process_UART_commands(statep, uart_rx_buf, UART_RX_BUFFER_SIZE, msg_obj);

        check_CAN_error();
	}

    return 0;
}
Пример #4
0
/**
 * @details Timer interrupt to request A123 MBB information
 */
void TIMER32_1_IRQHandler(void) {
	Chip_TIMER_ClearMatch(LPC_TIMER32_1, 0);
	// Update Battery Status
	if (RingBuffer_IsEmpty(&rx_buffer)) {
		// Send BCM_CMD
		mbb_cmd.request_type = BCM_REQUEST_TYPE_STD;
		mbb_cmd.request_id = 5;
		mbb_cmd.balance = out_state.balance;
		mbb_cmd.balance_target_mVolts = out_state.balance_mVolts;

		can_msg_obj.msgobj = BCM_STD_MSG_OBJ;
		MBB_MakeCMD(&mbb_cmd, &can_msg_obj);
		LPC_CCAN_API->can_transmit(&can_msg_obj);	

		new_std_msg_sent = true;
		if (std_msg_send_count++ == 4) {
			std_msg_send_count = 0;

			mbb_cmd.request_type = BCM_REQUEST_TYPE_EXT;
			can_msg_obj.msgobj = BCM_EXT_MSG_OBJ;
			mbb_cmd.request_id = 6;
			MBB_MakeCMD(&mbb_cmd, &can_msg_obj);
			LPC_CCAN_API->can_transmit(&can_msg_obj);

		}
	}
}
Пример #5
0
void sendUSBtoUSART ()
{
	if (Serial_IsSendReady() && !(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
	{
		Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));
	}
}
Пример #6
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
    RingBuffer_InitBuffer(&ToUSB_Buffer, ToUSB_Buffer_Data, sizeof(ToUSB_Buffer_Data));

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	sei();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}
		
		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		cdc_send_USB_data(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
Пример #7
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	GlobalInterruptEnable();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}

		/* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
		uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if (BufferCount)
		{
			Endpoint_SelectEndpoint(VirtualSerial_CDC_Interface.Config.DataINEndpoint.Address);

			/* Check if a packet is already enqueued to the host - if so, we shouldn't try to send more data
			 * until it completes as there is a chance nothing is listening and a lengthy timeout could occur */
			if (Endpoint_IsINReady())
			{
				/* Never send more than one bank size less one byte to the host at a time, so that we don't block
				 * while a Zero Length Packet (ZLP) to terminate the transfer is sent if the host isn't listening */
				uint8_t BytesToSend = MIN(BufferCount, (CDC_TXRX_EPSIZE - 1));

				/* Read bytes from the USART receive buffer into the USB IN endpoint */
				while (BytesToSend--)
				{
					/* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
					if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
											RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
					{
						break;
					}

					/* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
					RingBuffer_Remove(&USARTtoUSB_Buffer);
				}
			}
		}

		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
int RingBuffer_Compare(RingBuffer *rb,void *element,int compareCount)
{
	int i = 0;
	int ret = 0;

	for(i = 0 ; i < compareCount ; i++)
	{
		if (!RingBuffer_IsEmpty(rb))
		{
			ret = memcmp((char *)element + rb->element_size*i, rb->buffer + rb->start * rb->element_size, rb->element_size);

			if(0 == ret)
			{
				rb->start = (rb->start + 1) % rb->size;
				--rb->count;
			}else{
				ret = 0;
			}

		}
		else
		{
			ret = -1;
		}
	}

	return 0;
}
Пример #9
0
void RingBuffer_PutByte(RingBuffer * buffer, uint8_t b)
{
    buffer->buf[buffer->iEnd] = b;
    buffer->iEnd = ((buffer->iEnd+1)%(RINGBUFFER_SIZE));

    if (RingBuffer_IsEmpty(buffer))
        buffer->iStart = ((buffer->iStart+1)%(RINGBUFFER_SIZE));
}
Пример #10
0
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));

	LEDs_SetAllLEDs(0);

	sei();

	for (;;)
	{
		if ((PINF & 0x01) == 0x01)
			LEDs_SetAllLEDs(2);
		else
			LEDs_SetAllLEDs(0);
		/* Only try to read in bytes from the CDC interface if the (outbound) transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}

		/* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
		uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if ((TIFR0 & (1 << TOV0)) || (BufferCount > (uint8_t)(sizeof(USARTtoUSB_Buffer_Data) * .75)))
		{
			/* Clear flush timer expiry flag */
			TIFR0 |= (1 << TOV0);

			/* Read bytes from the USART receive buffer into the USB IN endpoint */
			while (BufferCount--)
			{
				/* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
				if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
				                        RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
				{
					break;
				}

				/* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
				RingBuffer_Remove(&USARTtoUSB_Buffer);
			}
		}

		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
Пример #11
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer);
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer);

	sei();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}

		/* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
		RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if ((TIFR0 & (1 << TOV0)) || (BufferCount > BUFFER_NEARLY_FULL))
		{
			TIFR0 |= (1 << TOV0);

			if (USARTtoUSB_Buffer.Count) {
				LEDs_TurnOnLEDs(LEDMASK_TX);
				PulseMSRemaining.TxLEDPulse = TX_RX_LED_PULSE_MS;
			}

			/* Read bytes from the USART receive buffer into the USB IN endpoint */
			while (BufferCount--)
			  CDC_Device_SendByte(&VirtualSerial_CDC_Interface, RingBuffer_Remove(&USARTtoUSB_Buffer));

			/* Turn off TX LED(s) once the TX pulse period has elapsed */
			if (PulseMSRemaining.TxLEDPulse && !(--PulseMSRemaining.TxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_TX);

			/* Turn off RX LED(s) once the RX pulse period has elapsed */
			if (PulseMSRemaining.RxLEDPulse && !(--PulseMSRemaining.RxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_RX);
		}

		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer))) {
		  Serial_TxByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		  	LEDs_TurnOnLEDs(LEDMASK_RX);
			PulseMSRemaining.RxLEDPulse = TX_RX_LED_PULSE_MS;
		}

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
Пример #12
0
uint8_t RingBuffer_GetByte(RingBuffer * buffer)
{
    uint8_t ret = 0;

    if (RingBuffer_IsEmpty(buffer)) return 0;

    ret = buffer->buf[buffer->iStart];
    buffer->iStart = ((buffer->iStart+1)%(RINGBUFFER_SIZE));

    return ret;
}
Пример #13
0
/**
 * Sends data
 */
void Bluetooth_Connection_Handler::_send_data(){

	//! New values?
	if(!RingBuffer_IsEmpty(this->_buff)){

		//! We process the data to be sent
		Data_Processor::create_data_packet(SENSOR_TYPE, SENSOR_ID, this->_buff, &this->_packet._data);
	}

	//! We send them
	this->write((void*)&this->_packet._data, sizeof(this->_packet._data));
}
Пример #14
0
int RingBuffer_Pop(RINGBUFF_T *RingBuff, void *data) {
	uint8_t *ptr = RingBuff->data;

	/* We cannot pop when queue is empty */
	if (RingBuffer_IsEmpty(RingBuff))
		return 0;

	ptr += RB_INDT(RingBuff) * RingBuff->itemSz;
	memcpy(data, ptr, RingBuff->itemSz);
	RingBuff->tail++;

	return 1;
}
Пример #15
0
// Read the dial commands and send them to the modem. Wait for the expected response then move on to the next command.
// Returns true if the last dial command has been processed.
static bool LinkManagement_DialConnection(const char** DialCommands)
{
	static char* ResponsePtr = NULL;
	char* CommandPtr = NULL;
	static uint8_t CharsMatched = 0;
	char c;

	if (USB_HostState != HOST_STATE_Configured)	
		return false;

	while (!RingBuffer_IsEmpty(&Modem_ReceiveBuffer))						    // Read back the response
	{	
		c = RingBuffer_Remove(&Modem_ReceiveBuffer);
		Debug_PrintChar(c);
		
		if (c == *(ResponsePtr + CharsMatched))									// Match the response character by character with the expected response						
			CharsMatched++;
		else
			CharsMatched = 0;
			
		if (CharsMatched != 0 && CharsMatched == strlen(ResponsePtr))			// Look for the expected response
		{
			DialSteps += 2;														// Move on to the next dial command
			CharsMatched = 0;
		}
	}	
		
	if (SystemTicks > 100)														// Space each command by 1 second
	{
		CommandPtr = (char*)DialCommands[DialSteps];
		ResponsePtr = (char*)DialCommands[DialSteps + 1];

		if (CommandPtr == NULL || ResponsePtr == NULL)							// No more dial commands
		{
			DialSteps = 0;
			return true;														// Finished dialling
		}

		SystemTicks = 0;

		Debug_Print("Send: "); Debug_Print(CommandPtr);
		Debug_Print("(Expect: "); Debug_Print(ResponsePtr); Debug_Print(")\r\n");
				
		while (*CommandPtr)														
			RingBuffer_Insert(&Modem_SendBuffer, *(CommandPtr++));			// Send the command	to the modem
	}

	return false;																// Haven't finished dialling
}
Пример #16
0
/* UART receive/transmit interrupt handler for ring buffers */
void Chip_UART_IRQRBHandler(LPC_USART_T *pUART, RINGBUFF_T *pRXRB, RINGBUFF_T *pTXRB)
{
	/* Handle transmit interrupt if enabled */
	if ((Chip_UART_GetStatus(pUART) & UART_STAT_TXRDY) != 0) {
		Chip_UART_TXIntHandlerRB(pUART, pTXRB);

		/* Disable transmit interrupt if the ring buffer is empty */
		if (RingBuffer_IsEmpty(pTXRB)) {
			Chip_UART_IntDisable(pUART, UART_INTEN_TXRDY);
		}
	}

	/* Handle receive interrupt */
	Chip_UART_RXIntHandlerRB(pUART, pRXRB);
}
Пример #17
0
/* UART receive/transmit interrupt handler for ring buffers */
void Chip_UART_IRQRBHandler(LPC_USART_T *pUART, RINGBUFF_T *pRXRB, RINGBUFF_T *pTXRB)
{
	/* Handle transmit interrupt if enabled */
	if (pUART->IER & UART_IER_THREINT) {
		Chip_UART_TXIntHandlerRB(pUART, pTXRB);

		/* Disable transmit interrupt if the ring buffer is empty */
		if (RingBuffer_IsEmpty(pTXRB)) {
			Chip_UART_IntDisable(pUART, UART_IER_THREINT);
		}
	}

	/* Handle receive interrupt */
	Chip_UART_RXIntHandlerRB(pUART, pRXRB);
}
Пример #18
0
/* Pop a 8-bit value from the ring buffer */
bool RingBuffer_Pop8(RINGBUFF_T *RingBuff, uint8_t *data8)
{
	bool empty = RingBuffer_IsEmpty(RingBuff);

	if (!empty) {
		*data8 = *RingBuff->bufferOut;
		RingBuff->used--;
		RingBuff->bufferOut++;
		if (RingBuff->bufferOut >= RingBuff->bufferLast) {
			RingBuff->bufferOut = RingBuff->bufferBase;
		}
	}

	return (bool) !empty;
}
Пример #19
0
/* Pop a 32-bit value from the ring buffer */
bool RingBuffer_Pop32(RINGBUFF_T *RingBuff, uint32_t *data32)
{
	bool empty = RingBuffer_IsEmpty(RingBuff);

	if (!empty) {
		uint32_t *buff32 = (uint32_t *) RingBuff->bufferOut;
		*data32 = *buff32;
		RingBuff->used--;
		data32++;
		RingBuff->bufferOut = (uint8_t *) data32;
		if (RingBuff->bufferOut >= RingBuff->bufferLast) {
			RingBuff->bufferOut = RingBuff->bufferBase;
		}
	}

	return (bool) !empty;
}
Пример #20
0
/* Pop a 16-bit value from the ring buffer */
bool RingBuffer_Pop16(RINGBUFF_T *RingBuff, uint16_t *data16)
{
	bool empty = RingBuffer_IsEmpty(RingBuff);

	if (!empty) {
		uint16_t *buff16 = (uint16_t *) RingBuff->bufferOut;
		*data16 = *buff16;
		RingBuff->used--;
		buff16++;
		RingBuff->bufferOut = (uint8_t *) buff16;
		if (RingBuff->bufferOut >= RingBuff->bufferLast) {
			RingBuff->bufferOut = RingBuff->bufferBase;
		}
	}

	return (bool) !empty;
}
Пример #21
0
void mood(void)
{
	static uint8_t command;
	static uint16_t i=0;
	static uint16_t r=MAXPWM,g=MAXPWM/2,b=MAXPWM/42;
	static uint16_t r_dir=R_SPEED, g_dir=G_SPEED, b_dir=B_SPEED;
	static bool loop=true;

	command=' ';	// default command: none

	/* Load the next command byte from the USB to USART transmit buffer */
	if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  command=RingBuffer_Remove(&USBtoUSART_Buffer);
	switch (command) {
		case 'r': if (r >=1000) r-=1000; break;
		case 'R': if (r <= MAXPWM-1000) r+=1000; break;
		case 'g': if (g >=1000) g-=1000; break;
		case 'G': if (g <= MAXPWM-1000) g+=1000; break;
		case 'b': if (b >=1000) b-=1000; break;
		case 'B': if (b <= MAXPWM-1000) b+=1000; break;
		case 'h': loop=true; helloworld(); break;
		case '#': loop=setcmd(&r,&g,&b); break;
		case 'm': loop=true;
		default:
			if (++i > DELAY) {
				if(loop) {
					if (r >= (MAXPWM - R_SPEED)) r_dir = -R_SPEED;
					if (r <= R_SPEED) r_dir = R_SPEED;
					if (g >= (MAXPWM - G_SPEED)) g_dir = -G_SPEED;
					if (g <= G_SPEED) g_dir = G_SPEED;
					if (b >= (MAXPWM - B_SPEED)) b_dir = -B_SPEED;
					if (b <= B_SPEED) b_dir = B_SPEED;
					r += r_dir; g += g_dir; b += b_dir;
				}
				setcolor(r,g,b);
				//if (lowvoltage()) {	// red light and stop
				//	setcolor(MAXPWM,0,0);
				//	for(;;);
				//}
				i=0;
			}
	}
}
Пример #22
0
/**
 * Reads as much as possible from the USART buffer
 * Guarantees reading at least one byte. If none present, blocks until at least one byte is received.
 */
size_t uart0_read(char* buf, size_t size) {
	xSemaphoreTake(mutex_uart_read_in_use, portMAX_DELAY);

	uint32_t read = 0;

	while (read == 0) {
		read += Chip_UART0_ReadRB(LPC_USART0, &rxring, buf, size);
		size -= read;
		buf += read;

		// Nothing read, wait
		if (RingBuffer_IsEmpty(&rxring) && xTaskGetSchedulerState() == taskSCHEDULER_RUNNING) {
			xSemaphoreTake(sem_uart_read_ready, portMAX_DELAY);
		}
	}

	xSemaphoreGive(mutex_uart_read_in_use);
	return read;
}
Пример #23
0
/**
 * This method is used when the request connection type is used.
 *
 * @param command						- The issued command
 */
void ConnectionProtocolHandler::request(uint8_t command, void* object){

	//! Cast the object
	ConnectionProtocolHandler* access = (ConnectionProtocolHandler*) object;

	//! Container
	buffer_t* buff;

	if(!RingBuffer_IsEmpty(access->_buffer)){

		//! We process the data to be sent
		buff = Data_Processor::process_data(access->_buffer, &access->_buff);
	}else{

		//! We get the last values processed
		buff = Data_Processor::get_last_values(&access->_buff);
	}

	//! We send them
	access->_serial->write(buff->data, buff->length);
}
Пример #24
0
static void s2e_sockinit_process(uint8_t sock)
{
	struct __network_info *net = (struct __network_info *)get_S2E_Packet_pointer()->network_info;
	uint8_t remote_ip[4];

	memcpy(remote_ip, net->remote_ip, sizeof(remote_ip));

	switch(net->working_mode) {
		case TCP_CLIENT_MODE:
			if(!reconn_flag) {
				connect(sock, remote_ip, net->remote_port);
				reconn_flag = 1;
			}

			break;

		case TCP_SERVER_MODE:
			listen(sock);
			break;
		case TCP_MIXED_MODE:
			if(RingBuffer_IsEmpty(&rxring)) {
				listen(sock);
				mixed_state = MIXED_SERVER;
			} else {
				if(!reconn_flag) {
					connect(sock, remote_ip, net->remote_port);
					reconn_flag = 1;
				}
				mixed_state = MIXED_CLIENT;
			}
			break;

		case UDP_MODE:
			close(sock);
			break;

		default:
			break;
	}
}
Пример #25
0
static void s2e_socklisten_process(uint8_t sock)
{
	struct __network_info *net = (struct __network_info *)get_S2E_Packet_pointer()->network_info;

	switch(net->working_mode) {
		case TCP_CLIENT_MODE:
			close(sock);
			break;

		case TCP_SERVER_MODE:
			break;

		case TCP_MIXED_MODE:
			if(!RingBuffer_IsEmpty(&rxring))
				close(sock);
			break;
		case UDP_MODE:
			close(sock);
			break;

		default:
			break;
	}
}
int RingBuffer_Get(RingBuffer *rb, void *element)
{
	int retval;

#ifdef RING_BUFFER_THREAD_SAFE
	VOS_SmP(rb->sem, 50);
#endif
	if (!RingBuffer_IsEmpty(rb))
	{
		memcpy(element, rb->buffer + rb->start * rb->element_size, rb->element_size);
		rb->start = (rb->start + 1) % rb->size;
		--rb->count;
		retval = 320;
	}
	else
	{
		retval = 0;
	}
#ifdef RING_BUFFER_THREAD_SAFE
	VOS_SmV(rb->sem);
#endif

	return retval;
}
Пример #27
0
int main(void)
{

	//---------------
	// Initialize SysTick Timer to generate millisecond count
	if (Board_SysTick_Init()) {
		// Unrecoverable Error. Hang.
		while(1);
	}

	//---------------
	// Initialize GPIO and LED as output
	Board_LEDs_Init();
	Board_LED_On(LED0);
	Board_LED_On(LED1);
	Board_LED_On(LED2);
	Board_LED_On(LED3);

	//Initialize I2C
	Board_I2C_Init();

	//---------------
	// Initialize UART Communication
	Board_UART_Init(UART_BAUD_RATE);
	Board_UART_Println("Started up");

	//---------------
	// Initialize CAN  and CAN Ring Buffer

	RingBuffer_Init(&can_rx_buffer, _rx_buffer, sizeof(CCAN_MSG_OBJ_T), BUFFER_SIZE);
	RingBuffer_Flush(&can_rx_buffer);

	Board_CAN_Init(CCAN_BAUD_RATE, CAN_rx, CAN_tx, CAN_error);

	// For your convenience.
	// typedef struct CCAN_MSG_OBJ {
	// 	uint32_t  mode_id;
	// 	uint32_t  mask;
	// 	uint8_t   data[8];
	// 	uint8_t   dlc;
	// 	uint8_t   msgobj;
	// } CCAN_MSG_OBJ_T;

	/* [Tutorial] How do filters work?

		Incoming ID & Mask == Mode_ID for msgobj to accept message

		Incoming ID : 0xabc
		Mask: 		  0xF0F &
		            -----------
		              0xa0c

		mode_id == 0xa0c for msgobj to accept message

	*/

	//Set mask to only accept messages from Driver Interface
	msg_obj.msgobj = 1;
	msg_obj.mode_id = DI_PACKET__id;
	msg_obj.mask = 0x555;
	LPC_CCAN_API->config_rxmsgobj(&msg_obj);

	can_error_flag = false;
	can_error_info = 0;
	
	lastPrint = msTicks;	

	PDM_STATUS_T pdm_status;
	
	int tmp;
	bool lv_i2c = true, cs_i2c = true, mux_i2c = true;

	//Board_I2C_Reset(I2C_GG_CONTINUOUS, i2c_tx_buffer);

	//Open I2C Channel 0
	i2c_tx_buffer[0] = I2C_MUX_CHANNEL_0;
	tmp = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_MUX_SLAVE_ADDRESS, i2c_tx_buffer, 1);
	Board_UART_Print("Opened Channel 0: ");
	Board_UART_PrintNum(tmp, 10, true);

	//Set Gas Gauge 0 to continuous data collection
	i2c_tx_buffer[0] = I2C_GG_CTRL_REG;
	i2c_tx_buffer[1] = I2C_GG_CONTINUOUS;
	tmp = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_GG_SLAVE_ADDRESS, i2c_tx_buffer, 2);
	Board_UART_Print("Set I2C0 to continuous data collection: ");
	Board_UART_PrintNum(tmp, 10, true);

	//Open I2C Channel 1
	i2c_tx_buffer[0] = I2C_MUX_CHANNEL_1;
	tmp = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_MUX_SLAVE_ADDRESS, i2c_tx_buffer, 1);
	Board_UART_Print("Opened Channel 1: ");
	Board_UART_PrintNum(tmp, 10, true);

	//Set Gas Gauge 1 to continuous data collection
	i2c_tx_buffer[0] = I2C_GG_CTRL_REG;
	i2c_tx_buffer[1] = I2C_GG_CONTINUOUS;
	tmp = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_GG_SLAVE_ADDRESS, i2c_tx_buffer, 2);
	Board_UART_Print("Set I2C1 to continuous data collection: ");
	Board_UART_PrintNum(tmp, 10, true);

	

	while (1) {
		
		//Set PDM status based on CAN messages from Driver Interface
		if (!RingBuffer_IsEmpty(&can_rx_buffer)) {					
			CCAN_MSG_OBJ_T temp_msg;
			RingBuffer_Pop(&can_rx_buffer, &temp_msg);
			//Test for DI OFF or SHUTDOWN IMPENDING message
			if((temp_msg.data[3] << 8 | temp_msg.data[2]) == ____DI_PACKET__DRIVE_STATUS__SHUTDOWN_IMPENDING ||	
					(temp_msg.data[3] << 8 | temp_msg.data[2]) == ____DI_PACKET__DRIVE_STATUS__OFF) {	
				if(pdm_status.pdm_on) {							
					pdm_status.pdm_on = false;
					Board_LED_Off(LED0);
					Board_I2C_Reset(I2C_GG_SLEEP, i2c_tx_buffer);
				}
			}
			else {
				if(!(pdm_status.pdm_on)) {
					pdm_status.pdm_on = true;
					Board_LED_On(LED0);
					Board_I2C_Reset(I2C_GG_CONTINUOUS, i2c_tx_buffer);
				}
			}
		}
		

		//Reset gas gauge 0 if it has been diconnected and then reconnected to power
		i2c_tx_buffer[0] = I2C_MUX_CHANNEL_0;
		tmp = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_MUX_SLAVE_ADDRESS, i2c_tx_buffer, 1);	//Open I2C Channel 0
		tmp = Chip_I2C_MasterCmdRead(DEFAULT_I2C, I2C_GG_SLAVE_ADDRESS, I2C_GG_CTRL_REG, i2c_rx_buffer, 1);	
		Board_UART_PrintNum(i2c_rx_buffer[0],16,true);
		if((uint16_t)i2c_rx_buffer[0] == I2C_GG_DEFAULT) {					//Test for default values in control register
			if(pdm_status.pdm_on) {
				Board_I2C_Reset(I2C_GG_CONTINUOUS, i2c_tx_buffer);
			}
			else {
				Board_I2C_Reset(I2C_GG_SLEEP, i2c_tx_buffer);
			}
			//Send a heartbeat with a com error
			Board_CAN_SendHeartbeat(&pdm_status, &msg_obj, true);
		}

			
		//Reset gas gauge 1 if it has been diconnected and then reconnected to power	
		i2c_tx_buffer[0] = I2C_MUX_CHANNEL_1;
		tmp = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_MUX_SLAVE_ADDRESS, i2c_tx_buffer, 1);	//Open 12C Channel 1
		tmp = Chip_I2C_MasterCmdRead(DEFAULT_I2C, I2C_GG_SLAVE_ADDRESS, I2C_MUX_CHANNEL_0, i2c_rx_buffer, 1);
		Board_UART_PrintNum(i2c_rx_buffer[0],16,true);
		if((uint16_t)i2c_rx_buffer[0] == I2C_GG_DEFAULT) {					//Test for default values in control register
			if(pdm_status.pdm_on) {
				Board_I2C_Reset(I2C_GG_CONTINUOUS, i2c_tx_buffer);
			}
			else {
				Board_I2C_Reset(I2C_GG_SLEEP, i2c_tx_buffer);
			}
			//Send a heartbeat with a com error
			Board_CAN_SendHeartbeat(&pdm_status, &msg_obj, true);
		}


		/* Update PDM and Debug LED code */

		//Attempt to open I2C Channel 0
		i2c_tx_buffer[0] = I2C_MUX_CHANNEL_0;
		mux_i2c = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_MUX_SLAVE_ADDRESS, i2c_tx_buffer, 1);	
		//Attempt to update Critical Systems PDM Struct
		cs_i2c = Board_PDM_Status_Update(&pdm_status, i2c_rx_buffer, true);			
		//Attempt to open I2C Channel 1
		i2c_tx_buffer[0] = I2C_MUX_CHANNEL_1;
		mux_i2c = Chip_I2C_MasterSend(DEFAULT_I2C, I2C_MUX_SLAVE_ADDRESS, i2c_tx_buffer, 1);	
		//Attempt to update Low Voltage PDM struct
		lv_i2c = Board_PDM_Status_Update(&pdm_status, i2c_rx_buffer, false);			
		//Run debug logic and update state
		Board_PDM_Status_Debug(&pdm_status, mux_i2c, cs_i2c, lv_i2c);

		if(msTicks - lastPrint > FREQ_THRESHOLD){				// 10 times per second
			lastPrint = msTicks;				// Store the current time, to allow the process to be done in another 1/10 seconds
			
			Board_CAN_SendHeartbeat(&pdm_status, &msg_obj, false);
		}
	}
}
Пример #28
0
uint16_t network_read(void)
{
	uint8_t c;
	
	while (!RingBuffer_IsEmpty(&Modem_ReceiveBuffer))
	{
		c = RingBuffer_Remove(&Modem_ReceiveBuffer);

		switch (PacketState)
		{
			case PACKET_STATE_NULL:
				if (c == 0x7e)												// New Packet
				{
					PacketState = PACKET_STATE_INHEADER;					// We're now in the header
					PacketLength = 0;
					CurrentChecksum = 0xffff;								// Start new checksum
				}
			break;

			case PACKET_STATE_INHEADER:
				if (c == 0x7d)												// Escaped character. Set flag and process next time around
				{
					Escape = true;
					continue;
				}
				else if (Escape)											// Escaped character. Process now.
				{
					Escape = false;
					c = (c ^ 0x20);
				}
				
				if (PacketLength == 1 && c != 0xff)							// Should be 0xff. If not then Address-and-Control-Field-Compression is switched on
				{
					PacketLength += 2;										// Adjust the length as if the 0xff 0x03 was there
				}		

				if (PacketLength == 3)
				{
					if (c & 1)												// Should be even. If it's odd then Protocol-Field-Compression is switched on
					{
						PacketProtocol = 0x00;								// Add in the initial 0x00
						PacketLength++;										// Adjust the length as if the 0x00 was there
					}
					else
						PacketProtocol = c * 256;							// Store the MSB of the protocol
				}

				if (PacketLength == 4)										// End of header
				{														
					PacketProtocol |= c;									// Store the LSB of the protocol
					PacketLength = -1;										// This will be incremented to 0 at the end of this loop
					Escape = false;
					PacketState = PACKET_STATE_INBODY;						// We're now in the body
				}

				CurrentChecksum = CALC_CRC16(CurrentChecksum, c);			// Calculate checksum
			break;

			case PACKET_STATE_INBODY:
				if (c == 0x7e)												// End of packet
				{
					uip_len = PacketLength - 2;								// Strip off the checksum and framing
					Escape = false;
					PacketState = PACKET_STATE_NULL;						// Back to waiting for a header

					Debug_Print("\r\nReceive ");
					DumpPacket();

					if (~TwoBackChecksum == (*(uip_buf + PacketLength - 1) * 256 + *(uip_buf + PacketLength - 2)))
						return PacketProtocol;
					else
						Debug_Print("Bad CRC\r\n");
				}
				else
				{	
					if (c == 0x7d)											// Escaped character. Set flag and process next time around
					{
						Escape = true;
						continue;
					}
					else if (Escape)										// Escaped character. Process now.
					{
						Escape = false;
						c = (c ^ 0x20);
					}
					
					*(uip_buf + PacketLength) = c;							// Store the character in the buffer

					TwoBackChecksum = OneBackChecksum;						// Keep a rolling count of the last 3 checksums
					OneBackChecksum = CurrentChecksum;						// Eventually we need to see if the checksum is valid
					CurrentChecksum = CALC_CRC16(CurrentChecksum, c);		// and we need the one two back (as the current one includes the checksum itself)
				}
			break;
		}
		
		PacketLength++;														// Increment the length of the received packet
	}

	return 0;																// No data or packet not complete yet 
}
Пример #29
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();
	
	RingBuffer_InitBuffer(&USBtoUSART_Buffer);
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer);

    setupEeprom();

	sei();


	for (;;)
	{

		// Only try to read in bytes from the CDC interface if the transmit buffer is not full
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			// Read bytes from the USB OUT endpoint into the USART transmit buffer
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}
		
		// Check if the UART receive buffer flush timer has expired or the buffer is nearly full
		RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if ((TIFR0 & (1 << TOV0)) || (BufferCount > BUFFER_NEARLY_FULL))
		{
			TIFR0 |= (1 << TOV0);

			if (USARTtoUSB_Buffer.Count) {
				LEDs_TurnOnLEDs(LEDMASK_TX);
				PulseMSRemaining.TxLEDPulse = TX_RX_LED_PULSE_MS;
			}

			// Read bytes from the USART receive buffer into the USB IN endpoint
			while (BufferCount--)
			  CDC_Device_SendByte(&VirtualSerial_CDC_Interface, RingBuffer_Remove(&USARTtoUSB_Buffer));
			  
			// Turn off TX LED(s) once the TX pulse period has elapsed
			if (PulseMSRemaining.TxLEDPulse && !(--PulseMSRemaining.TxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_TX);

			// Turn off RX LED(s) once the RX pulse period has elapsed
			if (PulseMSRemaining.RxLEDPulse && !(--PulseMSRemaining.RxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_RX);

			if (ResetTimer > 0)
			{
				// SAM3X RESET/ERASE Sequence
				// --------------------------
				if (ResetTimer == 95) {
                    eepromInterruptDisable();
					setErasePin(true);
					setResetPin(false);
				}
				if (ResetTimer == 35) {
                    eepromInterruptDisable();
					setErasePin(false);
					setResetPin(false);
				}
				if (ResetTimer == 25) {
                    eepromInterruptDisable();
					setErasePin(false);
					setResetPin(true);
				}
				if (ResetTimer == 1) {
                    eepromInterruptDisable();
					setErasePin(false);
					setResetPin(false);
				}
				ResetTimer--;
			} else {
				setErasePin(false);
				setResetPin(false);
                eepromInterruptEnable();
			}
		}
		
		// Load the next byte from the USART transmit buffer into the USART
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer))) {
			Serial_TxByte(RingBuffer_Remove(&USBtoUSART_Buffer));
			LEDs_TurnOnLEDs(LEDMASK_RX);
			PulseMSRemaining.RxLEDPulse = TX_RX_LED_PULSE_MS;
		}

        // CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
        // USB_USBTask();
        serviceEepromRequest();
		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}

}
Пример #30
0
int main(void)
{

	//---------------
	// Initialize UART Communication
	Board_UART_Init(UART_BAUD_RATE);
	Board_UART_Println("Started up");

	//---------------
	// Initialize SysTick Timer to generate millisecond count
	if (Board_SysTick_Init()) {
		Board_UART_Println("Failed to Initialize SysTick. ");
		// Unrecoverable Error. Hang.
		while(1);
	}

	//---------------
	// Initialize GPIO and LED as output
	Board_LEDs_Init();
	Board_LED_On(LED0);

	//---------------
	// Initialize CAN  and CAN Ring Buffer

	RingBuffer_Init(&can_rx_buffer, _rx_buffer, sizeof(CCAN_MSG_OBJ_T), BUFFER_SIZE);
	RingBuffer_Flush(&can_rx_buffer);

	Board_CAN_Init(CCAN_BAUD_RATE, CAN_rx, CAN_tx, CAN_error);

	// For your convenience.
	// typedef struct CCAN_MSG_OBJ {
	// 	uint32_t  mode_id;
	// 	uint32_t  mask;
	// 	uint8_t   data[8];
	// 	uint8_t   dlc;
	// 	uint8_t   msgobj;
	// } CCAN_MSG_OBJ_T;

	msg_obj.msgobj = 1;
	msg_obj.mode_id = 0x000;
	msg_obj.mask = 0x000;
	LPC_CCAN_API->config_rxmsgobj(&msg_obj);

	can_error_flag = false;
	can_error_info = 0;

	uint8_t status_led_state = 1;
	uint32_t status_led_time = msTicks;

	while (1) {
		if (!RingBuffer_IsEmpty(&can_rx_buffer)) {
			Board_LED_On(LED3);
			CCAN_MSG_OBJ_T temp_msg;
			RingBuffer_Pop(&can_rx_buffer, &temp_msg);
			Board_UART_PrintNum(temp_msg.mode_id, 16, false);
			Board_UART_Print("\t");
			Board_UART_PrintNum(temp_msg.dlc, 10, false);

			int i = 0;
			for (i = 0; i < temp_msg.dlc; i++) {
				Board_UART_Print("\t");
				Board_UART_PrintNum(temp_msg.data[i], 16, false);
			}

			Board_UART_Println("");
			Board_LED_Off(LED3);
		}	

		if (can_error_flag) {
			can_error_flag = false;
			Board_UART_Print("CAN Error: 0b");
			Board_UART_PrintNum(can_error_info, 2, true);
		}

		if (msTicks - status_led_time > STATUS_LED_PERIOD) {
			status_led_time = msTicks;
			status_led_state = 1 - status_led_state;
			Board_LED_Set(LED0, status_led_state);
		}
	}
}