2 * Copyright (C) 2016 "IoT.bzh"
3 * Author Fulup Ar Foll <fulup@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 * https://gist.github.com/ghedo/963382
19 * http://alsa-utils.sourcearchive.com/documentation/1.0.15/aplay_8c-source.html
24 #define BUFFER_FRAME_COUNT 10 /* max frames in buffer */
25 #define WAIT_TIMER_US 1000000 /* default waiting timer 1s */
27 #include <systemd/sd-event.h>
28 #include <sys/types.h>
38 #include "ucs_binding.h"
39 #include "ucs_interface.h"
43 #define MAX_FILENAME_LEN (100)
44 #define RX_BUFFER (64)
46 /** Internal structure, enabling multiple instances of this component.
47 * \note Do not access any of this variables.
52 char fileName[MAX_FILENAME_LEN];
53 uint8_t rxBuffer[RX_BUFFER];
62 UCSI_channelsT *channels;
65 static ucsContextT *ucsContextS;
67 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
68 /*AFB_DEBUG (afbIface, format, args); */
70 va_start (args, vargsCnt);
71 vfprintf (stderr, format, args);
76 va_start(argptr, vargsCnt);
77 vsprintf(outbuf, format, argptr);
82 PUBLIC uint16_t UCSI_CB_OnGetTime(void *pTag) {
83 struct timespec currentTime;
87 if (clock_gettime(CLOCK_MONOTONIC_RAW, ¤tTime)) {
92 timer = (uint16_t) ((currentTime.tv_sec * 1000 ) + ( currentTime.tv_nsec / 1000000 ));
96 STATIC int onTimerCB (sd_event_source* source,uint64_t timer, void* pTag) {
97 ucsContextT *ucsContext = (ucsContextT*) pTag;
99 sd_event_source_unref(source);
100 UCSI_Timeout(&ucsContext->ucsiData);
105 /* UCS2 Interface Timer Callback */
106 PUBLIC void UCSI_CB_OnSetServiceTimer(void *pTag, uint16_t timeout) {
108 /* set a timer with 250ms accuracy */
109 sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
110 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, onTimerCB, pTag);
115 * \brief Callback when ever an Unicens forms a human readable message.
116 * This can be error events or when enabled also debug messages.
117 * \note This function must be implemented by the integrator
118 * \param pTag - Pointer given by the integrator by UCSI_Init
119 * \param format - Zero terminated format string (following printf rules)
120 * \param vargsCnt - Amount of parameters stored in "..."
122 void UCSI_CB_OnUserMessage(void *pTag, bool isError, const char format[],
123 uint16_t vargsCnt, ...) {
127 va_start(argptr, vargsCnt);
128 vsprintf(outbuf, format, argptr);
134 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
135 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
136 ucsContextT *ucsContext = (ucsContextT*) pTag;
138 sd_event_source_unref(source);
139 UCSI_Service(&ucsContext->ucsiData);
143 /* UCS Callback fire when ever UNICENS needs to be serviced */
144 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
146 /* push an asynchronous request for loopback to call UCSI_Service */
147 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
150 /* Callback when ever this UNICENS wants to send a message to INIC. */
151 PUBLIC void UCSI_CB_OnTxRequest(void *pTag, const uint8_t *pData, uint32_t len) {
152 ucsContextT *ucsContext = (ucsContextT*) pTag;
153 CdevData_t *cdevTx = &ucsContext->tx;
156 if (NULL == pData || 0 == len) return;
158 if (O_RDONLY == cdevTx->fileFlags) return;
159 if (-1 == cdevTx->fileHandle)
160 cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
161 if (-1 == cdevTx->fileHandle)
165 ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
168 /* Silently ignore write error (only occur in non-blocking mode) */
171 total += (uint32_t) written;
176 * \brief Callback when UNICENS instance has been stopped.
177 * \note This event can be used to free memory holding the resources
178 * passed with UCSI_NewConfig
179 * \note This function must be implemented by the integrator
180 * \param pTag - Pointer given by the integrator by UCSI_Init
182 void UCSI_CB_OnStop(void *pTag) {
183 AFB_NOTICE ("UNICENS stopped");
187 /** This callback will be raised, when ever an applicative message on the control channel arrived */
188 void UCSI_CB_OnAmsMessageReceived(void *pTag)
190 /* If not interested, just ignore this event.
191 Otherwise UCSI_GetAmsMessage may now be called asynchronous (mainloop) to get the content.
192 Don't forget to call UCSI_ReleaseAmsMessage after that */
195 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
197 if (NULL == d || NULL == fileName) goto OnErrorExit;
199 memset(d, 0, sizeof(CdevData_t));
200 strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
204 d->fileFlags = O_RDWR | O_NONBLOCK;
206 d->fileFlags = O_RDONLY | O_NONBLOCK;
208 d->fileFlags = O_WRONLY | O_NONBLOCK;
210 /* open file to enable event loop */
211 d->fileHandle = open(d->fileName, d->fileFlags);
212 if (d->fileHandle <= 0) goto OnErrorExit;
220 static bool InitializeCdevs(ucsContextT *ucsContext)
222 if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
224 if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
229 /* Callback fire when something is avaliable on MOST cdev */
230 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
231 ucsContextT *ucsContext =( ucsContextT*) pTag;
233 uint8_t pBuffer[RX_BUFFER];
236 len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
239 ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
241 AFB_DEBUG ("Buffer overrun (not handle)");
242 /* Buffer overrun could replay pBuffer */
247 STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
252 UcsXmlVal_t* ucsConfig;
254 const char *filename = afb_req_value(request, "filename");
256 afb_req_fail_f (request, "filename-missing", "No filename given");
260 fdHandle = open(filename, O_RDONLY);
262 afb_req_fail_f (request, "fileread-error", "File not accessible: '%s' err=%s", filename, strerror(fdHandle));
266 /* read file into buffer as a \0 terminated string */
267 fstat(fdHandle, &fdStat);
268 xmlBuffer = (char*)alloca(fdStat.st_size + 1);
269 readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
271 xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
273 if (readSize != fdStat.st_size) {
274 afb_req_fail_f (request, "fileread-fail", "File to read fullfile '%s' size(%d!=%d)", filename, (int)readSize, (int)fdStat.st_size);
278 ucsConfig = UcsXml_Parse(xmlBuffer);
280 afb_req_fail_f (request, "filexml-error", "File XML invalid: '%s'", filename);
290 STATIC int volOnSvcCB (sd_event_source* source,uint64_t timer, void* pTag) {
291 ucsContextT *ucsContext = (ucsContextT*) pTag;
293 sd_event_source_unref(source);
294 UCSI_Vol_Service(&ucsContext->ucsiData);
299 /* This callback is fire each time an volume event wait in the queue */
300 void volumeCB (uint16_t timeout) {
302 sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
303 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, volOnSvcCB, ucsContextS);
306 STATIC int volSndCmd (struct afb_req request, struct json_object *commandJ, ucsContextT *ucsContext) {
308 struct json_object *nameJ, *channelJ, *volJ;
310 enum json_type jtype= json_object_get_type(commandJ);
312 case json_type_array:
313 if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 0)), "%d", &numid)) {
314 afb_req_fail_f (request, "channel-invalid","command=%s channel is not an integer", json_object_get_string (channelJ));
317 if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 1)), "%d", &vol)) {
318 afb_req_fail_f (request, "vol-invalid","command=%s vol is not an integer", json_object_get_string (channelJ));
323 case json_type_object:
324 if (json_object_object_get_ex (commandJ, "numid", &channelJ)) {
325 if (!sscanf (json_object_get_string (channelJ), "%d", &numid)) {
326 afb_req_fail_f (request, "channel-invalid","command=%s numid is not an integer", json_object_get_string (channelJ));
330 if (json_object_object_get_ex (commandJ, "channel", &nameJ)) {
332 const char *name = json_object_get_string(nameJ);
334 for (idx =0; ucsContext->channels[idx].name != NULL; idx++) {
335 if (!strcasecmp(ucsContext->channels[idx].name, name)) {
336 numid = ucsContext->channels[idx].numid;
340 if (ucsContext->channels[idx].name == NULL) {
341 afb_req_fail_f (request, "channel-invalid","command=%s channel name does not exist", name);
345 afb_req_fail_f (request, "channel-invalid","command=%s no valid channel name or channel", json_object_get_string(commandJ));
350 if (!json_object_object_get_ex (commandJ, "volume", &volJ)) {
351 afb_req_fail_f (request, "vol-missing","command=%s vol not present", json_object_get_string (commandJ));
355 if (!sscanf (json_object_get_string (volJ), "%d", &vol)) {
356 afb_req_fail_f (request, "vol-invalid","command=%s vol:%s is not an integer", json_object_get_string (commandJ), json_object_get_string (volJ));
363 afb_req_fail_f (request, "setvol-invalid","command=%s not valid JSON Volume Command", json_object_get_string(commandJ));
368 /* Fulup what's append when channel or vol are invalid ??? */
369 err = UCSI_Vol_Set (&ucsContext->ucsiData, numid, (uint8_t) vol);
371 /* Fulup this might only be a warning (not sure about it) */
372 afb_req_fail_f (request, "vol-refused","command=%s vol was refused by UNICENS", json_object_get_string (volJ));
383 PUBLIC void ucs2_volume (struct afb_req request) {
384 struct json_object *queryJ;
387 /* check UNICENS is initialised */
389 afb_req_fail_f (request, "UNICENS-init","Should Load Config before using setvol");
393 queryJ = afb_req_json(request);
395 afb_req_fail_f (request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
399 enum json_type jtype= json_object_get_type(queryJ);
401 case json_type_array:
402 for (int idx=0; idx < json_object_array_length (queryJ); idx ++) {
403 err= volSndCmd (request, json_object_array_get_idx (queryJ, idx), ucsContextS);
404 if (err) goto OnErrorExit;
408 case json_type_object:
409 err = volSndCmd (request, queryJ, ucsContextS);
410 if (err) goto OnErrorExit;
414 afb_req_fail_f (request, "query-notarray","query=%s not valid JSON Volume Command Array", afb_req_value(request,""));
419 afb_req_success(request,NULL,NULL);
426 PUBLIC void ucs2_configure (struct afb_req request) {
427 static UcsXmlVal_t *ucsConfig;
428 static ucsContextT ucsContext;
430 sd_event_source *evtSource;
433 /* Read and parse XML file */
434 ucsConfig = ParseFile (request);
435 if (NULL == ucsConfig) goto OnErrorExit;
437 /* When ucsContextS is set, do not initalize UNICENS, CDEVs or system hooks, just load new XML */
440 if (!ucsContextS && !InitializeCdevs(&ucsContext)) {
441 afb_req_fail_f (request, "devnit-error", "Fail to initialise device [rx=%s tx=%s]", CONTROL_CDEV_RX, CONTROL_CDEV_TX);
445 /* Initialise UNICENS Config Data Structure */
446 UCSI_Init(&ucsContext.ucsiData, &ucsContext);
448 /* register aplayHandle file fd into binder mainloop */
449 err = sd_event_add_io(afb_daemon_get_event_loop(), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
451 afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop");
455 /* init UNICENS Volume Library */
456 ucsContext.channels = UCSI_Vol_Init (&ucsContext.ucsiData, volumeCB);
457 if (!ucsContext.channels) {
458 afb_req_fail_f (request, "register-volume", "Could not enqueue new Unicens config");
461 /* save this in a statical variable until ucs2vol move to C */
462 ucsContextS = &ucsContext;
464 /* Initialise UNICENS with parsed config */
465 if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsConfig)) {
466 afb_req_fail_f (request, "UNICENS-init", "Fail to initialize UNICENS");
470 afb_req_success(request,NULL,"UNICENS-active");
476 PUBLIC void ucs2_monitor (struct afb_req request) {
478 afb_req_success(request,NULL,"UNICENS-to_be_done");