How to simulate multiple instances of the same program communicating in C? - c

I need to write code in C that will ultimately run on an embedded system and its purpose is that multiple physical instances of these embedded systems can communicate with each other.
I want to test this first in simulation, but I am not very experienced in C. In C++ or other object oriented languages, I would just create multiple instances of the same class and let them communicate in the simulation.
How could I do that in C?
Edit: To avoid misunderstandings: I am interested in how I can start up multiple instances of the code, so that every instance then has its own data.

You're being very vague in how exactly the two devices are going to communicate, so I'm going to assume the microchip (or whatever) you're using has some kind of interface, that will get digital pulses and store them in some fixed address in memory. If that's the case, you can make two functions:
send_data(char data), will send the other machine data
receive_data(), will get the most recently sent byte of data
Then, you can make use of the C's preprocessor:
#if SIMULATION
// Code for simulated data communication
#else
// Code for real data communication
#endif
void send_data(char data) {
#if SIMULATION
// Code for simulated data communication
#else
// Code for real data communication
#endif
}
char receive_data() {
#if SIMULATION
// Code for simulated data communication
#else
// Code for real data communication
#endif
}
Then, when simulating the program, just compile with gcc ... -D SIMULATION=1
You could then use some sort of multithreading to start up the main function multiple times. This is the easiest way I can think of

Related

Proxy pattern for hardware access in embedded C

I am reading a book that "Design Patterns for Embedded Systems in C" which is written by Bruce Powel Douglass and ı decided to using Hardware Proxy Pattern for providing encapsulated access to hardware but at some point ı am not sure exactly about impelementing proxy pattern.
For better understanding ı am going to add a scenario:
Let's assume there is a PMIC( power management ic) which can communicate over one of some serial communications.
We write a pmic.c and pmic.h file which are defined and declarated all variables,function and registers address and values to work with pmic. Let's look at definitions and declarations of some of them:
-in pmic.c-
//included already serial communucation header file like as #include "app_I2C.h"
uint32_t pmic_read_battery_voltage(){/*Some serial comm function here*/}
bool pmic_Init(){/*Some serial comm function here*/}
bool pmic_configure(uint32_t pmic_cfg){/*Some serial comm function here*/}
bool pmic_set_charge_current(uint8_t charge_curr){/*Some serial comm function here*/}
-in pmic.h-
uint32_t pmic_read_battery_voltage();
bool pmic_Init();
bool pmic_configure(uint32_t pmic_cfg);
bool pmic_set_charge_current(uint8_t charge_curr);
So you can see that if ı give that pmic.c file directly to client they never access directly hardware side and more than one clients can access this file (maybe another .c files). In fact this is nature of C.
Can we say this pmic.c driver written in proxy pattern because it is hiding hardware side from clients ? ( ı could change basically serial communication side without clients changing anything on their side)
or
have ı to create new pmicproxy.c file which is including above functions again with having generic struct(like as class ) for access all properties of hardware?

Stm32 Log Messages

good day, stm32 nucleo board I want to write informative Log messages using.
For example, I want to display the message that the program has started by using the Log("Program started") function when the program starts during this period, or I want to give the error message to the screen by using the Log("Program Failed') function when the program fails.
I using C programming langue and stm32cubeide & Nucleo f207zg board thanks in advance for your help
Thanks I solved the problem
Given that:
You know what the UART/USART peripheral is
You connected the right pins to a serial interface
You connected the other end of the interface (for instance an FTDI chip) to your computer
You can implement the logging with printf as you would do in C. Why? Because printf already takes care for you the formatting of the strings, which no one wants to reimplement, and then you redirect the printf output to the UART peripheral that handles low level serial protocol.
Following this guide the steps are easy enough:
Add #include <stdio.h> to the Includes section at the top of the main.c
#include "stdio.h"
Copy and paste the following code into the main.c file before the main() function but after the UART handle declaration
Note that you need to replace the question mark with the actual UART handle declaration, for instance huart1
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart?, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
return ch;
}
As pointed out by Fra93, you need to implement UART/USART protocol communication and print stuff to there. I'm writing this reply, because I'm getting a feeling you have some basic experience writing desktop applications, but not embedded, so I will clarify a few points.
There is no console to print to. There are no logs. They simply don't exist. At all. Not in a desktop app development sense.
What's usually done is that one of the UARTs of the MCU is used to print characters to the ST-Link, which converts it to USB (alternatively, can be FTDI IC, CP2102 or other USB-UART bridges/converters). So then your MCU will send out characters over UART, and the USB-UART converter will display them in a COM port terminal (programs like PuTTy)
If you start with empty project and no external libraries used, you will need 3 dozen lines of code alone just to be able to print stuff. Initially, you have nothing. You have to initialize UART, configure it, then implement how it handles characters, numbers. You need to literally write a basic UART driver. And you can call printing function whatever you want. You can call it Log("hello world"), you can call it Whisper("hi there"). Because you will actually create this function. You're the boss.
Now, given you are not very familiar with all of this, it may sound like a difficult task. And it most certainly is. Writing a driver from scratch on your day 1 is not a thing you want to do (unless you're into that kind of stuff on day 1).
I would strongly advise you to get some library, such as HAL by STMicroelectronics, and familiarize yourself with what it can do - including how to print stuff with UART. Internet is flooded with articles and videos of how to use UART with HAL, it's literally one of the first things to be implemented. Specifically for the reason, that it works like logs and simplifies further development/learning.
So, in order to get "logs" working, I would do the following:
Get HAL for your specific MCU
Familiarize yourself with UART - basic stuff about what it is and how it works. No need to be an expert, just learn what it is.
Familiarize yourself with how to use UART with HAL
From the schematic of the PCB of your nucleo board, find out which UART of the MCU is connected to ST-Link (I checked the schematic: it's USART3)
Get serial port (COM) terminal program for your computer
Use HAL to initialize USART3 and print to USART3. Whatever you print there will be visible in the terminal. Yes, you will not see anything in the IDE. You need a separate program to display what you receive via USB COM port.
In the end, your print function will be the one proposed by Fra93. HAL_UART_Transmit is the most basic HAL function to send stuff via UART. If you're very picky about using "Log" as a function you call to print via UART, you can always wrap HAL_UART_Transmit into your own function called Log.

How to structure an embedded application while decoupling application and driver code for a peripheral (UART)?

So I'm writing drivers for UART on STM32 and even though I kind of have an idea on laying out the structure, I'd still want to clarify prior to implementing, and also considering how essential it is to keep the code clean and organized.
So I have main.c, sensor.c (application file that uses UART layer), hal_usart.c (which is the driver file).
I have heard different things regarding how application code should have no clue whatsoever about the driver APIs, and read up an article the other day that you could decouple the sensor code from HAL driver code using function pointers but not sure how I could do that here, and if that will decouple it considering I'm still passing a reference to USART_Handle struct that contains info like baudRate, parityControl, wordLength, reference to USART_TypeDef etc.
Below is a snippet of my idea:
// main.c
static USART_Handle pUSART;
int main(void) {
// initialize clocks/HAL
// ...initialize USART struct
// Get data via UART (calling application API)
GetData(&pUSART);
}
// sensor.c (application)
void GetData(USART_Handle *pUSART) {
HAL_USART_TX();
HAL_USART_RX(); // assuming data is stored in one of the struct members
}
// hal_usart.c (Driver file)
void HAL_USART_TX() {}
void HAL_USART_RX() {}
Since you would like to separate Application code and Driver code in an embedded system, I suggest you study how to implement callback functions in C also embedded systems.
Here is the reference.
The utility of function pointers is maximum when you want to change the pointer while the program is running; or, in other words, when you have at least two different functions and, based on some condition, you want to use one or another.
For example, let's say you have a routine which reads a sensor using a serial port, and the user can switch from a sensor to another (two serial ports or even two different methods). In that case, the sensor routine could call a function, to read, using a function pointer, and manage the back read data. The main program, by changing the function pointer, can instruct the sensor routine to use one or the other sensor.
If you don't need to change things at runtime, you can simply write your sensor routine making it call a reading function (external) defined in some other file. The documentation of the sensor routine simply has to state that somewhere must be defined a routine called "int sensor_get_data()".
This involves to design your own "internal protocol" based on what data goes and comes from the "detached drivers". For example, the sensor routine, which copes with a precise model of a sensor, can have the need to send a command and receive a response. You can write your sensor routine which construct the command and decodes the answer, and take away the low level details wrapping all them in the single function "int sensor_get_data(int command)". You then link or include the sensor code, and implement the function sensor_get_data() in the main.
The main() does not know the details of the sensor, it only knows that the sensor code, when needed, will call the function sensor_get_data(). But this function can use an UART, or an i2c or a spi, without the sensor routine even noticing that; moreover, this routine can use any of the three ports, perhaps basing on parameters the user can modify at runtime.
All this can be named "callback mechanism", and implements a sort of separation between declaration and implementation, as mentioned in the other answer. What I depicted is not different from that, but it is static - the program is compiled with a fixed callback, instead of passing a function pointer in every call.

Embedded Firmware Architecture

I’ve been writing increasingly complex firmware and am starting to notice that my knowledge of design patterns and architecture is a bit lacking. I’m trying to work on developing these skills and am hoping for some input. Note: this is for embedded c for microcontrollers.
I’m working with a concept for a new project as an exercise right now that goes something like this:
We have a battery management module with user I/O
The main controller is responsible for I/O (button, LCD, UART debug), detecting things like the charger being plugged in/unplugged, and managing high level operations.
The sub controller is a battery management controller (pretty much a custom PMIC) capable of monitoring battery levels, running charging/discharging firmware etc.
The PMIC interfaces with a fuel gauge IC that it uses to read battery information from
The interface between the two controllers, fuel gauge and the LCD are all I2C
Here is a rough system diagram:
Now what I’m trying to do is to come up with a good firmware architecture that will allow for expandability (adding multiple batteries, adding more sensors, changing the LCD (or other) interface from I2C to SPI, etc), and for testing (simulate button presses via UART, replace battery readings with simulated values to test PMIC charge firmware, etc).
What I would normally do is write a custom driver for each peripheral, and a firmware module for each block. I would implement a flagging module as well with a globally available get/set that would be used throughout the system. For example my timers would set 100Hz, 5Hz, 1Hz, flags, which the main loop would handle and call the individual modules at their desired rate. Then the modules themselves could set flags for the main loop to handle for events like I2C transaction complete, transaction timed out, temperature exceeded, etc.
What I am hoping to get from this is a few suggestions on a better way to architect the system to achieve my goals of scalability, encapsulation and abstraction. It seems like what I’m doing is sort of a pseudo event-driven system but one that’s been hacked together.
In any case here’s my attempt at an architecture diagram:
The concept of an "event bus" is over-complicated. In many cases, the simplest approach is to minimize the number of things that need to happen asynchronously, but instead have a "main poll" routine which runs on an "as often as convenient" basis and calls polling routines for each subsystem. It may be helpful to have such routine in a compilation by itself, so that the essence of that file would simply be a list of all polling functions used by other subsystems, rather than anything with semantics of its own. If one has a "get button push" routine, one can have a loop within that routine which calls the main poll routine until a button is pushed, there's a keyboard timeout, or something else happens that the caller needs to deal with. That would then allow the main UI to be implemented using code like:
void maybe_do_something_fun(void)
{
while(1)
{
show_message("Do something fun?");
wait_for_button();
if (button_hit(YES_BUTTON))
{
... do something fun
return;
}
else if (button_hit(NO_BUTTON))
{
... do something boring
return;
}
} while(1);
}
This is often much more convenient than trying to have a giant state machine and say that if the code is the STATE_MAYBE_DO_SOMETHING_FUN state and the yes or no button is pushed, it will need to advance to the STATE_START_DOING_SOMETHING_FUN or STATE_START_DOING_SOMETHING_BORING state.
Note that if one uses this approach, one will need to ensure that the worst-case time between calls to main_poll will always satisfy the timeliness requirements of the polling operations handled through main_poll, but in cases where that requirement can be met, this approach can be far more convenient and efficient than doing everything necessary to preemptively-scheduled multi-threaded code along with the locks and other guards needed to make it work reliably.

netfilter_queue : use --queue-balance in multithreaded environment

I'm using libnetfilter_queue for userspace modification of
incoming/outgoing packets. I have been using a single threaded model.
But i've found out that from 2.6.31 kernel, its possible to have
different queues for different connection. so i was wandering if its
possible to manage each queues in different threads.
normally i set up the queue handling like bellow:
struct nfq_handle * h = nfq_open();
nfq_unbind_pf(h, AF_NET);
nfq_bind_pf(h,m AF_NET);
struct nfq_q_handle(h, 0, &cb, NULL);
nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff);
now if i want to manage like 100 queues, i will pack h,qh and que_num in
a structure and loop over it to initialize.
now my question is :
if i initialize above in the main thread and want to run the callbacks
in separate threads, is it enough to run the even loop in a function which will
be given to pthread_create()? Will it run the callbacks in threads?
i'm not sure, but my understanding tells me, a packet is popped from the
queues when nfq_set_verdict is returned. so i need to run
nfq_set_verdict in separate threads so that i packets can be popped from
queues parallel.
EDIT: i provide my code if someone needs them to understand my problem. pasting all codes here seems unreasonable as it creates visual noise.
I know this is a bit of necroposting, but in case anyone stumbles on this problem.
If you use --queue-balance for multithreading and netfilter seems to put all packets in one queue, one should add --queue-cpu-fanout, which forces iptables to share packets based on cpuid instead of flow.

Resources