Am I complicating things?
I'm architecting my code to talk from a 8051 micro to a peripheral device over UART. The peripheral responds to commands from the host and can only respond to one command at a time. It's a simple send and receive protocol. (tx1, rx1, tx2, rx2, tx3, rx3) Each TX message is terminated with a CR, each response is terminated with a >. I can't send a new message until I receive the response to the last one. Responses can also echo print the original TX message in the beginning if I enable that option (but this causes more traffic)
An example message would be:
TX: Hello
RX: World!>
Or with echo option...
TX: Hello
RX: Hello\rWorld!>
Option A
A function such as getHello would consist of both the send and receive. A parallel ISR routine would gather the incoming bytes and throw a flag when the '>' character is received.
char* getHello(char * buf){
sendMsg("Hello\r");
delay(10ms); //wait a little bit
//wait for receive to come in or timeout to occur
while(!receiveFlag || !timeoutFlag); //thrown by ISR
receiveMsg(buf);
//parse the message and do some other stuff
return buf;
}
Pros:
Everything is contained within one function.
Easier to debug
Cons:
This function is blocking and could hang if the peripheral never responds so a timeout must be implemented.
Messages can't be received out of order, must be in series (ie, tx1, rx1, tx2, rx2, tx3, rx3)
Option B
A parallel approach is taken. Two separate functions would created. one to send the message, and one that would vertexed upon receiving a response from the ISR.
void sendHello(){
sendMsg("Hello\r");
//do some other stuff if needed
}
char* receiveMsg(char * buf){
//figure out from echo print what the tx message was
//use a switch statement to decide which response parser to call
switch(txMessage){ //pseudo code
case "Hello":
receiveMsg(buf);
//parse the message and do some other stuff
break;
}
return buf;
}
Pros:
Can handle parallel messages coming back out of order because it relies on the echo printing of the tx message to figure out how to parse it. (ie, tx1, tx2, tx3, rx1,rx2,rx3)
Cons:
quite difficult to debug
spawns multiple threads
lots of extra code
not worth it since messages will definitely come back in order
Right now, I'm doing Option B, but as I continue on with the project, I begin to feel like this is getting overly complex. I'm curious what you guys think.
Thanks!
I tend to do this kind of stuff, though, Id tend to have a separate serial port "class" ( struct + functions ) and a protocol class that lives over the top of serial port. I used these all the time in my embedded systems. This gives you the best of both worlds, a blocking synchronous call and an async call so you can pseudo multitask.
typedef struct serial_port_s serial_port;
typedef void (*serial_on_recived_proc)(serial_port* p);
typedef struct serial_port_s{
bool timeoutFlag;
bool receiveFlag;
void* context;
serial_on_recived_proc response_handler;
};
void send_serial(serial_port* p, char* message)
{
//SendMsg?
}
void receive_serial(serial_port* p, char* response)
{
//receiveMsg?
}
bool has_data(serial_port* p)
{
return p->receiveFlag;
}
bool has_timed_out(serial_port* p)
{
return p->timeoutFlag;
}
bool is_serial_finished(serial_port* p)
{
return has_data(p) || has_timed_out(p);
}
bool serial_check(serial_port* p)
{
if(is_serial_finished(p) && p->response_handler != NULL)
{
p->response_handler(p)
p-> response_handler = NULL;
return true;
}
return false;
}
void send(serial_port* p, char* message, char* response)
{
p->response_handler=NULL;
send_serial(p, message);
while(!is_serial_finished(p));
receive_serial(p, response);
}
void sendAsync(serial_port* p, char* message, serial_on_recived_proc handler, void* context)
{
p->response_handler = handler;
p->context = context;
send_serial(p, message);
}
void pow_response(serial_port* p)
{
// could pass a pointer to a struct, or anything depending on what you want to do
char* r = (char*)p->context;
receive_serial(p, r);
// do stuff with the pow response
}
typedef struct
{
char text[100];
int x;
bool has_result;
} bang_t;
void bang_parse(bang_t* bang)
{
bang->x = atoi(bang->text);
}
void bang_response(serial_port* p)
{
bang_t* bang = (bang_t*)p->context;
receive_serial(p, bang->text);
bang_parse(bang);
bang->has_result=true;
}
void myFunc();
{
char response[100];
char pow[100];
bang_t bang1;
bang_t bang2;
serial_port p; //
int state = 1;
// whatever you need to do to set the serial port
// sends and blocks till a response/timeout
send(&p, "Hello", response);
// do what you like with the response
// alternately, lets do an async send...
sendAsync(&p, "Pow", pow_response, pow);
while(true)
{
// non block check, will process the response when it arrives
if(serial_check(p))
{
// it has responded to something, we can send something else...
// using a very simple state machine, work out what to send next.
// in practice I'd use enum for states, and functions for managing state
// transitions, but for this example I'm just using an int which
// I just increment to move to the next state
switch(state)
{
case 1:
// bang1 is the context, and will receive the data
sendAsync(&p, "Bang1", bang_response, &bang1);
state++;
break;
case 2:
// now bang2 is the context and will get the data...
sendAsync(&p, "Bang2", bang_response, &bang2);
state++;
break;
default:
//nothing more to send....
break;
}
}
// do other stuff you want to do in parallel
}
};
Take things simple. An ISR routine must be very fast so for me the best approch is to have a global RXBuffer like this:
#include <cstdint>
#include <deque>
#include <algorithm>
class RXBuffer {
public:
friend class ISR;
typedef std::deque<uint8_t>::const_iterator const_iterator;
RXBuffer();
size_t size() const { m_buffer.size(); }
// read from the buffer in a container in the range [first, last)
template <typename Iterator>
void read(Iterator first, Iterator last, Iterator to)
{
// how many bytes do you want to read?
size_t bytes_to_read = std::distance(first, last);
if (bytes_to_read >= size())
{
// read the whole buffer
std::copy(begin(), end(), first);
// empty the buffer
m_buffer.clear();
return size();
}
else
{
// copy the data
copy(begin(), begin() + bytes_to_read, firt);
// now enque the element
m_buffer.erase(begin(), begon() + bytes_to_read);
return bytes_to_read;
}
}
private:
void put(uint8_t data)
{
// check buffer overflow
m_buffer.push_back(data);
}
const_iterator begin() const { return m_buffer.begin(); }
const_iterator end() const { return m_buffer.end(); }
private:
std::deque<uint8_t> m_buffer; // buffer where store data
size_t m_size; // effective size of the container
};
class ISR {
public:
ISR(RXBuffer& buffer) : m_buffer(buffer) {}
// ISR Routine
void operator () (uint8_t data)
{
m_buffer.put(data);
}
private:
RXBuffer& m_buffer;
};
RXBuffer g_uart1_rx_buffer;
Now you have the ISR and a RXBuffer where search data, so you need something to wrap the UART functions. You can implement as follow:
class UART {
public:
UART(unsigned int uart_device, RXBuffer& rx_buffer) :
m_uart(uart_device), m_buffer(rx_buffer)
{
}
unsigned int uart_device() const { return m_uart; }
// set the timeout during a read operation
void timeout(unsigned ms) { m_timer.countdown(ms); }
template <typename InputIterator>
void read(InputIterator first, InputIterator last)
{
// start the timer
m_timer.start();
size_t size = std::distance(first, last);
size_t read_bytes = 0;
while (read_bytes != size && !m_timer.is_expired())
{
read_bytes += m_buffer.read(first + read_bytes, last);
}
if (read_bytes != size) throw std::exception("timeout");
}
template <typename OutputIterator>
void send(OutputIterator first, OutputIterator last)
{
size_t size = std::distance(first, last);
uart_send(m_uart, &(*first), size);
}
private:
unsigned int m_uart;
RXBuffer& m_buffer;
timer m_timer;
};
Related
I'm in a pickle regarding concepts relating to timers. How can I can I operate a "delay" inside a timer? This is the best way I can frame the question knowing full well what I'm trying to do is nonsense. The objective is: I wish to test the pinState condition 2 times (once initially and then 4 seconds later) but this all needs to happen periodically (hence a timer).
The platform is NodeMCU running a WiFi (ESP8266 chip) and coding done inside Arduino IDE.
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;
char auth[] = "x"; //Auth code sent via Email
char ssid[] = "x"; //Wifi name
char pass[] = "x"; //Wifi Password
int flag=0;
void notifyOnFire()
{
int pinState = digitalRead(D1);
if (pinState==0 && flag==0) {
delay(4000);
int pinStateAgain = digitalRead(D1);
if (pinStateAgain==0) {
Serial.println("Alarm has gone off");
Blynk.notify("House Alarm!!!");
flag=1;
}
}
else if (pinState==1)
{
flag=0;
}
}
void setup()
{
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
pinMode(D1,INPUT_PULLUP);
timer.setInterval(1000L,notifyOnFire);
}
void loop()
{
//Serial.println(WiFi.localIP());
Blynk.run();
timer.run();
}
an easy fix would be to set the periodicity of the timer to be 4000L timer.setInterval(4000L,notifyOnFire); and in notifyOnFire use a static variable and toggle its value whenever notifyOnFire is called
void notifyOnFire()
{
static char state = 0;
if( state == 0)
{
/* Write here the code you need to be executed before the 4 sec delay */
state = 1;
}
else
{
/* Write here the code you need to be executed after the 4 sec delay */
state = 0;
}
}
The nice thing about static variables is that they are initialized only once at compile time and they retain their values after the scope of code changes (In this case function notifyOnFire exits).
I have a proto message defined as:
message SimpleMessage {
repeated int32 number = 1;}
now, after compiling, the field is of pb_callback_t and I suppose to write that function. (without .options file)
now, where and what should the function contain? where does the data itself being stored and how can I access it/ assign new data to it?
* EDIT *
according to #Groo 's answer, this is the code I tried:
typedef struct {
int numbers_decoded;
} DecodingState;
bool read_single_number(pb_istream_t *istream, const pb_field_t *field, void **arg)
{
// get the pointer to the custom state
DecodingState *state = (DecodingState*)(*arg);
int32_t value;
if (!pb_decode_varint32(istream, &value))
{
const char * error = PB_GET_ERROR(istream);
printf("Protobuf error: %s", error);
return false;
}
printf("Decoded successfully: %d", value);
state->numbers_decoded++;
return true;
}
int main(void) {
int32_t arr[3] = {10, 22, 342};
uint8_t buffer[128];
size_t message_length;
bool status;
SimpleMessage simple = SimpleMessage_init_zero;
printf("\nbefore : arr[0] = %d\n",arr[0]);
// set the argument and the callback fn
simple.number.arg = &arr;
simple.number.funcs.decode = read_single_number;
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
status = pb_encode(&ostream, SimpleMessage_fields, &simple);
message_length = ostream.bytes_written;
SimpleMessage simple1 = SimpleMessage_init_zero;
simple = simple1;
arr[0] = 0;
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// this function will call read_single_number several times
status = pb_decode(&istream, SimpleMessage_fields, &simple);
printf("\nafter : arr[0] = %d\n",arr[0]);
return EXIT_SUCCESS;
}
and the output is:
before : arr[0] = 10
Decoded successfully: 17
after : arr[0] = 0
what do I do wrong?
You can use some nanopb-specific proto flags to force nanopb to generate structs with statically allocated arrays.
However, the default behavior of nanopb's protogen is to generate a callback function which is called by nanopb during encoding (once for the entire list) and decoding (once for each item in the list). This is sometimes preferred in low-memory embedded systems, because you don't need to allocate more than one item at a time.
So, for your .proto file:
message SimpleMessage {
repeated int32 number = 1;
}
You might get something like:
typedef struct _SimpleMessage {
pb_callback_t number;
} SimpleMessage;
Meaning you will have to create your own callback function which will be called for each item in succession.
So for simplicity, let's say you have a simple "variable length" list like this:
#define MAX_NUMBERS 32
typedef struct
{
int32_t numbers[MAX_NUMBERS];
int32_t numbers_count;
}
IntList;
// add a number to the int list
void IntList_add_number(IntList * list, int32_t number)
{
if (list->numbers_count < MAX_NUMBERS)
{
list->numbers[list->numbers_count] = number;
list->numbers_count++;
}
}
Obviously, for such an example, using callbacks wouldn't make any sense, but it makes the example simple.
Encoding callback must iterate through the list, and write the protobuf tag and the value for each item in the list:
bool SimpleMessage_encode_numbers(pb_ostream_t *ostream, const pb_field_t *field, void * const *arg)
{
IntList * source = (IntList*)(*arg);
// encode all numbers
for (int i = 0; i < source->numbers_count; i++)
{
if (!pb_encode_tag_for_field(ostream, field))
{
const char * error = PB_GET_ERROR(ostream);
printf("SimpleMessage_encode_numbers error: %s", error);
return false;
}
if (!pb_encode_svarint(ostream, source->numbers[i]))
{
const char * error = PB_GET_ERROR(ostream);
printf("SimpleMessage_encode_numbers error: %s", error);
return false;
}
}
return true;
}
Decoding callback is called once for each item, and "appends" to the list:
bool SimpleMessage_decode_single_number(pb_istream_t *istream, const pb_field_t *field, void **arg)
{
IntList * dest = (IntList*)(*arg);
// decode single number
int64_t number;
if (!pb_decode_svarint(istream, &number))
{
const char * error = PB_GET_ERROR(istream);
printf("SimpleMessage_decode_single_number error: %s", error);
return false;
}
// add to destination list
IntList_add_number(dest, (int32_t)number);
return true;
}
With these two in place, you must be careful to assign the right callback to the right function:
uint8_t buffer[128];
size_t total_bytes_encoded = 0;
// encoding
{
// prepare the actual "variable" array
IntList actualData = { 0 };
IntList_add_number(&actualData, 123);
IntList_add_number(&actualData, 456);
IntList_add_number(&actualData, 789);
// prepare the nanopb ENCODING callback
SimpleMessage msg = SimpleMessage_init_zero;
msg.number.arg = &actualData;
msg.number.funcs.encode = SimpleMessage_encode_numbers;
// call nanopb
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
if (!pb_encode(&ostream, SimpleMessage_fields, &msg))
{
const char * error = PB_GET_ERROR(&ostream);
printf("pb_encode error: %s", error);
return;
}
total_bytes_encoded = ostream.bytes_written;
printf("Encoded size: %d", total_bytes_encoded);
}
And similar for decoding:
// decoding
{
// empty array for decoding
IntList decodedData = { 0 };
// prepare the nanopb DECODING callback
SimpleMessage msg = SimpleMessage_init_zero;
msg.number.arg = &decodedData;
msg.number.funcs.decode = SimpleMessage_decode_single_number;
// call nanopb
pb_istream_t istream = pb_istream_from_buffer(buffer, total_bytes_encoded);
if (!pb_decode(&istream, SimpleMessage_fields, &msg))
{
const char * error = PB_GET_ERROR(&istream);
printf("pb_decode error: %s", error);
return;
}
printf("Bytes decoded: %d", total_bytes_encoded - istream.bytes_left);
}
If you have a repeated struct inside your message, your callback will not use
nanopb primitive functions (like pb_decode_varint32 above), but again pb_decode for each concrete message type. Your callback can also attach new callbacks to those nested structs, if needed.
To complement Groo's answer, here are answers to your specific questions.
1. Now, where and what should the function contain?
Groo provided good explanation of the callback functions. The network_server example in nanopb repository also uses callbacks and can be a useful reference: network_server/server.c network_server/client.c
2. Where does the data itself being stored?
Wherever you want! The whole point of nanopb's callbacks is that it gives you full flexibility in deciding how to store your data. In some cases you may want to even process the data on the fly, not storing it anywhere.
For example, the network_server example above gets the filenames from filesystem and sends them to the network directly - this way it can handle any amount of files without requiring much memory.
3. How can I access it/ assign new data to it?
Now this is the downside of callbacks - you'll have to implement your own access and allocation functions for whatever storage you use. That's why for the most common cases, either static allocation (with fixed maximum size) or dynamic allocation (which malloc()s required amount of memory) are more convenient.
I'm using a microcontroller to communicate with a SIM808 module and I want to send and receive AT commands.
The problem right now is that for some commands I receive only some portions of the answers I should receive, but for some others I receive what I should. For example, if I shut down the module I receive "NORMAL POWER DOWN", as expected.
I believe I'm receiving everything, I'm just not being capable of seeing it. I receive the beginning and the end of the response, so the problem should be on the way I parse and buffer. I'm using a FIFO buffered RXC interrupt.
For example, for the command "AT+CBC" I should receive something like:
"
+CBC: 1,96,4175
OK
"
But I receive "+CBC1,4130OK"
(I replaced the unreadable characters with a dot)
bool USART_RXBufferData_Available(USART_data_t * usart_data)
{
/* Make copies to make sure that volatile access is specified. */
uint8_t tempHead = usart_data->buffer.RX_Head;
uint8_t tempTail = usart_data->buffer.RX_Tail;
/* There are data left in the buffer unless Head and Tail are equal. */
return (tempHead != tempTail);
}
uint8_t USART_receive_array (USART_data_t * usart_data, uint8_t * arraybuffer)
{
uint8_t i = 0;
while (USART_RXBufferData_Available(usart_data))
{
arraybuffer[i] = USART_RXBuffer_GetByte(usart_data);
++i;
}
return i;
}
void USART_send_array (USART_data_t * usart_data, uint8_t * arraybuffer, uint8_t buffersize)
{
uint8_t i = 0;
/* Wait until it is possible to put data into TX data register.
* NOTE: If TXDataRegister never becomes empty this will be a DEADLOCK. */
while (i < buffersize)
{
bool byteToBuffer;
byteToBuffer = USART_TXBuffer_PutByte(usart_data, arraybuffer[i]);
if(byteToBuffer)
{
++i;
}
}
}
void send_AT(char * command){
uint8_t TXbuff_size = strlen((const char*)command);
USART_send_array(&expa_USART_data, (uint8_t *)command, TXbuff_size);
fprintf(PRINT_DEBUG, "Sent: %s\n\n", command);
}
void receive_AT(uint8_t *RXbuff){
memset (RXbuff, 0, 100);
uint8_t bytes = 0;
bytes = USART_receive_array(&expa_USART_data, RXbuff);
int n;
if (bytes>0)
{
RXbuff[bytes]=0;
for (n=0;n<bytes;n++)
{
if (RXbuff[n]<32)
{
RXbuff[n]='.';
}
}
}
fprintf(PRINT_DEBUG, "Received: %s\n\n", RXbuff);
}
int main(){
unsigned char RXbuff[2000];
send_AT("ATE0\r\n");
receive_AT(RXbuff);
send_AT("AT\r\n");
receive_AT(RXbuff);
send_AT("AT+IPR=9600\r\n");
receive_AT(RXbuff);
send_AT("AT+ECHARGE=1\r\n");
receive_AT(RXbuff);
send_AT("AT+CBC\r\n");
_delay_ms(2000);
receive_AT(RXbuff);
send_AT("AT+CSQ\r\n");
_delay_ms(2000);
receive_AT(RXbuff);
}
So, the problem didn't have to do with this part of the code. I am using an emulated serial port to print stuff from the micro-controller to the PC. The issue was that the rate with which I was printing a char to the PC was much faster than what the PC was receiving, that's why some parts didn't appear.
I've got a problem with my arduino program. I'm using a RFID reader to scan cards (this part works flawlessly). I want the program to grant access to using some buttons (doesn't matter to be honest). The user who uses a verified card can use the functionalities until he scans a card again. I've deleted some unnecessary parts of the code.
#include <SPI.h>
#include <MFRC522.h>
String read_rfid;
String ok_rfid_1="a3f90f7"; //ID of the verified CARD
const int buzzer=8; //Buzzer
const int redLed=7;
const int greenLed=6;
const int yellowLed=5;
byte access=false; //
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
read_rfid="";
for (byte i = 0; i < bufferSize; i++) {
read_rfid=read_rfid + String(buffer[i], HEX);
}
}
void granted() { } //it lights up the green led
void denied() { } //it lights up the red led
void login() {
if (read_rfid==ok_rfid_1) {
granted();
access=true;
} else {
denied();
}
delay(1000);
}
void logout() {
if (read_rfid==ok_rfid_1 && access==1) {
access=false;
Serial.println("Logout ");
}
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println(read_rfid);
login();
while(access==true)
{logout();};
}
The logging in part works well, but it logs out automatically. As I observed the problem might be that if(read_rfid==ok_rfid_1 && access==1) is always true, because the read_rfid does not change. Do you have any ideas to solve my dillema?
I have ran into very strange behavior of my code, the basic flow of code is
main () parses a file and sets global variables accordingly.. such as
int frame_size, version;
typedef struct//file parsing variables
{
int frame,
int version; } configuration;
***//the function init_parse calls***
static int handler(void* user, const char* section, const char* name,
const char* value)
{
configuration* pconfig = (configuration*)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
if (MATCH("protocol", "version")) {
pconfig->version = atoi(value);
}
else if (MATCH("basic", "frames")) {
pconfig->frames= atoi(value);
frame_size=pconfig->frames;
}
else {
return 0; /* unknown section/name, error */
}
return 1;
}
main (){
configuration config;
if (ini_parse("test.ini", handler, &config) < 0) {
printf("Can't load 'test.ini'\n");
getchar();
iret = pthread_create(&hThread,NULL, pcapreader, NULL);
if(iret)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret);
exit(EXIT_FAILURE);
}
}
Now, the line followed by main()'s parsing line, everything seems set, but as soon as thread is started , the value frame_size changes to something 6345720:/
I have double checked code for possible replicated variable. thread only uses frame_size in for loop to check the limit.
the only problem was with initialization, once initialized, everything worked like a charm :)
I think it might never initialize the frame_size variable and never reached MATCH("basic", "frames") statement too.