Watch for volume changes in ALSA/Pulseaudio - alsa

How do you listen to changes in volume on the Master channel on the default sound card? I'd like to be notified through dbus or a callback or something that the volume has changed.
I have tried looking and the ALSA and PulseAudio APIs and they only seem to allow you to set and get the volume, but not listen for changes in the volume.
Any programming language is fine.

Edit: In the second example, an event isn't generated for me when volume is below 5% or above 100%. The first example works perfectly as far as I know.
pactl subscribe will print out data about the sinks when the volume changes. What I'm doing now is piping the output to a small C program that will run a script.
run.sh:
pactl subscribe | grep --line-buffered "sink" | ./prog
or for a specific sink, e.g. 3:
pactl subscribe | grep --line-buffered "sink #3" | ./prog
prog.c:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
while(1){
while(getchar() != '\n');
system("./volume_notify.sh");
}
}
When the volume of the sink is changed, pactl will print a line, which will cause the program to run the script.
-or-
Here's an example based on the amixer monitor, as referenced by CL.
The while loop will iterate each time the volume changes, so put your callback in there.
#include <stdio.h>
#include <alsa/asoundlib.h>
#define MAX_CARDS 256
int monitor_native(char const *name);
int open_ctl(const char *name, snd_ctl_t **ctlp);
void close_all(snd_ctl_t* ctls[], int ncards);
int main(int argc, char* argv[]){
const char *ctl_name = "hw:0";
while(monitor_native(ctl_name) == 1){
//volume has been changed, do something
system("~/.volume_notify.sh");
}
return 0;
}
int monitor_native(char const *name) {
snd_ctl_t *ctls[MAX_CARDS];
int ncards = 0;
int i, err = 0;
if (!name) {
int card = -1;
while (snd_card_next(&card) >= 0 && card >= 0) {
char cardname[16];
if (ncards >= MAX_CARDS) {
fprintf(stderr, "alsactl: too many cards\n");
close_all(ctls, ncards);
return -E2BIG;
}
sprintf(cardname, "hw:%d", card);
err = open_ctl(cardname, &ctls[ncards]);
if (err < 0) {
close_all(ctls, ncards);
return err;
}
ncards++;
}
} else {
err = open_ctl(name, &ctls[0]);
if (err < 0) {
close_all(ctls, ncards);
return err;
}
ncards++;
}
for (;ncards > 0;) {
pollfd* fds = new pollfd[ncards];
for (i = 0; i < ncards; i++) {
snd_ctl_poll_descriptors(ctls[i], &fds[i], 1);
}
err = poll(fds, ncards, -1);
if (err <= 0) {
err = 0;
break;
}
for (i = 0; i < ncards; i++) {
unsigned short revents;
snd_ctl_poll_descriptors_revents(ctls[i], &fds[i], 1, &revents);
if (revents & POLLIN) {
snd_ctl_event_t *event;
snd_ctl_event_alloca(&event);
if (snd_ctl_read(ctls[i], event) < 0) {
continue;
}
if (snd_ctl_event_get_type(event) != SND_CTL_EVENT_ELEM) {
continue;
}
unsigned int mask = snd_ctl_event_elem_get_mask(event);
if (mask & SND_CTL_EVENT_MASK_VALUE) {
close_all(ctls, ncards);
return 1;
}
}
}
}
close_all(ctls, ncards);
return 0;
}
int open_ctl(const char *name, snd_ctl_t **ctlp) {
snd_ctl_t *ctl;
int err;
err = snd_ctl_open(&ctl, name, SND_CTL_READONLY);
if (err < 0) {
fprintf(stderr, "Cannot open ctl %s\n", name);
return err;
}
err = snd_ctl_subscribe_events(ctl, 1);
if (err < 0) {
fprintf(stderr, "Cannot open subscribe events to ctl %s\n", name);
snd_ctl_close(ctl);
return err;
}
*ctlp = ctl;
return 0;
}
void close_all(snd_ctl_t* ctls[], int ncards) {
for (ncards -= 1; ncards >= 0; --ncards) {
snd_ctl_close(ctls[ncards]);
}
}

This is possible with the ALSA API.
When you have a control device, call snd_ctl_subscribe_events() to enable events.
Then use snd_ctl_read() to read events; to wait for them, use blocking mode or poll().
If the event is of type SND_CTL_EVENT_ELEM, and if its event bit mask contains SND_CTL_EVENT_MASK_VALUE, that element's value has changed.
See the implementation of amixer monitor for an example.

Similar to #sealj553's answer, but does not need a C-program:
pactl subscribe | grep --line-buffered "sink" | xargs -n1 ./volume_notify.sh

Related

How to stop the repetition of inotify result?

In this code, I am trying to monitor two paths at the same time. I used while(1) for this purpose. But the problem that I am facing is that whenever I run the code, it gives me the same result two times like this.
Giving result
Pathname1 "file" is modified
Pathname1 "file" is modified
Expected result
Pathname1 "file" is modified
I debugged the code. After breaking the main function and stepping over it, the next command stops at this line length = read(fd, buffer, EVENT_BUF_LEN ). Whenever I break a line after this length variable command, the program starts and after modifying the file, the program stops at this line struct inotify_event *event = ( struct inotify_event *)&buffer[i]; Although the program should not break.
I also used IN_CLOSE_WRITE instead of IN_MODIFY but no change in the result.
typedef struct{
int length, fd, wd1, wd2;
char buffer[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
} notification;
notification inotify;
int getNotified(char *pathname1, char *pathname2){
inotify.fd = inotify_init();
inotify.wd1 = inotify_add_watch(inotify.fd, pathname1, IN_MODIFY);
inotify.wd2 = inotify_add_watch(inotify.fd, pathname2, IN_MODIFY);
while(1){
inotify.length = read(inotify.fd, inotify.buffer, EVENT_BUF_LEN);
int i = 0;
while(i < inotify.length){
struct inotify_event *event = (struct inotify_event *)&inotify.buffer[i];
if(event->len){
if(event->mask & IN_MODIFY){
if(event->wd == inotify.wd1){
printf("Pathname1 '%s' is modified\n", event->name);
break;
}
if(event->wd == inotify.wd2){
printf("Pathname2 '%s' is modified\n", event->name);
break;
}
}
}
i += EVENT_SIZE + event->len;
}
}
inotify_rm_watch(inotify.fd, inotify.wd1);
inotify_rm_watch(inotify.fd, inotify.wd2);
close(inotify.fd);
exit(0);
}
Some remarks:
You should not "break" as you go out of the inside "while" loop and call read() again
The IN_MODIFY event does not fill the event->name field (i.e. event->len = 0)
The number of IN_MODIFY events depends on how you modify the files ("echo xxx >> file" = write only = 1 IN_MODIFY; "echo xxx > file" = truncate + write = 2 IN_MODIFY)
Here is a proposition for your program (with additional prints):
#include <stdio.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <stdlib.h>
#define EVENT_BUF_LEN 4096
#define EVENT_SIZE sizeof(struct inotify_event)
typedef struct{
int length, fd, wd1, wd2;
char buffer[EVENT_BUF_LEN] __attribute__ ((aligned(__alignof__(struct inotify_event))));
} notification;
notification inotify;
int getNotified(char *pathname1, char *pathname2){
inotify.fd = inotify_init();
inotify.wd1 = inotify_add_watch(inotify.fd, pathname1, IN_MODIFY);
printf("wd1 = %d\n", inotify.wd1);
inotify.wd2 = inotify_add_watch(inotify.fd, pathname2, IN_MODIFY);
printf("wd2 = %d\n", inotify.wd2);
while(1){
inotify.length = read(inotify.fd, inotify.buffer, EVENT_BUF_LEN);
int i = 0;
printf("read() = %d\n", inotify.length);
while(i < inotify.length){
struct inotify_event *event = (struct inotify_event *)&inotify.buffer[i];
printf("event->len = %u\n", event->len);
if(event->mask & IN_MODIFY){
if(event->wd == inotify.wd1){
printf("Pathname1 is modified\n");
} else if (event->wd == inotify.wd2){
printf("Pathname2 is modified\n");
}
}
i += (EVENT_SIZE + event->len);
printf("i=%d\n", i);
}
}
inotify_rm_watch(inotify.fd, inotify.wd1);
inotify_rm_watch(inotify.fd, inotify.wd2);
close(inotify.fd);
exit(0);
}
int main(void)
{
getNotified("/tmp/foo", "/tmp/bar");
return 0;
} // main
Here is an example of execution:
$ gcc notif.c -o notif
$ > /tmp/foo
$ > /tmp/bar
$ ./notif
wd1 = 1
wd2 = 2
====== Upon "> /tmp/foo": 1 event (truncate operation)
read() = 16
event->len = 0
Pathname1 is modified
i=16
====== Upon "echo qwerty > /tmp/foo": 2 events (write operation, one event for truncate operation and one for the write of "qwerty" at the beginning of the file)
read() = 16
event->len = 0
Pathname1 is modified
i=16
read() = 16
event->len = 0
Pathname1 is modified
i=16
====== Upon "echo qwerty >> /tmp/foo": 1 event (write of "qwerty" at the end of the file)
read() = 16
event->len = 0
Pathname1 is modified
i=16
If the two pathnames refer to the same inode, then inotify.wd1 == inotify.wd2. In that case, because you have
if (event->wd == inotify.wd1) {
printf("Pathname1 '%s' is modified\n", event->name);
}
if (event->wd == inotify.wd2) {
printf("Pathname2 '%s' is modified\n", event->name);
}
both bodies would be executed; but the outputs would differ (Pathname1 ... and Pathname2 ...).
You really should be monitoring the directories the files reside in, rather than the actual pathnames, so you can catch rename events also. (Many editors create a temporary file, and rename or hardlink the temporary file over the old file, so that programs see either the old or the new file, and never a mix of the two.)
Consider the following program, which does not exhibit any undue duplication of events:
// SPDX-License-Identifier: CC0-1.0
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
static volatile sig_atomic_t done = 0;
static void handle_done(int signum)
{
done = signum;
}
static int install_done(int signum)
{
struct sigaction act;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_handler = handle_done;
act.sa_flags = 0;
return sigaction(signum, &act, NULL);
}
struct monitor {
/* Supplied by caller */
const char *directory;
const char *pathname;
int (*modified)(struct monitor *);
int (*completed)(struct monitor *);
/* Reserved for internal use */
int dirwatch;
};
int monitor_files(struct monitor *const list, const size_t count)
{
char *events_ptr = NULL;
size_t events_len = 65536;
size_t i;
int err;
/* Verify sane parameters */
if (count < 1) {
errno = ENOENT;
return -1;
} else
if (!list) {
errno = EINVAL;
return -1;
}
for (i = 0; i < count; i++) {
if (!list[i].directory || !list[i].directory[0]) {
errno = EINVAL;
return -1;
}
if (!list[i].pathname || !list[i].pathname[0]) {
errno = EINVAL;
return -1;
}
list[i].dirwatch = -1;
}
/* Obtain a descriptor for inotify event queue */
int queue = inotify_init1(IN_CLOEXEC);
if (queue == -1) {
/* errno set by inotify_init1() */
return -1;
}
/* Use a reasonable dynamically allocated buffer for events */
events_ptr = malloc(events_len);
if (!events_ptr) {
close(queue);
errno = ENOMEM;
return -1;
}
/* Add a watch for each directory to be watched */
for (i = 0; i < count; i++) {
list[i].dirwatch = inotify_add_watch(queue, list[i].directory, IN_CLOSE_WRITE | IN_MOVED_TO | IN_MODIFY);
if (list[i].dirwatch == -1) {
err = errno;
close(queue);
free(events_ptr);
errno = err;
return -1;
}
}
/* inotify event loop */
err = 0;
while (!done) {
ssize_t len = read(queue, events_ptr, events_len);
if (len == -1) {
/* Interrupted due to signal delivery? */
if (errno == EINTR)
continue;
/* Error */
err = errno;
break;
} else
if (len < -1) {
/* Should never occur */
err = EIO;
break;
} else
if (len == 0) {
/* No events watched anymore */
err = 0;
break;
}
char *const end = events_ptr + len;
char *ptr = events_ptr;
while (ptr < end) {
struct inotify_event *event = (struct inotify_event *)ptr;
/* Advance buffer pointer for next event */
ptr += sizeof (struct inotify_event) + event->len;
if (ptr > end) {
close(queue);
free(events_ptr);
errno = EIO;
return -1;
}
/* Call all event handlers, even duplicate ones */
for (i = 0; i < count; i++) {
if (event->wd == list[i].dirwatch && !strcmp(event->name, list[i].pathname)) {
if ((event->mask & (IN_MOVED_TO | IN_CLOSE_WRITE)) && list[i].completed) {
err = list[i].completed(list + i);
if (err)
break;
} else
if ((event->mask & IN_MODIFY) && list[i].modified) {
err = list[i].modified(list + i);
if (err)
break;
}
}
}
if (err)
break;
}
if (err)
break;
}
close(queue);
free(events_ptr);
errno = 0;
return err;
}
static int report_modified(struct monitor *m)
{
printf("%s/%s: Modified\n", m->directory, m->pathname);
fflush(stdout);
return 0;
}
static int report_completed(struct monitor *m)
{
printf("%s/%s: Completed\n", m->directory, m->pathname);
fflush(stdout);
return 0;
}
int main(void)
{
struct monitor watch[2] = {
{ .directory = ".",
.pathname = "file1",
.modified = report_modified,
.completed = report_completed },
{ .directory = ".",
.pathname = "file2",
.modified = report_modified,
.completed = report_completed }
};
int err;
if (install_done(SIGINT) == -1 ||
install_done(SIGHUP) == -1 ||
install_done(SIGTERM) == -1) {
fprintf(stderr, "Cannot set signal handlers: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
fprintf(stderr, "To stop this program, press Ctrl+C, or send\n");
fprintf(stderr, "INT, HUP, or TERM signal (to process %ld).\n", (long)getpid());
fflush(stderr);
err = monitor_files(watch, 2);
if (err == -1) {
fprintf(stderr, "Error monitoring files: %s.\n", strerror(errno));
return EXIT_FAILURE;
} else
if (err) {
fprintf(stderr, "Monitoring files failed [%d].\n", err);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
If you compile it using e.g. gcc -Wall -Wextra -O2 example.c -o example and run it via ./example, it will report IN_MODIFY events (as "Modified") and IN_CLOSE_WRITE and IN_MOVED_TO events (as "Completed") for file1 and file2 in the same directory (current working directory). To exit the program, press Ctrl+C.
(Note that we should probably add third event type, "Deleted", corresponding to IN_DELETE and IN_MOVED_FROM events.)
If you open file1 or file2 in say a text editor, saving the file generates one or more Modified (IN_MODIFY) events, and exactly one Completed (IN_CLOSE_WRITE or IN_MOVED_TO) event. This is because each open()/truncate()/ftruncate() syscall that causes the file to be truncated, generates one IN_MODIFY event for that file; as does every underlying write() syscall that modifies the file contents. Thus, it is natural to receive multiple IN_MODIFY events when some process modifies the file.
If you have multiple struct monitor entries in the list with the same effective directory and the same pathname, the example program will provide multiple events for them. If you wish to avoid this, just make sure that whenever .pathname matches, the two get differing .dirwatches.
rewriting the while() loop into a for() loop, and flattening out the if()s"
while(1){
int i ;
struct inotify_event *event ;
inotify.length = read(inotify.fd, inotify.buffer, EVENT_BUF_LEN);
for(i=0; i < inotify.length; i += EVENT_SIZE + event->len ) {
event = (struct inotify_event *)&inotify.buffer[i];
if (!event->len) continue;
if (!(event->mask & IN_MODIFY)) continue;
if (event->wd == inotify.wd1){
printf("Pathname1 '%s' is modified\n", event->name);
continue;
}
if (event->wd == inotify.wd2){
printf("Pathname2 '%s' is modified\n", event->name);
continue;
}
}
}

Unable to receive serial data

I modified serial communication loopback code written by someone else in C (codeblocks/mingw) under windows platform. I am able to send the data correctly. I verified this by opening terminal software. But I am unable to receive the data. I get the error message error reading from input buffer 998 for ReadFile() in the below code. Not sure what the mistake is.
I am using two CP210x USB to serial modules and connected TxD to RxD of one to other.
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <commdlg.h>
//#include <windef.h>
#include <time.h>
int nread,nwrite;
void myDelay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int main(int argc, char* argv[])
{
HANDLE hSerial;
COMMTIMEOUTS timeouts;
COMMCONFIG dcbSerialParams;
char *words, *buffRead, *buffWrite;
DWORD dwBytesWritten, dwBytesRead;
if(argc<3)
{
printf("Enter the com port as command line parameter and t for transmitter and r for receiver\n");
printf("Example: Serial.exe com4 t\n");
return(1);
}
hSerial = CreateFile(argv[1],GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if ( hSerial == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
printf(" serial port does not exist \n");
}
else
{
printf(" some other error occured\n");
}
return(1);
}
if (!GetCommState(hSerial, &dcbSerialParams.dcb))
{
printf("error getting state \n");
return(1);
}
dcbSerialParams.dcb.DCBlength = sizeof(dcbSerialParams.dcb);
// Set various serial port parameters.
dcbSerialParams.dcb.BaudRate = CBR_9600;
dcbSerialParams.dcb.ByteSize = 8;
dcbSerialParams.dcb.StopBits = ONESTOPBIT;
dcbSerialParams.dcb.Parity = NOPARITY;
dcbSerialParams.dcb.fBinary = TRUE;
dcbSerialParams.dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcbSerialParams.dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcbSerialParams.dcb.fOutxCtsFlow = FALSE;
dcbSerialParams.dcb.fOutxDsrFlow = FALSE;
dcbSerialParams.dcb.fDsrSensitivity= FALSE;
dcbSerialParams.dcb.fAbortOnError = TRUE;
if (!SetCommState(hSerial, &dcbSerialParams.dcb))
{
printf(" error setting serial port state \n");
return(1);
}
GetCommTimeouts(hSerial,&timeouts);
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier= 10;
if(!SetCommTimeouts(hSerial, &timeouts))
{
printf("error setting port state \n");
return(1);
}
while(1)
{
// Use a delay of 500 msec
myDelay(500);
if(!strcmp(argv[2],"t"))
{
printf("Write Mode\n");
//****************Write Operation*********************//
words = "This is a string to be written to serial port COM1";
nwrite = strlen(words);
buffWrite = words;
dwBytesWritten = 0;
if (!WriteFile(hSerial, buffWrite, nwrite, &dwBytesWritten, NULL))
{
printf("error writing to output buffer \n");
return(1);
}
}
//***************Read Operation******************//
else
{
dwBytesRead = 0;
nread = strlen(words);
if (!ReadFile(hSerial, buffRead, nread, &dwBytesRead, NULL))
{
printf("error reading from input buffer %d\n", GetLastError());
continue;
}
printf("Data read from read buffer is \n %s \n",buffRead);
}
}
CloseHandle(hSerial);
return(0);
}
Read and Write to COM port is blocking each other making your reading almost alway timeout when the FIFO's runs out. Also there could be some data oin the FIFO's already so... If you sending and receiving too big chunks of data the data loss is more probable in this way.
Here small ancient example of non threaded COM port access
//---------------------------------------------------------------------------
//--- port class ver: 1.0 ------------------------------------------------
//---------------------------------------------------------------------------
#ifndef _port_h
#define _port_h
//---------------------------------------------------------------------------
class port
{
public: HANDLE hnd;
AnsiString error;
DWORD rlen,wlen,err;
DCB rs232_state;
COMMPROP properties;
COMMTIMEOUTS timeouts;
COMSTAT stat;
port();
~port();
int open(AnsiString name);
void close();
int get_stat(); // err,stat
int get_timeouts(); // timeouts
int set_timeouts();
int get_properties(); // properties
int get_rs232_state(); // rs232_state
int set_rs232_state();
void rst_rs232_state();
void out(BYTE data) { WriteFile(hnd,&data,1,&wlen,NULL); }
void in (BYTE *data) { ReadFile (hnd, data,1,&rlen,NULL); }
void in (char *data) { ReadFile (hnd, data,1,&rlen,NULL); }
void out(BYTE *data,DWORD len) { WriteFile(hnd,data,len,&wlen,NULL); }
void in (BYTE *data,DWORD len) { ReadFile (hnd,data,len,&rlen,NULL); }
};
//---------------------------------------------------------------------------
port::port()
{
rlen=0;
wlen=0;
err =0;
error="";
hnd=NULL;
rst_rs232_state();
}
//---------------------------------------------------------------------------
port::~port()
{
close();
}
//---------------------------------------------------------------------------
int port::open(AnsiString name)
{
close();
rlen=0;
wlen=0;
hnd=CreateFile( name.c_str(),GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_ALWAYS,0,NULL);
if (hnd==NULL) return 0;
get_timeouts();
get_properties();
get_rs232_state();
timeouts.ReadIntervalTimeout;
timeouts.ReadTotalTimeoutMultiplier;
timeouts.ReadTotalTimeoutConstant;
timeouts.WriteTotalTimeoutMultiplier;
timeouts.WriteTotalTimeoutConstant;
properties.wPacketLength;
properties.wPacketVersion;
properties.dwServiceMask;
properties.dwReserved1;
properties.dwMaxTxQueue;
properties.dwMaxRxQueue;
properties.dwMaxBaud;
properties.dwProvSubType;
properties.dwProvCapabilities;
properties.dwSettableParams;
properties.dwSettableBaud;
properties.wSettableData;
properties.wSettableStopParity;
properties.dwCurrentTxQueue;
properties.dwCurrentRxQueue;
properties.dwProvSpec1;
properties.dwProvSpec2;
properties.wcProvChar[1];
return 1;
}
//---------------------------------------------------------------------------
void port::close()
{
if (hnd==NULL) return;
CloseHandle(hnd);
hnd=NULL;
}
//---------------------------------------------------------------------------
int port::get_stat()
{
if (ClearCommError(hnd,&err,&stat)) return 1;
error=GetLastError();
return 0;
}
//---------------------------------------------------------------------------
int port::get_timeouts()
{
if (GetCommTimeouts(hnd,&timeouts)) return 1;
error=GetLastError();
get_stat();
return 0;
}
//---------------------------------------------------------------------------
int port::set_timeouts()
{
if (SetCommTimeouts(hnd,&timeouts)) return 1;
error=GetLastError();
get_stat();
return 0;
}
//---------------------------------------------------------------------------
int port::get_properties()
{
if (GetCommProperties(hnd,&properties)) return 1;
error=GetLastError();
get_stat();
return 0;
}
//---------------------------------------------------------------------------
int port::get_rs232_state()
{
if (GetCommState(hnd,&rs232_state)) return 1;
error=GetLastError();
get_stat();
return 0;
}
//---------------------------------------------------------------------------
int port::set_rs232_state()
{
if (SetCommState(hnd,&rs232_state)) return 1;
error=GetLastError();
get_stat();
return 0;
}
//---------------------------------------------------------------------------
void port::rst_rs232_state()
{
rs232_state.BaudRate = CBR_9600;
rs232_state.ByteSize = 8;
rs232_state.Parity = NOPARITY;
rs232_state.StopBits = ONESTOPBIT;
rs232_state.fOutxCtsFlow= FALSE;
rs232_state.fOutxDsrFlow= FALSE;
rs232_state.fOutX = FALSE;
rs232_state.fInX = FALSE;
rs232_state.fBinary = FALSE;
rs232_state.fRtsControl = RTS_CONTROL_DISABLE;
}
//---------------------------------------------------------------------------//---------------------------------------------------------------------------
//---------------------------------------------------------------------------//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
It is in C++/VCL so just rewrite AnsiString to char* or any string type you got and also change the File routines to yours. If you do not have access to classes rewrite to C. Usage is simple:
// globals and init
port com;
com.open("COM2");
com.timeouts.ReadIntervalTimeout =10;
com.timeouts.ReadTotalTimeoutMultiplier =10;
com.timeouts.ReadTotalTimeoutConstant =10;
com.timeouts.WriteTotalTimeoutMultiplier=10;
com.timeouts.WriteTotalTimeoutConstant =10;
com.set_timeouts();
// send/recv
char q;
com.out(`x`); // send x
com.in (&q); // recv ...
You should use threads to remedy this because without the threads the communications is blocking. Anyway without threads for loop-back you should:
set both COM ports to the same protocol
always first send then receive
set small enough timeout (not to block for too long)
expect data loss and timeouts (and handle as such... do not block sending by it)
send just BYTES not all COM ports have big FIFOs along the way...
To be more safe do the reading inside thread ... like:
volatile bool _stop=false; // set this to true when you want to exit
unsigned long __stdcall thread_com(LPVOID p)
{
char q;
for (;!_stop;)
{
com.in (&q); // recv ...
if (q<32) q=`.`; // data loss due to timeout if not sending `0..31` of coarse
Sleep(1); // just not to burn CPU ...
}
}
HANDLE thread_com_hnd=CreateThread(0,0,thread_com,NULL,0,0); // do this only after COM port is initialized

libgps for extract data from the gpsd daemon

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.

Server unexpectedly closed network connection

I am running the following code using putty and the expected behaviour should be the following: when the thread responsible with the reading from a file has ended, the other thread responsible with the timer has to end too and reverse: if the thread responsible with the timer has ended, the other one has to end too. But i get this fatal error: Server unexpectedly closed network connection when there is one minute left. What i am doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/* global variables to check the state*/
int read = 0;
int timeLeft = 0;
void *readFromFile(void *myFile)
{
int state;
char *theFile;
theFile = (char*) myFile;
char question[100];
char answer[100];
state = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL );
FILE *file = fopen(theFile, "r");
if (file != NULL )
{
while (fgets(question, sizeof question, file) != NULL )
{
fputs(question, stdout);
scanf("%s", &answer);
}
fclose(file);
state = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL );
printf("Done with questions!\n");
read = 1;
}
else
{
perror(theFile);
}
}
void displayTimeLeft(void *arg)
{
int *time;
int state;
time = (int*) arg;
int i;
state = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL );
for (i = time; i >= 0; i -= 60)
{
if (i / 60 != 0)
{
printf("You have %d %s left.\n", i / 60,
(i / 60 > 1) ? "minutes" : "minute");
sleep(60);
}
else
{
state = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL );
printf("The time is over \n");
timeLeft = 1;
break;
}
}
}
int main()
{
pthread_t thread1;
pthread_t thread2;
char *file = "/home/osystems01/laura/test";
int *time = 180;
int ret1;
int ret2;
ret1 = pthread_create(&thread1, NULL, readFromFile, file);
ret2 = pthread_create(&thread2, NULL, displayTimeLeft, time);
printf("Main function after pthread_create\n");
while (1)
{
if (read == 1)
{
pthread_cancel(thread2);
pthread_cancel(thread1);
break;
}
else if (timeLeft == 1)
{
pthread_cancel(thread1);
pthread_cancel(thread2);
break;
}
}
printf("After the while loop!\n");
return 0;
}
As mentioned in my comment I strongly doubt the server shuts down the connection established via putty because issues with your program.
However here are several issues with the program's code.
The ost critical issue is you are accessing the two global variable concurrently from two threads.
Concurrent access needs to be protected. To do so declare two mutexes like so:
pthread_mutex_t mutex_read = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_time = PTHREAD_MUTEX_INITIALIZER;
void *readFromFile(void *myFile)
{
...
{
int result = pthread_mutex_lock(mutex_read);
if (0 != result)
{
perror("pthread_mutex_lock(mutex_read) failed");
}
}
read = 1;
{
int result = pthread_mutex_unlock(mutex_read);
if (0 != result)
{
perror("pthread_mutex_unlock(mutex_read) failed");
}
}
...
}
void displayTimeLeft(void *arg)
{
...
{
int result = pthread_mutex_lock(mutex_time);
if (0 != result)
{
perror("pthread_mutex_lock(mutex_time) failed");
}
}
timeLeft= 1;
{
int result = pthread_mutex_unlock(mutex_time);
if (0 != result)
{
perror("pthread_mutex_unlock(mutex_time) failed");
}
}
...
}
int main(void)
{
...
while(1)
{
int bread = 0;
int btimeLeft = 0;
{
int result = pthread_mutex_lock(mutex_read);
if (0 != result)
{
perror("pthread_mutex_lock() failed");
}
}
bread = (1 == read);
{
int result = pthread_mutex_unlock(mutex_read);
if (0 != result)
{
perror("pthread_mutex_unlock() failed");
}
}
{
int result = pthread_mutex_lock(mutex_time);
if (0 != result)
{
perror("pthread_mutex_lock() failed");
}
}
btimeLeft = (1 == timeLEft);
{
int result = pthread_mutex_unlock(mutex_time);
if (0 != result)
{
perror("pthread_mutex_unlock() failed");
}
}
if (bread == 1)
{
pthread_cancel(thread2);
pthread_cancel(thread1);
break;
}
else if (btimeLeft == 1)
{
pthread_cancel(thread1);
pthread_cancel(thread2);
break;
}
}
...
For PThreads thr threas function needs to be declared as:
void * (*) (void *)
This isn't the case for displayTimeLeft
When scanning in a "string" one need to pass the address of the first element of the character array representing the string. So this
scanf("%s", &answer);
should be this
scanf("%s", &answer[0]);
or this
scanf("%s", answer);
The code misses the protoype for sleep(), so add
#include <unistd.h>
Having done so the compiler detects a name clash between the system call read() and the global variable read declared by your code. This is not nice. Rename readto something like readit.
Last not least there is the issue mentioend by suspectus in his answer. You are misusing a pointer to an int to store some time value (int * time = 180). Do not do that.
To fix this do like so:
int main(void)
{
...
int time = 180;
...
ret2 = pthread_create(&thread2, NULL, displayTimeLeft, &time);
and in displayTimeLeft do:
int time = *((int*) arg);
Here you are initialising a pointer to the memory location 180.
int *time = 180;
What is needed is:
int time = 180;
...
...
ret2 = pthread_create(&thread2, NULL, displayTimeLeft, &time);

Get master sound volume in C in Linux

I'm trying to retrieve (and probably later set) the master sound volume in Linux. I'm using PulseAudio, but ideally it should work for ALSA too.
I found this very helpful post on how to set the volume, and from that I was able to deduce the existence of snd_mixer_selem_get_playback_volume() to retrieve the current setting. However on my system, this seems to be giving me wrong readings - where mixer programs show 100%, this tops out at about 66%.
If I open pavucontrol I can see the volume for this output device matches the readings I get from here, so I assume it's giving me the hardware volume setting, not the global master volume that I wanted.
Compile the below code with gcc audio_volume.c -o audio_volume -lasound or altenatively with gcc audio_volume.c -o audio_volume_oss -DOSSCONTROL. OSS version is written very crudely and does not give precise results. Setting volume to 100 sets 97% volume in my system. ALSA version works for me and PulseAudio in openSUSE. Needs some cleanup and love but I hope it is what you need, I grant the permission to use it on the WTFPL license.
#include <unistd.h>
#include <fcntl.h>
#ifdef OSSCONTROL
#define MIXER_DEV "/dev/dsp"
#include <sys/soundcard.h>
#include <sys/ioctl.h>
#include <stdio.h>
#else
#include <alsa/asoundlib.h>
#endif
typedef enum {
AUDIO_VOLUME_SET,
AUDIO_VOLUME_GET,
} audio_volume_action;
/*
Drawbacks. Sets volume on both channels but gets volume on one. Can be easily adapted.
*/
int audio_volume(audio_volume_action action, long* outvol)
{
#ifdef OSSCONTROL
int ret = 0;
int fd, devs;
if ((fd = open(MIXER_DEV, O_WRONLY)) > 0)
{
if(action == AUDIO_VOLUME_SET) {
if(*outvol < 0 || *outvol > 100)
return -2;
*outvol = (*outvol << 8) | *outvol;
ioctl(fd, SOUND_MIXER_WRITE_VOLUME, outvol);
}
else if(action == AUDIO_VOLUME_GET) {
ioctl(fd, SOUND_MIXER_READ_VOLUME, outvol);
*outvol = *outvol & 0xff;
}
close(fd);
return 0;
}
return -1;;
#else
snd_mixer_t* handle;
snd_mixer_elem_t* elem;
snd_mixer_selem_id_t* sid;
static const char* mix_name = "Master";
static const char* card = "default";
static int mix_index = 0;
long pmin, pmax;
long get_vol, set_vol;
float f_multi;
snd_mixer_selem_id_alloca(&sid);
//sets simple-mixer index and name
snd_mixer_selem_id_set_index(sid, mix_index);
snd_mixer_selem_id_set_name(sid, mix_name);
if ((snd_mixer_open(&handle, 0)) < 0)
return -1;
if ((snd_mixer_attach(handle, card)) < 0) {
snd_mixer_close(handle);
return -2;
}
if ((snd_mixer_selem_register(handle, NULL, NULL)) < 0) {
snd_mixer_close(handle);
return -3;
}
ret = snd_mixer_load(handle);
if (ret < 0) {
snd_mixer_close(handle);
return -4;
}
elem = snd_mixer_find_selem(handle, sid);
if (!elem) {
snd_mixer_close(handle);
return -5;
}
long minv, maxv;
snd_mixer_selem_get_playback_volume_range (elem, &minv, &maxv);
fprintf(stderr, "Volume range <%i,%i>\n", minv, maxv);
if(action == AUDIO_VOLUME_GET) {
if(snd_mixer_selem_get_playback_volume(elem, 0, outvol) < 0) {
snd_mixer_close(handle);
return -6;
}
fprintf(stderr, "Get volume %i with status %i\n", *outvol, ret);
/* make the value bound to 100 */
*outvol -= minv;
maxv -= minv;
minv = 0;
*outvol = 100 * (*outvol) / maxv; // make the value bound from 0 to 100
}
else if(action == AUDIO_VOLUME_SET) {
if(*outvol < 0 || *outvol > VOLUME_BOUND) // out of bounds
return -7;
*outvol = (*outvol * (maxv - minv) / (100-1)) + minv;
if(snd_mixer_selem_set_playback_volume(elem, 0, *outvol) < 0) {
snd_mixer_close(handle);
return -8;
}
if(snd_mixer_selem_set_playback_volume(elem, 1, *outvol) < 0) {
snd_mixer_close(handle);
return -9;
}
fprintf(stderr, "Set volume %i with status %i\n", *outvol, ret);
}
snd_mixer_close(handle);
return 0;
#endif
}
int main(void)
{
long vol = -1;
printf("Ret %i\n", audio_volume(AUDIO_VOLUME_GET, &vol));
printf("Master volume is %i\n", vol);
vol = 100;
printf("Ret %i\n", audio_volume(AUDIO_VOLUME_SET, &vol));
return 0;
}

Resources