summarylogtreecommitdiffstats
path: root/fbdaemon.c
blob: a3d103150a697dd0d648e85a0f2d4ed5d535abc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
 * File: fbdaemon.c
 * Tone generator for alsa audio api
 * based on alsatonic by Coolbrother
 * */

#include <alsa/asoundlib.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>

#define BUF_LEN 48000
#define DEF_FREQ 400
#define DEF_DUR  0.1F
#define DEF_NOTE 48
#define MAX_NOTE 87
static unsigned char buffer[BUF_LEN];
static snd_pcm_t *g_handle;
static snd_pcm_sframes_t g_frames;
static int channels =1;
static snd_pcm_format_t format = SND_PCM_FORMAT_U8;
static int rate = 48000;
static float freq = DEF_FREQ; // in hertz
static float dur = DEF_DUR; // in seconds
static int kind = 1; //0 for sine 1 for square wave
static float vol = 0.025F;
static const char *fbdevpath="/dev/beep";
static const char *prog;
static const char *device = "default";

#define HELP_TEXT "%s Usage:\n\
  -a dev   : use alsa device dev (default '%s')\n\
  -d dur   : set duration in seconds (default: %.2f)\n\
  -f freq  : set frequency in HZ, and play it. (default: %.0fHZ)\n\
  -h       : print this Help\n\
  -t kind  : sine or square wave (default square)\n\
  -v vol   : volume (default %.3f)\n\
  -r path  : daemonize and beep on reads of path (default '%s')\n\
\n\
%s is a simple alsa beep daemon designed to work with the fancybeep\n\
kernel module, normally started via /etc/udev/rules.d/90-fancybeep.rules\n\
other daemons can be used with fancybeep see eg\n\
https://github.com/mozzwald/Fancy-Beeper-Daemon/tree/master/daemons\n\n"

static unsigned char clamp(float val){
	val = 127.5+(val*127.5);
	return val<=0.0? 0: val>=254.5? 255: (unsigned char)(val+0.5);
}

static void genSine() {
	float t = 2*M_PI*freq/(rate*channels);
	for (int i=0; i< BUF_LEN; i++) {
		buffer[i] = clamp(vol*sin(t*i));
	}
}

static void genSquare(){
	int full_cycle = floorf((float)(rate*channels)/freq),
		half_cycle = floorf((float)full_cycle / 2.0f),
		cycle_index = 0;
	for (int i = 0; i < BUF_LEN; i++) {
		buffer[i] = clamp((cycle_index < half_cycle) ? vol: -vol);
		cycle_index = (cycle_index + 1) % full_cycle;
		}
}

static void openDevice(){
	// open sound device and set params
	snd_output_t *output = NULL;
	int err;

	if ((err = snd_pcm_open(&g_handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
		fprintf(stderr, "%s: Playback open error: %s\n", prog, snd_strerror(err));
		exit(EXIT_FAILURE);
	}

	if ((err = snd_pcm_set_params(g_handle,
		format,
		// SND_PCM_FORMAT_S16_LE,
		SND_PCM_ACCESS_RW_INTERLEAVED,
		channels,
		// BUF_LEN,
		rate,
		1, /* period */
		500000)) < 0) { /* latency: 0.5sec */ 
		fprintf(stderr, "%s: Playback open error: %s\n", prog, snd_strerror(err));
		exit(EXIT_FAILURE);
	}

}

static void closeDevice() {
	// closing sound device
	// necessary to flush and send short sample
	snd_pcm_drain(g_handle);
	snd_pcm_close(g_handle);
}

static void writeBuf(unsigned char *buf, int nbFrames, int nbTimes) {
	for (int i=0; i < nbTimes; i++) {
		// Sending the sound
		g_frames += snd_pcm_writei(g_handle, buf, nbFrames);
	}
	// printf("WriteBuf nbFrames: %d\n", g_frames);
}

static void playFreq() {
	// playing one freq
	int nbSamples = rate * channels * dur;
	int nbTimes = nbSamples / BUF_LEN;
	int restFrames = nbSamples % BUF_LEN;
	// printf("restFrames: %d\n", restFrames);
	if (nbSamples >0) {
		(kind==0?genSine:genSquare)();
		if (nbTimes >0) {
			writeBuf(buffer, BUF_LEN, nbTimes);	
		}
		if (restFrames > 0) {
			writeBuf(buffer, restFrames, 1);
		}
	
	}
	// printf("nbFrames: %d\n", g_frames);
}

static void beep(){
	openDevice();
 
	//printf("Playing %s %.3fHz during %.3f secs with vol=%.3f\n", (kind?"square":"sine"), freq, dur, vol);
	playFreq();
	//printf("nbFrames played: %d\n", g_frames);

	closeDevice();
}

// Function to handle termination signals
void sigterm_handler(int sig) {
    exit(0);
}

pid_t detach(void) {
    // Set up signal handler
    signal(SIGTERM, sigterm_handler);

    // Create a child process to become the daemon
    pid_t pid = fork();

    if (pid < 0) {
        perror("fork");
        exit(1);
    }

    if (pid > 0) return pid;

    // Child process continues as the daemon

    // Change working directory to avoid file system clutter
    if (chdir("/") != 0) {
        perror("chdir");
        exit(1);
    }

	int bno = open(fbdevpath,O_RDONLY);
	if (bno < 0) {
        perror("beep open");
		exit(1);
	}

    // Close standard input, output, and error
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

	int c;
	size_t n;

    // Main loop for handling server logic
    while (1) {
        // Replace this with your actual server logic
        // (e.g., reading from /dev/beep, processing data, etc.)
		n = read(bno,&c,1);
		if (n==1) {
			beep();
		} else {
			perror("read failed");
			exit(1);
		}
    }
	return 0;
}

int main(int argc, char *argv[]) {
	int optIndex=0;
	int daemonize = 0;
	prog = strrchr(argv[0],'/');
	prog = prog? prog+1: "fbdaemon";
	while (( optIndex = getopt(argc, argv, "a::d:f:hr::t:v:")) != -1) {
		switch (optIndex) {
			case 'a':
				if (optarg && *optarg) {
					device = optarg;
				}
			case 'd':
				dur = atof(optarg); break;
			case 'f':
				freq = atof(optarg); break;
			case 'h':
				printf(HELP_TEXT, prog, device, dur, freq, vol, fbdevpath, prog);
				return 0;
			case 't':
				if(strncmp(optarg,"sine",5)==0) {kind=0;break;}
				if(strncmp(optarg,"square",7)==0) {kind=1;break;}
				printf("kind incorrect should be sine or square not %s\n", optarg);
				return 1;
			case 'v':
				vol = atof(optarg); break;
			case 'r':
				daemonize = 1;
				if (optarg && *optarg) fbdevpath = optarg;
				break;
			default:
				printf("Option '%c' incorrect\n",optIndex);
				return 1;
		  }
	}

	if (daemonize) {
		pid_t pid = detach();
		if (pid>0) {
        	exit(0); // Parent process exits
		} else {
			printf("failed to detach\n");
			exit(1);
		}
	} else {
		beep();
	}

	return EXIT_SUCCESS;
}