2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Manuel Bachmann"
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "local-def.h"
22 /* -------------- RADIO DEFINITIONS ------------------ */
28 #define pthread_signal(n, m) pthread_mutex_lock(m); pthread_cond_signal(n); pthread_mutex_unlock(m)
29 #define pthread_wait(n, m) pthread_mutex_lock(m); pthread_cond_wait(n, m); pthread_mutex_unlock(m)
30 #define BUF_LEN 16*16384
32 typedef enum { FM, AM } Mode;
33 typedef struct dongle_ctx dongle_ctx;
34 typedef struct demod_ctx demod_ctx;
35 typedef struct output_ctx output_ctx;
36 typedef struct dev_ctx dev_ctx_T;
40 unsigned char thr_finished;
41 uint16_t buf[BUF_LEN];
47 unsigned char thr_finished;
51 int pre_r, pre_j, now_r, now_j, index;
52 int pre_index, now_index;
61 unsigned char thr_finished;
70 int used; // radio is free ???
75 unsigned char should_run;
83 STATIC void* _dongle_thread_fn (void *);
84 STATIC void* _demod_thread_fn (void *);
85 STATIC void* _output_thread_fn (void *);
86 STATIC unsigned int _radio_dev_count (void);
87 STATIC const char* _radio_dev_name (unsigned int);
88 STATIC unsigned char _radio_dev_init (struct dev_ctx *, unsigned int);
89 STATIC unsigned char _radio_dev_free (struct dev_ctx *);
90 STATIC void _radio_apply_params (struct dev_ctx *);
91 STATIC void _radio_start_threads (struct dev_ctx *);
92 STATIC void _radio_stop_threads (struct dev_ctx *);
94 static unsigned int init_dev_count;
95 static struct dev_ctx **dev_ctx;
97 /* ------------- RADIO IMPLEMENTATION ----------------- */
100 // Radio initialization should be done only when user start the radio and not at plugin initialization
101 // Making this call too early would impose to restart the binder to detect a radio.
102 STATIC void initRadio () {
104 init_dev_count = _radio_dev_count();
107 dev_ctx = (dev_ctx_T**) malloc(init_dev_count * sizeof(dev_ctx_T));
109 for (i = 0; i < init_dev_count; i++) {
110 dev_ctx[i] = (dev_ctx_T*) malloc(sizeof(dev_ctx_T));
111 dev_ctx[i]->dev = NULL;
112 dev_ctx[i]->mode = FM;
113 dev_ctx[i]->freq = 100.0;
114 dev_ctx[i]->mute = 0;
115 dev_ctx[i]->should_run = 0;
116 dev_ctx[i]->dongle = NULL;
117 dev_ctx[i]->demod = NULL;
118 dev_ctx[i]->output = NULL;
119 _radio_dev_init(dev_ctx[i], i);
123 STATIC void radio_off () {
126 for (i = 0; i < init_dev_count; i++) {
127 _radio_dev_free(dev_ctx[i]);
133 STATIC void radio_set_mode (dev_ctx_T *dev_ctx, Mode mode) {
134 dev_ctx->mode = mode;
135 _radio_apply_params(dev_ctx);
138 STATIC void radio_set_freq (dev_ctx_T *dev_ctx, float freq) {
139 dev_ctx->freq = freq;
140 _radio_apply_params(dev_ctx);
143 STATIC void radio_set_mute (dev_ctx_T *dev_ctx, unsigned char mute) {
144 dev_ctx->mute = mute;
145 _radio_apply_params(dev_ctx);
148 STATIC void radio_play (dev_ctx_T *dev_ctx) {
149 _radio_start_threads(dev_ctx);
152 STATIC void radio_stop (dev_ctx_T *dev_ctx) {
153 _radio_stop_threads(dev_ctx);
156 /* --- HELPER FUNCTIONS --- */
158 STATIC unsigned int _radio_dev_count () {
159 return rtlsdr_get_device_count();
162 STATIC const char* _radio_dev_name (unsigned int num) {
163 return rtlsdr_get_device_name(num);
166 STATIC unsigned char _radio_dev_init (dev_ctx_T *dev_ctx, unsigned int num) {
167 rtlsdr_dev_t *dev = dev_ctx->dev;
169 if (rtlsdr_open(&dev, num) < 0)
172 rtlsdr_set_tuner_gain_mode(dev, 0);
174 if (rtlsdr_reset_buffer(dev) < 0)
179 _radio_apply_params(dev_ctx);
184 STATIC unsigned char _radio_dev_free (dev_ctx_T *dev_ctx) {
185 rtlsdr_dev_t *dev = dev_ctx->dev;
187 if (rtlsdr_close(dev) < 0)
196 STATIC void _radio_apply_params (dev_ctx_T *dev_ctx) {
197 rtlsdr_dev_t *dev = dev_ctx->dev;
198 Mode mode = dev_ctx->mode;
199 float freq = dev_ctx->freq;
203 rate = ((1000000 / 200000) + 1) * 200000;
209 rtlsdr_set_center_freq(dev, freq);
210 rtlsdr_set_sample_rate(dev, rate);
215 STATIC void _radio_start_threads (dev_ctx_T *dev_ctx) {
216 rtlsdr_dev_t *dev = dev_ctx->dev;
217 dev_ctx->dongle = (dongle_ctx*) malloc(sizeof(dongle_ctx));
218 dev_ctx->demod = (demod_ctx*) malloc(sizeof(demod_ctx));
219 dev_ctx->output = (output_ctx*) malloc(sizeof(output_ctx));
221 dongle_ctx *dongle = dev_ctx->dongle;
222 demod_ctx *demod = dev_ctx->demod;
223 output_ctx *output = dev_ctx->output;
225 pthread_rwlock_init(&demod->lck, NULL);
226 pthread_cond_init(&demod->ok, NULL);
227 pthread_mutex_init(&demod->ok_m, NULL);
228 pthread_rwlock_init(&output->lck, NULL);
229 pthread_cond_init(&output->ok, NULL);
230 pthread_mutex_init(&output->ok_m, NULL);
232 dev_ctx->should_run = 1;
235 dongle->thr_finished = 0;
236 pthread_create(&dongle->thr, NULL, _dongle_thread_fn, (void*)dev_ctx);
239 demod->pre_r = demod->pre_j = 0;
240 demod->now_r = demod->now_j = 0;
241 demod->index = demod->pre_index = demod->now_index = 0;
242 demod->thr_finished = 0;
243 pthread_create(&demod->thr, NULL, _demod_thread_fn, (void*)dev_ctx);
246 output->thr_finished = 0;
247 pthread_create(&output->thr, NULL, _output_thread_fn, (void*)dev_ctx);
250 STATIC void _radio_stop_threads (dev_ctx_T *dev_ctx) {
251 rtlsdr_dev_t *dev = dev_ctx->dev;
252 dongle_ctx *dongle = dev_ctx->dongle;
253 demod_ctx *demod = dev_ctx->demod;
254 output_ctx *output = dev_ctx->output;
256 if (!dongle || !demod || !output)
259 /* stop each "while" loop in threads */
260 dev_ctx->should_run = 0;
262 rtlsdr_cancel_async(dev);
263 pthread_signal(&demod->ok, &demod->ok_m);
264 pthread_signal(&output->ok, &output->ok_m);
266 while (!dongle->thr_finished ||
267 !demod->thr_finished ||
268 !output->thr_finished)
271 pthread_join(dongle->thr, NULL);
272 pthread_join(demod->thr, NULL);
273 pthread_join(output->thr, NULL);
274 pthread_rwlock_destroy(&demod->lck);
275 pthread_cond_destroy(&demod->ok);
276 pthread_mutex_destroy(&demod->ok_m);
277 pthread_rwlock_destroy(&output->lck);
278 pthread_cond_destroy(&output->ok);
279 pthread_mutex_destroy(&output->ok_m);
281 free(dongle); dev_ctx->dongle = NULL;
282 free(demod); dev_ctx->demod = NULL;
283 free(output); dev_ctx->output = NULL;
286 /* ---- LOCAL THREADED FUNCTIONS ---- */
288 STATIC void _rtlsdr_callback (unsigned char *buf, uint32_t len, void *ctx) {
289 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
290 dongle_ctx *dongle = dev_ctx->dongle;
291 demod_ctx *demod = dev_ctx->demod;
295 if (!dev_ctx->should_run)
299 for (i = 0; i < (int)len; i += 8) {
300 tmp = 255 - buf[i+3];
304 buf[i+4] = 255 - buf[i+4];
305 buf[i+5] = 255 - buf[i+5];
307 tmp = 255 - buf[i+6];
313 for (i = 0; i < (int)len; i++)
314 dongle->buf[i] = (int16_t)buf[i] - 127;
316 /* lock demod thread, write to it, unlock */
317 pthread_rwlock_wrlock(&demod->lck);
318 memcpy(demod->buf, dongle->buf, 2 * len);
319 demod->buf_len = len;
320 pthread_rwlock_unlock(&demod->lck);
321 pthread_signal(&demod->ok, &demod->ok_m);
324 STATIC void* _dongle_thread_fn (void *ctx) {
325 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
326 dongle_ctx *dongle = dev_ctx->dongle;
328 rtlsdr_read_async(dev_ctx->dev, _rtlsdr_callback, dev_ctx, 0, 0);
330 dongle->thr_finished = 1;
334 STATIC void _lowpass_demod (void *ctx) {
335 demod_ctx *demod = (demod_ctx *)ctx;
338 while (i < demod->buf_len) {
339 demod->now_r += demod->buf[i];
340 demod->now_j += demod->buf[i+1];
343 if (demod->index < ((1000000 / 200000) + 1))
345 demod->buf[i2] = demod->now_r;
346 demod->buf[i2+1] = demod->now_j;
348 demod->now_r = demod->now_j = 0;
354 STATIC void _lowpassreal_demod (void *ctx) {
355 demod_ctx *demod = (demod_ctx *)ctx;
360 while (i < demod->res_len) {
361 demod->now_index += demod->res[i];
363 demod->pre_index += slow;
364 if (demod->pre_index < fast)
366 demod->res[i2] = (int16_t)(demod->now_index / (fast/slow));
367 demod->pre_index -= fast;
368 demod->now_index = 0;
374 STATIC void _multiply (int ar, int aj, int br, int bj, int *cr, int *cj) {
379 STATIC int _polar_discriminant (int ar, int aj, int br, int bj) {
382 _multiply(ar, aj, br, -bj, &cr, &cj);
383 angle = atan2((double)cj, (double)cr);
384 return (int)(angle / 3.14159 * (1<<14));
387 STATIC void _fm_demod (void *ctx) {
388 demod_ctx *demod = (demod_ctx *)ctx;
389 int16_t *buf = demod->buf;
390 int buf_len = demod->buf_len;
393 pcm = _polar_discriminant(buf[0], buf[1], demod->pre_r, demod->pre_j);
394 demod->res[0] = (int16_t)pcm;
396 for (i = 2; i < (buf_len-1); i += 2) {
397 pcm = _polar_discriminant(buf[i], buf[i+1], buf[i-2], buf[i-1]);
398 demod->res[i/2] = (int16_t)pcm;
400 demod->pre_r = buf[buf_len - 2];
401 demod->pre_j = buf[buf_len - 1];
402 demod->res_len = buf_len/2;
405 STATIC void _am_demod (void *ctx) {
406 demod_ctx *demod = (demod_ctx *)ctx;
407 int16_t *buf = demod->buf;
408 int buf_len = demod->buf_len;
411 for (i = 0; i < buf_len; i += 2) {
412 pcm = buf[i] * buf[i];
413 pcm += buf[i+1] * buf[i+1];
414 demod->res[i/2] = (int16_t)sqrt(pcm);
416 demod->res_len = buf_len/2;
419 STATIC void* _demod_thread_fn (void *ctx) {
420 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
421 demod_ctx *demod = dev_ctx->demod;
422 output_ctx *output = dev_ctx->output;
424 while(dev_ctx->should_run) {
425 pthread_wait(&demod->ok, &demod->ok_m);
426 pthread_rwlock_wrlock(&demod->lck);
427 _lowpass_demod(demod);
428 if (dev_ctx->mode == FM)
432 _lowpassreal_demod(demod);
433 pthread_rwlock_unlock(&demod->lck);
435 /* lock demod thread, write to it, unlock */
436 pthread_rwlock_wrlock(&output->lck);
437 memcpy(output->buf, demod->res, 2 * demod->res_len);
438 output->buf_len = demod->res_len;
439 pthread_rwlock_unlock(&output->lck);
440 pthread_signal(&output->ok, &output->ok_m);
443 demod->thr_finished = 1;
447 STATIC void* _output_thread_fn (void *ctx) {
448 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
449 output_ctx *output = dev_ctx->output;
451 while (dev_ctx->should_run) {
452 pthread_wait(&output->ok, &output->ok_m);
453 pthread_rwlock_rdlock(&output->lck);
454 //if (!dev_ctx->mute)
455 // mRadio->PlayAlsa((void*)&output->buf, output->buf_len);
456 pthread_rwlock_unlock(&output->lck);
459 output->thr_finished = 1;
465 STATIC json_object* start (AFB_session *session, AFB_request *request, void* handle) {
466 json_object *response;
469 // request all query key/value
470 getQueryAll (request, query, sizeof(query));
472 // check if we have some post data
473 if (request->post == NULL) request->post="NoData";
475 // return response to caller
476 response = jsonNewMessage(AFB_SUCCESS, "Start Radio plugin query={%s} PostData: \'%s\' ", query, request->post);
478 //if (verbose) fprintf(stderr, "%d: \n", pingcount);
482 STATIC json_object* stop (AFB_session *session, AFB_request *request, void* handle) {
483 json_object *response;
486 getQueryAll (request, query, sizeof(query));
488 if (request->post == NULL) request->post="NoData";
490 response = jsonNewMessage(AFB_SUCCESS, "Stop Radio plugin query={%s} PostData: \'%s\' ", query, request->post);
496 // ********************************************************
498 // FULUP integration proposal with client session context
500 // ********************************************************
505 // Structure holding existing radio with current usage status
512 // Radio plugin handle should store everething API may need
514 radioDevT *radios[MAX_RADIO]; // pointer to existing radio
518 // Client Context Structure Hold any specific to client [will be destroyed when client leave]
520 dev_ctx_T radio; // pointer to client radio
521 int idx; // index of radio within global array
525 // It his was not a demo only, it should be smarter to enable hot plug/unplug
526 STATIC void updateRadioDevList(pluginHandleT *handle) {
529 // loop on existing radio if any
530 for (idx = 0; idx < _radio_dev_count(); idx++) {
531 if (idx == MAX_RADIO) break;
532 handle->radios[idx] = calloc(1, sizeof(radioDevT)); // use calloc to set used to FALSE
533 handle->radios[idx]->name = (char *) _radio_dev_name(idx);
535 handle->devCount = _radio_dev_count();
539 // This is call at plugin load time [radio devices might still not be visible]
540 STATIC pluginHandleT* initRadioPlugin() {
542 // Allocate Plugin handle
543 pluginHandleT *handle = calloc (1,sizeof (pluginHandleT)); // init handle with zero
545 // Some initialization steps
546 updateRadioDevList(handle);
551 // Stop a radio free related ressource and make it avaliable for other clients
552 STATIC AFB_error releaseRadio (pluginHandleT* handle, ctxHandleT *ctx) {
554 // change radio status
555 (handle->radios[ctx->idx])->used = FALSE;
557 // stop related threads and free attached resources
558 radio_stop (&ctx->radio);
560 // May be some further cleanup ????
562 return (AFB_SUCCESS); // Could it fails ????
566 // Start a radio and reserve exclusive usage to requesting client
567 STATIC ctxHandleT *reserveRadio (pluginHandleT* handle) {
571 // loop on existing radio if any
572 for (idx = 0; idx < _radio_dev_count(); idx++) {
573 if ((handle->radios[client->idx])->used = FALSE) break;
576 // No avaliable radio return now
577 if (idx == MAX_RADIO) return (NULL);
580 (handle->radios[client->idx])->used = TRUE;
582 // create client handle
583 client = calloc (1, sizeof (ctxHandleT));
585 // stop related threads and free attached resources
586 _radio_start_threads (&client->radio);
588 // May be some things to do ????
594 // This is called when client session died [ex; client quit for more than 15mn]
595 STATIC json_object* freeRadio () {
597 //releaseRadio (client->handle, client);
602 STATIC json_object* powerOnOff (AFB_request *request) {
604 AFB_clientCtx *client = request->client; // get client context from request
606 // Make sure binder was started with client session
607 if (client == NULL) {
608 request->errcode=MHD_HTTP_FORBIDDEN;
609 return (jsonNewMessage(AFB_FAIL, "Radio binder need session [--token=xxxx]"));
612 // If we have a handle radio was on let power it down
613 if (client->ctx != NULL) {
614 dev_ctx_T *dev_ctx = (dev_ctx_T *)client->ctx;
616 releaseRadio (client->plugin->handle, client->ctx); // poweroff client related radio
618 jresp = json_object_new_object();
619 json_object_object_add(jresp, "power", json_object_new_string ("off"));
623 // request a new client context token and check result
624 if (AFB_UNAUTH == ctxTokenCreate (request)) {
625 request->errcode=MHD_HTTP_UNAUTHORIZED;
626 jresp= jsonNewMessage(AFB_FAIL, "You're not authorized to request a radio [make sure you have the right authentication token");
630 // Client is clean let's look it we have an avaliable radio to propose
632 // make sure we have last hot plug dongle visible
633 updateRadioDevList (client->plugin->handle);
635 // get try to get an unused radio
636 client->ctx = reserveRadio (client->plugin->handle);
637 if (client->ctx == NULL) {
638 return (jsonNewMessage(AFB_FAIL, "Sory No More Radio Avaliable"));
641 // At this point we should have something to retreive radio status before last poweroff [but this is only a demonstrator]
645 STATIC AFB_restapi pluginApis[]= {
646 {"power" , (AFB_apiCB)powerOnOff , "Ping Application Framework"},
647 {"start" , (AFB_apiCB)start , "Ping Application Framework"},
648 {"stop" , (AFB_apiCB)stop , "Ping Application Framework"},
652 PUBLIC AFB_plugin *radioRegister (AFB_session *session) {
653 AFB_plugin *plugin = malloc (sizeof (AFB_plugin));
654 plugin->type = AFB_PLUGIN_JSON;
655 plugin->info = "Application Framework Binder - Radio plugin";
656 plugin->prefix = "radio";
657 plugin->apis = pluginApis;
659 plugin->handle = initRadioPlugin();
660 plugin->freeCtxCB = freeRadio;