I have everything was working OK, until today I on MQOPEN got error
2085 MQRC_UNKNOWN_OBJECT_NAME
#include <stdio.h>
#include <cmqc.h>
#include <cmqxc.h>
#include "dte_mq.h"
#include <string.h>
#include <stdlib.h>
typedef struct tagDTE_QUEUE_DESCRIPTOR
{
MQHOBJ handle;
int IsSyncpointControled;
} DTE_QUEUE_DESCRIPTOR, *PDTE_QUEUE_DESCRIPTOR;
static MQHCONN sHConn = 0;
static MQLONG sCompCode = MQCC_OK;
static MQLONG sReason = MQRC_NONE;
static int sNumOpenQueues = 0;
static PDTE_QUEUE_DESCRIPTOR sQueues = NULL;
MQLONG OpenCode;
MQOD od = {MQOD_DEFAULT}; /* Object Descriptor */
MQMD md = {MQMD_DEFAULT};
MQPMO pmo = {MQPMO_DEFAULT};
MQLONG O_options;/* MQCONNX options */
MQCNO Connect_options = {MQCNO_DEFAULT};
/* Client connection channel */
MQCD ClientConn = {MQCD_CLIENT_CONN_DEFAULT};
#define MAX_NUM_OPEN_QUEUES 10
int dteMqOpen(const char *name, int *qd)
{
MQLONG options;
MQHOBJ hObj;
int i;
printf("SAM\n");
strncpy(od.ObjectName, name, MQ_Q_NAME_LENGTH);
printf("SAM2\n");
O_options = MQOO_INPUT_AS_Q_DEF + MQOO_FAIL_IF_QUIESCING;
printf("SAM3\n");
MQOPEN(sHConn, &od, O_options, &hObj, &sCompCode, &sReason);
printf("MQopen = %d and %d\n",sCompCode,sReason);
if (sCompCode != MQCC_OK)
{
printf("RETURN %d\n",DTE_MQR_FAILED);
return DTE_MQR_FAILED;
}
++sNumOpenQueues;
*qd = 1;
for(i = 0; i < MAX_NUM_OPEN_QUEUES; i++)
{
printf("In the loop1\n");
if(sQueues[i].handle == -1)
{
*qd = i;
printf("QDESC1 = %d\n",qd);
sQueues[i].handle = hObj;
sQueues[i].IsSyncpointControled = 0;
break;
}
printf("In the loop\n");
}
printf("QDESC = %d\n",qd);
return DTE_MQR_OK;
}
Function call is:
qd = -1;
dteretopen = dteMqOpen(QName, &qd);
printf ("Return code from dteMqOpen = %d\n",dteretopen);
if (dteretopen ==0)
{
printf("MQOPEN could not open MQ, check errpr log\n");
exit(99);
}
Error 2085. But several days before there was no such error
Connection is OK, but MQOPEN failed
dteretopen = dteMqOpen(QName, &qd);
Clearly 'QName' has an invalid value.
You have been posting question after question about the same program. Obviously, you have zero training in MQ programming. You need to get some MQ training ASAP. There is lots and lots of information on the web and videos too.
Why aren't you doing some basic debugging and outputting 'QName?
You need to take some initiative in debugging your program before posting questions here. We are not here to do your work.
Related
I am trying to work with an API of one device, but it is using a WS interface with enforced Origin header, which is giving me troubles.
In Chrome, I can open the Console while a page with the correct Origin is loaded, create the WS connection, and send/receive messages without difficulties:
Note that sent messages (in green) are always acknowledged by the server.
For reference, this is what happens if I create the connection on a different page, which results in an Origin header mismatch, reported as 404:
To sidestep this problem, I turned to C, because the rest of my program is written in that anyway. This is the code I have right now, based mostly on this answer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <libwebsockets.h>
#define KGRN "\033[0;32;32m"
#define KCYN "\033[0;36m"
#define KRED "\033[0;32;31m"
#define KYEL "\033[1;33m"
#define KBLU "\033[0;32;34m"
#define KCYN_L "\033[1;36m"
#define KBRN "\033[0;33m"
#define RESET "\033[0m"
static int destroy_flag = 0;
static int connection_flag = 0;
static int writeable_flag = 0;
static void INT_HANDLER(int signo) {
destroy_flag = 1;
}
struct session_data {
int fd;
};
struct pthread_routine_tool {
struct lws_context *context;
struct lws *wsi;
};
static int websocket_write_back(struct lws *wsi_in, char *str, int str_size_in)
{
if (str == NULL || wsi_in == NULL)
return -1;
int n;
int len;
char *out = NULL;
if (str_size_in < 1)
len = strlen(str);
else
len = str_size_in;
out = (char *)malloc(sizeof(char)*(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING));
//* setup the buffer*/
memcpy (out + LWS_SEND_BUFFER_PRE_PADDING, str, len );
//* write out*/
n = lws_write(wsi_in, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
printf(KBLU"[websocket_write_back] %s\n"RESET, str);
//* free the buffer*/
free(out);
return n;
}
static int ws_service_callback(
struct lws *wsi,
enum lws_callback_reasons reason, void *user,
void *in, size_t len)
{
switch (reason) {
case LWS_CALLBACK_CLIENT_ESTABLISHED:
printf(KYEL"[Main Service] Connect with server success.\n"RESET);
connection_flag = 1;
break;
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
printf(KRED"[Main Service] Connect with server error.\n"RESET);
destroy_flag = 1;
connection_flag = 0;
break;
case LWS_CALLBACK_CLOSED:
printf(KYEL"[Main Service] LWS_CALLBACK_CLOSED\n"RESET);
destroy_flag = 1;
connection_flag = 0;
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
printf(KCYN_L"[Main Service] Client recvived:%s\n"RESET, (char *)in);
if (writeable_flag)
destroy_flag = 1;
break;
case LWS_CALLBACK_CLIENT_WRITEABLE :
printf(KYEL"[Main Service] On writeable is called. send byebye message\n"RESET);
websocket_write_back(wsi, "{\"command\":\"subscribe\",\"identifier\":\"{\\\"channel\\\":\\\"DevicesChannel\\\",\\\"share_token\\\":\\\"D0E91\\\"}\"}", -1);
websocket_write_back(wsi, "{\"command\":\"message\",\"identifier\":\"{\\\"channel\\\":\\\"DevicesChannel\\\",\\\"share_token\\\":\\\"D0E91\\\"}\",\"data\":\"{\\\"value\\\":100,\\\"action\\\":\\\"set_buzz\\\"}\"}", -1);
writeable_flag = 1;
break;
default:
break;
}
return 0;
}
static void *pthread_routine(void *tool_in)
{
struct pthread_routine_tool *tool = tool_in;
printf(KBRN"[pthread_routine] Good day. This is pthread_routine.\n"RESET);
//* waiting for connection with server done.*/
while(!connection_flag)
usleep(1000*20);
//*Send greeting to server*/
lws_callback_on_writable(tool->wsi);
}
int main(void)
{
//* register the signal SIGINT handler */
struct sigaction act;
act.sa_handler = INT_HANDLER;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction( SIGINT, &act, 0);
struct lws_context *context = NULL;
struct lws_context_creation_info info;
struct lws *wsi = NULL;
struct lws_protocols protocol;
memset(&info, 0, sizeof info);
info.port = CONTEXT_PORT_NO_LISTEN;
info.iface = NULL;
info.protocols = &protocol;
info.ssl_cert_filepath = NULL;
info.ssl_private_key_filepath = NULL;
info.extensions = lws_get_internal_extensions();
info.gid = -1;
info.uid = -1;
info.options = 0;
protocol.name = "websockets";
protocol.callback = &ws_service_callback;
protocol.per_session_data_size = sizeof(struct session_data);
protocol.rx_buffer_size = 0;
protocol.id = 0;
protocol.user = NULL;
context = lws_create_context(&info);
printf(KRED"[Main] context created.\n"RESET);
if (context == NULL) {
printf(KRED"[Main] context is NULL.\n"RESET);
return -1;
}
wsi = lws_client_connect(context, "mobu1.herokuapp.com", 443, 1,
"/cable", "mobu1.herokuapp.com", "link.motorbunny.com",
if (wsi == NULL) {
printf(KRED"[Main] wsi create error.\n"RESET);
return -1;
}
printf(KGRN"[Main] wsi create success.\n"RESET);
struct pthread_routine_tool tool;
tool.wsi = wsi;
tool.context = context;
pthread_t pid;
pthread_create(&pid, NULL, pthread_routine, &tool);
pthread_detach(pid);
while(!destroy_flag)
{
lws_service(context, 50);
}
lws_context_destroy(context);
return 0;
}
The result of running the above program is this:
As you can see, the periodic pings from server to my client are being picked up, but the lws_callback_on_writable(wsi); seems to have no effect as the LWS_CALLBACK_CLIENT_WRITEABLE callback never gets called. Additionally, if I call websocket_write_back() directly anywhere else, it doesn't seem to be sending anything to the server, and no acknowledgement is present either.
Is there something obvious I am doing wrong?
EDIT 1:
I found this neat wscat, where I can replicate the results from Chrome:
Now the question is, how can I interface this with my C program in a way that it can wait for the Welcome message from the server, and then send two messages?
And better yet, how to stay connected, so that my program can send multiple commands at different points of time without having to do the handshake all the time?
The reason why the LWS_CALLBACK_CLIENT_WRITEABLE callback never got called was because this particular server uses non-standard handshake. So, to bypass this, I forked a fork of libwsclient and modified the handshake checking function to not fail on mismatch. I also added an optional Origin header.
Now, all I need to do in my original program is
wsclient *client;
char sync_str[6];
void mb_send(int power, char* type)
{
char cmd[2048];
sprintf (cmd, "{\"command\":\"message\",\"identifier\":\"{\\\"channel\\\":\\\"DevicesChannel\\\",\\\"share_token\\\":\\\"%s\\\"}\",\"data\":\"{\\\"value\\\":%d,\\\"action\\\":\\\"set_%s\\\"}\"}",sync_str,power,type);
libwsclient_send(client,cmd);
}
void mb_connect()
{
char cmd[2048];
sprintf (cmd, "{\"command\":\"subscribe\",\"identifier\":\"{\\\"channel\\\":\\\"DevicesChannel\\\",\\\"share_token\\\":\\\"%s\\\"}\"}",sync_str);
libwsclient_send(client,cmd);
mb_send(0,"buzz");
}
int nop()
{
return 0;
}
int main()
{
client = libwsclient_new_extra("wss://mobu1.herokuapp.com/cable","https://link.motorbunny.com");
if(!client) {
fprintf(stderr, "Unable to initialize new WS client.\n");
exit(1);
}
libwsclient_onopen(client, &nop);
libwsclient_onmessage(client, &nop);
libwsclient_onerror(client, &nop);
libwsclient_onclose(client, &nop);
libwsclient_run(client);
...
mb_connect();
...
mb_send(200,"buzz");
mb_send(40,"twirl");
...
mb_send(0,"buzz");
mb_send(0,"twirl");
}
I found an ugly hack to make my C program send WebSocket messages to a server via the wsta program.
It requires a text file, into which my program will append whenever it wants to send a message to the server. The new lines are then picked up in the background by tail -f, and are piped to wsta which maintains the connection. Output can be redirected to /dev/null so that the wsta output doesn't pollute the output of my program, or sent to a file if responses from the server need to be parsed.
The whole script to make this work would look like this (or you could use FIFO pipe with cat instead of a file with tail):
#!/bin/bash
touch commands.txt
tail commands.txt -f -n 0 | wsta --header "Origin: https://link.motorbunny.com" "wss://mobu1.herokuapp.com/cable" &> /dev/null &
./program
In the C program, I just need to write to the commands.txt file:
FILE* cmd;
char sync_str[6];
void mb_connect()
{
fprintf (cmd, "{\"command\":\"subscribe\",\"identifier\":\"{\\\"channel\\\":\\\"DevicesChannel\\\",\\\"share_token\\\":\\\"%s\\\"}\"}\n",sync_str);
fflush(cmd);
}
void mb_send(int power, char* type)
{
fprintf (cmd, "{\"command\":\"message\",\"identifier\":\"{\\\"channel\\\":\\\"DevicesChannel\\\",\\\"share_token\\\":\\\"%s\\\"}\",\"data\":\"{\\\"value\\\":%d,\\\"action\\\":\\\"set_%s\\\"}\"}\n",sync_str,power,type);
fflush(cmd);
}
int main()
{
cmd = fopen ("commands.txt","w");
...
mb_connect();
...
mb_send(200,"buzz");
...
mb_send(0,"buzz");
}
I have a program below
#include <stdio.h>
#include <cmqc.h>
#include <cmqxc.h>
#include "dte_mq.h"
#include <string.h>
#include <stdlib.h>
typedef struct tagDTE_QUEUE_DESCRIPTOR
{
MQHOBJ handle;
int IsSyncpointControled;
} DTE_QUEUE_DESCRIPTOR, *PDTE_QUEUE_DESCRIPTOR;
static MQHCONN sHConn = 0;
static MQLONG sCompCode = MQCC_OK;
static MQLONG sReason = MQRC_NONE;
static int sNumOpenQueues = 0;
static PDTE_QUEUE_DESCRIPTOR sQueues = NULL;
MQLONG OpenCode;
MQOD od = {MQOD_DEFAULT}; /* Object Descriptor */
MQMD md = {MQMD_DEFAULT};
MQPMO pmo = {MQPMO_DEFAULT};
MQLONG O_options;
MQLONG C_options;
MQGMO gmo = {MQGMO_DEFAULT};
/* MQCONNX options */
MQCNO Connect_options = {MQCNO_DEFAULT};
/* Client connection channel */
MQCD ClientConn = {MQCD_CLIENT_CONN_DEFAULT};
DTE_MQ_RESULT dteMqSend(int qd, void *buf, int len)
{
printf("oleg\n");
/* memcpy(md.Format, MQFMT_STRING, MQ_FORMAT_LENGTH); */
md.MsgType = MQMT_DATAGRAM;
printf("oleg1\n");
memcpy(md.MsgId, MQMI_NONE, sizeof(md.MsgId));
printf("oleg2\n");
memcpy(md.CorrelId, MQCI_NONE, sizeof(md.CorrelId));
printf("oleg3\n");
memcpy(md.Format, MQFMT_STRING, (size_t)MQ_FORMAT_LENGTH);
printf("oleg4\n");
if(sQueues[qd].IsSyncpointControled)
pmo.Options |= MQPMO_SYNCPOINT;
printf("oleg5\n");
MQPUT(sHConn, sQueues[qd].handle, &md, &pmo, len, buf, &sCompCode, &sReason);
printf("MQput CC=%ld RC=%ld\n", sCompCode, sReason);
if (sCompCode != MQCC_OK) return DTE_MQR_FAILED;
return DTE_MQR_OK;
}
I put print statement and found out that after printf("oleg4\n";) I get error
Segmentation fault
Could you please help me top debug the program? Do I have to use malloc for the structure? It is written in C and using MQPUT
Below is a program, where above function is called
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmqc.h> /* includes for MQI */
#include <cmqxc.h>
int main(int argc, char **argv)
{
MQLONG messlen; /* message length received */
char QMgrName[MQ_Q_MGR_NAME_LENGTH+1];
char QName[MQ_Q_NAME_LENGTH+1];
char channelName[MQ_CHANNEL_NAME_LENGTH+1];
char hostname[1024];
char port[4];
MQLONG buflen;
MQBYTE TmpBuf[65536] = "This is a simple test message.";
int msgsToGet;
int msgsGot;
int dteretinit;
int dteretdeinit;
int dteretopen;
int dteretclose;
int qd;
int dteretput;
if (argc != 6)
{
printf("Usage: NewMQTest QMgrName ChlName hostname port QName\n");
exit(-1);
}
strncpy(QMgrName, argv[1], MQ_Q_MGR_NAME_LENGTH);
QMgrName[MQ_Q_MGR_NAME_LENGTH] = '\0';
strncpy(channelName, argv[2], MQ_CHANNEL_NAME_LENGTH);
channelName[MQ_CHANNEL_NAME_LENGTH] = '\0';
strncpy(hostname, argv[3], 1023);
hostname[1023] = '\0';
strncpy(port,argv[4],4);
strncpy(QName, argv[5], MQ_Q_NAME_LENGTH);
QName[MQ_Q_NAME_LENGTH] = '\0';
dteretinit = dteMqInit(QMgrName,hostname,channelName);
printf("Return code from dteMqInit = %d\n",dteretinit);
qd = -1;
dteretopen = dteMqOpen(QName, qd);
printf ("Return code from dteMqOpen = %d\n",dteretopen);
if (dteretopen == 0 )
{
buflen = strlen(TmpBuf);
TmpBuf[buflen + 1] = '\0';
dteretput = dteMqSend(qd,*TmpBuf,buflen);
printf("return mqput %d\n",dteretput);
}
dteretclose = dteMqClose(qd);
printf("Return code from dteMqClose = %d\n",dteretclose);
dteretdeinit = dteMqDeinit();
printf("Return code from dteMqDeinit = %d\n",dteretdeinit);
}
I analyzed my program and check MQ. SSL didn't let me connect to MQ, that is why I couldn't change qd. The program is very old, and when failed, return value was set up as 0, 1 is success. I never did it like that. 0 is always success.
Thanks
This is some bad code.
typedef struct tagDTE_QUEUE_DESCRIPTOR
{
MQHOBJ handle;
int IsSyncpointControled;
} DTE_QUEUE_DESCRIPTOR, *PDTE_QUEUE_DESCRIPTOR;
static PDTE_QUEUE_DESCRIPTOR sQueues = NULL;
if(sQueues[qd].IsSyncpointControled)
In the code that you have posted, 'sQueues' is never set, so that is why it is throwing segmentation fault on the 'if' statement. And if 'qd' is really '-1' as per your comment, then I have to wonder what in the world you are doing.
dteretinit = dteMqInit(QMgrName,hostname,channelName);
How come you don't pass the port number into the dteMqInit subroutine?
Again a problem with MQPUT
Below is my function
#include <stdio.h>
#include <cmqc.h>
#include <cmqxc.h>
#include "dte_mq.h"
#include <string.h>
#include <stdlib.h>
typedef struct tagDTE_QUEUE_DESCRIPTOR
{
MQHOBJ handle;
int IsSyncpointControled;
} DTE_QUEUE_DESCRIPTOR, *PDTE_QUEUE_DESCRIPTOR;
static MQHCONN sHConn = 0;
static MQLONG sCompCode = MQCC_OK;
static MQLONG sReason = MQRC_NONE;
static int sNumOpenQueues = 0;
static PDTE_QUEUE_DESCRIPTOR sQueues = NULL;
MQLONG OpenCode;
MQOD od = {MQOD_DEFAULT}; /* Object Descriptor */
MQMD md = {MQMD_DEFAULT};
MQPMO pmo = {MQPMO_DEFAULT};
MQLONG O_options;
MQGMO gmo = {MQGMO_DEFAULT};
/* MQCONNX options */
MQCNO Connect_options = {MQCNO_DEFAULT};
/* Client connection channel */
MQCD ClientConn = {MQCD_CLIENT_CONN_DEFAULT};
#define MAX_NUM_OPEN_QUEUES 10
DTE_MQ_RESULT dteMqSend(int qd, void *buf, int len)
{
printf("oleg\n");
/* memcpy(md.Format, MQFMT_STRING, MQ_FORMAT_LENGTH); */
md.MsgType = MQMT_DATAGRAM;
printf("oleg1\n");
memcpy(md.MsgId, MQMI_NONE, sizeof(md.MsgId));
printf("oleg2\n");
memcpy(md.CorrelId, MQCI_NONE, sizeof(md.CorrelId));
printf("oleg3\n");
memcpy(md.Format, MQFMT_STRING, (size_t)MQ_FORMAT_LENGTH);
printf("oleg4\n");
printf("QD is = %d\n",qd);
if(sQueues[qd].IsSyncpointControled)
pmo.Options |= MQPMO_SYNCPOINT;
printf("oleg5\n");
MQPUT(sHConn, sQueues[qd].handle, &md, &pmo, len, buf, &sCompCode, &sReason);
printf("MQput CC=%ld RC=%ld\n", sCompCode, sReason);
if (sCompCode != MQCC_OK) return DTE_MQR_FAILED;
return DTE_MQR_OK;
}
Below is a program with function call:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmqc.h> /* includes for MQI */
#include <cmqxc.h>
int main(int argc, char **argv)
{
MQLONG messlen; /* message length received */
char QMgrName[MQ_Q_MGR_NAME_LENGTH+1];
char QName[MQ_Q_NAME_LENGTH+1];
char channelName[MQ_CHANNEL_NAME_LENGTH+1];
char hostname[1024];
char port[4];
MQLONG buflen;
/* MQBYTE TmpBuf[65536] = "This is a simple test message."; */
MQBYTE TmpBuf[1024] = "This is a simple test message.";
int msgsToGet;
int msgsGot;
int dteretinit;
int dteretdeinit;
int dteretopen;
int dteretclose;
int qd;
int dteretput;
dteretinit = dteMqInit(QMgrName,hostname,channelName);
printf("Return code from dteMqInit = %d\n",dteretinit);
if (dteretinit == 0)
{
printf("Connection ro MQ failed, check the error log\n");
exit(99);
}
qd = -1;
dteretopen = dteMqOpen(QName, &qd);
printf ("Return code from dteMqOpen = %d\n",dteretopen);
if (dteretopen ==0)
{
printf("MQOPEN could not open MQ, check errpr log\n");
exit(99);
}
buflen = strlen(TmpBuf);
TmpBuf[buflen + 1] = '\0';
dteretput = dteMqSend(qd,*TmpBuf,buflen);
printf("return mqput %d\n",dteretput);
if (dteretput == 0)
{
printf("Could not put the message to MQ, check error log\n");
exit(99);
}
dteretclose = dteMqClose(qd);
printf("Return code from dteMqClose = %d\n",dteretclose);
if (dteretclose == 0)
{
printf("Could not close MQ, check error log\n");
exit(99);
}
dteretdeinit = dteMqDeinit();
printf("Return code from dteMqDeinit = %d\n",dteretdeinit);
if (dteretdeinit == 0)
{
printf("Could not disconnect from MQ, check error log\n");
exit(99);
}
}
The program started running, connected to MQ, open MQ, then go to send message, print all including "oleg5", and aborted
This is output:
Using values:
QMgrName : QM.SU00005
QName : AP.TR.FROM.ADS
ChannelName: AVNCHCTM.CLIENT
hostname : enbmqu02.uk.db.com
port : 1415
CC = 0, RS = 0
Return code from dteMqInit = 1
SAM
SAM2
SAM3
MQopen = 0 and 0
In the loop1
QDESC1 = -990964260
QDESC = -990964260
Return code from dteMqOpen = 1
oleg
oleg1
oleg2
oleg3
oleg4
QD is = 0
oleg5
Aborted
as you can see qd=0 and in this place before MQPUT in if statement it didn't come. May be I have to make else statement and assign Options?
if(sQueues[qd].IsSyncpointControled)
{
pmo.Options |= MQPMO_SYNCPOINT;
printf("Synchronized\n");
}
This happened exactly on MQPUT call
Could you please help me?
I wanted to use libgps to interface with gpsd daemon. That's why I've implemented a little testing application in order to extract a value from a specific satellite.
The documentation on its HOWTO page tells us that
The tricky part is interpreting what you get from the blocking read.
The reason it’s tricky is that you’re not guaranteed that every read
will pick up exactly one complete JSON object from the daemon. It may
grab one response object, or more than one, or part of one, or one or
more followed by a fragment.
As recommended the documentation, the PACKET_SET mask bit is checked before doing anything else.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <gps.h>
#include <pthread.h>
pthread_t t_thread;
struct t_args {
unsigned int ID;
};
unsigned int status = 0;
int elevation;
int p_nmea(void *targs);
void start_test(void)
{
struct t_args *args = malloc(sizeof *args);
status = 1;
args->ID = 10;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if (pthread_create(&t_thread, &attr, (void *)&p_nmea, args) != 0)
{
perror("create: \n");
}
}
int test_result(int * Svalue)
{
int res;
if(status == 1)
{
void * t_res;
if(pthread_tryjoin_np(t_thread, &t_res) != 0)
{
status = 1;
}
else
{
if((int)t_res == 1)
{
res = 3;
*Svalue = elevation;
elevation = 0;
}
else
{
res = 4;
}
}
}
return res;
}
int p_nmea(void *targs)
{
struct t_args *thread_args = targs;
struct gps_data_t gpsdata;
int ret = -1;
int count = 10;
int i,j;
if(gps_open((char *)"localhost", (char *)DEFAULT_GPSD_PORT, &gpsdata) != 0)
{
(void)fprintf(stderr, "cgps: no gpsd running or network error: %d, %s\n", errno, gps_errstr(errno));
return (-1);
}
else
{
(void)gps_stream(&gpsdata, WATCH_ENABLE, NULL);
do
{
if(!gps_waiting(&gpsdata, 1000000))
{
(void)gps_close(&gpsdata);
}
else
{
if(gps_read(&gpsdata) == -1)
{
return (-1);
}
else
{
if(gpsdata.set & PACKET_SET)
{
for (i = 0; i < MAXCHANNELS; i++)
{
for (j = 0; j < gpsdata->satellites_visible; j++)
{
if(gpsdata->PRN[i] == thread_args.ID)
{
elevation = (int)gpsdata->elevation[i];
ret = 1;
break;
}
}
if(gpsdata->PRN[i] == thread_args.ID)
{
break;
}
}
}
}
}
--count;
}while(count != 0);
}
(void)gps_stream(&gpsdata, WATCH_DISABLE, NULL);
(void)gps_close(&gpsdata);
(void)free(thread_args);
(void)pthread_exit((void*) ret);
}
As recommended in the documentation too, I had a look at cgps and gpxlogger for example codes, but the subtleties of libgps escape me. A while loop has been added before gps_waiting() in order to get, at least, one entire response object. Before introducing pthread, I noted that call the function test_result() just after start_test() take few seconds before returning an answer. By using a thread I thought that 3 would be imediately returned, then 3 or 4 .. but it's not ! I am still losing few seconds. In addition, I voluntarily use pthread_tryjoin_np() because its man page says
The pthread_tryjoin_np() function performs a nonblocking join with the thread
Can anybody give me his help, I guess that I understand something wrongly but I am not able to say about which part yet? Basically, why I come into the do while loop at least four times before returning the first value ?
EDIT 1 :
After reading the documentation HOWTO again I highlight the lines :
The fact that the data-waiting check and the read both block means that, if your application has to deal with other input sources than the GPS, you will probably have to isolate the read loop in a thread with a mutex lock on the gps_data structure.
I am a little bit confusing. What does it really mean ?
Your loop is executing multiple times before returning a full packet because you do not have a sleep condition. Therefore each time the daemon registers a packet (even when not a full NMEA message), the gps_waiting() function returns. I'd recommend sleeping at least as long as it takes your GPS to register a full message.
For example, if you expect GPPAT messages, you could reasonably expect to have 12 characters in the message. Thus at 9600 baud, that would take 1/17.5 seconds or about 57 ms. In this case, your code could look like this:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <gps.h>
#include <pthread.h>
pthread_t t_thread;
struct t_args {
unsigned int ID;
};
unsigned int status = 0;
int elevation;
int p_nmea(void *targs);
void start_test(void)
{
struct t_args *args = malloc(sizeof *args);
status = 1;
args->ID = 10;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if (pthread_create(&t_thread, &attr, (void *)&p_nmea, args) != 0)
{
perror("create: \n");
}
}
int test_result(int * Svalue)
{
int res;
if(status == 1)
{
void * t_res;
if(pthread_tryjoin_np(t_thread, &t_res) != 0)
{
status = 1;
}
else
{
if((int)t_res == 1)
{
res = 3;
*Svalue = elevation;
elevation = 0;
}
else
{
res = 4;
}
}
}
return res;
}
int p_nmea(void *targs)
{
struct t_args *thread_args = targs;
struct gps_data_t gpsdata;
int ret = 0;
int count = 10;
int i,j;
if(gps_open((char *)"localhost", (char *)DEFAULT_GPSD_PORT, &gpsdata) != 0)
{
(void)fprintf(stderr, "cgps: no gpsd running or network error: %d, %s\n", errno, gps_errstr(errno));
return (-1);
}
else
{
(void)gps_stream(&gpsdata, WATCH_ENABLE, NULL);
do
{
ret = 0; // Set this here to allow breaking correctly
usleep(50000); // Sleep here to wait for approx 1 msg
if(!gps_waiting(&gpsdata, 1000000)) break;
if(gps_read(&gpsdata) == -1) break;
if(gpsdata.set & PACKET_SET)
{
for (i = 0; i < MAXCHANNELS && !ret; i++)
{
for (j = 0; j < gpsdata.satellites_visible; j++)
{
if(gpsdata.PRN[i] == thread_args.ID)
{
elevation = (int)gpsdata.elevation[i]; // Be sure to not deref structure here
ret = 1;
break;
}
}
}
--count;
}while(count != 0);
}
(void)gps_stream(&gpsdata, WATCH_DISABLE, NULL);
(void)gps_close(&gpsdata);
(void)free(thread_args);
(void)pthread_exit((void*) ret);
}
Alternatively, you could just set your count higher and wait for the full message.
I am trying to create a music visualizer application in PortAudio, I did some basic research and found some examples on how to record from a mic to a (temporary) file. But there was no example where the data is not used runtime during the recording.
So how can I start a continuous audio-stream where I can catch the data from the current "frame"?
This is how I tried to do it:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include "portaudio.h"
#define SAMPLE_RATE (44100)
typedef struct{
int frameIndex;
int maxFrameIndex;
char* recordedSamples;
}
testData;
PaStream* stream;
static int recordCallback(const void* inputBuffer, void* outputBuffer, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData){
testData* data = (testData*)userData;
const char* buffer_ptr = (const char*)inputBuffer;
char* index_ptr = &data->recordedSamples[data->frameIndex];
long framesToCalc;
long i;
int finished;
unsigned long framesLeft = data->maxFrameIndex - data->frameIndex;
if(framesLeft < frameCount){
framesToCalc = framesLeft;
finished = paComplete;
}else{
framesToCalc = frameCount;
finished = paContinue;
}
if(inputBuffer == NULL){
for(i = 0; i < framesToCalc; i++){
*index_ptr++ = 0;
}
}else{
for(i = 0; i < framesToCalc; i++){
*index_ptr++ = *buffer_ptr++;
}
}
data->frameIndex += framesToCalc;
return finished;
}
int setup(testData streamData){
PaError err;
err = Pa_Initialize();
if(err != paNoError){
fprintf(stderr, "Pa_Initialize error: %s\n", Pa_GetErrorText(err));
return 1;
}
PaStreamParameters inputParameters;
inputParameters.device = Pa_GetDefaultInputDevice();
if (inputParameters.device == paNoDevice) {
fprintf(stderr, "Error: No default input device.\n");
return 1;
}
inputParameters.channelCount = 1;
inputParameters.sampleFormat = paInt8;
inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(&stream, &inputParameters, NULL, SAMPLE_RATE, 256, paClipOff, recordCallback, &streamData);
if(err != paNoError){
fprintf(stderr, "Pa_OpenDefaultStream error: %s\n", Pa_GetErrorText(err));
return 1;
}
err = Pa_StartStream(stream);
if(err != paNoError){
fprintf(stderr, "Pa_StartStream error: %s\n", Pa_GetErrorText(err));
return 1;
}
return 0;
}
void quit(testData streamData){
PaError err;
err = Pa_Terminate();
if(err != paNoError){
fprintf(stderr, "Pa_Terminate error: %s\n", Pa_GetErrorText(err));
}
if(streamData.recordedSamples)
free(streamData.recordedSamples);
}
int main(){
int i;
PaError err;
testData streamData = {0};
streamData.frameIndex = 0;
streamData.maxFrameIndex = SAMPLE_RATE;
streamData.recordedSamples = (char*)malloc(SAMPLE_RATE * sizeof(char));
if(streamData.recordedSamples == NULL)
printf("Could not allocate record array.\n");
for(i=0; i<SAMPLE_RATE; i++)
streamData.recordedSamples[i] = 0;
//int totalFrames = SAMPLE_RATE;
if(!setup(streamData)){
printf("Opened\n");
int i = 0;
while(i++ < 500){
if((err = Pa_GetStreamReadAvailable(stream)) != paNoError)
break;
while((err = Pa_IsStreamActive(stream)) == 1){
Pa_Sleep(1000);
}
err = Pa_CloseStream(stream);
if(err != paNoError)
break;
streamData.frameIndex = 0;
for(i=0; i<SAMPLE_RATE; i++)
streamData.recordedSamples[i] = 0;
}
if(err != paNoError){
fprintf(stderr, "Active stream error: %s\n", Pa_GetErrorText(err));
}
quit(streamData);
}else{
puts("Couldn't open\n");
}
return 0;
}
But it gives the following output:
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only playback stream
Active stream error: Can't read from a callback stream
Update:
What is the purpose of this code?
if((err = Pa_GetStreamReadAvailable(stream)) != paNoError)
break;
It seems to me like this is causing your (latest) problem. Why do you need to retrieve (and then discard) the number of frames that can be read from the stream without waiting, which would presumably be zero since stream is a callback stream?
Previous answer:
This seems highly suspicious:
static void* data;
/* ... */
static int recordCallback(const void* inputBuffer, void* outputBuffer, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData){
testData* data = (testData*)userData;
/* ... */
}
Firstly, why are there two variables named data? That's just silly... Can you think of more appropriate identifiers?
Secondly, you're passing a &data (a void **) to Pa_OpenStream. Presumably, Pa_OpenStream passes that same value on to your callback function, where you treat that pointer to void * as though it points to a testData *. That's undefined behaviour.
Remove static void* data;. That's not necessary, here. Declare a new testData data = { 0 }; inside main, right at the very top. Now you're passing a testData * (converted to void *) to Pa_OpenStream, Pa_OpenStream will pass that on to your callback where you can safely convert it back to a testData * as you are. You might want to set the members of data before calling Pa_OpenStream...
To interact with the data stream real-time you'll need a mechanism that either sleeps (busy waits on Windows) for the frame period (sample rate / samples per frame) or uses a thread synchronization primitive to trigger your thread int main that there is audio ready to be processed. This will give you access to each frame of data that PortAudio delivers during its callback (called from the PortAudio thread). Here's how the concept works using boost::condition and boost::mutex.
//CAUTION THIS SNIPPET IS ONLY INTENDED TO DEMONSTRATE HOW ONE MIGHT
//SYNCHRONIZE WITH THE PORTAUDIO THREAD
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "portaudio.h"
boost::condition waitForAudio;
boost::mutex waitForAudioMutex;
boost::mutex audioBufferMutex;
bool trigger = false;
std::deque<char> audioBuffer;
static int recordCallback(const void* inputBuffer, void* outputBuffer, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData){
const char* buffer_ptr = (const char*)inputBuffer;
//Lock mutex to block user thread from modifying data buffer
audioBufferMutex.lock();
//Copy data to user buffer
for(i = 0; i < frameCount; ++i) {
audioBuffer.push_back(buffer_ptr + i);
}
//Unlock mutex, allow user to manipulate buffer
audioBufferMutex.unlock();
//Signal user thread to process audio
waitForAudioMutex.lock();
trigger= true;
waitForAudio.notify_one();
waitForAudioMutex.unlock();
return finished;
}
int main(){
Pa_Initialize();
//OPEN AND START PORTAUDIO STREAM
while(true){ //Catch signal (Ctrl+C) or some other mechanism to interrupt this loop
boost::xtime duration;
boost::xtime_get(&duration, boost::TIME_UTC);
boost::interprocess::scoped_lock<boost::mutex> lock(waitForAudioMutex);
if(!trigger) {
if(!waitForAudio.timed_wait(lock, duration)) {
//Condition timed out -- assume audio stream failed
break;
}
}
trigger= false;
audioBufferMutex.lock();
//VISUALIZE AUDIO HERE
//JUST MAKE SURE TO FINISH BEFORE PORTAUDIO MAKES ANOTHER CALLBACK
audioBufferMutex.unlock();
}
//STOP AND CLOSE PORTAUDIO STEAM
Pa_Terminate();
return 0;
}
Generally, this technique is cross-platform, however this specific implementation may only work on Linux. On Windows use SetEvent(eventVar) in place of condition::notify_one() and WaitForSingleObject(eventVar, duration) instead of condition::timed_wait(lock, duration).
You closed the stream err = Pa_CloseStream(stream); in the first iteration. In the second iteration, the channel was already closed. Try the operation err = Pa_CloseStream(stream); after all iterations.
I solved it this way:
PaStreamParameters inputParameters ,outputParameters;
PaStream* stream;
PaError err;
paTestData data;
int i;
int totalFrames;
int numSamples;
int numBytes;
err = paNoError;
inputParameters.device = 4;
data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE;
data.frameIndex = 0;
numSamples = totalFrames * NUM_CHANNELS;
numBytes = numSamples * sizeof(SAMPLE);
data.recordedSamples = (SAMPLE *) malloc( numBytes );
std::ofstream arch;
arch.open("signal.csv");
err = Pa_Initialize();
inputParameters.channelCount = 1;
inputParameters.sampleFormat = PA_SAMPLE_TYPE;
inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
int contador = 0;
bool strec = true;
while (strec)
{
err = Pa_OpenStream(
&stream,
&inputParameters,
NULL,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paClipOff,
recordCallback,
&data );
err = Pa_StartStream( stream );
printf("\n===Grabando.... ===\n"); fflush(stdout);
Pa_Sleep(3000);
while( ( err = Pa_IsStreamActive(stream) ) == 1 )
{
}
err = Pa_CloseStream( stream );
for( i=0; i<numSamples; i++ )
{
val = data.recordedSamples[i];
arch << val << std::endl;
std::cout << std::endl << "valor : " << val;
}
data.frameIndex = 0;
contador++;
if (contador >= 100) //if you delete this condition continuously recorded this audio
{
strec = false;
arch.close();
}
}