Genişleyen buffer algoritması

Başlatan yldzelektronik, 25 Ocak 2017, 09:41:51

yldzelektronik

Merhaba,

Şöyle bir sorunum var.Nasıl çözeceğimi bilemedim.

Birbirini çağıran class'lar var.Programı C++ ile yazdım (Birebir kopyalayıp editleyip kısımlar da var).

En altta RingBuffer için bir class var. Usart classı var.Bu class içinde TxRb ve RxRb eleman oluşturdum.Bunlar public.Bu arada yeri gelmişken söyleyeyim. İsimlendirmeler saçma olabilir.Bu konuda da eleştiri bekliyorum.

Rs485 classı GenericDriver diye bir class var.Onu kalıt alıyor. Ayrıca
RS485(UsartPHY &usart, GPIO_TypeDef *TrancieverPort, uint32_t TrancieverPin);
tanımıyla referans olarak UsartPHY classını alıyor.

Buradan sonra işler biraz farklılaşıyor.Arada  bir GenericDriver var.Daha üst katmanların hangi haberleşme alt yapısını kullanacağını bilmesine gerek kalmaması için arada GenericDriver var. Methodları  hep virtual.

Bunun üstünde verinin adresleme işini yapan Datagram class var. Bu class
Datagram(GenericDriver& driver, uint8_t thisAddress = 0);
tanımıyla GenericDriver classını referans alıyor.

Bunun bir üstünde ise bir class daha var.Burada işler biraz özelleştiği için onu şimdilik veremiyorum.Zaten düzenlemeyi de bitirmedim henüz.

Şimdi hiyerarşi şöyle;

Veri göndermek istediğimde;

Henüz bitirmediğim class.sendtoWait(uint8_t_dataBuf, destAddr,PLlen,CMD, bir kaç veri daha) -> Datagram.sendto(uint8_t_dataBuf, bir kaç veri daha) -> GenericDriver üzerinden RS485.send(uint8_t_dataBuf, crc, STX, ETX vs bir kaç byte daha) -> UsartPHY.write(gelen buffer adresi) -> RingBuffer.InserMulti(buffer, len);

Veri alırken de bunun tersini yapıyorum.UsartPHY RxRingbuffer verileri kendisi depoluyor zaten.Ben bir flag a bakıp, veriyi her seferinde parse edip doğru ise üstteki classa aktarıp true dönüyorum.

Şimdi burada sorun şu.Ben en üstten itibaren fonksiyonların içinde gelen veriye ekleme yapabilmek için ramden yeni buffer alanı talep ediyorum.Gönderip aldığım veriler firmware update modda 1kb boyutlara ulaşacağından (güncellemeyi 1kblık paketler halinde yapmayı düşünüyorum.64kb flash olan bir mcu için 64 pakette güncelleme tamamlanmış olacak.) alt alta 4 class varsa her bir metod içinde 1kb yerden 4 kb a kadar çıkıyor.Ha çağırımlardan geri döndüğümde aldığım alanları delete[] ile geri veriyorum.Ama burada sorun olarak gördüğüm ilk olarak alt katlara doğru indikçe, ayırdığım yer büyüyor.Ve ben bu büyümenin gereksiz ve verimsiz olduğunu düşünüyorum. Diğer konu, bu kadar ram kullanımı için keil da ayarlardan heap ve stack alanını büyütmek zorunda kalıyorum. Bu da bana riskli görünüyor.

Böyle bir uygulama için nasıl bir algoritma önerirsiniz? Bir de programcılığı geliştirebilmek adına neler önerirsiniz?Modüler programlama yapabilmek zevkli geldi.Bu konuyu RTOS ile nasıl birlikte götürebiliriz?

RingBuffer.cpp
#include "RingBuffer.hpp"
#include "string.h"

#define RB_INDH(rb)                ((rb)->head & ((rb)->count - 1))
#define RB_INDT(rb)                ((rb)->tail & ((rb)->count - 1))

#define MIN(X,Y) ( X < Y ? X : Y )

/**
 * @brief  			
 * @param 		
 * @retval	
 */
RingBuffer::RingBuffer(){
	head = tail = 0;
	count = 256;
	itemSize = 1;
	data = new uint8_t[count];
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
RingBuffer::RingBuffer(uint16_t buffer_size){
	head = tail = 0;
	count = buffer_size;
	itemSize = 1;
    data = new uint8_t[count];
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
void RingBuffer::Init(void){
	
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
bool rb_search(uint8_t *search_data, uint8_t *startaddr, uint16_t size){
//    uint8_t tail[3];
//    RxRingBuffer.PopMulti(tail, 2);

//	uint8_t *p = (uint8_t*)strstr((const char*)tail, (const char*)search_data) + 2;
//	if(p != 2){
//		startaddr = p;
//		return true;
//	}
//	else{
//		startaddr = NULL;
//		return false;
//	}
	return false;
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
uint8_t RingBuffer::Insert(uint8_t rcdata){
	uint8_t *p = data + RB_INDH(this) *  this->itemSize;
	//We cannot insert any data when queue is full
	if(isFull() == true)
		return 0;
	memcpy(p, &rcdata, 1);
	head++;
	
	return 1;
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
uint8_t RingBuffer::InsertMulti(uint8_t *buf, uint16_t size){
	uint8_t *ptr = data;
	uint16_t cnt1, cnt2;
	
	if(isFull() == true)
		return 0;
	
	cnt1 = cnt2 = GetFree();
	
	if(RB_INDH(this) + cnt1 >= count)
		cnt1 = count - RB_INDH(this);
	cnt2 -= cnt1;
	
	cnt1 = MIN(cnt1, size);
	size -= cnt1;
	
	cnt2 = MIN(cnt2, size);
	size -= cnt2;
	
	//Write segment 1
	ptr += RB_INDH(this) * itemSize;
	memcpy(ptr, buf, cnt1 * itemSize);
	head += cnt1;
	
	//Write segment 2
	ptr = data + RB_INDH(this) * itemSize;
	buf = buf + cnt1 * itemSize;
	memcpy(ptr, buf, cnt2 * itemSize);
	head += cnt2;
	
	return cnt1 + cnt2;
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
uint8_t RingBuffer::Pop(void){
	if(isEmpty())
		return 0;
	
	uint8_t val = data[RB_INDT(this) * itemSize];
	tail++;
	
	return val;
}
/**
 * @brief  			
 * @param 		
 * @retval	
 */
uint8_t RingBuffer::PopMulti(uint8_t *buf, uint16_t size){
	uint8_t *ptr = data;
	uint16_t cnt1, cnt2;
	
	if(isEmpty() == true)
		return 0;
	
	//Calculate segment lengths
	cnt1 = cnt2 = GetCount();
	if(RB_INDT(this) + cnt1 >= count)
		cnt1 = count - RB_INDT(this);
	cnt2 -= cnt1;
	
	cnt1 = MIN(cnt1, size);
	size -= cnt1;
	
	cnt2 = MIN(cnt2 , size);
	
	size -= cnt2;
	
	//Write segment 1
	ptr += RB_INDT(this) * itemSize;
	memcpy(buf, ptr, cnt1 * itemSize);
	tail += cnt1;
	
	//Write segment 2
	ptr = data + RB_INDT(this);
	buf = buf + cnt1 * itemSize;
	memcpy(buf, ptr, cnt2 * itemSize);
	tail += cnt2;
	
	return cnt1 + cnt2;
}
/**
 * @brief	Resets the ring buffer to empty
 * @param	RingBuff	: Pointer to ring buffer
 * @return	Nothing
 */
void RingBuffer::Flush(void)
{
	head = tail = 0;
}
/**
 * @brief	Return size the ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	Size of the ring buffer in bytes
 */
uint16_t RingBuffer::GetSize(void)
{
	return count;
}
/**
 * @brief	Return number of items in the ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	Number of items in the ring buffer
 */
uint16_t RingBuffer::GetCount(void)
{
	return head - tail;
}
/**
 * @brief	Return number of free items in the ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	Number of free items in the ring buffer
 */
uint16_t RingBuffer::GetFree(void)
{
	return count - GetCount();
}
/**
 * @brief	Return number of items in the ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	1 if the ring buffer is full, otherwise 0
 */
bool RingBuffer::isFull(void)
{
	if(GetCount() >= count)
		return true;
	else
		return false;
}

/**
 * @brief	Return empty status of ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	1 if the ring buffer is empty, otherwise 0
 */
bool RingBuffer::isEmpty(void)
{
	if(head == tail)
		return true;
	else
		return false;
}
/**
 * @brief	Return empty status of ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	1 if the ring buffer is empty, otherwise 0
 */
uint8_t* RingBuffer::bufferAddress(){
	return data;
}
/**
 * @brief	Return empty status of ring buffer
 * @param	RingBuff	: Pointer to ring buffer
 * @return	1 if the ring buffer is empty, otherwise 0
 */
uint8_t* RingBuffer::nextBufferAddress(){
	return &data[RB_INDT(this) * itemSize];
}


/************************************************End Of The File*************************************************/


RingBuffer.hpp
#ifndef __RINGBUFFER_CPP_H__
#define __RINGBUFFER_CPP_H__

#ifdef __cplusplus
 extern "C" {
#endif 

//#include "stddef.h"
//#include "stdint.h"
//#include "stdbool.h"
#include "stm32f10x.h"

//#define MAXIMUM_TX_RING_BUFFER_SIZE	1024
//#define MAXIMUM_RX_RING_BUFFER_SIZE	1024

/**
 * @def		RB_VHEAD(rb)
 * volatile typecasted head index
 */
#define RB_VHEAD(rb)              /*(*(volatile uint32_t *) &*/(rb).head)

/**
 * @def		RB_VTAIL(rb)
 * volatile typecasted tail index
 */
#define RB_VTAIL(rb)              /*(*(volatile uint32_t *) &*/(rb).tail)

class RingBuffer{

    public:
        /**
        * @brief  Constructer
        * @param 		
        * @retval	
        */
        RingBuffer();

        /**
        * @brief  Constructer
        * @param 		
        * @retval	
        */
        RingBuffer(uint16_t buffer_size = 1024);

        /**
        * @brief  			
        * @param 		
        * @retval	
        */
        bool Search(uint8_t *data, uint8_t *buf, uint16_t size);

        /**
        * @brief	Initialize ring buffer
        * @param	RingBuff	: Pointer to ring buffer to initialize
        * @param	buffer		: Pointer to buffer to associate with RingBuff
        * @param	itemSize	: Size of each buffer item size
        * @param	count		: Size of ring buffer
        * @note	Memory pointed by @a buffer must have correct alignment of
        * 			@a itemSize, and @a count must be a power of 2 and must at
        * 			least be 2 or greater.
        * @return	Nothing
        */
        void Init(void);

        /**
        * @brief	Insert a single item into ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @param	data		: pointer to item
        * @return	1 when successfully inserted,
        *			0 on error (Buffer not initialized using
        *			RingBuffer_Init() or attempted to insert
        *			when buffer is full)
        */
        uint8_t Insert(uint8_t data);

        /**
        * @brief	Insert an array of items into ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @param	data		: Pointer to first element of the item array
        * @param	num			: Number of items in the array
        * @return	number of items successfully inserted,
        *			0 on error (Buffer not initialized using
        *			RingBuffer_Init() or attempted to insert
        *			when buffer is full)
        */
        uint8_t InsertMulti(uint8_t *buf, uint16_t size);

        /**
        * @brief	Pop an item from the ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @param	data		: Pointer to memory where popped item be stored
        * @return	1 when item popped successfuly onto @a data,
        * 			0 When error (Buffer not initialized using
        * 			RingBuffer_Init() or attempted to pop item when
        * 			the buffer is empty)
        */
        uint8_t Pop(void);

        /**
        * @brief	Pop an array of items from the ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @param	data		: Pointer to memory where popped items be stored
        * @param	num			: Max number of items array @a data can hold
        * @return	Number of items popped onto @a data,
        * 			0 on error (Buffer not initialized using RingBuffer_Init()
        * 			or attempted to pop when the buffer is empty)
        */
        uint8_t PopMulti(uint8_t *buf, uint16_t size);

        /**
        * @brief	Resets the ring buffer to empty
        * @param	RingBuff	: Pointer to ring buffer
        * @return	Nothing
        */
        void Flush(void);

        /**
        * @brief	Return size the ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @return	Size of the ring buffer in bytes
        */
        uint16_t GetSize(void);
				
        /**
        * @brief	Return number of items in the ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @return	Number of items in the ring buffer
        */
        uint16_t GetCount(void);

        /**
        * @brief	Return number of free items in the ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @return	Number of free items in the ring buffer
        */
        uint16_t GetFree(void);

        /**
        * @brief	Return number of items in the ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @return	1 if the ring buffer is full, otherwise 0
        */
        bool isFull(void);

        /**
        * @brief	Return empty status of ring buffer
        * @param	RingBuff	: Pointer to ring buffer
        * @return	1 if the ring buffer is empty, otherwise 0
        */
        bool isEmpty(void);
				
				uint8_t* bufferAddress();
				uint8_t* nextBufferAddress();
    protected:

    private:

        uint16_t count;
        uint16_t itemSize;
        
        uint16_t head;
        uint16_t tail;
        
        uint8_t *data;
//        uint8_t data[256];
	
};


/**
 * @}
 */
#ifdef __cplusplus
}
#endif 
#endif


UsartPHY.cpp
#include "UartPHY.h"
#include "stm32f10x.h"

#define USART3_DR_Base	((uint32_t)0x40004804)

UsartPHY *pCOM3;

/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
UsartPHY::~UsartPHY(){

}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
UsartPHY::UsartPHY(USART_TypeDef *usartx) : 
RxRingBuffer(128) , TxRingBuffer(2048)
{
	_port = usartx;
	pCOM3 = this;
}

/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool UsartPHY::init(uint32_t baud){
#ifdef	STM32F10X_MD
  DMA_InitTypeDef 	DMA_InitStructure;
  GPIO_InitTypeDef 	GPIO_InitStructure;
  NVIC_InitTypeDef 	NVIC_InitStructure;
	USART_InitTypeDef	UART_InitStructure;

  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
	
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
	
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	
	if(_port == USART3){
		RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, 		ENABLE);
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, 	ENABLE);
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
		
		NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
		NVIC_Init(&NVIC_InitStructure);
		NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel2_IRQn;
		NVIC_Init(&NVIC_InitStructure);
		
		GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_10;
		GPIO_InitStructure.GPIO_Mode 	= GPIO_Mode_AF_PP;
		GPIO_Init(GPIOB, &GPIO_InitStructure);
		
		GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_11;
		GPIO_InitStructure.GPIO_Mode 	= GPIO_Mode_IN_FLOATING;
		GPIO_Init(GPIOB, &GPIO_InitStructure);		
		
		_dmaChannel = DMA1_Channel2;
		
		DMA_DeInit(_dmaChannel);
		DMA_InitStructure.DMA_BufferSize 					= 0;
		DMA_InitStructure.DMA_PeripheralBaseAddr 	= USART3_DR_Base;
		DMA_InitStructure.DMA_Mode 								= DMA_Mode_Normal;
		DMA_InitStructure.DMA_M2M 								= DMA_M2M_Disable;
		DMA_InitStructure.DMA_Priority 						= DMA_Priority_Low;
		DMA_InitStructure.DMA_MemoryInc 					= DMA_MemoryInc_Enable;
		DMA_InitStructure.DMA_DIR 								= DMA_DIR_PeripheralDST;
		DMA_InitStructure.DMA_MemoryDataSize 			= DMA_MemoryDataSize_Byte;
		DMA_InitStructure.DMA_PeripheralInc 			= DMA_PeripheralInc_Disable;
		DMA_InitStructure.DMA_MemoryBaseAddr 			= (uint32_t)TxRingBuffer.bufferAddress();
		DMA_InitStructure.DMA_PeripheralDataSize 	= DMA_PeripheralDataSize_Byte;	
		
	}
	else
		return false;
	
	UART_InitStructure.USART_Mode 								= USART_Mode_Rx | USART_Mode_Tx;
  UART_InitStructure.USART_Parity 							= USART_Parity_No;
	UART_InitStructure.USART_BaudRate 						= baud;
  UART_InitStructure.USART_StopBits 						= USART_StopBits_1;
	UART_InitStructure.USART_WordLength 					= USART_WordLength_8b;
  UART_InitStructure.USART_HardwareFlowControl 	= USART_HardwareFlowControl_None;
	
  RxRingBuffer.Init();
  TxRingBuffer.Init();
	
  USART_Cmd(_port, ENABLE);
	USART_Init(_port, &UART_InitStructure);
	
	DMA_ITConfig(_dmaChannel, DMA_IT_TC, ENABLE);
	DMA_ITConfig(_dmaChannel, DMA_IT_HT, ENABLE);
	DMA_ITConfig(_dmaChannel, DMA_IT_TE, ENABLE);
	
	DMA_Init(_dmaChannel, &DMA_InitStructure);	
	
  USART_DMACmd(_port, USART_DMAReq_Tx, ENABLE);
	
  USART_ITConfig(_port, USART_IT_RXNE, ENABLE);
	
	return true;
#else
	#error 	"Herhangi bir denetleyici ailesi seçilmemiş. \
            Doğru mcu tanımlaması yaptıktan sonra tekrar derlemeyi deneyin.\
            Aksi halde UART birimi doğru çalışmayacaktır."
#endif
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool UsartPHY::available(){
	if(RxRingBuffer.isEmpty())
		return false;
	
	return true;
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool UsartPHY::write(uint8_t data){
	while(USART_GetFlagStatus(_port, USART_FLAG_TXE) == RESET){}
	USART_SendData(_port, data);
	while(USART_GetFlagStatus(_port, USART_FLAG_TC) == RESET){}
	
	return true;
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool UsartPHY::write(uint8_t *buf, uint16_t bufsize){
	_dmaChannel->CMAR = (uint32_t)TxRingBuffer.nextBufferAddress();
	TxRingBuffer.InsertMulti(buf, bufsize);
	DMA_SetCurrDataCounter(_dmaChannel, TxRingBuffer.GetCount());
	DMA_Cmd(_dmaChannel, ENABLE);
	
//	USART_SendData(_port, TxRingBuffer.Pop());
//  USART_ITConfig(_port, USART_IT_TC, ENABLE);
	
//	while(TxRingBuffer.GetCount()){
//			while(USART_GetFlagStatus(_port, USART_FLAG_TXE) == RESET);
//			USART_SendData(_port, TxRingBuffer.Pop());
//			while(USART_GetFlagStatus(_port, USART_FLAG_TC) == RESET);
//	}
		
    return true;
}


void UsartPHY::println(const char* str){
	while(*str != '\0'){
		TxRingBuffer.Insert(*str);
		str++;
	}
	TxRingBuffer.Insert('\n');
	
	_dmaChannel->CMAR = (uint32_t)TxRingBuffer.nextBufferAddress();
	DMA_SetCurrDataCounter(_dmaChannel, TxRingBuffer.GetCount());
	DMA_Cmd(_dmaChannel, ENABLE);
	
//	USART_SendData(_port, TxRingBuffer.Pop());
//  USART_ITConfig(_port, USART_IT_TC, ENABLE);
}

/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
USART_TypeDef * UsartPHY::port(){
	return _port;
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
uint8_t UsartPHY::read(){
	if(RxRingBuffer.isEmpty())
		return 0;
	return RxRingBuffer.Pop();
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool UsartPHY::read(uint8_t *data, uint16_t *len){
	if(RxRingBuffer.isEmpty()){
		*len = 0;
		return false;
	}
	*len = RxRingBuffer.GetCount();
	RxRingBuffer.PopMulti(data, *len);
	return true;
}


extern "C"{
	/**
	* @brief  This function handles USART3 interrupt request.
	* @param  None
	* @retval None
	*/
	void USART3_IRQHandler(void){
		if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET){
			pCOM3->RxRingBuffer.Insert(USART_ReceiveData(USART3));
			pCOM3->avaliable = true;
			USART_ClearITPendingBit(USART3, USART_IT_RXNE);
		}
		else if(USART_GetITStatus(USART3, USART_IT_TC) != RESET){
			if(pCOM3->TxRingBuffer.isEmpty()){
				USART_ITConfig(pCOM3->port(), USART_IT_TC, DISABLE);
				pCOM3->DataShifted = true;
			}
			else{
				USART_SendData(pCOM3->port(), pCOM3->TxRingBuffer.Pop());
			}
			USART_ClearITPendingBit(USART3, USART_IT_TC);
		}
	}
	/**
		* @brief  This function handles DMA1_Channel2 interrupt request.
		* @param  None
		* @retval None
		*/
	void DMA1_Channel2_IRQHandler(void){
		if(DMA_GetITStatus(DMA1_IT_TC2)){
			uint16_t dataCounter = pCOM3->txCounter();
			pCOM3->DataShifted = true;
			DMA_Cmd(DMA1_Channel2, DISABLE);
//			pCOM3->TxRingBuffer.Flush();
			uint8_t *temp = new uint8_t[dataCounter];
			pCOM3->TxRingBuffer.PopMulti(temp, dataCounter);
			delete[] temp;
			DMA_ClearITPendingBit(DMA1_IT_TC2);
		}
		else if(DMA_GetITStatus(DMA1_IT_HT2)){
			
	    DMA_ClearITPendingBit(DMA1_IT_HT2);
		}
		else if(DMA_GetITStatus(DMA1_IT_TE2)){
			DMA_Cmd(DMA1_Channel2, DISABLE);
	    DMA_ClearITPendingBit(DMA1_IT_TE2);
		}
		DMA_ClearITPendingBit(DMA1_IT_GL2);
	}
}


UsartPHY.h
/***********************
 * @brief
 * @note
 */

 #ifndef __UARTPHY_H
 #define __UARTPHY_H

#include "stm32f10x.h"
#include "RingBuffer.hpp"

/** UART Class
 +  Bu class verinin uart bufferdan çıkarılmasından ve uart bufferdaki verinin çekilmesinden sorumludur.
 + 	Hattın müsait olup olmaması durumuyla ilgilenmez.
 - 	Veriyi farklı formatlarda gönderebilir.
 - 	printf() fonkisyonunda olduğu gibi gönderebilir.
 +	Yalnızca basit veri alma ve göndermeyi destekler.
 + 	Interrupt ile almayı destekler.
 + 	Bir veri geldiğinde Rx isr içinde veri RingBuffer içine alınır.
 + 	avaliable flagını set eder ve buffer içindeki veri miktarını countera atar.
 *	Veri göndermek için DMA kullanımını da destekler.
 +	Bir veri gönderilmek istendiğinde, veri TxRingBuffer içine yazılır.
 *	Burada iki seçenek vardır.
 +	1- Veri başında bekleyerek gönderilir:
 * 		Bu seçenek ile gönderilmek istendiğinde, State Transmit'e set edilir.
 *		RingBuffer içindeki veri sırasıyla Uart Tx Buffera yazılır ve her byte tek tek kontrol edilerek gönderilir.
 *		Gönderilecek bytelar tamamlandığında write fonksiyonu true ile geri döner.
 *	2- Veri DMA ile gönderilir:
 *		Bu seçenek seçildiğinde, DMA için gönderilecek veri boyutu ringbufferdaki veri miktarı olarak ayarlanır.
 *		DMA TC_IRQ ve TE_IRQ (Transfer Error Interrupt) açılır. DMA Tx Enable edilir. TC_IRQ içinde data_shifted flagı set edilir.
 *		TE_IRQ içinde transfer_error flagı set edilir.
 * 
 *	Bu class dma ile ve/veya dmasız göndermede hiç bir hata kontrolünden sorumlu değildir.
 *	Bus collision algılamaz!Benzeri bir hata kontrolü de yoktur.
 *		
 *		
 */
class UsartPHY{
public:
	bool avaliable;
	bool DataShifted;
	bool TransferError;

	RingBuffer	RxRingBuffer;
	RingBuffer	TxRingBuffer;

	~UsartPHY();
	UsartPHY(USART_TypeDef *usartx = USART3);

	bool init(uint32_t baud);

	bool available();

	bool write(uint8_t data);
	bool write(uint8_t *data, uint16_t bufsize);
	
	void println(const char* str);
	
	uint8_t read();
	bool read(uint8_t *data, uint16_t *len);
	
	inline uint16_t rxCounter(){return RxRingBuffer.GetCount();}
	inline uint16_t txCounter(){return TxRingBuffer.GetCount();}
	
	USART_TypeDef * port();
  DMA_Channel_TypeDef *DMAChannel();
private:
	uint16_t _rxDataCount;
	uint16_t _txDataCount;

	USART_TypeDef *_port;
  DMA_Channel_TypeDef *_dmaChannel;
};
#endif


rs485.cpp
#include "crc.h"
#include "rs485.h"
#include "Delay.h"
#include "string.h"
#include "UartPHY.h"
#include "stm32f10x.h"

#define MAX_RETRY			3

#define PACKET_SIZE		8
#define RS485_TxMode	(BitAction)Bit_SET
#define RS485_RxMode	(BitAction)Bit_RESET

const uint8_t STX_CHAR[] = {0x57, 0x95};
const uint8_t ETX_CHAR[] = {0x49, 0x88};

/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
RS485::RS485(UsartPHY &usart, GPIO_TypeDef *TrancieverPort, uint32_t TrancieverPin) 
	:	_serial(usart)
{
	_trancieverport = TrancieverPort;
	_trancieverpin = TrancieverPin;
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool RS485::init(){
	if (!GenericDriver::init())
		return false;
//	if(!_usart.init(baud))
//		return false;
	
//	_TxToRxuSDelay = (1 / (baud / 10) * 100000);	// @todo
	GPIO_InitTypeDef GPIO_Struct;
	/* 11.520 byte 1 saniyede
	 * 1 byte				x saniyede
	 * --------------------------
	 * 					1
	 * x =	----------
	 *				11.520
	 * 
	 * x = 0,000086,8
	 */
	GPIO_Struct.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Struct.GPIO_Speed = GPIO_Speed_2MHz;
	GPIO_Struct.GPIO_Pin = _trancieverpin;
	GPIO_Init(_trancieverport, &GPIO_Struct);
	
	GPIO_WriteBit(_trancieverport, _trancieverpin, RS485_RxMode);
	
	return true;
}
/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
UsartPHY& RS485::serial(){
    return _serial;
}
/**
  * @brief  Checks if there are some data in the rx ringbuffer more than PACKET_SIZE
  * @param  None
  * @retval None
  * @note   None
  */
bool RS485::available()
{	
	return (bool)~_serial.RxRingBuffer.isEmpty();
}

void RS485::waitAvailable()
{
	GenericDriver::waitAvailable();
}

bool RS485::waitAvailableTimeout(uint16_t timeout)
{
    return GenericDriver::waitAvailableTimeout(timeout);
}
/**
  * @brief  Reads "len" bytes from RxRingBuffer.
  * @param  None
  * @retval None
  * @note   None
  */
//bool RS485::read(uint8_t *data, uint16_t len){
//	if(_usart.RxRingBuffer.isEmpty())
//		return false;
//	
//	_usart.RxRingBuffer.PopMulti(data, len);
//	
//	return true;
//}
/**
  * @brief  Reads all the data in the RxRingBuffer and 
	* writes to the "*len" buffer count.
  * @param  None
	* @retval Returns false, if STX_CHAR or ETX_CHAR or CRC doesn't match. 
	* 				If matchs, returns true!
  * @note   Only this read function checks the CRC if its right or not.
  */
bool RS485::recv(uint8_t *data, uint16_t *len){
	if(data && len){
		uint16_t rxcounter = _serial.rxCounter();
		if(rxcounter < 5)
			return false;
		
		_serial.RxRingBuffer.PopMulti(data, rxcounter);
		
		if(std::strncmp((const char*)data, (const char*)STX_CHAR, 2) != 0){
			memset(data, 0, rxcounter);
			return false;
		}
		if(std::strncmp((const char*)&data[rxcounter - 2], (const char*)ETX_CHAR, 2) != 0){
			memset(data, 0, rxcounter);
			return false;
		}
		
		uint16_t crc = (data[rxcounter - 4] << 8) | data[rxcounter - 3];
		if(CRC16(data, rxcounter - 4) != crc)
			return false;
		
		*len = rxcounter;
		
		return true;
	}
	else
		return false;
}

/**
  * @brief  
  * @param  None
  * @retval None
  * @note   None
  */
bool RS485::send(uint8_t *buffer, uint16_t len){
	if(BusBussy == true){
		for(int i = 0; i < MAX_RETRY; i++){
			BusBussy = false;
			Delay(_thisAddress * 10);
			if(!BusBussy)
				break;
		}
		if(BusBussy)
			return false;
	}
	USART_ITConfig(_serial.port(), USART_IT_RXNE, DISABLE);
	GPIO_WriteBit(_trancieverport, _trancieverpin, RS485_TxMode);
	
	uint8_t *sendbuf = new uint8_t[len + 6];
	
	if(!sendbuf)
		return false;
	
	memcpy(&sendbuf[2], buffer, len);
	
	uint16_t crc = CRC16(buffer, len);
	
	memcpy(sendbuf, STX_CHAR, 2);
	
	sendbuf[len + 2] = crc >> 8;
	sendbuf[len + 3] = crc & 0xFF;
	
	memcpy(&sendbuf[len + 4], ETX_CHAR, 2);
	
	bool result = _serial.write(sendbuf, len + 6);
	delete [] sendbuf;
	Delay(2);	// @todo bu değeri doğru hesapla.!!!
	
	GPIO_WriteBit(_trancieverport, _trancieverpin, RS485_RxMode);
	USART_ITConfig(_serial.port(), USART_IT_RXNE, ENABLE);
	
	return result;
}

uint16_t RS485::rxCount(){
	return _serial.rxCounter();
}

uint16_t RS485::maxMessageLength(){
	return _serial.RxRingBuffer.GetSize();
}


rs485.h
#ifndef __RS485_H
#define __RS485_H

//#include "UartPHY.h"
#include "stm32f10x.h"
#include "GenericDriver.h"

#define RS485_ENABLE	1
 
// Special characters
//#define STX 0x02
//#define ETX 0x03
#define DLE 0x10
#define SYN 0x16

// Maximum message length (including the headers) we are willing to support
#define RH_SERIAL_MAX_PAYLOAD_LEN 64

// The length of the headers we add.
// The headers are inside the payload and are therefore protected by the FCS
//#define RH_SERIAL_HEADER_LEN 4

// This is the maximum message length that can be supported by this library. 
// It is an arbitrary limit.
// Can be pre-defined to a smaller size (to save SRAM) prior to including this header
// Here we allow for 4 bytes of address and header and payload to be included in the 64 byte encryption limit.
// the one byte payload length is not encrpyted
#ifndef RH_SERIAL_MAX_MESSAGE_LEN
#define RH_SERIAL_MAX_MESSAGE_LEN (RH_SERIAL_MAX_PAYLOAD_LEN - RH_SERIAL_HEADER_LEN)
#endif

class UsartPHY;

class RS485 : public GenericDriver
{ 
public:
	bool BusBussy;

// ~RS485();
	/// Constructor
	/// \param[in] serial Reference to the HardwareSerial port which will be used by this instance.
	/// On Unix and OSX, this is an instance of RHutil/HardwareSerial. On 
	/// Arduino and other, it is an instance of the built in HardwareSerial class.
	RS485(UsartPHY &usart, GPIO_TypeDef *TrancieverPort, uint32_t TrancieverPin);

	/// Return the HardwareSerial port in use by this instance
	/// \return The current HardwareSerial as a reference
	UsartPHY& serial();

	/// Initialise the Driver transport hardware and software.
	/// Make sure the Driver is properly configured before calling init().
	/// \return true if initialisation succeeded.
	virtual bool init();

	/// Tests whether a new message is available
	/// This can be called multiple times in a timeout loop.
	/// \return true if a new, complete, error-free uncollected message is available to be retreived by recv()
	virtual bool available();

	/// Wait until a new message is available from the driver.
	/// Blocks until a complete message is received as reported by available()
	virtual void waitAvailable();

	/// Wait until a new message is available from the driver or the timeout expires.
	/// Blocks until a complete message is received as reported by available() or the timeout expires.
	/// \param[in] timeout The maximum time to wait in milliseconds
	/// \return true if a message is available as reported by available(), false on timeout.
	virtual bool waitAvailableTimeout(uint16_t timeout);

	/// If there is a valid message available, copy it to buf and return true
	/// else return false.
	/// If a message is copied, *len is set to the length (Caution, 0 length messages are permitted).
	/// You should be sure to call this function frequently enough to not miss any messages
	/// It is recommended that you call it in your main loop.
	/// \param[in] buf Location to copy the received message
	/// \param[in,out] len Pointer to available space in buf. Set to the actual number of octets copied.
	/// \return true if a valid message was copied to buf
	virtual bool recv(uint8_t* buf, uint16_t* len);

	/// Waits until any previous transmit packet is finished being transmitted with waitPacketSent().
	/// Then loads a message into the transmitter and starts the transmitter. Note that a message length
	/// of 0 is NOT permitted. 
	/// \param[in] data Array of data to be sent
	/// \param[in] len Number of bytes of data to send (> 0)
	/// \return true if the message length was valid and it was correctly queued for transmit
	virtual bool send(uint8_t* data, uint16_t len);

	/// Returns the maximum message length 
	/// available in this Driver.
	/// \return The maximum legal message length
	virtual uint16_t maxMessageLength();
	
	virtual uint16_t rxCount();
protected:
	/// Reference to the HardwareSerial port we will use
	UsartPHY& _serial;


	/// The Rx buffer
	uint8_t         _rxBuf[RH_SERIAL_MAX_PAYLOAD_LEN];

	/// Current length of data in the Rx buffer
	uint8_t         _rxBufLen;

	/// True if the data in the Rx buffer is value and uncorrupted and complete message is available for collection
	bool            _rxBufValid;
private:
	uint16_t 			_TxToRxuSDelay;
	uint32_t 			_trancieverpin;
	GPIO_TypeDef *_trancieverport;

};
#endif


GenericDriver.cpp
#include "Delay.h"
#include "stdlib.h"
#include <GenericDriver.h>

GenericDriver::GenericDriver()
    :
    _mode(RHModeInitialising),
    _thisAddress(RH_BROADCAST_ADDRESS),
    _txHeaderTo(RH_BROADCAST_ADDRESS),
    _txHeaderFrom(RH_BROADCAST_ADDRESS),
    _txHeaderId(0),
    _txHeaderFlags(0),
    _rxBad(0),
    _rxGood(0),
    _txGood(0),
    _cad_timeout(0)
{
}

bool GenericDriver::init()
{
    return true;
}

// Blocks until a valid message is received
void GenericDriver::waitAvailable()
{
    while (!available());
//	YIELD;
}

// Blocks until a valid message is received or timeout expires
// Return true if there is a message available
// Works correctly even on millis() rollover
bool GenericDriver::waitAvailableTimeout(uint16_t timeout)
{
    unsigned long starttime = GetTick();
    while ((GetTick() - starttime) < timeout)
    {
        if (available())
	{
           return true;
	}
//	YIELD;
    }
    return false;
}

bool GenericDriver::waitPacketSent()
{
    while (_mode == RHModeTx);
//	YIELD; // Wait for any previous transmit to finish
    return true;
}

bool GenericDriver::waitPacketSent(uint16_t timeout)
{
    unsigned long starttime = GetTick();
    while ((GetTick() - starttime) < timeout)
    {
        if (_mode != RHModeTx) // Any previous transmit finished?
           return true;
//	YIELD;
    }
    return false;
}

// Wait until no channel activity detected or timeout
bool GenericDriver::waitCAD()
{
    if (!_cad_timeout)
	return true;

    // Wait for any channel activity to finish or timeout
    // Sophisticated DCF function...
    // DCF : BackoffTime = random() x aSlotTime
    // 100 - 1000 ms
    // 10 sec timeout
    unsigned long t = GetTick();
    while (isChannelActive())
    {
         if (GetTick() - t > _cad_timeout) 
	     return false;
         Delay(rand() * 100); // Should these values be configurable? Macros?
    }

    return true;
}

// subclasses are expected to override if CAD is available for that radio
bool GenericDriver::isChannelActive()
{
    return false;
}

void GenericDriver::setPromiscuous(bool promiscuous)
{
    _promiscuous = promiscuous;
}

void GenericDriver::setThisAddress(uint8_t address)
{
    _thisAddress = address;
}

void GenericDriver::setHeaderTo(uint8_t to)
{
    _txHeaderTo = to;
}

void GenericDriver::setHeaderFrom(uint8_t from)
{
    _txHeaderFrom = from;
}

void GenericDriver::setHeaderId(uint8_t id)
{
    _txHeaderId = id;
}

void GenericDriver::setHeaderFlags(uint8_t set, uint8_t clear)
{
    _txHeaderFlags &= ~clear;
    _txHeaderFlags |= set;
}

uint8_t GenericDriver::headerTo()
{
    return _rxHeaderTo;
}

uint8_t GenericDriver::headerFrom()
{
    return _rxHeaderFrom;
}

uint8_t GenericDriver::headerId()
{
    return _rxHeaderId;
}

uint8_t GenericDriver::headerFlags()
{
    return _rxHeaderFlags;
}

int8_t GenericDriver::lastRssi()
{
    return _lastRssi;
}

GenericDriver::RHMode  GenericDriver::mode()
{
    return _mode;
}

void  GenericDriver::setMode(RHMode mode)
{
    _mode = mode;
}

bool  GenericDriver::sleep()
{
    return false;
}

// Diagnostic help
void GenericDriver::printBuffer(const char* prompt, const uint8_t* buf, uint8_t len)
{
//    uint8_t i;

//#ifdef RH_HAVE_SERIAL
//    Serial.println(prompt);
//    for (i = 0; i < len; i++)
//    {
//	if (i % 16 == 15)
//	    Serial.println(buf[i], HEX);
//	else
//	{
//	    Serial.print(buf[i], HEX);
//	    Serial.print(' ');
//	}
//    }
//    Serial.println("");
//#endif
}

uint16_t GenericDriver::rxBad()
{
    return _rxBad;
}

uint16_t GenericDriver::rxGood()
{
    return _rxGood;
}

uint16_t GenericDriver::txGood()
{
    return _txGood;
}

void GenericDriver::setCADTimeout(unsigned long cad_timeout)
{
    _cad_timeout = cad_timeout;
}


GenericDriver.h
#ifndef GenericDriver_h
#define GenericDriver_h

//#include <RadioHead.h>
#include "stm32f10x.h"

// This is the address that indicates a broadcast
#define RH_BROADCAST_ADDRESS 0xff
// Defines bits of the FLAGS header reserved for use by the RadioHead library and 
// the flags available for use by applications
#define RH_FLAGS_RESERVED                 0xf0
#define RH_FLAGS_APPLICATION_SPECIFIC     0x0f
#define RH_FLAGS_NONE                     0

// Default timeout for waitCAD() in ms
#define RH_CAD_DEFAULT_TIMEOUT            10000
class GenericDriver
{
public:
	/// \brief Defines different operating modes for the transport hardware
	///
	/// These are the different values that can be adopted by the _mode variable and 
	/// returned by the mode() member function,
	typedef enum{
		RHModeInitialising = 0, ///< Transport is initialising. Initial default value until init() is called..
		RHModeSleep,            ///< Transport hardware is in low power sleep mode (if supported)
		RHModeIdle,             ///< Transport is idle.
		RHModeTx,               ///< Transport is in the process of transmitting a message.
		RHModeRx,               ///< Transport is in the process of receiving a message.
		RHModeCad               ///< Transport is in the process of detecting channel activity (if supported)
	} RHMode;

	/// Constructor
	GenericDriver();

	/// Initialise the Driver transport hardware and software.
	/// Make sure the Driver is properly configured before calling init().
	/// \return true if initialisation succeeded.
	virtual bool init();

	/// Tests whether a new message is available
	/// from the Driver. 
	/// On most drivers, if there is an uncollected received message, and there is no message
	/// currently bing transmitted, this will also put the Driver into RHModeRx mode until
	/// a message is actually received by the transport, when it will be returned to RHModeIdle.
	/// This can be called multiple times in a timeout loop.
	/// \return true if a new, complete, error-free uncollected message is available to be retreived by recv().
	virtual bool available() = 0;

	/// Turns the receiver on if it not already on.
	/// If there is a valid message available, copy it to buf and return true
	/// else return false.
	/// If a message is copied, *len is set to the length (Caution, 0 length messages are permitted).
	/// You should be sure to call this function frequently enough to not miss any messages
	/// It is recommended that you call it in your main loop.
	/// \param[in] buf Location to copy the received message
	/// \param[in,out] len Pointer to available space in buf. Set to the actual number of octets copied.
	/// \return true if a valid message was copied to buf
	virtual bool recv(uint8_t* buf, uint16_t* len) = 0;

	/// Waits until any previous transmit packet is finished being transmitted with waitPacketSent().
	/// Then optionally waits for Channel Activity Detection (CAD) 
	/// to show the channnel is clear (if the radio supports CAD) by calling waitCAD().
	/// Then loads a message into the transmitter and starts the transmitter. Note that a message length
	/// of 0 is NOT permitted. If the message is too long for the underlying radio technology, send() will
	/// return false and will not send the message.
	/// \param[in] data Array of data to be sent
	/// \param[in] len Number of bytes of data to send (> 0)
	/// specify the maximum time in ms to wait. If 0 (the default) do not wait for CAD before transmitting.
	/// \return true if the message length was valid and it was correctly queued for transmit. Return false
	/// if CAD was requested and the CAD timeout timed out before clear channel was detected.
	virtual bool send(uint8_t* data, uint16_t len) = 0;

	/// Returns the maximum message length 
	/// available in this Driver.
	/// \return The maximum legal message length
	virtual uint16_t maxMessageLength() = 0;

	/// Starts the receiver and blocks until a valid received 
	/// message is available.
	virtual void            waitAvailable();

	/// Blocks until the transmitter 
	/// is no longer transmitting.
	virtual bool            waitPacketSent();

	/// Blocks until the transmitter is no longer transmitting.
	/// or until the timeout occuers, whichever happens first
	/// \param[in] timeout Maximum time to wait in milliseconds.
	/// \return true if the radio completed transmission within the timeout period. False if it timed out.
	virtual bool            waitPacketSent(uint16_t timeout);

	/// Starts the receiver and blocks until a received message is available or a timeout
	/// \param[in] timeout Maximum time to wait in milliseconds.
	/// \return true if a message is available
	virtual bool            waitAvailableTimeout(uint16_t timeout);

	// Bent G Christensen (bentor@gmail.com), 08/15/2016
	/// Channel Activity Detection (CAD).
	/// Blocks until channel activity is finished or CAD timeout occurs.
	/// Uses the radio's CAD function (if supported) to detect channel activity.
	/// Implements random delays of 100 to 1000ms while activity is detected and until timeout.
	/// Caution: the random() function is not seeded. If you want non-deterministic behaviour, consider
	/// using something like randomSeed(analogRead(A0)); in your sketch.
	/// Permits the implementation of listen-before-talk mechanism (Collision Avoidance).
	/// Calls the isChannelActive() member function for the radio (if supported) 
	/// to determine if the channel is active. If the radio does not support isChannelActive(),
	/// always returns true immediately
	/// \return true if the radio-specific CAD (as returned by isChannelActive())
	/// shows the channel is clear within the timeout period (or the timeout period is 0), else returns false.
	virtual bool            waitCAD();

	/// Sets the Channel Activity Detection timeout in milliseconds to be used by waitCAD().
	/// The default is 0, which means do not wait for CAD detection.
	/// CAD detection depends on support for isChannelActive() by your particular radio.
	void setCADTimeout(unsigned long cad_timeout);

	/// Determine if the currently selected radio channel is active.
	/// This is expected to be subclassed by specific radios to implement their Channel Activity Detection
	/// if supported. If the radio does not support CAD, returns true immediately. If a RadioHead radio 
	/// supports isChannelActive() it will be documented in the radio specific documentation.
	/// This is called automatically by waitCAD().
	/// \return true if the radio-specific CAD (as returned by override of isChannelActive()) shows the
	/// current radio channel as active, else false. If there is no radio-specific CAD, returns false.
	virtual bool            isChannelActive();

	/// Sets the address of this node. Defaults to 0xFF. Subclasses or the user may want to change this.
	/// This will be used to test the adddress in incoming messages. In non-promiscuous mode,
	/// only messages with a TO header the same as thisAddress or the broadcast addess (0xFF) will be accepted.
	/// In promiscuous mode, all messages will be accepted regardless of the TO header.
	/// In a conventional multinode system, all nodes will have a unique address 
	/// (which you could store in EEPROM).
	/// You would normally set the header FROM address to be the same as thisAddress (though you dont have to, 
	/// allowing the possibilty of address spoofing).
	/// \param[in] thisAddress The address of this node.
	virtual void setThisAddress(uint8_t thisAddress);

	/// Sets the TO header to be sent in all subsequent messages
	/// \param[in] to The new TO header value
	virtual void           setHeaderTo(uint8_t to);

	/// Sets the FROM header to be sent in all subsequent messages
	/// \param[in] from The new FROM header value
	virtual void           setHeaderFrom(uint8_t from);

	/// Sets the ID header to be sent in all subsequent messages
	/// \param[in] id The new ID header value
	virtual void           setHeaderId(uint8_t id);

	/// Sets and clears bits in the FLAGS header to be sent in all subsequent messages
	/// First it clears he FLAGS according to the clear argument, then sets the flags according to the 
	/// set argument. The default for clear always clears the application specific flags.
	/// \param[in] set bitmask of bits to be set. Flags are cleared with the clear mask before being set.
	/// \param[in] clear bitmask of flags to clear. Defaults to RH_FLAGS_APPLICATION_SPECIFIC
	///            which clears the application specific flags, resulting in new application specific flags
	///            identical to the set.
	virtual void           setHeaderFlags(uint8_t set, uint8_t clear = RH_FLAGS_APPLICATION_SPECIFIC);

	/// Tells the receiver to accept messages with any TO address, not just messages
	/// addressed to thisAddress or the broadcast address
	/// \param[in] promiscuous true if you wish to receive messages with any TO address
	virtual void           setPromiscuous(bool promiscuous);

	/// Returns the TO header of the last received message
	/// \return The TO header
	virtual uint8_t        headerTo();

	/// Returns the FROM header of the last received message
	/// \return The FROM header
	virtual uint8_t        headerFrom();

	/// Returns the ID header of the last received message
	/// \return The ID header
	virtual uint8_t        headerId();

	/// Returns the FLAGS header of the last received message
	/// \return The FLAGS header
	virtual uint8_t        headerFlags();

	/// Returns the most recent RSSI (Receiver Signal Strength Indicator).
	/// Usually it is the RSSI of the last received message, which is measured when the preamble is received.
	/// If you called readRssi() more recently, it will return that more recent value.
	/// \return The most recent RSSI measurement in dBm.
	int8_t        lastRssi();

	/// Returns the operating mode of the library.
	/// \return the current mode, one of RF69_MODE_*
	RHMode          mode();

	/// Sets the operating mode of the transport.
	void            setMode(RHMode mode);

	/// Sets the transport hardware into low-power sleep mode
	/// (if supported). May be overridden by specific drivers to initialte sleep mode.
	/// If successful, the transport will stay in sleep mode until woken by 
	/// changing mode it idle, transmit or receive (eg by calling send(), recv(), available() etc)
	/// \return true if sleep mode is supported by transport hardware and the RadioHead driver, and if sleep mode
	///         was successfully entered. If sleep mode is not suported, return false.
	virtual bool    sleep();

	/// Prints a data buffer in HEX.
	/// For diagnostic use
	/// \param[in] prompt string to preface the print
	/// \param[in] buf Location of the buffer to print
	/// \param[in] len Length of the buffer in octets.
	static void    printBuffer(const char* prompt, const uint8_t* buf, uint8_t len);

	/// Returns the count of the number of bad received packets (ie packets with bad lengths, checksum etc)
	/// which were rejected and not delivered to the application.
	/// Caution: not all drivers can correctly report this count. Some underlying hardware only report
	/// good packets.
	/// \return The number of bad packets received.
	uint16_t       rxBad();

	/// Returns the count of the number of 
	/// good received packets
	/// \return The number of good packets received.
	uint16_t       rxGood();

	/// Returns the count of the number of 
	/// packets successfully transmitted (though not necessarily received by the destination)
	/// \return The number of packets successfully transmitted
	uint16_t       txGood();
	
	virtual uint16_t rxCount() = 0;
protected:

	/// The current transport operating mode
	volatile RHMode     _mode;

	/// This node id
	uint8_t             _thisAddress;
	
	/// Whether the transport is in promiscuous mode
	bool                _promiscuous;

	/// TO header in the last received mesasge
	volatile uint8_t    _rxHeaderTo;

	/// FROM header in the last received mesasge
	volatile uint8_t    _rxHeaderFrom;

	/// ID header in the last received mesasge
	volatile uint8_t    _rxHeaderId;

	/// FLAGS header in the last received mesasge
	volatile uint8_t    _rxHeaderFlags;

	/// TO header to send in all messages
	uint8_t             _txHeaderTo;

	/// FROM header to send in all messages
	uint8_t             _txHeaderFrom;

	/// ID header to send in all messages
	uint8_t             _txHeaderId;

	/// FLAGS header to send in all messages
	uint8_t             _txHeaderFlags;

	/// The value of the last received RSSI value, in some transport specific units
	volatile int8_t     _lastRssi;

	/// Count of the number of bad messages (eg bad checksum etc) received
	volatile uint16_t   _rxBad;

	/// Count of the number of successfully transmitted messaged
	volatile uint16_t   _rxGood;

	/// Count of the number of bad messages (correct checksum etc) received
	volatile uint16_t   _txGood;
	
	/// Channel activity detected
	volatile bool       _cad;
	unsigned int        _cad_timeout;

private:

};


#endif


Datagram.cpp
// Datagram.cpp
//

#include <Datagram.h>
#include "stm32f10x.h"
#include "string.h"

Datagram::Datagram(GenericDriver& driver, uint8_t thisAddress) : _driver(driver), _thisAddress(thisAddress)
{
}

////////////////////////////////////////////////////////////////////
// Public methods
bool Datagram::init()
{
	bool ret = _driver.init();
	if (ret)
		setThisAddress(_thisAddress);
	return ret;
}

void Datagram::setThisAddress(uint8_t thisAddress)
{
//    _driver.setThisAddress(thisAddress);
    // Use this address in the transmitted FROM header
//    setHeaderFrom(thisAddress);
	_thisAddress = thisAddress;
}

bool Datagram::sendto(uint8_t* buf, uint16_t len, uint8_t address)
{
//	setHeaderTo(address);
	uint8_t *data = new uint8_t[len + 2];
	if(data == 0)
		return false;
	data[0] = _thisAddress;
	data[1] = address;
	
	memcpy(&data[2], buf, len);
	
	bool result = _driver.send(data, len + 2);
	
	delete[] data;
	
	return result;
}

bool Datagram::recvfrom(uint8_t* buf, uint16_t* len, uint8_t* from, uint8_t* to){
	if(_driver.rxCount() < 9)
		return false;
	
	if (_driver.recv(buf, len)){
		if (from)  
			*from =  buf[0];
		if (to)    
			*to =    buf[1];
		
		return true;
	}
	return false;
}

bool Datagram::available()
{
	return (_driver.rxCount() > 9) ? true : false;
}

void Datagram::waitAvailable()
{
    _driver.waitAvailable();
}

bool Datagram::waitPacketSent()
{
    return _driver.waitPacketSent();
}

bool Datagram::waitPacketSent(uint16_t timeout)
{
    return _driver.waitPacketSent(timeout);
}

bool Datagram::waitAvailableTimeout(uint16_t timeout)
{
    return _driver.waitAvailableTimeout(timeout);
}

uint8_t Datagram::thisAddress()
{
    return _thisAddress;
}

void Datagram::setHeaderTo(uint8_t to)
{
    _driver.setHeaderTo(to);
}

void Datagram::setHeaderFrom(uint8_t from)
{
    _driver.setHeaderFrom(from);
}

void Datagram::setHeaderId(uint8_t id)
{
    _driver.setHeaderId(id);
}

void Datagram::setHeaderFlags(uint8_t set, uint8_t clear)
{
    _driver.setHeaderFlags(set, clear);
}

uint8_t Datagram::headerTo()
{
    return _driver.headerTo();
}

uint8_t Datagram::headerFrom()
{
    return _driver.headerFrom();
}

uint8_t Datagram::headerId()
{
    return _driver.headerId();
}

uint8_t Datagram::headerFlags()
{
    return _driver.headerFlags();
}


Datagram.h
[code]
#ifndef Datagram_h
#define Datagram_h

//#include <iostream>
//#include "rs485.h"
#include <GenericDriver.h>

// This is the maximum possible message size for radios supported by RadioHead.
// Not all radios support this length, and many are much smaller
#define RH_MAX_MESSAGE_LEN 255

/////////////////////////////////////////////////////////////////////
/// \class RHDatagram RHDatagram.h <RHDatagram.h>
/// \brief Manager class for addressed, unreliable messages
///
/// Every RHDatagram node has an 8 bit address (defaults to 0).
/// Addresses (DEST and SRC) are 8 bit integers with an address of RH_BROADCAST_ADDRESS (0xff)
/// reserved for broadcast.
///
/// \par Media
Kişinin başına gelen hayır Allah'tandır. Kişinin başına gelen şer nefsindendir. Nefislerimizle kendimize zulüm ediyoruz.

yamak

Hocam mümkünse heap kullanma.Data 1kb lık framler halinde geliyorsa 1kb aldığın datayı flash a yazıp sonra da bir sonraki frame i alabilirsin.

yldzelektronik

Hocam daha alma kısmını bitmedim bile.Gönderme kısmını bitirmeye çalışıyorum.Göndermek istediğim veriyi alt katlara gönderirken çok ram ihtiyacım oluyor. Ne tür bir algoritma kullanmak gerekir?
Kişinin başına gelen hayır Allah'tandır. Kişinin başına gelen şer nefsindendir. Nefislerimizle kendimize zulüm ediyoruz.

yamak

Hocam gönderirken de aynı şekilde yap.Bir kerede göndereceğin data 1 kb ı geçmesin.Tüm class lar aynı bufferı ı kullasın.Hepsi için ayrı buffer oluşturma.