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];
65 struct afb_event node_event;
69 static ucsContextT *ucsContextS;
70 static EventData_t *eventData = NULL;
72 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
73 /*AFB_DEBUG (afbIface, format, args); */
75 va_start (args, vargsCnt);
76 vfprintf (stderr, format, args);
81 va_start(argptr, vargsCnt);
82 vsprintf(outbuf, format, argptr);
87 PUBLIC uint16_t UCSI_CB_OnGetTime(void *pTag) {
88 struct timespec currentTime;
92 if (clock_gettime(CLOCK_MONOTONIC_RAW, ¤tTime)) {
97 timer = (uint16_t) ((currentTime.tv_sec * 1000 ) + ( currentTime.tv_nsec / 1000000 ));
101 STATIC int onTimerCB (sd_event_source* source,uint64_t timer, void* pTag) {
102 ucsContextT *ucsContext = (ucsContextT*) pTag;
104 sd_event_source_unref(source);
105 UCSI_Timeout(&ucsContext->ucsiData);
110 /* UCS2 Interface Timer Callback */
111 PUBLIC void UCSI_CB_OnSetServiceTimer(void *pTag, uint16_t timeout) {
113 /* set a timer with 250ms accuracy */
114 sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
115 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, onTimerCB, pTag);
120 * \brief Callback when ever an Unicens forms a human readable message.
121 * This can be error events or when enabled also debug messages.
122 * \note This function must be implemented by the integrator
123 * \param pTag - Pointer given by the integrator by UCSI_Init
124 * \param format - Zero terminated format string (following printf rules)
125 * \param vargsCnt - Amount of parameters stored in "..."
127 void UCSI_CB_OnUserMessage(void *pTag, bool isError, const char format[],
128 uint16_t vargsCnt, ...) {
132 va_start(argptr, vargsCnt);
133 vsprintf(outbuf, format, argptr);
139 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
140 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
141 ucsContextT *ucsContext = (ucsContextT*) pTag;
143 sd_event_source_unref(source);
144 UCSI_Service(&ucsContext->ucsiData);
148 /* UCS Callback fire when ever UNICENS needs to be serviced */
149 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
151 /* push an asynchronous request for loopback to call UCSI_Service */
152 sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
155 /* Callback when ever this UNICENS wants to send a message to INIC. */
156 PUBLIC void UCSI_CB_OnTxRequest(void *pTag, const uint8_t *pData, uint32_t len) {
157 ucsContextT *ucsContext = (ucsContextT*) pTag;
158 CdevData_t *cdevTx = &ucsContext->tx;
161 if (NULL == pData || 0 == len) return;
163 if (O_RDONLY == cdevTx->fileFlags) return;
164 if (-1 == cdevTx->fileHandle)
165 cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
166 if (-1 == cdevTx->fileHandle)
170 ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
173 /* Silently ignore write error (only occur in non-blocking mode) */
176 total += (uint32_t) written;
181 * \brief Callback when UNICENS instance has been stopped.
182 * \note This event can be used to free memory holding the resources
183 * passed with UCSI_NewConfig
184 * \note This function must be implemented by the integrator
185 * \param pTag - Pointer given by the integrator by UCSI_Init
187 void UCSI_CB_OnStop(void *pTag) {
188 AFB_NOTICE ("UNICENS stopped");
192 /** This callback will be raised, when ever an applicative message on the control channel arrived */
193 void UCSI_CB_OnAmsMessageReceived(void *pTag)
195 /* If not interested, just ignore this event.
196 Otherwise UCSI_GetAmsMessage may now be called asynchronous (mainloop) to get the content.
197 Don't forget to call UCSI_ReleaseAmsMessage after that */
200 void UCSI_CB_OnRouteResult(void *pTag, uint16_t routeId, bool isActive)
204 void UCSI_CB_OnGpioStateChange(void *pTag, uint16_t nodeAddress, uint8_t gpioPinId, bool isHighState)
208 PUBLIC void UCSI_CB_OnMgrReport(void *pTag, Ucs_MgrReport_t code, uint16_t nodeAddress, Ucs_Rm_Node_t *pNode){
212 if (code == UCS_MGR_REP_AVAILABLE) {
215 else if (code == UCS_MGR_REP_NOT_AVAILABLE) {
219 /*untracked event - just exit*/
225 json_object *j_event_info = json_object_new_object();
226 json_object_object_add(j_event_info, "node", json_object_new_int(nodeAddress));
227 json_object_object_add(j_event_info, "available", json_object_new_boolean(available));
229 afb_event_push(eventData->node_event, j_event_info);
233 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
235 if (NULL == d || NULL == fileName) goto OnErrorExit;
237 memset(d, 0, sizeof(CdevData_t));
238 strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
242 d->fileFlags = O_RDWR | O_NONBLOCK;
244 d->fileFlags = O_RDONLY | O_NONBLOCK;
246 d->fileFlags = O_WRONLY | O_NONBLOCK;
248 /* open file to enable event loop */
249 d->fileHandle = open(d->fileName, d->fileFlags);
250 if (d->fileHandle <= 0) goto OnErrorExit;
258 static bool InitializeCdevs(ucsContextT *ucsContext)
260 if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
262 if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
267 /* Callback fire when something is avaliable on MOST cdev */
268 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
269 ucsContextT *ucsContext =( ucsContextT*) pTag;
271 uint8_t pBuffer[RX_BUFFER];
274 len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
277 ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
279 AFB_DEBUG ("Buffer overrun (not handle)");
280 /* Buffer overrun could replay pBuffer */
285 STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
290 UcsXmlVal_t* ucsConfig;
292 const char *filename = afb_req_value(request, "filename");
294 afb_req_fail_f (request, "filename-missing", "No filename given");
298 fdHandle = open(filename, O_RDONLY);
300 afb_req_fail_f (request, "fileread-error", "File not accessible: '%s' err=%s", filename, strerror(fdHandle));
304 /* read file into buffer as a \0 terminated string */
305 fstat(fdHandle, &fdStat);
306 xmlBuffer = (char*)alloca(fdStat.st_size + 1);
307 readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
309 xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
311 if (readSize != fdStat.st_size) {
312 afb_req_fail_f (request, "fileread-fail", "File to read fullfile '%s' size(%d!=%d)", filename, (int)readSize, (int)fdStat.st_size);
316 ucsConfig = UcsXml_Parse(xmlBuffer);
318 afb_req_fail_f (request, "filexml-error", "File XML invalid: '%s'", filename);
328 PUBLIC void ucs2_initialise (struct afb_req request) {
329 static UcsXmlVal_t *ucsConfig;
330 static ucsContextT ucsContext;
332 sd_event_source *evtSource;
335 /* Read and parse XML file */
336 ucsConfig = ParseFile (request);
337 if (NULL == ucsConfig) goto OnErrorExit;
339 /* When ucsContextS is set, do not initalize UNICENS, CDEVs or system hooks, just load new XML */
342 if (!ucsContextS && !InitializeCdevs(&ucsContext)) {
343 afb_req_fail_f (request, "devnit-error", "Fail to initialise device [rx=%s tx=%s]", CONTROL_CDEV_RX, CONTROL_CDEV_TX);
347 /* Initialise UNICENS Config Data Structure */
348 UCSI_Init(&ucsContext.ucsiData, &ucsContext);
350 /* register aplayHandle file fd into binder mainloop */
351 err = sd_event_add_io(afb_daemon_get_event_loop(), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
353 afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop");
357 /* save this in a statical variable until ucs2vol move to C */
358 ucsContextS = &ucsContext;
360 /* Initialise UNICENS with parsed config */
361 if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsConfig)) {
362 afb_req_fail_f (request, "UNICENS-init", "Fail to initialize UNICENS");
366 afb_req_success(request,NULL,"UNICENS-active");
373 // List Avaliable Configuration Files
374 PUBLIC void ucs2_listconfig (struct afb_req request) {
375 struct json_object *queryJ, *tmpJ, *responseJ;
377 char *dirPath, *dirList;
380 queryJ = afb_req_json(request);
381 if (queryJ && json_object_object_get_ex (queryJ, "cfgpath" , &tmpJ)) {
382 dirList = strdup (json_object_get_string(tmpJ));
384 dirList = strdup (UCS2_CFG_PATH);
385 AFB_NOTICE ("fgpath:missing uses UCS2_CFG_PATH=%s", UCS2_CFG_PATH);
388 responseJ = json_object_new_array();
389 for (dirPath= strtok(dirList, ":"); dirPath && *dirPath; dirPath=strtok(NULL,":")) {
390 struct dirent *dirEnt;
392 dirHandle = opendir (dirPath);
394 AFB_NOTICE ("ucs2_listconfig dir=%s not readable", dirPath);
399 AFB_NOTICE ("ucs2_listconfig scanning: %s", dirPath);
400 while ((dirEnt = readdir(dirHandle)) != NULL) {
401 // Unknown type is accepted to support dump filesystems
402 if (dirEnt->d_type == DT_REG || dirEnt->d_type == DT_UNKNOWN) {
403 struct json_object *pathJ = json_object_new_object();
404 json_object_object_add(pathJ, "dirpath", json_object_new_string(dirPath));
405 json_object_object_add(pathJ, "basename", json_object_new_string(dirEnt->d_name));
406 json_object_array_add(responseJ, pathJ);
413 if (!error) afb_req_success(request,responseJ,NULL);
416 snprintf (info, sizeof(info), "[%d] where not scanned", error);
417 afb_req_success(request,responseJ, info);
423 PUBLIC void ucs2_subscribe (struct afb_req request) {
427 eventData = malloc(sizeof(EventData_t));
429 eventData->node_event = afb_daemon_make_event ("node-availibility");
432 if (!eventData || !afb_event_is_valid(eventData->node_event)) {
433 afb_req_fail_f (request, "create-event", "Cannot create or register event");
438 if (afb_req_subscribe(request, eventData->node_event) != 0) {
440 afb_req_fail_f (request, "subscribe-event", "Cannot subscribe to event");
444 afb_req_success(request,NULL,"event subscription successful");
450 STATIC void ucs2_writei2c_CB (void *result_ptr, void *request_ptr) {
453 afb_req *req = (afb_req *)request_ptr;
454 Ucs_I2c_ResultCode_t *res = (Ucs_I2c_ResultCode_t *)result_ptr;
457 afb_req_fail(*req, "processing","busy or lost initialization");
459 else if (*res != UCS_I2C_RES_SUCCESS){
460 afb_req_fail_f(*req, "error-result", "result code: %d", *res);
463 afb_req_success(*req, NULL, "success");
470 AFB_NOTICE("write_i2c: ambiguous response data");
474 /* write a single i2c command */
475 STATIC void ucs2_writei2c_cmd(struct afb_req request, json_object *j_obj) {
477 static uint8_t i2c_data[I2C_MAX_DATA_SZ];
478 uint8_t i2c_data_sz = 0;
479 uint16_t node_addr = 0;
480 struct afb_req *async_req_ptr = NULL;
482 node_addr = (uint16_t)json_object_get_int(json_object_object_get(j_obj, "node"));
483 AFB_NOTICE("node_address: 0x%02X", node_addr);
485 if (node_addr == 0) {
486 afb_req_fail_f(request, "query-params","params wrong or missing");
490 if (json_object_get_type(json_object_object_get(j_obj, "data"))==json_type_array) {
491 int size = json_object_array_length(json_object_object_get(j_obj, "data"));
492 if ((size > 0) && (size <= I2C_MAX_DATA_SZ)) {
496 struct json_object *j_elem;
497 struct json_object *j_arr = json_object_object_get(j_obj, "data");
499 for (i = 0; i < size; i++) {
502 j_elem = json_object_array_get_idx(j_arr, i);
503 val = json_object_get_int(j_elem);
504 if ((val < 0) && (val > 0xFF)){
508 i2c_data[i] = (uint8_t)json_object_get_int(j_elem);
511 i2c_data_sz = (uint8_t)i;
515 if (i2c_data_sz == 0) {
516 AFB_NOTICE("data: invalid or not found");
517 afb_req_fail_f(request, "query-params","params wrong or missing");
521 async_req_ptr = malloc(sizeof(afb_req));
522 *async_req_ptr = request;
524 if (UCSI_I2CWrite( &ucsContextS->ucsiData, /* UCSI_Data_t *pPriv*/
525 node_addr, /* uint16_t targetAddress*/
526 false, /* bool isBurst*/
527 0u, /* block count */
528 0x2Au, /* i2c slave address */
529 0x03E8u, /* timeout 1000 milliseconds */
530 i2c_data_sz, /* uint8_t dataLen */
531 &i2c_data[0], /* uint8_t *pData */
532 &ucs2_writei2c_CB, /* callback*/
533 (void*)async_req_ptr /* callback argument */
535 /* asynchronous command is running */
536 afb_req_addref(request);
539 AFB_NOTICE("i2c write: scheduling command failed");
540 afb_req_fail_f(request, "query-command-queue","command queue overload");
542 async_req_ptr = NULL;
550 /* parse array or single command */
551 PUBLIC void ucs2_writei2c (struct afb_req request) {
553 struct json_object *j_obj;
555 /* check UNICENS is initialised */
557 afb_req_fail_f(request, "unicens-init","Should Load Config before using setvol");
561 j_obj = afb_req_json(request);
563 afb_req_fail_f(request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
567 AFB_DEBUG("request: %s", json_object_to_json_string(j_obj));
569 if (json_object_get_type(j_obj)==json_type_array) {
572 int len = json_object_array_length(j_obj);
575 afb_req_fail_f(request, "query-array","query of multiple commands is not supported");
579 for (cnt = 0; cnt < len; cnt++) {
581 json_object *j_cmd = json_object_array_get_idx(j_obj, cnt);
582 ucs2_writei2c_cmd(request, j_cmd);
586 ucs2_writei2c_cmd(request, j_obj);