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;
84 // Structure holding existing radio with current usage status
91 // Radio plugin handle should store everething API may need
93 radioDevT *radios[MAX_RADIO]; // pointer to existing radio
97 /* private client context [will be destroyed when client leaves] */
99 radioDevT *radio; /* pointer to client radio */
100 int idx; /* radio index within global array */
101 Mode mode; /* radio mode: AM/FM */
102 float freq; /* radio frequency (Mhz) */
103 unsigned char mute; /* radio muted: 0(false)/1(true) */
107 STATIC void* _dongle_thread_fn (void *);
108 STATIC void* _demod_thread_fn (void *);
109 STATIC void* _output_thread_fn (void *);
110 STATIC unsigned int _radio_dev_count (void);
111 STATIC const char* _radio_dev_name (unsigned int);
112 STATIC unsigned char _radio_dev_init (struct dev_ctx *, unsigned int);
113 STATIC unsigned char _radio_dev_free (struct dev_ctx *);
114 STATIC void _radio_apply_params (struct dev_ctx *);
115 STATIC void _radio_start_threads (struct dev_ctx *);
116 STATIC void _radio_stop_threads (struct dev_ctx *);
118 static unsigned int init_dev_count = 0;
119 static struct dev_ctx **dev_ctx = NULL;
121 /* ------------- RADIO IMPLEMENTATION ----------------- */
124 // Radio initialization should be done only when user start the radio and not at plugin initialization
125 // Making this call too early would impose to restart the binder to detect a radio.
126 STATIC unsigned char _radio_on (unsigned int num, radioCtxHandleT *ctx) {
128 if (num >= _radio_dev_count())
131 if (init_dev_count < _radio_dev_count()) {
132 init_dev_count = _radio_dev_count();
133 dev_ctx = (dev_ctx_T**) realloc (dev_ctx, init_dev_count * sizeof(dev_ctx_T));
136 dev_ctx[num] = (dev_ctx_T*) malloc (sizeof(dev_ctx_T));
137 dev_ctx[num]->dev = NULL;
138 dev_ctx[num]->mode = ctx->mode;
139 dev_ctx[num]->freq = ctx->freq;
140 dev_ctx[num]->mute = ctx->mute;
141 dev_ctx[num]->should_run = 0;
142 dev_ctx[num]->dongle = NULL;
143 dev_ctx[num]->demod = NULL;
144 dev_ctx[num]->output = NULL;
145 _radio_dev_init(dev_ctx[num], num);
150 STATIC void _radio_off (unsigned int num) {
152 if (num >= _radio_dev_count())
156 _radio_dev_free(dev_ctx[num]);
162 STATIC void _radio_set_mode (unsigned int num, Mode mode) {
163 if (!dev_ctx || !dev_ctx[num])
166 dev_ctx[num]->mode = mode;
167 _radio_apply_params(dev_ctx[num]);
170 STATIC void _radio_set_freq (unsigned int num, float freq) {
171 if (!dev_ctx || !dev_ctx[num])
174 dev_ctx[num]->freq = freq;
175 _radio_apply_params(dev_ctx[num]);
178 STATIC void _radio_set_mute (unsigned int num, unsigned char mute) {
179 if (!dev_ctx || !dev_ctx[num])
182 dev_ctx[num]->mute = mute;
183 _radio_apply_params(dev_ctx[num]);
186 STATIC void _radio_play (unsigned int num) {
187 if (!dev_ctx || !dev_ctx[num])
190 _radio_start_threads(dev_ctx[num]);
193 STATIC void _radio_stop (unsigned int num) {
194 if (!dev_ctx || !dev_ctx[num])
197 _radio_stop_threads(dev_ctx[num]);
200 /* --- HELPER FUNCTIONS --- */
202 STATIC unsigned int _radio_dev_count () {
203 return rtlsdr_get_device_count();
206 STATIC const char* _radio_dev_name (unsigned int num) {
207 return rtlsdr_get_device_name(num);
210 STATIC unsigned char _radio_dev_init (dev_ctx_T *dev_ctx, unsigned int num) {
211 rtlsdr_dev_t *dev = dev_ctx->dev;
213 if (rtlsdr_open(&dev, num) < 0)
216 rtlsdr_set_tuner_gain_mode(dev, 0);
218 if (rtlsdr_reset_buffer(dev) < 0)
223 _radio_apply_params(dev_ctx);
228 STATIC unsigned char _radio_dev_free (dev_ctx_T *dev_ctx) {
229 rtlsdr_dev_t *dev = dev_ctx->dev;
231 if (rtlsdr_close(dev) < 0)
240 STATIC void _radio_apply_params (dev_ctx_T *dev_ctx) {
241 rtlsdr_dev_t *dev = dev_ctx->dev;
242 Mode mode = dev_ctx->mode;
243 float freq = dev_ctx->freq;
247 rate = ((1000000 / 200000) + 1) * 200000;
253 rtlsdr_set_center_freq(dev, freq);
254 rtlsdr_set_sample_rate(dev, rate);
259 STATIC void _radio_start_threads (dev_ctx_T *dev_ctx) {
260 rtlsdr_dev_t *dev = dev_ctx->dev;
261 dev_ctx->dongle = (dongle_ctx*) malloc(sizeof(dongle_ctx));
262 dev_ctx->demod = (demod_ctx*) malloc(sizeof(demod_ctx));
263 dev_ctx->output = (output_ctx*) malloc(sizeof(output_ctx));
265 dongle_ctx *dongle = dev_ctx->dongle;
266 demod_ctx *demod = dev_ctx->demod;
267 output_ctx *output = dev_ctx->output;
269 pthread_rwlock_init(&demod->lck, NULL);
270 pthread_cond_init(&demod->ok, NULL);
271 pthread_mutex_init(&demod->ok_m, NULL);
272 pthread_rwlock_init(&output->lck, NULL);
273 pthread_cond_init(&output->ok, NULL);
274 pthread_mutex_init(&output->ok_m, NULL);
276 dev_ctx->should_run = 1;
279 dongle->thr_finished = 0;
280 pthread_create(&dongle->thr, NULL, _dongle_thread_fn, (void*)dev_ctx);
283 demod->pre_r = demod->pre_j = 0;
284 demod->now_r = demod->now_j = 0;
285 demod->index = demod->pre_index = demod->now_index = 0;
286 demod->thr_finished = 0;
287 pthread_create(&demod->thr, NULL, _demod_thread_fn, (void*)dev_ctx);
290 output->thr_finished = 0;
291 pthread_create(&output->thr, NULL, _output_thread_fn, (void*)dev_ctx);
294 STATIC void _radio_stop_threads (dev_ctx_T *dev_ctx) {
295 rtlsdr_dev_t *dev = dev_ctx->dev;
296 dongle_ctx *dongle = dev_ctx->dongle;
297 demod_ctx *demod = dev_ctx->demod;
298 output_ctx *output = dev_ctx->output;
300 if (!dongle || !demod || !output)
303 /* stop each "while" loop in threads */
304 dev_ctx->should_run = 0;
306 rtlsdr_cancel_async(dev);
307 pthread_signal(&demod->ok, &demod->ok_m);
308 pthread_signal(&output->ok, &output->ok_m);
310 while (!dongle->thr_finished ||
311 !demod->thr_finished ||
312 !output->thr_finished)
315 pthread_join(dongle->thr, NULL);
316 pthread_join(demod->thr, NULL);
317 pthread_join(output->thr, NULL);
318 pthread_rwlock_destroy(&demod->lck);
319 pthread_cond_destroy(&demod->ok);
320 pthread_mutex_destroy(&demod->ok_m);
321 pthread_rwlock_destroy(&output->lck);
322 pthread_cond_destroy(&output->ok);
323 pthread_mutex_destroy(&output->ok_m);
325 free(dongle); dev_ctx->dongle = NULL;
326 free(demod); dev_ctx->demod = NULL;
327 free(output); dev_ctx->output = NULL;
330 /* ---- LOCAL THREADED FUNCTIONS ---- */
332 STATIC void _rtlsdr_callback (unsigned char *buf, uint32_t len, void *ctx) {
333 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
334 dongle_ctx *dongle = dev_ctx->dongle;
335 demod_ctx *demod = dev_ctx->demod;
339 if (!dev_ctx->should_run)
343 for (i = 0; i < (int)len; i += 8) {
344 tmp = 255 - buf[i+3];
348 buf[i+4] = 255 - buf[i+4];
349 buf[i+5] = 255 - buf[i+5];
351 tmp = 255 - buf[i+6];
357 for (i = 0; i < (int)len; i++)
358 dongle->buf[i] = (int16_t)buf[i] - 127;
360 /* lock demod thread, write to it, unlock */
361 pthread_rwlock_wrlock(&demod->lck);
362 memcpy(demod->buf, dongle->buf, 2 * len);
363 demod->buf_len = len;
364 pthread_rwlock_unlock(&demod->lck);
365 pthread_signal(&demod->ok, &demod->ok_m);
368 STATIC void* _dongle_thread_fn (void *ctx) {
369 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
370 dongle_ctx *dongle = dev_ctx->dongle;
372 rtlsdr_read_async(dev_ctx->dev, _rtlsdr_callback, dev_ctx, 0, 0);
374 dongle->thr_finished = 1;
378 STATIC void _lowpass_demod (void *ctx) {
379 demod_ctx *demod = (demod_ctx *)ctx;
382 while (i < demod->buf_len) {
383 demod->now_r += demod->buf[i];
384 demod->now_j += demod->buf[i+1];
387 if (demod->index < ((1000000 / 200000) + 1))
389 demod->buf[i2] = demod->now_r;
390 demod->buf[i2+1] = demod->now_j;
392 demod->now_r = demod->now_j = 0;
398 STATIC void _lowpassreal_demod (void *ctx) {
399 demod_ctx *demod = (demod_ctx *)ctx;
404 while (i < demod->res_len) {
405 demod->now_index += demod->res[i];
407 demod->pre_index += slow;
408 if (demod->pre_index < fast)
410 demod->res[i2] = (int16_t)(demod->now_index / (fast/slow));
411 demod->pre_index -= fast;
412 demod->now_index = 0;
418 STATIC void _multiply (int ar, int aj, int br, int bj, int *cr, int *cj) {
423 STATIC int _polar_discriminant (int ar, int aj, int br, int bj) {
426 _multiply(ar, aj, br, -bj, &cr, &cj);
427 angle = atan2((double)cj, (double)cr);
428 return (int)(angle / 3.14159 * (1<<14));
431 STATIC void _fm_demod (void *ctx) {
432 demod_ctx *demod = (demod_ctx *)ctx;
433 int16_t *buf = demod->buf;
434 int buf_len = demod->buf_len;
437 pcm = _polar_discriminant(buf[0], buf[1], demod->pre_r, demod->pre_j);
438 demod->res[0] = (int16_t)pcm;
440 for (i = 2; i < (buf_len-1); i += 2) {
441 pcm = _polar_discriminant(buf[i], buf[i+1], buf[i-2], buf[i-1]);
442 demod->res[i/2] = (int16_t)pcm;
444 demod->pre_r = buf[buf_len - 2];
445 demod->pre_j = buf[buf_len - 1];
446 demod->res_len = buf_len/2;
449 STATIC void _am_demod (void *ctx) {
450 demod_ctx *demod = (demod_ctx *)ctx;
451 int16_t *buf = demod->buf;
452 int buf_len = demod->buf_len;
455 for (i = 0; i < buf_len; i += 2) {
456 pcm = buf[i] * buf[i];
457 pcm += buf[i+1] * buf[i+1];
458 demod->res[i/2] = (int16_t)sqrt(pcm);
460 demod->res_len = buf_len/2;
463 STATIC void* _demod_thread_fn (void *ctx) {
464 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
465 demod_ctx *demod = dev_ctx->demod;
466 output_ctx *output = dev_ctx->output;
468 while(dev_ctx->should_run) {
469 pthread_wait(&demod->ok, &demod->ok_m);
470 pthread_rwlock_wrlock(&demod->lck);
471 _lowpass_demod(demod);
472 if (dev_ctx->mode == FM)
476 _lowpassreal_demod(demod);
477 pthread_rwlock_unlock(&demod->lck);
479 /* lock demod thread, write to it, unlock */
480 pthread_rwlock_wrlock(&output->lck);
481 memcpy(output->buf, demod->res, 2 * demod->res_len);
482 output->buf_len = demod->res_len;
483 pthread_rwlock_unlock(&output->lck);
484 pthread_signal(&output->ok, &output->ok_m);
487 demod->thr_finished = 1;
491 STATIC void* _output_thread_fn (void *ctx) {
492 dev_ctx_T *dev_ctx = (dev_ctx_T *)ctx;
493 output_ctx *output = dev_ctx->output;
495 while (dev_ctx->should_run) {
496 pthread_wait(&output->ok, &output->ok_m);
497 pthread_rwlock_rdlock(&output->lck);
498 //if (!dev_ctx->mute)
499 // mRadio->PlayAlsa((void*)&output->buf, output->buf_len);
500 pthread_rwlock_unlock(&output->lck);
503 output->thr_finished = 1;
508 /* ********************************************************
510 FULUP integration proposal with client session context
512 ******************************************************** */
514 // It his was not a demo only, it should be smarter to enable hot plug/unplug
515 STATIC void updateRadioDevList(pluginHandleT *handle) {
518 // loop on existing radio if any
519 for (idx = 0; idx < _radio_dev_count(); idx++) {
520 if (idx == MAX_RADIO) break;
521 handle->radios[idx] = calloc(1, sizeof(radioDevT)); // use calloc to set used to FALSE
522 handle->radios[idx]->name = (char *) _radio_dev_name(idx);
524 handle->devCount = _radio_dev_count();
528 /* global plugin context creation ; at loading time [radio devices might still not be visible] */
529 STATIC pluginHandleT* initRadioPlugin() {
531 pluginHandleT *handle;
533 handle = calloc (1, sizeof(pluginHandleT));
534 updateRadioDevList (handle);
540 /* private client context creation ; default values */
541 STATIC radioCtxHandleT* initRadioCtx () {
543 radioCtxHandleT *ctx;
545 ctx = malloc (sizeof(radioCtxHandleT));
556 /* reserve a radio device to requesting client, start it */
557 STATIC AFB_error reserveRadio (pluginHandleT *handle, radioCtxHandleT *ctx) {
560 /* loop on all devices, find an unused one */
561 for (idx = 0; idx < _radio_dev_count(); idx++) {
562 if (idx == MAX_RADIO) break;
563 if (handle->radios[idx]->used == FALSE) goto found_radio; /* found one */
568 /* try to power it on, passing client context info such as frequency... */
569 _radio_on (idx, ctx);
570 /* TODO : try to re-iterate from the next ones if it failed ! */
572 /* globally mark it as reserved */
573 handle->radios[idx]->used = TRUE;
575 /* store relevant info to client context (direct pointer, index) */
576 ctx->radio = handle->radios[idx];
582 /* free a radio device from requesting client, stop it */
583 STATIC AFB_error releaseRadio (pluginHandleT *handle, radioCtxHandleT *ctx) {
585 /* globally mark it as free */
586 handle->radios[ctx->idx]->used = FALSE;
589 _radio_off (ctx->idx);
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* power (AFB_request *request) { /* AFB_SESSION_CREATE */
604 pluginHandleT *handle = request->client->plugin->handle;
605 radioCtxHandleT *ctx = (radioCtxHandleT*)request->client->ctx;
606 const char *value = getQueryValue (request, "value");
609 /* create a private client context if needed */
610 if (!ctx) ctx = initRadioCtx();
612 /* no "?value=" parameter : return current state */
614 jresp = json_object_new_object();
616 json_object_object_add (jresp, "power", json_object_new_string ("on"))
617 : json_object_object_add (jresp, "power", json_object_new_string ("off"));
620 /* "?value=" parameter is "1" or "on" */
621 else if ( atoi(value) == 1 || !strcasecmp(value, "on") ) {
623 if (reserveRadio (handle, ctx) == AFB_FAIL) {
624 request->errcode = MHD_HTTP_SERVICE_UNAVAILABLE;
625 return (jsonNewMessage (AFB_FAIL, "No more radio devices available"));
628 jresp = json_object_new_object();
629 json_object_object_add (jresp, "power-on", json_object_new_string ("ok"));
632 /* "?value=" parameter is "0" or "off" */
633 else if ( atoi(value) == 0 || !strcasecmp(value, "off") ) {
635 if (releaseRadio (handle, ctx) == AFB_FAIL) {
636 request->errcode = MHD_HTTP_SERVICE_UNAVAILABLE;
637 return (jsonNewMessage (AFB_FAIL, "Unable to release radio device"));
640 jresp = json_object_new_object();
641 json_object_object_add (jresp, "power-off", json_object_new_string ("ok"));
647 STATIC json_object* mode (AFB_request *request) { /* AFB_SESSION_CHECK */
649 radioCtxHandleT *ctx = (radioCtxHandleT*)request->client->ctx;
650 const char *value = getQueryValue (request, "value");
654 /* no "?value=" parameter : return current state */
656 jresp = json_object_new_object();
658 json_object_object_add (jresp, "mode", json_object_new_string ("AM"))
659 : json_object_object_add (jresp, "mode", json_object_new_string ("FM"));
662 /* "?value=" parameter is "1" or "on" */
663 else if ( atoi(value) == 1 || !strcasecmp(value, "AM") ) {
664 mode_str = strdup ("mode-AM");
668 /* "?value=" parameter is "0" or "off" */
669 else if ( atoi(value) == 0 || !strcasecmp(value, "FM") ) {
670 mode_str = strdup ("mode-FM");
675 request->errcode = MHD_HTTP_SERVICE_UNAVAILABLE;
676 return (jsonNewMessage (AFB_FAIL, "Invalid value for mode"));
679 _radio_set_mode (ctx->idx, ctx->mode);
681 jresp = json_object_new_object();
682 json_object_object_add (jresp, mode_str, json_object_new_string ("ok"));
687 STATIC json_object* freq (AFB_request *request) { /* AFB_SESSION_CHECK */
689 radioCtxHandleT *ctx = (radioCtxHandleT*)request->client->ctx;
690 const char *value = getQueryValue (request, "value");
691 json_object *jresp = json_object_new_object();
694 /* no "?value=" parameter : return current state */
696 asprintf (&freq_str, "%f", ctx->freq);
697 json_object_object_add (jresp, "freq", json_object_new_string (freq_str));
700 /* "?value=" parameter, set frequency */
702 ctx->freq = strtof(value, NULL);
703 _radio_set_freq (ctx->idx, ctx->freq);
705 asprintf (&freq_str, "freq-%f", ctx->freq);
706 json_object_object_add (jresp, freq_str, json_object_new_string ("ok"));
712 STATIC json_object* mute (AFB_request *request) { /* AFB_SESSION_CHECK */
714 radioCtxHandleT *ctx = (radioCtxHandleT*)request->client->ctx;
715 const char *value = getQueryValue (request, "value");
719 /* no "?value=" parameter : return current state */
721 asprintf (&mute_str, "%d", ctx->mute);
722 jresp = json_object_new_object();
723 json_object_object_add (jresp, "mute", json_object_new_string (mute_str));
726 /* "?value=" parameter is "1" or "on" */
727 else if ( atoi(value) == 1 || !strcasecmp(value, "on") )
730 /* "?value=" parameter is "0" or "off" */
731 else if ( atoi(value) == 0 || !strcasecmp(value, "off") )
735 request->errcode = MHD_HTTP_SERVICE_UNAVAILABLE;
736 return (jsonNewMessage (AFB_FAIL, "Invalid value for mute"));
739 _radio_set_mute (ctx->idx, ctx->mute);
741 asprintf (&mute_str, "mute-%d", ctx->mute);
742 jresp = json_object_new_object();
743 json_object_object_add (jresp, mute_str, json_object_new_string ("ok"));
748 STATIC json_object* play (AFB_request *request) { /* AFB_SESSION_CHECK */
750 radioCtxHandleT *ctx = (radioCtxHandleT*)request->client->ctx;
751 const char *value = getQueryValue (request, "value");
755 request->errcode = MHD_HTTP_SERVICE_UNAVAILABLE;
756 return (jsonNewMessage (AFB_FAIL, "Radio device not powered on"));
759 /* "?value=" parameter is "1" or "on" */
760 else if ( atoi(value) == 1 || !strcasecmp(value, "on") ) {
762 _radio_play (ctx->idx);
763 jresp = json_object_new_object();
764 json_object_object_add (jresp, "play-on", json_object_new_string ("ok"));
767 /* "?value=" parameter is "0" or "off" */
768 else if ( atoi(value) == 0 || !strcasecmp(value, "off") ) {
770 _radio_stop (ctx->idx);
771 jresp = json_object_new_object();
772 json_object_object_add (jresp, "play-on", json_object_new_string ("ok"));
778 STATIC json_object* status (AFB_request *request) {
783 STATIC AFB_restapi pluginApis[]= {
784 {"power" , AFB_SESSION_CREATE, (AFB_apiCB)power , "Radio API - power"},
785 {"mode" , AFB_SESSION_CHECK, (AFB_apiCB)mode , "Radio API - mode"},
786 {"freq" , AFB_SESSION_CHECK, (AFB_apiCB)freq , "Radio API - freq"},
787 {"mute" , AFB_SESSION_CHECK, (AFB_apiCB)mute , "Radio API - mute"},
788 {"play" , AFB_SESSION_CHECK, (AFB_apiCB)play , "Radio API - play"},
789 {"status" , AFB_SESSION_RENEW, (AFB_apiCB)status , "Radio API - status"},
793 PUBLIC AFB_plugin* radioRegister (AFB_session *session) {
794 AFB_plugin *plugin = malloc (sizeof(AFB_plugin));
795 plugin->type = AFB_PLUGIN_JSON;
796 plugin->info = "Application Framework Binder - Radio plugin";
797 plugin->prefix = "radio";
798 plugin->apis = pluginApis;
800 plugin->handle = initRadioPlugin();
801 plugin->freeCtxCB = freeRadio;