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 */
26 #define I2C_MAX_DATA_SZ 32 /* max. number of bytes to be written to i2c */
28 #include <systemd/sd-event.h>
29 #include <sys/types.h>
40 #include "ucs_binding.h"
41 #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;
66 struct afb_event node_event;
70 static ucsContextT *ucsContextS;
71 static EventData_t *eventData = NULL;
73 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
74 /*AFB_DEBUG (afbIface, format, args); */
76 va_start (args, vargsCnt);
77 vfprintf (stderr, format, args);
82 va_start(argptr, vargsCnt);
83 vsprintf(outbuf, format, argptr);
88 PUBLIC uint16_t UCSI_CB_OnGetTime(void *pTag) {
89 struct timespec currentTime;
93 if (clock_gettime(CLOCK_MONOTONIC_RAW, ¤tTime)) {
98 timer = (uint16_t) ((currentTime.tv_sec * 1000 ) + ( currentTime.tv_nsec / 1000000 ));
102 STATIC int onTimerCB (sd_event_source* source,uint64_t timer, void* pTag) {
103 ucsContextT *ucsContext = (ucsContextT*) pTag;
105 sd_event_source_unref(source);
106 UCSI_Timeout(&ucsContext->ucsiData);
111 /* UCS2 Interface Timer Callback */
112 PUBLIC void UCSI_CB_OnSetServiceTimer(void *pTag, uint16_t timeout) {
114 /* set a timer with 250ms accuracy */
115 sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
116 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, onTimerCB, pTag);
121 * \brief Callback when ever an Unicens forms a human readable message.
122 * This can be error events or when enabled also debug messages.
123 * \note This function must be implemented by the integrator
124 * \param pTag - Pointer given by the integrator by UCSI_Init
125 * \param format - Zero terminated format string (following printf rules)
126 * \param vargsCnt - Amount of parameters stored in "..."
128 void UCSI_CB_OnUserMessage(void *pTag, bool isError, const char format[],
129 uint16_t vargsCnt, ...) {
133 va_start(argptr, vargsCnt);
134 vsprintf(outbuf, format, argptr);
140 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
141 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
142 ucsContextT *ucsContext = (ucsContextT*) pTag;
144 sd_event_source_unref(source);
145 UCSI_Service(&ucsContext->ucsiData);
149 /* UCS Callback fire when ever UNICENS needs to be serviced */
150 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
152 /* push an asynchronous request for loopback to call UCSI_Service */
153 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
156 /* Callback when ever this UNICENS wants to send a message to INIC. */
157 PUBLIC void UCSI_CB_OnTxRequest(void *pTag, const uint8_t *pData, uint32_t len) {
158 ucsContextT *ucsContext = (ucsContextT*) pTag;
159 CdevData_t *cdevTx = &ucsContext->tx;
162 if (NULL == pData || 0 == len) return;
164 if (O_RDONLY == cdevTx->fileFlags) return;
165 if (-1 == cdevTx->fileHandle)
166 cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
167 if (-1 == cdevTx->fileHandle)
171 ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
174 /* Silently ignore write error (only occur in non-blocking mode) */
177 total += (uint32_t) written;
182 * \brief Callback when UNICENS instance has been stopped.
183 * \note This event can be used to free memory holding the resources
184 * passed with UCSI_NewConfig
185 * \note This function must be implemented by the integrator
186 * \param pTag - Pointer given by the integrator by UCSI_Init
188 void UCSI_CB_OnStop(void *pTag) {
189 AFB_NOTICE ("UNICENS stopped");
193 /** This callback will be raised, when ever an applicative message on the control channel arrived */
194 void UCSI_CB_OnAmsMessageReceived(void *pTag)
196 /* If not interested, just ignore this event.
197 Otherwise UCSI_GetAmsMessage may now be called asynchronous (mainloop) to get the content.
198 Don't forget to call UCSI_ReleaseAmsMessage after that */
201 void UCSI_CB_OnRouteResult(void *pTag, uint16_t routeId, bool isActive)
205 void UCSI_CB_OnGpioStateChange(void *pTag, uint16_t nodeAddress, uint8_t gpioPinId, bool isHighState)
209 PUBLIC void UCSI_CB_OnMgrReport(void *pTag, Ucs_MgrReport_t code, uint16_t nodeAddress, Ucs_Rm_Node_t *pNode){
213 if (code == UCS_MGR_REP_AVAILABLE) {
216 else if (code == UCS_MGR_REP_NOT_AVAILABLE) {
220 /*untracked event - just exit*/
226 json_object *j_event_info = json_object_new_object();
227 json_object_object_add(j_event_info, "node", json_object_new_int(nodeAddress));
228 json_object_object_add(j_event_info, "available", json_object_new_boolean(available));
230 afb_event_push(eventData->node_event, j_event_info);
234 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
236 if (NULL == d || NULL == fileName) goto OnErrorExit;
238 memset(d, 0, sizeof(CdevData_t));
239 strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
243 d->fileFlags = O_RDWR | O_NONBLOCK;
245 d->fileFlags = O_RDONLY | O_NONBLOCK;
247 d->fileFlags = O_WRONLY | O_NONBLOCK;
249 /* open file to enable event loop */
250 d->fileHandle = open(d->fileName, d->fileFlags);
251 if (d->fileHandle <= 0) goto OnErrorExit;
259 static bool InitializeCdevs(ucsContextT *ucsContext)
261 if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
263 if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
268 /* Callback fire when something is avaliable on MOST cdev */
269 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
270 ucsContextT *ucsContext =( ucsContextT*) pTag;
272 uint8_t pBuffer[RX_BUFFER];
275 len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
278 ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
280 AFB_DEBUG ("Buffer overrun (not handle)");
281 /* Buffer overrun could replay pBuffer */
286 STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
291 UcsXmlVal_t* ucsConfig;
293 const char *filename = afb_req_value(request, "filename");
295 afb_req_fail_f (request, "filename-missing", "No filename given");
299 fdHandle = open(filename, O_RDONLY);
301 afb_req_fail_f (request, "fileread-error", "File not accessible: '%s' err=%s", filename, strerror(fdHandle));
305 /* read file into buffer as a \0 terminated string */
306 fstat(fdHandle, &fdStat);
307 xmlBuffer = (char*)alloca(fdStat.st_size + 1);
308 readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
310 xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
312 if (readSize != fdStat.st_size) {
313 afb_req_fail_f (request, "fileread-fail", "File to read fullfile '%s' size(%d!=%d)", filename, (int)readSize, (int)fdStat.st_size);
317 ucsConfig = UcsXml_Parse(xmlBuffer);
319 afb_req_fail_f (request, "filexml-error", "File XML invalid: '%s'", filename);
329 STATIC int volOnSvcCB (sd_event_source* source,uint64_t timer, void* pTag) {
330 ucsContextT *ucsContext = (ucsContextT*) pTag;
332 sd_event_source_unref(source);
333 UCSI_Vol_Service(&ucsContext->ucsiData);
338 /* This callback is fire each time an volume event wait in the queue */
339 void volumeCB (uint16_t timeout) {
341 sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
342 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, volOnSvcCB, ucsContextS);
345 STATIC int volSndCmd (struct afb_req request, struct json_object *commandJ, ucsContextT *ucsContext) {
347 struct json_object *nameJ, *channelJ, *volJ;
349 enum json_type jtype= json_object_get_type(commandJ);
351 case json_type_array:
352 if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 0)), "%d", &numid)) {
353 afb_req_fail_f (request, "channel-invalid","command=%s channel is not an integer", json_object_get_string (channelJ));
356 if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 1)), "%d", &vol)) {
357 afb_req_fail_f (request, "vol-invalid","command=%s vol is not an integer", json_object_get_string (channelJ));
362 case json_type_object:
363 if (json_object_object_get_ex (commandJ, "numid", &channelJ)) {
364 if (!sscanf (json_object_get_string (channelJ), "%d", &numid)) {
365 afb_req_fail_f (request, "channel-invalid","command=%s numid is not an integer", json_object_get_string (channelJ));
369 if (json_object_object_get_ex (commandJ, "channel", &nameJ)) {
371 const char *name = json_object_get_string(nameJ);
373 for (idx =0; ucsContext->channels[idx].name != NULL; idx++) {
374 if (!strcasecmp(ucsContext->channels[idx].name, name)) {
375 numid = ucsContext->channels[idx].numid;
379 if (ucsContext->channels[idx].name == NULL) {
380 afb_req_fail_f (request, "channel-invalid","command=%s channel name does not exist", name);
384 afb_req_fail_f (request, "channel-invalid","command=%s no valid channel name or channel", json_object_get_string(commandJ));
389 if (!json_object_object_get_ex (commandJ, "volume", &volJ)) {
390 afb_req_fail_f (request, "vol-missing","command=%s vol not present", json_object_get_string (commandJ));
394 if (!sscanf (json_object_get_string (volJ), "%d", &vol)) {
395 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));
402 afb_req_fail_f (request, "setvol-invalid","command=%s not valid JSON Volume Command", json_object_get_string(commandJ));
407 /* Fulup what's append when channel or vol are invalid ??? */
408 err = UCSI_Vol_Set (&ucsContext->ucsiData, numid, (uint8_t) vol);
410 /* Fulup this might only be a warning (not sure about it) */
411 afb_req_fail_f (request, "vol-refused","command=%s vol was refused by UNICENS", json_object_get_string (volJ));
421 PUBLIC void ucs2_volume (struct afb_req request) {
422 struct json_object *queryJ;
425 /* check UNICENS is initialised */
427 afb_req_fail_f (request, "UNICENS-init","Should Load Config before using setvol");
431 queryJ = afb_req_json(request);
433 afb_req_fail_f (request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
437 enum json_type jtype= json_object_get_type(queryJ);
439 case json_type_array:
440 for (int idx=0; idx < json_object_array_length (queryJ); idx ++) {
441 err= volSndCmd (request, json_object_array_get_idx (queryJ, idx), ucsContextS);
442 if (err) goto OnErrorExit;
446 case json_type_object:
447 err = volSndCmd (request, queryJ, ucsContextS);
448 if (err) goto OnErrorExit;
452 afb_req_fail_f (request, "query-notarray","query=%s not valid JSON Volume Command Array", afb_req_value(request,""));
457 afb_req_success(request,NULL,NULL);
464 PUBLIC void ucs2_initialise (struct afb_req request) {
465 static UcsXmlVal_t *ucsConfig;
466 static ucsContextT ucsContext;
468 sd_event_source *evtSource;
471 /* Read and parse XML file */
472 ucsConfig = ParseFile (request);
473 if (NULL == ucsConfig) goto OnErrorExit;
475 /* When ucsContextS is set, do not initalize UNICENS, CDEVs or system hooks, just load new XML */
478 if (!ucsContextS && !InitializeCdevs(&ucsContext)) {
479 afb_req_fail_f (request, "devnit-error", "Fail to initialise device [rx=%s tx=%s]", CONTROL_CDEV_RX, CONTROL_CDEV_TX);
483 /* Initialise UNICENS Config Data Structure */
484 UCSI_Init(&ucsContext.ucsiData, &ucsContext);
486 /* register aplayHandle file fd into binder mainloop */
487 err = sd_event_add_io(afb_daemon_get_event_loop(), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
489 afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop");
493 /* init UNICENS Volume Library */
494 ucsContext.channels = UCSI_Vol_Init (&ucsContext.ucsiData, volumeCB);
495 if (!ucsContext.channels) {
496 afb_req_fail_f (request, "register-volume", "Could not enqueue new Unicens config");
499 /* save this in a statical variable until ucs2vol move to C */
500 ucsContextS = &ucsContext;
502 /* Initialise UNICENS with parsed config */
503 if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsConfig)) {
504 afb_req_fail_f (request, "UNICENS-init", "Fail to initialize UNICENS");
508 afb_req_success(request,NULL,"UNICENS-active");
515 // List Avaliable Configuration Files
516 PUBLIC void ucs2_listconfig (struct afb_req request) {
517 struct json_object *queryJ, *tmpJ, *responseJ;
519 char *dirPath, *dirList;
522 queryJ = afb_req_json(request);
523 if (queryJ && json_object_object_get_ex (queryJ, "cfgpath" , &tmpJ)) {
524 dirList = strdup (json_object_get_string(tmpJ));
526 dirList = strdup (UCS2_CFG_PATH);
527 AFB_NOTICE ("fgpath:missing uses UCS2_CFG_PATH=%s", UCS2_CFG_PATH);
530 responseJ = json_object_new_array();
531 for (dirPath= strtok(dirList, ":"); dirPath && *dirPath; dirPath=strtok(NULL,":")) {
532 struct dirent *dirEnt;
534 dirHandle = opendir (dirPath);
536 AFB_NOTICE ("ucs2_listconfig dir=%s not readable", dirPath);
541 AFB_NOTICE ("ucs2_listconfig scanning: %s", dirPath);
542 while ((dirEnt = readdir(dirHandle)) != NULL) {
543 // Unknown type is accepted to support dump filesystems
544 if (dirEnt->d_type == DT_REG || dirEnt->d_type == DT_UNKNOWN) {
545 struct json_object *pathJ = json_object_new_object();
546 json_object_object_add(pathJ, "dirpath", json_object_new_string(dirPath));
547 json_object_object_add(pathJ, "basename", json_object_new_string(dirEnt->d_name));
548 json_object_array_add(responseJ, pathJ);
555 if (!error) afb_req_success(request,responseJ,NULL);
558 snprintf (info, sizeof(info), "[%d] where not scanned", error);
559 afb_req_success(request,responseJ, info);
565 PUBLIC void ucs2_subscribe (struct afb_req request) {
569 eventData = malloc(sizeof(EventData_t));
571 eventData->node_event = afb_daemon_make_event ("node-availibility");
574 if (!eventData || !afb_event_is_valid(eventData->node_event)) {
575 afb_req_fail_f (request, "create-event", "Cannot create or register event");
580 if (afb_req_subscribe(request, eventData->node_event) != 0) {
582 afb_req_fail_f (request, "subscribe-event", "Cannot subscribe to event");
586 afb_req_success(request,NULL,"event subscription successful");
592 STATIC void ucs2_writei2c_CB (void *result_ptr, void *request_ptr) {
595 afb_req *req = (afb_req *)request_ptr;
596 Ucs_I2c_ResultCode_t *res = (Ucs_I2c_ResultCode_t *)result_ptr;
599 afb_req_fail(*req, "processing","busy or lost initialization");
601 else if (*res != UCS_I2C_RES_SUCCESS){
602 afb_req_fail_f(*req, "error-result", "result code: %d", *res);
605 afb_req_success(*req, NULL, "success");
612 AFB_NOTICE("write_i2c: ambiguous response data");
616 PUBLIC void ucs2_writei2c (struct afb_req request) {
618 struct json_object *j_obj;
619 static uint8_t i2c_data[I2C_MAX_DATA_SZ];
620 uint8_t i2c_data_sz = 0;
621 uint16_t node_addr = 0;
622 struct afb_req *async_req_ptr = NULL;
624 /* check UNICENS is initialised */
626 afb_req_fail_f(request, "unicens-init","Should Load Config before using setvol");
630 j_obj = afb_req_json(request);
632 afb_req_fail_f(request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
636 node_addr = (uint16_t)json_object_get_int(json_object_object_get(j_obj, "node"));
637 AFB_NOTICE("node_address: 0x%02X", node_addr);
639 if (node_addr == 0) {
640 afb_req_fail_f(request, "query-params","params wrong or missing");
644 if (json_object_get_type(json_object_object_get(j_obj, "data"))==json_type_array) {
645 int size = json_object_array_length(json_object_object_get(j_obj, "data"));
646 if ((size > 0) && (size <= I2C_MAX_DATA_SZ)) {
650 struct json_object *j_elem;
651 struct json_object *j_arr = json_object_object_get(j_obj, "data");
653 for (i = 0; i < size; i++) {
656 j_elem = json_object_array_get_idx(j_arr, i);
657 val = json_object_get_int(j_elem);
658 if ((val < 0) && (val > 0xFF)){
662 i2c_data[i] = (uint8_t)json_object_get_int(j_elem);
665 i2c_data_sz = (uint8_t)i;
669 if (i2c_data_sz == 0) {
670 AFB_NOTICE("data: invalid or not found");
671 afb_req_fail_f(request, "query-params","params wrong or missing");
675 async_req_ptr = malloc(sizeof(afb_req));
676 *async_req_ptr = request;
678 if (UCSI_I2CWrite( &ucsContextS->ucsiData, /* UCSI_Data_t *pPriv*/
679 node_addr, /* uint16_t targetAddress*/
680 false, /* bool isBurst*/
681 0u, /* block count */
682 0x2Au, /* i2c slave address */
683 0x03E8u, /* timeout 1000 milliseconds */
684 i2c_data_sz, /* uint8_t dataLen */
685 &i2c_data[0], /* uint8_t *pData */
686 &ucs2_writei2c_CB, /* callback*/
687 (void*)async_req_ptr /* callback argument */
689 /* asynchronous command is running */
690 afb_req_addref(request);
693 AFB_NOTICE("i2c write: scheduling command failed");
694 afb_req_fail_f(request, "query-command-queue","command queue overload");
696 async_req_ptr = NULL;