I have some (mostly CubeMX-generated) code:
volatile uint8_t buf[4];
int main(void)
{
...
HAL_UART_Receive_IT(&huart3, buf, sizeof(buf));
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
if (huart->Instance == USART3) {
HAL_UART_Transmit(&huart3, buf, sizeof(buf), 0xFFFF);
HAL_UART_Receive_IT(&huart3, buf, sizeof(buf));
}
}
This successfully echos everything which is received on USART3. (This code is just a throw-away example to learn about the serial port.)
I am concerned about the time between HAL_UART_RxCpltCallback() being called and HAL_UART_Receive_IT() setting up the next receive.
Is there any feature of the STM32F103 which guarantees that data won't be lost in this interval? I haven't found any evidence of more than a two byte receive buffer on the USART.
I am particularly concerned that some higher-priority USB-device activity might delay the calling of HAL_UART_RxCpltCallback(), and so one or more characters might be lost.
Quick answer:
HAL_UART_Transmit is a blocking function, so, until it completes HAL_UART_Receive_IT is not called and the uart will surely go overflow. If you are worried of any other interrupt can preemt your execution, use dma or disable the troublesome interrupts while you issue the command. You could also rise UART interrupt priority but....
Hints:
....you should not call HAL_UART_Transmit and HAL_UART_Receive_IT within HAL_UART_RxCpltCallback as here you are in ISR mode. This cause some side issues on certain versions of the HAL framework. Better to set a flag and check for it from the main code.
Also you should really avoid the use of volatile, better if you use a compiler barrier like gcc __asm volatile("" ::: "memory")
I'm playing on this example:
https://doc-snapshots.qt.io/qt5-dev/qtbluetooth-heartrate-server-example.html
to better understand how to configure a GATT server.
The example fakes a HeartRate profile. In detail it creates a characteristic with this client descriptor:
const QLowEnergyDescriptorData clientConfig(QBluetoothUuid::ClientCharacteristicConfiguration, QByteArray(2, 0));
from here:
https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
I understand it has both notifications and indications disabled by default (in fact I need to enable them from a client application in order to be notified).
What I really don't understand is this code:
quint8 currentHeartRate = 60;
const auto heartbeatProvider = [&service, ¤tHeartRate, &valueChange]() {
QByteArray value;
value.append(char(0)); // Flags that specify the format of the value.
value.append(char(currentHeartRate)); // Actual value.
QLowEnergyCharacteristic characteristic = service->characteristic(QBluetoothUuid::HeartRateMeasurement);
service->writeCharacteristic(characteristic, value); // Potentially causes notification.
...
Well, it appends two bytes to the characteristic's value because it was defined above:
QLowEnergyCharacteristicData charData;
charData.setUuid(QBluetoothUuid::HeartRateMeasurement);
charData.setValue(QByteArray(2, 0));
but what does the first one mean?
value.append(char(0)); // Flags that specify the format of the value.
I cannot find any documentation about this "format".
The first byte is the flags field specified in the Heart Rate Service (HRS)here. In this example, flags field indicates that the heart rate measurement value is in uint8 format.
MyApp.exe is installed using an InstallScript 2014 project. The folks in manufacturing recently tried to upgrade to a more recent development version but did not close the existing instance of MyApp. This resulted in many permission denied errors since the various dll's used by the app were locked and in use.
I expected the InstallScript executable to do the usual "stage and reboot" thing that all Windows folks are intimate with. It did not do that, and I can't see anything in the InstallShield project editor that obviously lets me force that behavior.
I also expected InstallScript to allow me to somehow detect that my app was already running - if I can do that, I can display a dialog to give the user a chance to close the app and continue. The only solution for this is InstallSite.org List and Shutdown Running Processes. (Note this is unanswered on another S/O question.)
That does not properly detect all of the running tasks, including my own.
Before I spend a couple of days trying to fix what seems to be an obviously missing feature of InstallScript, I thought I'd ask if there's a better approach.
Here's what I came up with. Hope this helps.
// defines/protos for finding a process
#define TH32CS_SNAPPROCESS 0x00000002
// in Kernel32.dll
prototype NUMBER Kernel32.CreateToolhelp32Snapshot(NUMBER , NUMBER);
prototype BOOL Kernel32.Process32First(HWND , POINTER );
prototype BOOL Kernel32.Process32Next(HWND , POINTER );
// from minwindef.h, windows api
typedef PROCESSENTRY32
begin
number dwSize;
number cntUsage;
number th32ProcessID; // this process
number th32DefaultHeapID;
number th32ModuleID; // associated exe
number cntThreads;
number th32ParentProcessID; // this process's parent process
number pcPriClassBase; // Base priority of process's threads
number dwFlags;
STRING szExeFile[MAX_PATH]; // Path
end;
// ========================================================================================
// list all of the running processes, see if Flex is running
// based on https://msdn.microsoft.com/en-us/library/windows/desktop/ms686701(v=vs.85).aspx
// ========================================================================================
function BOOL IsProcessRunning(sProcessName)
HWND hProcessSnap;
PROCESSENTRY32 pe;
POINTER ppe;
NUMBER ret;
begin
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize = SizeOf(pe);
ppe = &pe;
ret = Process32First(hProcessSnap, ppe);
if (ret == 0) then
//printError(TEXT("Process32First")); // show cause of failure
CloseHandle(hProcessSnap); // clean the snapshot object
return(FALSE);
endif;
repeat
if (StrCompare(sProcessName, pe.szExeFile) == 0) then
CloseHandle(hProcessSnap); // clean the snapshot object
return(TRUE);
endif;
ret = Process32Next(hProcessSnap, ppe);
until (ret == 0);
return(FALSE);
end;
You then call it
if (IsProcessRunning("WORD.EXE")) then
blah blah
endif;
So, I've already read this article Counting machine instructions of a process using PTRACE_SINGLESTEP, and i understand that dynamically linking a testprogram to my ptrace program will return an instruction count that also counts the initialization of the run-time library. However, I'm trying to get a valid count for my test program, which is:
int main(){
return 0;
}
My ptrace program first also returned 90k+ values, so I changed it to statically linking the used testprogram. The counter is now less, but still over 12k. The program I used to count the instructions is:
#include <sys/ptrace.h>
#include <unistd.h>
#include <stdio.h>
int main() {
long long counter = 1; // machine instruction counter
int wait_val; // child's return value
int pid; // child's process id
int dat;
switch (pid = fork()) { // copy entire parent space in child
case -1: perror("fork");
break;
case 0: // child process starts
ptrace(PTRACE_TRACEME,0,NULL,NULL);
/*
must be called in order to allow the
control over the child process and trace me (child)
0 refers to the parent pid
*/
execl("./returntestprog","returntestprog",NULL);
/*
executes the testprogram and causes
the child to stop and send a signal
to the parent, the parent can now
switch to PTRACE_SINGLESTEP
*/
break;
// child process ends
default: // parent process starts
wait(&wait_val);
if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) != 0)
perror("ptrace");
/*
switch to singlestep tracing and
release child
if unable call error.
*/
wait(&wait_val);
// parent waits for child to stop at next
// instruction (execl())
while (wait_val == 1407) {
counter++;
if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) != 0)
perror("ptrace");
/*
switch to singlestep tracing and
release child
if unable call error.
*/
wait(&wait_val);
// wait for next instruction to complete */
}
/*
continue to stop, wait and release until
the child is finished; wait_val != 1407
Low=0177L and High=05 (SIGTRAP)
*/
}
printf("Number of machine instructions : %lld\n", counter);
return 0;
} // end of switch
Any help would be really appreciated as I'm not quite sure if it's working right, or not at all. Once I get this thing started, I want to work on timing analysis with ptrace, but first things first and try to count the number of executed instructions
thanks!
I've kind of figured it out by now. So even when statically linking your code, you try to prevent the libraries to be dynamically linked to your program and thus also included into your count. The other side of it however is that executing your file, or basically invoking under the operating system also takes an enormous amount of instructions. So basically, as long as the instruction count is constant and the same under the same conditions, you can subtract this count (when using a return 0 program for instance) from your original program, to count the real number of instructions.
I want to write an FSM which starts with an idle state and moves from one state to another based on some event. I am not familiar with coding of FSM and google didn't help.
Appreciate if someone could post the C data structure that could be used for the same.
Thanks,
syuga2012
We've implemented finite state machine for Telcos in the past and always used an array of structures, pre-populated like:
/* States */
#define ST_ANY 0
#define ST_START 1
: : : : :
/* Events */
#define EV_INIT 0
#define EV_ERROR 1
: : : : :
/* Rule functions */
int initialize(void) {
/* Initialize FSM here */
return ST_INIT_DONE
}
: : : : :
/* Structures for transition rules */
typedef struct {
int state;
int event;
(int)(*fn)();
} rule;
rule ruleset[] = {
{ST_START, EV_INIT, initialize},
: : : : :
{ST_ANY, EV_ERROR, error},
{ST_ANY, EV_ANY, fatal_fsm_error}
};
I may have the function pointer fn declared wrong since this is from memory. Basically the state machine searched the array for a relevant state and event and called the function which did what had to be done then returned the new state.
The specific states were put first and the ST_ANY entries last since priority of the rules depended on their position in the array. The first rule that was found was the one used.
In addition, I remember we had an array of indexes to the first rule for each state to speed up the searches (all rules with the same starting state were grouped).
Also keep in mind that this was pure C - there may well be a better way to do it with C++.
A finite state machine consists of a finite number discrete of states (I know pedantic, but still), which can generally be represented as integer values. In c or c++ using an enumeration is very common.
The machine responds to a finite number of inputs which can often be represented with another integer valued variable. In more complicated cases you can use a structure to represent the input state.
Each combination of internal state and external input will cause the machine to:
possibly transition to another state
possibly generate some output
A simple case in c might look like this
enum state_val {
IDLE_STATE,
SOME_STATE,
...
STOP_STATE
}
//...
state_val state = IDLE_STATE
while (state != STOP_STATE){
int input = GetInput();
switch (state) {
case IDLE_STATE:
switch (input) {
case 0:
case 3: // note the fall-though here to handle multiple states
write(input); // no change of state
break;
case 1:
state = SOME_STATE;
break
case 2:
// ...
};
break;
case SOME_STATE:
switch (input) {
case 7:
// ...
};
break;
//...
};
};
// handle final output, clean up, whatever
though this is hard to read and more easily split into multiple function by something like:
while (state != STOP_STATE){
int input = GetInput();
switch (state) {
case IDLE_STATE:
state = DoIdleState(input);
break;
// ..
};
};
with the complexities of each state held in it's own function.
As m3rLinEz says, you can hold transitions in an array for quick indexing. You can also hold function pointer in an array to efficiently handle the action phase. This is especially useful for automatic generation of large and complex state machines.
The answers here seem really complex (but accurate, nonetheless.) So here are my thoughts.
First, I like dmckee's (operational) definition of an FSM and how they apply to programming.
A finite state machine consists of a
finite number discrete of states (I
know pedantic, but still), which can
generally be represented as integer
values. In c or c++ using an
enumeration is very common.
The machine responds to a finite
number of inputs which can often be
represented with another integer
valued variable. In more complicated
cases you can use a structure to
represent the input state.
Each combination of internal state and
external input will cause the machine
to:
possibly transition to another state
possibly generate some output
So you have a program. It has states, and there is a finite number of them. ("the light bulb is bright" or "the light bulb is dim" or "the light bulb is off." 3 states. finite.) Your program can only be in one state at a time.
So, say you want your program to change states. Usually, you'll want something to happen to trigger a state change. In this example, how about we take user input to determine the state - say, a key press.
You might want logic like this. When the user presses a key:
If the bulb is "off" then make the bulb "dim".
If the bulb is "dim", make the bulb "bright".
If the bulb is "bright", make the bulb "off".
Obviously, instead of "changing a bulb", you might be "changing the text color" or whatever it is you program needs to do. Before you start, you'll want to define your states.
So looking at some pseudoish C code:
/* We have 3 states. We can use constants to represent those states */
#define BULB_OFF 0
#define BULB_DIM 1
#define BULB_BRIGHT 2
/* And now we set the default state */
int currentState = BULB_OFF;
/* now we want to wait for the user's input. While we're waiting, we are "idle" */
while(1) {
waitForUserKeystroke(); /* Waiting for something to happen... */
/* Okay, the user has pressed a key. Now for our state machine */
switch(currentState) {
case BULB_OFF:
currentState = BULB_DIM;
break;
case BULB_DIM:
currentState = BULB_BRIGHT;
doCoolBulbStuff();
break;
case BULB_BRIGHT:
currentState = BULB_OFF;
break;
}
}
And, voila. A simple program which changes the state.
This code executes only a small part of the switch statement - depending on the current state. Then it updates that state. That's how FSMs work.
Now here are some things you can do:
Obviously, this program just changes the currentState variable. You'll want your code to do something more interesting on a state change. The doCoolBulbStuff() function might, i dunno, actually put a picture of a lightbulb on a screen. Or something.
This code only looks for a keypress. But your FSM (and thus your switch statement) can choose state based on what the user inputted (eg, "O" means "go to off" rather than just going to whatever is next in the sequence.)
Part of your question asked for a data structure.
One person suggested using an enum to keep track of states. This is a good alternative to the #defines that I used in my example. People have also been suggesting arrays - and these arrays keep track of the transitions between states. This is also a fine structure to use.
Given the above, well, you could use any sort of structure (something tree-like, an array, anything) to keep track of the individual states and define what to do in each state (hence some of the suggestions to use "function pointers" - have a state map to a function pointer which indicates what to do at that state.)
Hope that helps!
See Wikipedia for the formal definition. You need to decide on your set of states S, your input alphabet Σ and your transition function δ. The simplest representation is to have S be the set of integers 0, 1, 2, ..., N-1, where N is the number of states, and for Σ be the set of integers 0, 1, 2, ..., M-1, where M is the number of inputs, and then δ is just a big N by M matrix. Finally, you can store the set of accepting states by storing an array of N bits, where the ith bit is 1 if the ith state is an accepting state, or 0 if it is not an accepting state.
For example, here is the FSM in Figure 3 of the Wikipedia article:
#define NSTATES 2
#define NINPUTS 2
const int transition_function[NSTATES][NINPUTS] = {{1, 0}, {0, 1}};
const int is_accepting_state[NSTATES] = {1, 0};
int main(void)
{
int current_state = 0; // initial state
while(has_more_input())
{
// advance to next state based on input
int input = get_next_input();
current_state = transition_function[current_state][input];
}
int accepted = is_accepting_state[current_state];
// do stuff
}
You can basically use "if" conditional and a variable to store the current state of FSM.
For example (just a concept):
int state = 0;
while((ch = getch()) != 'q'){
if(state == 0)
if(ch == '0')
state = 1;
else if(ch == '1')
state = 0;
else if(state == 1)
if(ch == '0')
state = 2;
else if(ch == '1')
state = 0;
else if(state == 2)
{
printf("detected two 0s\n");
break;
}
}
For more sophisticated implementation, you may consider store state transition in two dimension array:
int t[][] = {{1,0},{2,0},{2,2}};
int state = 0;
while((ch = getch()) != 'q'){
state = t[state][ch - '0'];
if(state == 2){
...
}
}
A few guys from AT&T, now at Google, wrote one of the best FSM libraries available for general use. Check it out here, it's called OpenFST.
It's fast, efficient, and they created a very clear set of operations you can perform on the FSMs to do things like minimize them or determinize them to make them even more useful for real world problems.
if by FSM you mean finite state machine,
and you like it simple, use enums to name your states
and switch betweem them.
Otherwise use functors. you can look the
fancy definition up in the stl or boost docs.
They are more or less objects, that have a
method e.g. called run(), that executes
everything that should be done in that state,
with the advantage that each state has it's own
scope.