I don't find the way to get the string specified in the dialog box of an S-function (C, level 2) block and save it in a variable, inside the .c file corresponding to the block.
Through *mxGetPr(ssGetSFcnParam(S, 0)) I can only get the first position value in the string.
The parameter entered in the dialog block what it is related to the ssGetSFcnParam(S, 0) is '123'.
In the mask editor of the block the type is 'edit'.
#define S_FUNCTION_NAME ver_file_data
#define S_FUNCTION_LEVEL 2
#define NPARAMS 14
#define DVC_TYPE(S) ssGetSFcnParam(S, 0)
static void mdlInitializeSizes(SimStruct *S){
DECL_AND_INIT_DIMSINFO(outputDimsInfo);
ssSetNumSFcnParams(S, NPARAMS); /* Number of expected parameters */
ssSetSFcnParamTunable(S, 0, 0);
ssSetSFcnParamTunable(S, 1, 0);
#if defined(MATLAB_MEX_FILE) if (ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S)) {
mdlCheckParameters(S);
if (ssGetErrorStatus(S) != NULL) {
return;
} } else {
return; }
#endif
ssSetNumContStates(S, 0);
ssSetNumDiscStates(S, 0);
if (!ssSetNumInputPorts(S, NUM_INPUTS)) return;
if (!ssSetNumOutputPorts(S, NUM_OUTPUTS)) return;
/* Output Port 0 */
ssSetOutputPortWidth(S, 0, 1);
ssSetOutputPortDataType(S, 0, SS_UINT8);
ssSetNumSampleTimes(S, 1);
ssSetNumRWork(S, 0);
ssSetNumIWork(S, 0);
ssSetNumPWork(S, 0);
ssSetNumModes(S, 0);
ssSetNumNonsampledZCs(S, 0);
}
static void mdlInitializeSampleTimes(SimStruct *S){
ssSetSampleTime(S, 0, -1);
ssSetOffsetTime(S, 0, 0.0);
}
static void mdlOutputs(SimStruct *S, int_T tid){
ssPrintf("DVC_IND_NO = %x\n",*mxGetPr(DVC_IND_NO(S)));
}
mdlRTW (SimStruct *S){
}
Before getting anything through the outputport, I would like to be able to print with ssPrintf("DVC_IND_NO = %x\n",*mxGetPr(DVC_IND_NO(S))); the 123.
Thank you, best regards.
mxGetPr returns a pointer to double, so makes no sense if the parameter is a char array. And in using *mxGetPr you are saying that you want the value that is pointed to (i.e. the first element, if it is a multi-element double array), which is why you are only getting the first value.
If the input is expected to be a string (i.e. array of char) then you should be using mxArrayToString to access it.
Either way, you should definitely be using helper functions like mxIsChar and mxIsDouble to check the data type before using the appropriate function to access the data.
Add the following at the top
#define DVC_IND_NO(S) = ssGetSFcnParam(S,0)
and the follwoing in your mdlOutputs
char* str;
int i = 0;
str = mxArrayToString(DVC_IND_NO(S));
ssPrintf("DVC_IND_NO = ");
while (str[i]!='\0')
{
ssPrintf("%c",str[i]);
i++;
}
Related
I want to have my Zedboard return a numeric value using the Xilinx lwIP example as a base but no matter what I do I can't figure out what stores the data received or transmitted.
I have found the void type payload but I don't know what to do with it.
Snapshot of one instance of payload and a list of lwIP files
Below is the closest function to my goal:
err_t recv_callback(void *arg, struct tcp_pcb *tpcb,
struct pbuf *p, err_t err){
/* do not read the packet if we are not in ESTABLISHED state */
if (!p) {
tcp_close(tpcb);
tcp_recv(tpcb, NULL);
return ERR_OK;
}
/* indicate that the packet has been received */
tcp_recved(tpcb, p->len);
/* echo back the payload */
/* in this case, we assume that the payload is < TCP_SND_BUF */
if (tcp_sndbuf(tpcb) > p->len) {
err = tcp_write(tpcb, p->payload, p->len, 1);
//I need to change p->paylod but IDK where it is given a value.
} else
xil_printf("no space in tcp_sndbuf\n\r");
/* free the received pbuf */
pbuf_free(p);
return ERR_OK;
}
Any guidance is appreciated.
Thanks,
Turtlemii
-I cheated and just made sure that the function has access to Global_tpcb from echo.c
-tcp_write() reads in an address and displays each char it seems.
void Print_Code()
{
/* Prepare for TRANSMISSION */
char header[] = "\rSwitch: 1 2 3 4 5 6 7 8\n\r"; //header text
char data_t[] = " \n\r\r"; //area for storing the
data
unsigned char mask = 10000000; //mask to decode switches
swc_value = XGpio_DiscreteRead(&SWCInst, 1); //Save switch values
/* Write switch values to the LEDs for visual. */
XGpio_DiscreteWrite(&LEDInst, LED_CHANNEL, swc_value);
for (int i =0; i<=7; i++) //load data_t with switch values (0/1)
{
data_t[8+2*i] = '0' + ((swc_value & mask)/mask); //convert one bit to 0/1
mask = mask >> 1;//move to next bit
}
int len_header = *(&header + 1) - header; //find the length of the
header string
int len_data = *(&data_t + 1) - data_t; //find the length of the data string
tcp_write(Global_tpcb, &header, len_header, 1); //print the header
tcp_write(Global_tpcb, &data_t, len_data, 1); //print the data
}
I'm using boost::asio with ncurses for a command-line game. The game needs to draw on the screen at a fixed time interval, and other operations (e.g. networking or file operations) are also executed whenever necessary. All these things can be done with async_read()/async_write() or equivalent on boost::asio.
However, I also need to read keyboard input, which (I think) comes from stdin. The usual way to read input in ncurses is to call getch(), which can be configured to either blocking (wait until there is a character available for consumption) or non-blocking (return a sentinel value of there no characters available) mode.
Using blocking mode would necessitate running getch() on a separate thread, which doesn't play well with ncurses. Using non-blocking mode, however, would cause my application to consume CPU time spinning in a loop until the user presses their keyboard. I've read this answer, which suggests that we can add stdin to the list of file descriptors in a select() call, which would block until one of the file descriptors has new data.
Since I'm using boost::asio, I can't directly use select(). I can't call async_read, because that would consume the character, leaving getch() with nothing to read. Is there something in boost::asio like async_read, but merely checks the existence of input without consuming it?
I think you should be able to use the posix stream descriptor to watch for input on file descriptor 0:
ba::posix::stream_descriptor d(io, 0);
input_loop = [&](error_code ec) {
if (!ec) {
program.on_input();
d.async_wait(ba::posix::descriptor::wait_type::wait_read, input_loop);
}
};
There, program::on_input() would call getch() with no timeout() until it returns ERR:
struct Program {
Program() {
initscr();
ESCDELAY = 0;
timeout(0);
cbreak();
noecho();
keypad(stdscr, TRUE); // receive special keys
clock = newwin(2, 40, 0, 0);
monitor = newwin(10, 40, 2, 0);
syncok(clock, true); // automatic updating
syncok(monitor, true);
scrollok(monitor, true); // scroll the input monitor window
}
~Program() {
delwin(monitor);
delwin(clock);
endwin();
}
void on_clock() {
wclear(clock);
char buf[32];
time_t t = time(NULL);
if (auto tmp = localtime(&t)) {
if (strftime(buf, sizeof(buf), "%T", tmp) == 0) {
strncpy(buf, "[error formatting time]", sizeof(buf));
}
} else {
strncpy(buf, "[error getting time]", sizeof(buf));
}
wprintw(clock, "Async: %s", buf);
wrefresh(clock);
}
void on_input() {
for (auto ch = getch(); ch != ERR; ch = getch()) {
wprintw(monitor, "received key %d ('%c')\n", ch, ch);
}
wrefresh(monitor);
}
WINDOW *monitor = nullptr;
WINDOW *clock = nullptr;
};
With the following main program you'd run it for 10 seconds (because Program doesn't yet know how to exit):
int main() {
Program program;
namespace ba = boost::asio;
using boost::system::error_code;
using namespace std::literals;
ba::io_service io;
std::function<void(error_code)> input_loop, clock_loop;
// Reading input when ready on stdin
ba::posix::stream_descriptor d(io, 0);
input_loop = [&](error_code ec) {
if (!ec) {
program.on_input();
d.async_wait(ba::posix::descriptor::wait_type::wait_read, input_loop);
}
};
// For fun, let's also update the time
ba::high_resolution_timer tim(io);
clock_loop = [&](error_code ec) {
if (!ec) {
program.on_clock();
tim.expires_from_now(100ms);
tim.async_wait(clock_loop);
}
};
input_loop(error_code{});
clock_loop(error_code{});
io.run_for(10s);
}
This works:
Full Listing
#include <boost/asio.hpp>
#include <boost/asio/posix/descriptor.hpp>
#include <iostream>
#include "ncurses.h"
#define CTRL_R 18
#define CTRL_C 3
#define TAB 9
#define NEWLINE 10
#define RETURN 13
#define ESCAPE 27
#define BACKSPACE 127
#define UP 72
#define LEFT 75
#define RIGHT 77
#define DOWN 80
struct Program {
Program() {
initscr();
ESCDELAY = 0;
timeout(0);
cbreak();
noecho();
keypad(stdscr, TRUE); // receive special keys
clock = newwin(2, 40, 0, 0);
monitor = newwin(10, 40, 2, 0);
syncok(clock, true); // automatic updating
syncok(monitor, true);
scrollok(monitor, true); // scroll the input monitor window
}
~Program() {
delwin(monitor);
delwin(clock);
endwin();
}
void on_clock() {
wclear(clock);
char buf[32];
time_t t = time(NULL);
if (auto tmp = localtime(&t)) {
if (strftime(buf, sizeof(buf), "%T", tmp) == 0) {
strncpy(buf, "[error formatting time]", sizeof(buf));
}
} else {
strncpy(buf, "[error getting time]", sizeof(buf));
}
wprintw(clock, "Async: %s", buf);
wrefresh(clock);
}
void on_input() {
for (auto ch = getch(); ch != ERR; ch = getch()) {
wprintw(monitor, "received key %d ('%c')\n", ch, ch);
}
wrefresh(monitor);
}
WINDOW *monitor = nullptr;
WINDOW *clock = nullptr;
};
int main() {
Program program;
namespace ba = boost::asio;
using boost::system::error_code;
using namespace std::literals;
ba::io_service io;
std::function<void(error_code)> input_loop, clock_loop;
// Reading input when ready on stdin
ba::posix::stream_descriptor d(io, 0);
input_loop = [&](error_code ec) {
if (!ec) {
program.on_input();
d.async_wait(ba::posix::descriptor::wait_type::wait_read, input_loop);
}
};
// For fun, let's also update the time
ba::high_resolution_timer tim(io);
clock_loop = [&](error_code ec) {
if (!ec) {
program.on_clock();
tim.expires_from_now(100ms);
tim.async_wait(clock_loop);
}
};
input_loop(error_code{});
clock_loop(error_code{});
io.run_for(10s);
}
I wrote the following to fetch the next value in a sequence. It works perfectly:
static int64 _get_md_key_next_serial()
{
int ret = SPI_execute("SELECT nextval('md_key_seq')", true, 1);
if (ret <= 0)
return (int64)ret;
if (SPI_processed)
{
SPITupleTable *tuptable = SPI_tuptable;
bool fieldNull;
Datum datum = SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &fieldNull);
if (!fieldNull)
return DatumGetInt64(datum);
}
return NULL_ZERO;
}
However, surely there is a function call I can make without having to go through SPI?
Unfortunately nextval_internal is not exported, but you could try to call nextval_oid. I did not test this code, so you'll probably have to debug it:
#include "fmgr.h"
#include "commands/sequence.h"
static int64 nextval(Oid sequenceID, FunctionCallInfo fcinfo)
{
FunctionCallInfoData locfcinfo;
InitFunctionCallInfoData(locfcinfo, fcinfo->flinfo, 1,
InvalidOid, NULL, NULL);
locfcinfo.arg[0] = ObjectIdGetDatum(sequenceID);
locfcinfo.argnull[0] = false;
return DatumGetInt64(nextval_oid(&locfcinfo));
}
Pass the Oid of the sequence and the fcinfo from your own SQL function.
So I'm working on a Gtk/X11/Linux app that does screen capture to .gif and one of the methods of stopping the capture is a key press (Esc, Space or End). You can also use a timeout. However to implement the key press to end capture I have to be able to grab the key such that I can get an event even though my window doesn't have focus (it's actually invisible during capture). I believe XGrabKey is the right X11 function for this task:
Window w = Gtk::gdk_x11_drawable_get_xid(Gtk::gtk_widget_get_window(Handle()));
KeyCode kc = XKeysymToKeycode(Gtk::gdk_display, HotKeyCode);
int r = XGrabKey( Gtk::gdk_display,
kc,
0 /* modifiers */,
w /* grab_window */,
TRUE /* owner_events */,
GrabModeAsync /* pointer_mode */,
GrabModeAsync /* keyboard_mode */);
printf("XGrabKey(%p, 0x%x/%x)=%i\n", w, HotKeyCode, kc, r);
Where 'HotKeyCode' is say XK_Escape or something e.g.:
XGrabKey(0x3e00003, 0xff1b/9)=1
XGrabKey is returning '1' or BadRequest. What am I doing wrong here?
FYI the actual Xorg Xserver code in question appears to be here.
Edit: The latest incarnation of the code is:
int x_err_callback(Display *d, XErrorEvent *e)
{
char msg[256];
XGetErrorText(d, e->error_code, msg, sizeof(msg));
printf("X11Error %d (%s): request %d.%d\n",
e->error_code, msg, e->request_code,
e->minor_code);
return 0;
}
Gtk::GdkFilterReturn key_filter(Gtk::GdkXEvent *gdk_xevent,
Gtk::GdkEvent *event,
Gtk::gpointer data)
{
XKeyEvent *xevent = gdk_xevent;
if (xevent->type == KeyPress)
{
int key = ((XKeyEvent *)gdk_xevent)->keycode;
int keysym = XKeycodeToKeysym(Gtk::gdk_display, key, 0);
printf("caught keysym %i\n", keysym);
switch (keysym)
{
case 1: // your_keysym
// your key handler code
break;
}
}
return Gtk::GDK_FILTER_CONTINUE;
}
Gtk::GdkWindow *Root = Gtk::gdk_get_default_root_window();
KeyCode kc = XKeysymToKeycode(Gtk::gdk_display, HotKeyCode);
XSetErrorHandler(x_err_callback);
int r = XGrabKey( Gtk::gdk_display,
kc,
AnyModifier /* modifiers */,
GDK_WINDOW_XWINDOW(Root) /* grab_window */,
TRUE /* owner_events */,
GrabModeAsync /* pointer_mode */,
GrabModeSync /* keyboard_mode */);
Gtk::gdk_window_set_events(Root,
(Gtk::GdkEventMask)
(Gtk::GDK_KEY_PRESS_MASK |
Gtk::GDK_KEY_RELEASE_MASK));
Gtk::gdk_window_add_filter(NULL, key_filter, this);
AnyModifier actually results in an error. '0' doesn't. I know about the NumLock issue...
A return value of 1 does not mean that a BadRequest error occured. Xlib handles errors via an error handler, and the function will always return 1, if it returns at all.
Your code does not work because you have to do the XGrabKey on the root window (GetDefaultRootWindow(Gtk::gdk_display)). Here's a pure Xlib demo:
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <stdio.h>
int main() {
Display *d = XOpenDisplay(0);
Window root = DefaultRootWindow(d);
int keycode = XKeysymToKeycode(d, XK_BackSpace);
int rv = XGrabKey(d, keycode, AnyModifier, root, 1, GrabModeAsync, GrabModeAsync);
printf("XGrabKey returned %d\n", rv);
XEvent evt;
while(1) {
XNextEvent(d, &evt);
printf("Got event %d\n", evt.type);
}
}
To then capture the X11 events from GTK use gdk_window_add_filter on a NULL or on the root window and a GdkFilterFunc that processes the events associated with your global hotkey:
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <stdio.h>
GdkFilterReturn filter(GdkXEvent *xevent, GdkEvent *event, gpointer data) {
XKeyEvent *ev = (XKeyEvent *)xevent;
if(ev->type == 2) {
printf("Backspace hit.\n");
}
return GDK_FILTER_CONTINUE;
}
int main(int argc, char *argv[]) {
gtk_init(&argc, &argv);
GdkScreen *scr = gdk_screen_get_default();
GdkWindow *groot = gdk_screen_get_root_window(scr);
gdk_window_set_events(groot, GDK_KEY_PRESS_MASK);
gdk_window_add_filter(groot, filter, NULL);
Display *d = gdk_x11_get_default_xdisplay();
Window root = GDK_WINDOW_XID(groot);
int keycode = XKeysymToKeycode(d, XK_BackSpace);
XGrabKey(d, keycode, AnyModifier, root, 1, GrabModeAsync, GrabModeAsync);
gtk_main();
}
As a side note, a modifier mask of 0 means that no modifiers must be enabled, even those that would not modify the meaning of a key. A grab on the letter "A" with a 0 modifier would not match NumLock + A. That's why I used AnyModifer.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/sem.h>
#include<sys/ipc.h>
int sem_id;
void update_file(int number)
{
struct sembuf sem_op;
FILE* file;
printf("Inside Update Process\n");
/* wait on the semaphore, unless it's value is non-negative. */
sem_op.sem_num = 0;
sem_op.sem_op = -1; /* <-- Amount by which the value of the semaphore is to be decreased */
sem_op.sem_flg = 0;
semop(sem_id, &sem_op, 1);
/* we "locked" the semaphore, and are assured exclusive access to file. */
/* manipulate the file in some way. for example, write a number into it. */
file = fopen("file.txt", "a+");
if (file) {
fprintf(file, " \n%d\n", number);
fclose(file);
}
/* finally, signal the semaphore - increase its value by one. */
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop( sem_id, &sem_op, 1);
}
void write_file(char* contents)
{
printf("Inside Write Process\n");
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = -1;
sem_op.sem_flg = 0;
semop( sem_id, &sem_op, 1);
FILE *file = fopen("file.txt","w");
if(file)
{
fprintf(file,contents);
fclose(file);
}
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop( sem_id, &sem_op, 1);
}
int main()
{
//key_t key = ftok("file.txt",'E');
sem_id = semget( IPC_PRIVATE, 1, 0600 | IPC_CREAT);
/*here 100 is any arbit number to be assigned as the key of the
semaphore,1 is the number of semaphores in the semaphore set, */
if(sem_id == -1)
{
perror("main : semget");
exit(1);
}
int rc = semctl( sem_id, 0, SETVAL, 1);
pid_t u = fork();
if(u == 0)
{
update_file(100);
exit(0);
}
else
{
wait();
}
pid_t w = fork();
if(w == 0)
{
write_file("Hello!!");
exit(0);
}
else
{
wait();
}
}
If I run the above code as a c code, the write_file() function is called after the update_file () function
Whereas if I run the same code as a c++ code, the order of execution is reverse... why is it so??
Just some suggestions, but it looks to me like it could be caused by a combination of things:
The wait() call is supposed to take a pointer argument (that can
be NULL). Compiler should have caught this, but you must be picking
up another definition somewhere that permits your syntax. You are
also missing an include for sys/wait.h. This might be why the
compiler isn't complaining as I'd expect it to.
Depending on your machine/OS configuration the fork'd process may
not get to run until after the parent yields. Assuming the "wait()"
you are calling isn't working the way we would be expecting, it is
possible for the parent to execute completely before the children
get to run.
Unfortunately, I wasn't able to duplicate the same temporal behavior. However, when I generated assembly files for each of the two cases (C & C++), I noticed that the C++ version is missing the "wait" system call, but the C version is as I would expect. To me, this suggests that somewhere in the C++ headers this special version without an argument is being #defined out of the code. This difference could be the reason behind the behavior you are seeing.
In a nutshell... add the #include, and change your wait calls to "wait(0)"