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;
39 unsigned char thr_finished;
40 uint16_t buf[BUF_LEN];
46 unsigned char thr_finished;
50 int pre_r, pre_j, now_r, now_j, index;
51 int pre_index, now_index;
60 unsigned char thr_finished;
69 int used; // radio is free ???
74 unsigned char should_run;
82 void* _dongle_thread_fn (void *);
83 void* _demod_thread_fn (void *);
84 void* _output_thread_fn (void *);
85 unsigned int _radio_dev_count (void);
86 const char* _radio_dev_name (unsigned int);
87 unsigned char _radio_dev_init (struct dev_ctx *, unsigned int);
88 unsigned char _radio_dev_free (struct dev_ctx *);
89 void _radio_apply_params (struct dev_ctx *);
90 void _radio_start_threads (struct dev_ctx *);
91 void _radio_stop_threads (struct dev_ctx *);
93 static unsigned int init_dev_count;
94 static dev_ctx **dev_ctx;
96 /* ------------- RADIO IMPLEMENTATION ----------------- */
99 // Radio initialisation should be done only when user start the radio and not at plugin intialisation
100 // Making this call too early would impose to restart the binder to detect a radio.
103 init_dev_count = _radio_dev_count();
106 dev_ctx = (dev_ctx**) malloc(init_dev_count * sizeof(dev_ctx));
108 for (i = 0; i < init_dev_count; i++) {
109 dev_ctx[i] = (struct dev_ctx*) malloc(sizeof(struct dev_ctx));
110 dev_ctx[i]->dev = NULL;
111 dev_ctx[i]->mode = FM;
112 dev_ctx[i]->freq = 100.0;
113 dev_ctx[i]->mute = 0;
114 dev_ctx[i]->should_run = 0;
115 dev_ctx[i]->dongle = NULL;
116 dev_ctx[i]->demod = NULL;
117 dev_ctx[i]->output = NULL;
118 _radio_dev_init(dev_ctx[i], i);
122 STATIC void radio_off () {
125 for (i = 0; i < init_dev_count; i++) {
126 _radio_dev_free(dev_ctx[i]);
132 STATIC void radio_set_mode (dev_ctx *dev_ctx, Mode mode) {
133 dev_ctx->mode = mode;
134 _radio_apply_params(dev_ctx);
137 STATIC void radio_set_freq (dev_ctx *dev_ctx, float freq) {
138 dev_ctx->freq = freq;
139 _radio_apply_params(dev_ctx);
142 STATIC void radio_set_mute (dev_ctx *dev_ctx, unsigned char mute) {
143 dev_ctx->mute = mute;
144 _radio_apply_params(dev_ctx);
147 STATIC void radio_play (dev_ctx *dev_ctx) {
148 _radio_start_threads(dev_ctx);
151 STATIC void radio_stop (dev_ctx *dev_ctx) {
152 _radio_stop_threads(dev_ctx);
155 /* --- HELPER FUNCTIONS --- */
157 STATIC unsigned int _radio_dev_count () {
158 return rtlsdr_get_device_count();
161 STATIC const char* _radio_dev_name (unsigned int num) {
162 return rtlsdr_get_device_name(num);
165 STATIC unsigned char _radio_dev_init (dev_ctx *dev_ctx, unsigned int num) {
166 rtlsdr_dev_t *dev = dev_ctx->dev;
168 if (rtlsdr_open(&dev, num) < 0)
171 rtlsdr_set_tuner_gain_mode(dev, 0);
173 if (rtlsdr_reset_buffer(dev) < 0)
176 // dev_ctx->dev = dev; REQUIRED IN C TOO ? TEST !
178 _radio_apply_params(dev_ctx);
183 STATIC unsigned char _radio_dev_free (dev_ctx *dev_ctx) {
184 rtlsdr_dev_t *dev = dev_ctx->dev;
186 if (rtlsdr_close(dev) < 0)
193 STATIC void _radio_apply_params (dev_ctx *dev_ctx) {
194 rtlsdr_dev_t *dev = dev_ctx->dev;
195 Mode mode = dev_ctx->mode;
196 float freq = dev_ctx->freq;
200 rate = ((1000000 / 200000) + 1) * 200000;
206 rtlsdr_set_center_freq(dev, freq);
207 rtlsdr_set_sample_rate(dev, rate);
209 // dev_ctx->dev = dev; REQUIRED IN C TOO ? TEST !
212 STATIC void _radio_start_threads (dev_ctx *dev_ctx) {
213 rtlsdr_dev_t *dev = dev_ctx->dev;
214 dev_ctx->dongle = (dongle_ctx*) malloc(sizeof(dongle_ctx));
215 dev_ctx->demod = (demod_ctx*) malloc(sizeof(demod_ctx));
216 dev_ctx->output = (output_ctx*) malloc(sizeof(output_ctx));
218 dongle_ctx *dongle = dev_ctx->dongle;
219 demod_ctx *demod = dev_ctx->demod;
220 output_ctx *output = dev_ctx->output;
222 pthread_rwlock_init(&demod->lck, NULL);
223 pthread_cond_init(&demod->ok, NULL);
224 pthread_mutex_init(&demod->ok_m, NULL);
225 pthread_rwlock_init(&output->lck, NULL);
226 pthread_cond_init(&output->ok, NULL);
227 pthread_mutex_init(&output->ok_m, NULL);
229 dev_ctx->should_run = 1;
232 dongle->thr_finished = 0;
233 pthread_create(&dongle->thr, NULL, _dongle_thread_fn, (void*)dev_ctx);
236 demod->pre_r = demod->pre_j = 0;
237 demod->now_r = demod->now_j = 0;
238 demod->index = demod->pre_index = demod->now_index = 0;
239 demod->thr_finished = 0;
240 pthread_create(&demod->thr, NULL, _demod_thread_fn, (void*)dev_ctx);
243 output->thr_finished = 0;
244 pthread_create(&output->thr, NULL, _output_thread_fn, (void*)dev_ctx);
247 STATIC void _radio_stop_threads (dev_ctx *dev_ctx) {
248 rtlsdr_dev_t *dev = dev_ctx->dev;
249 dongle_ctx *dongle = dev_ctx->dongle;
250 demod_ctx *demod = dev_ctx->demod;
251 output_ctx *output = dev_ctx->output;
253 if (!dongle || !demod || !output)
256 /* stop each "while" loop in threads */
257 dev_ctx->should_run = 0;
259 rtlsdr_cancel_async(dev);
260 pthread_signal(&demod->ok, &demod->ok_m);
261 pthread_signal(&output->ok, &output->ok_m);
263 while (!dongle->thr_finished ||
264 !demod->thr_finished ||
265 !output->thr_finished)
268 pthread_join(dongle->thr, NULL);
269 pthread_join(demod->thr, NULL);
270 pthread_join(output->thr, NULL);
271 pthread_rwlock_destroy(&demod->lck);
272 pthread_cond_destroy(&demod->ok);
273 pthread_mutex_destroy(&demod->ok_m);
274 pthread_rwlock_destroy(&output->lck);
275 pthread_cond_destroy(&output->ok);
276 pthread_mutex_destroy(&output->ok_m);
278 free(dongle); dev_ctx->dongle = NULL;
279 free(demod); dev_ctx->demod = NULL;
280 free(output); dev_ctx->output = NULL;
283 /* ---- LOCAL THREADED FUNCTIONS ---- */
285 STATIC void _rtlsdr_callback (unsigned char *buf, uint32_t len, void *ctx) {
286 dev_ctx *dev_ctx = (dev_ctx *)ctx;
287 dongle_ctx *dongle = dev_ctx->dongle;
288 demod_ctx *demod = dev_ctx->demod;
292 if (!dev_ctx->should_run)
296 for (i = 0; i < (int)len; i += 8) {
297 tmp = 255 - buf[i+3];
301 buf[i+4] = 255 - buf[i+4];
302 buf[i+5] = 255 - buf[i+5];
304 tmp = 255 - buf[i+6];
310 for (i = 0; i < (int)len; i++)
311 dongle->buf[i] = (int16_t)buf[i] - 127;
313 /* lock demod thread, write to it, unlock */
314 pthread_rwlock_wrlock(&demod->lck);
315 memcpy(demod->buf, dongle->buf, 2 * len);
316 demod->buf_len = len;
317 pthread_rwlock_unlock(&demod->lck);
318 pthread_signal(&demod->ok, &demod->ok_m);
321 STATIC void* _dongle_thread_fn (void *ctx) {
322 dev_ctx *dev_ctx = (dev_ctx *)ctx;
323 dongle_ctx *dongle = dev_ctx->dongle;
325 rtlsdr_read_async(dev_ctx->dev, _rtlsdr_callback, dev_ctx, 0, 0);
327 dongle->thr_finished = 1;
331 STATIC void _lowpass_demod (void *ctx) {
332 demod_ctx *demod = (demod_ctx *)ctx;
335 while (i < demod->buf_len) {
336 demod->now_r += demod->buf[i];
337 demod->now_j += demod->buf[i+1];
340 if (demod->index < ((1000000 / 200000) + 1))
342 demod->buf[i2] = demod->now_r;
343 demod->buf[i2+1] = demod->now_j;
345 demod->now_r = demod->now_j = 0;
351 STATIC void _lowpassreal_demod (void *ctx) {
352 demod_ctx *demod = (demod_ctx *)ctx;
357 while (i < demod->res_len) {
358 demod->now_index += demod->res[i];
360 demod->pre_index += slow;
361 if (demod->pre_index < fast)
363 demod->res[i2] = (int16_t)(demod->now_index / (fast/slow));
364 demod->pre_index -= fast;
365 demod->now_index = 0;
371 STATIC void _multiply (int ar, int aj, int br, int bj, int *cr, int *cj) {
376 STATIC int _polar_discriminant (int ar, int aj, int br, int bj) {
379 _multiply(ar, aj, br, -bj, &cr, &cj);
380 angle = atan2((double)cj, (double)cr);
381 return (int)(angle / 3.14159 * (1<<14));
384 STATIC void _fm_demod (void *ctx) {
385 demod_ctx *demod = (demod_ctx *)ctx;
386 int16_t *buf = demod->buf;
387 int buf_len = demod->buf_len;
390 pcm = _polar_discriminant(buf[0], buf[1], demod->pre_r, demod->pre_j);
391 demod->res[0] = (int16_t)pcm;
393 for (i = 2; i < (buf_len-1); i += 2) {
394 pcm = _polar_discriminant(buf[i], buf[i+1], buf[i-2], buf[i-1]);
395 demod->res[i/2] = (int16_t)pcm;
397 demod->pre_r = buf[buf_len - 2];
398 demod->pre_j = buf[buf_len - 1];
399 demod->res_len = buf_len/2;
402 STATIC void _am_demod (void *ctx) {
403 demod_ctx *demod = (demod_ctx *)ctx;
404 int16_t *buf = demod->buf;
405 int buf_len = demod->buf_len;
408 for (i = 0; i < buf_len; i += 2) {
409 pcm = buf[i] * buf[i];
410 pcm += buf[i+1] * buf[i+1];
411 demod->res[i/2] = (int16_t)sqrt(pcm);
413 demod->res_len = buf_len/2;
416 STATIC void* _demod_thread_fn (void *ctx) {
417 dev_ctx *dev_ctx = (dev_ctx *)ctx;
418 demod_ctx *demod = dev_ctx->demod;
419 output_ctx *output = dev_ctx->output;
421 while(dev_ctx->should_run) {
422 pthread_wait(&demod->ok, &demod->ok_m);
423 pthread_rwlock_wrlock(&demod->lck);
424 _lowpass_demod(demod);
425 if (dev_ctx->mode == FM)
429 _lowpassreal_demod(demod);
430 pthread_rwlock_unlock(&demod->lck);
432 /* lock demod thread, write to it, unlock */
433 pthread_rwlock_wrlock(&output->lck);
434 memcpy(output->buf, demod->res, 2 * demod->res_len);
435 output->buf_len = demod->res_len;
436 pthread_rwlock_unlock(&output->lck);
437 pthread_signal(&output->ok, &output->ok_m);
440 demod->thr_finished = 1;
444 STATIC void* _output_thread_fn (void *ctx) {
445 dev_ctx *dev_ctx = (dev_ctx *)ctx;
446 output_ctx *output = dev_ctx->output;
448 while (dev_ctx->should_run) {
449 pthread_wait(&output->ok, &output->ok_m);
450 pthread_rwlock_rdlock(&output->lck);
451 //if (!dev_ctx->mute)
452 // mRadio->PlayAlsa((void*)&output->buf, output->buf_len);
453 pthread_rwlock_unlock(&output->lck);
456 output->thr_finished = 1;
462 STATIC json_object* start (AFB_session *session, AFB_request *request, void* handle) {
463 json_object *response;
466 // request all query key/value
467 getQueryAll (request, query, sizeof(query));
469 // check if we have some post data
470 if (request->post == NULL) request->post="NoData";
472 // return response to caller
473 response = jsonNewMessage(AFB_SUCCESS, "Start Radio plugin query={%s} PostData: \'%s\' ", query, request->post);
475 //if (verbose) fprintf(stderr, "%d: \n", pingcount);
479 STATIC json_object* stop (AFB_session *session, AFB_request *request, void* handle) {
480 json_object *response;
483 getQueryAll (request, query, sizeof(query));
485 if (request->post == NULL) request->post="NoData";
487 response = jsonNewMessage(AFB_SUCCESS, "Stop Radio plugin query={%s} PostData: \'%s\' ", query, request->post);
493 // ********************************************************
495 // FULUP integration proposal with client session context
497 // ********************************************************
502 // Structure holding existing radio with current usage status
509 // Radio plugin handle should store everething API may need
511 radioT *radios[MAX_RADIO]; // pointer to existing radio
516 // Client Context Structure Hold any specific to client [will be destroyed when client leave]
518 dev_ctx radio; // pointer to client radio
519 int idx; // index of radio within global array
524 // It his was not a demo only, it should be smarter to enable hot plug/unplug
525 STATIC updateRadioDevList(pluginHandleT *handle) {
528 // loop on existing radio if any
529 for (idx = 0; idx < _radio_dev_count; idx++) {
530 if (idx == MAX_RADIO) break;
531 handle->radios[idx] = calloc(1, sizeof(radioDevT)) // use calloc to set used to FALSE
532 handle->radios[idx]->name = _radio_dev_name(num);
534 handle->devCount = _radio_dev_count;
538 // This is call at plugin load time [radio devices might still not be visible]
539 STATIC pluginHandleT* initRadioPlugin() {
541 // Allocate Plugin handle
542 pluginHandleT *handle = calloc (1,sizeof (pluginHandleT)); // init handle with zero
544 // Some initialisation steps
545 updateRadioDevList(handle);
550 // Stop a radio free related ressource and make it avaliable for other clients
551 STATIC AFB_error releaseRadio (pluginHandleT* handle, AFB_clientCtx *client) {
553 // change radio status
554 handle->radios[client->idx].used = FALSE;
556 // stop related threads and free attached resources
557 radio_stop (client->radio);
559 // May be some further cleanup ????
561 return (AFB_SUCCESS); // Could it fails ????
565 // Start a radio and reserve exclusive usage to requesting client
566 STATIC clientHandleT *reserveRadio (pluginHandleT* handle) {
567 clientHandleT *client;
569 // loop on existing radio if any
570 for (idx = 0; idx < _radio_dev_count; idx++) {
571 if (handle->radios[client->idx].used = FALSE) break;
574 // No avaliable radio return now
575 if (idx == MAX_RADIO) return (NULL);
578 handle->radios[client->idx].used = TRUE;
580 // create client handle
581 client = calloc (1, sizeof (clientHandleT));
583 // stop related threads and free attached resources
584 radio_start (client->radio);
586 // May be some things to do ????
592 // This is called when client session died [ex; client quit for more than 15mn]
593 STATIC freeRadio (clientHandleT *client) {
595 releaseRadio (handle, client);
600 STATIC json_object* powerOnOff (AFB_session *session, AFB_request *request, void* handle) {
602 dev_ctx *dev_ctx = (dev_ctx *)handle;
603 AFB_clientCtx *client=request->client; // get client context from request
605 // Make sure binder was started with client session
606 if ((client != NULL) {
607 request->errcode=MHD_HTTP_FORBIDDEN;
608 return (jsonNewMessage(AFB_FAIL, "Radio binder need session [--token=xxxx]"));
611 // If we have a handle radio was on let power it down
612 if (client->handle != NULL) {
614 releaseRadio (handle, client); // poweroff client related radio
616 jresp = json_object_new_object();
617 json_object_object_add(jresp, "power", json_object_new_string ("off"));
621 // request a new client context token and check result
622 if (AFB_UNAUTH == ctxTokenCreate (request)) {
623 request->errcode=MHD_HTTP_UNAUTHORIZED;
624 jresp= jsonNewMessage(AFB_FAIL, "You're not authorized to request a radio [make sure you have the right authentication token");
628 // Client is clean let's look it we have an avaliable radio to propose
630 // make sure we have last hot plug dongle visible
631 updateRadioDevList (handle);
633 // get try to get an unused radio
634 client->handle = reserveRadio (handle);
635 if (client->handle == NULL) {
636 return (jsonNewMessage(AFB_FAIL, "Sory No More Radio Avaliable"));
639 // At this point we should have something to retreive radio status before last poweroff [but this is only a demonstrator]
643 STATIC AFB_restapi pluginApis[]= {
644 {"power" , (AFB_apiCB)powerOnOff , "Ping Application Framework"},
645 {"start" , (AFB_apiCB)start , "Ping Application Framework"},
646 {"stop" , (AFB_apiCB)stop , "Ping Application Framework"},
650 PUBLIC AFB_plugin *radioRegister (AFB_session *session) {
651 AFB_plugin *plugin = malloc (sizeof (AFB_plugin));
652 plugin->type = AFB_PLUGIN_JSON;
653 plugin->info = "Application Framework Binder - Radio plugin";
654 plugin->prefix = "radio";
655 plugin->apis = pluginApis;
657 plugin->handle = initRadioPlugin();
658 plugin->freeHandleCB = freeRadio();