2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@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.
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/ioctl.h>
28 #include <linux/can.h>
29 #include <linux/can/raw.h>
32 #include <systemd/sd-event.h>
35 #include <json-c/json.h>
36 #include <openxc.pb.h>
38 #include <afb/afb-binding.h>
39 #include <afb/afb-service-itf.h>
41 #include "ll-can-binding.h"
44 /*************************************************************************/
45 /*************************************************************************/
48 /** SECTION: UTILITY FUNCTIONS **/
51 /*************************************************************************/
52 /*************************************************************************/
55 * Retry a function 3 times
57 * param int function(): function that return an int wihtout any parameter
59 * return : 0 if ok, -1 if failed
62 static int retry( int(*func)())
78 * Test that socket is really opened
82 * return : 0 or positive int if ok, negative value if failed
85 static int socket_test()
87 if (can_handler.socket < 0)
95 * Browse chained list and return the one with specified id
97 * param uint32_t id : can arbitration identifier
101 static can_event *get_event_list_of_id(uint32_t id)
105 /* create and return if lists not exists */
106 if (!can_events_list)
108 can_events_list = (can_event*)calloc(1, sizeof(can_event));
109 can_events_list->id = id;
110 return can_events_list;
114 current = can_events_list;
117 if (current->id == id)
121 current->next = (can_event*)calloc(1, sizeof(can_event));
122 current->next->id = id;
123 return current->next;
125 current = current->next;
132 * Take an id and return it into a char array
134 static char* create_name(uint32_t id)
139 nchar = (size_t)sprintf(name, "can_%u", id);
142 char *result = (char*)malloc(nchar + 1);
143 memcpy(result, name, nchar);
152 * Create json object that will be pushed through event_loop to any subscriber
154 * param : openxc_CanMessage structure complete with data to put into json
157 * return : json object
159 static json_object* create_json_from_openxc_CanMessage(event *event)
161 struct json_object *json;
164 * TODO: process the openxc_CanMessage struct. Should be a call to a
165 * decoder function relative to that msg
167 openxc_CanMessage can_message;
168 can_message = event->can_message;
171 json = json_object_new_object();
172 json_object_object_add(json, "name", json_object_new_string(event->name));
177 /*************************************************************************/
178 /*************************************************************************/
181 /** SECTION: HANDLE CAN DEVICE **/
184 /*************************************************************************/
185 /*************************************************************************/
187 * open the can socket
189 static int open_can_dev()
191 const int canfd_on = 1;
193 struct timeval timeout = {1,0};
195 DEBUG(interface, "open_can_dev: CAN Handler socket : %d", can_handler.socket);
196 if (can_handler.socket >= 0)
197 close(can_handler.socket);
199 can_handler.socket = socket(PF_CAN, SOCK_RAW, CAN_RAW);
200 if (can_handler.socket < 0)
202 ERROR(interface, "open_can_dev: socket could not be created");
206 /* Set timeout for read */
207 setsockopt(can_handler.socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
208 /* try to switch the socket into CAN_FD mode */
209 if (setsockopt(can_handler.socket, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
211 NOTICE(interface, "open_can_dev: Can not switch into CAN Extended frame format.");
212 can_handler.is_fdmode_on = false;
214 can_handler.is_fdmode_on = true;
217 /* Attempts to open a socket to CAN bus */
218 strcpy(ifr.ifr_name, can_handler.device);
219 if(ioctl(can_handler.socket, SIOCGIFINDEX, &ifr) < 0)
220 ERROR(interface, "open_can_dev: ioctl failed");
223 can_handler.txAddress.can_family = AF_CAN;
224 can_handler.txAddress.can_ifindex = ifr.ifr_ifindex;
226 /* And bind it to txAddress */
227 if (bind(can_handler.socket, (struct sockaddr *)&can_handler.txAddress, sizeof(can_handler.txAddress)) < 0)
229 ERROR(interface, "open_can_dev: bind failed");
233 fcntl(can_handler.socket, F_SETFL, O_NONBLOCK);
237 close(can_handler.socket);
238 can_handler.socket = -1;
244 * TODO : test that socket is really opened
246 static int write_can()
251 rc = can_handler.socket;
255 * TODO change old hvac write can frame to generic on_event
257 nbytes = sendto(can_handler.socket, &canfd_frame, sizeof(struct canfd_frame), 0,
258 (struct sockaddr*)&can_handler.txAddress, sizeof(can_handler.txAddress));
261 ERROR(interface, "write_can: Sending CAN frame failed.");
266 ERROR(interface, "write_can: socket not initialized. Attempt to reopen can device socket.");
273 * Parse the CAN frame data payload as a CAN packet
274 * TODO: parse as an OpenXC Can Message. Don't translate as ASCII and put bytes
275 * directly into openxc_CanMessage
277 static int parse_can_frame(openxc_CanMessage *can_message, struct canfd_frame *canfd_frame, int maxdlen)
282 len = (canfd_frame->len > maxdlen) ? maxdlen : canfd_frame->len;
284 can_message->has_id = true;
285 if (canfd_frame->can_id & CAN_ERR_FLAG)
286 can_message->id = canfd_frame->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG);
287 else if (canfd_frame->can_id & CAN_EFF_FLAG)
289 can_message->has_frame_format = true;
290 can_message->frame_format = openxc_CanMessage_FrameFormat_EXTENDED;
291 can_message->id = canfd_frame->can_id & CAN_EFF_MASK;
294 can_message->has_frame_format = true;
295 can_message->frame_format = openxc_CanMessage_FrameFormat_STANDARD;
296 can_message->id = canfd_frame->can_id & CAN_SFF_MASK;
299 /* Don't know what to do with that for now as we haven't
300 * len fields in openxc_CanMessage struct
302 * standard CAN frames may have RTR enabled. There are no ERR frames with RTR
303 if (maxdlen == CAN_MAX_DLEN && canfd_frame->can_id & CAN_RTR_FLAG)
305 // print a given CAN 2.0B DLC if it's not zero
306 if (canfd_frame->len && canfd_frame->len <= CAN_MAX_DLC)
307 buf[offset++] = hex_asc_upper[canfd_frame->len & 0xF];
314 /* Doesn't handle real canfd_frame for now
315 if (maxdlen == CANFD_MAX_DLEN)
317 // add CAN FD specific escape char and flags
318 canfd_frame->flags & 0xF;
321 if (sizeof(canfd_frame->data) <= sizeof(can_message->data.bytes))
323 for (i = 0; i < len; i++)
324 can_message->data.bytes[i] = canfd_frame->data[i];
326 } else if (sizeof(canfd_frame->data) <= CAN_MAX_DLEN)
328 ERROR(interface, "parse_can_frame: can_frame data too long to be stored into openxc_CanMessage data field");
330 /* TODO create as many as needed openxc_CanMessage into an array to store all data from canfd_frame
331 n_msg = CAN_MAX_DLEN / sizeof(canfd_frame->data.bytes);
332 for (i = 0; i < len; i++)
333 can_message->data.bytes[i] = canfd_frame->data[i]; */
336 ERROR(interface, "parse_can_frame: can_frame is really too long here. Size of data greater than canfd maximum 64bytes size. Is it a CAN message ?");
340 /* You should not reach this return statement */
346 * Read on CAN bus and return how much bytes has been read.
348 static int read_can(openxc_CanMessage *can_message)
353 /* Test that socket is really opened */
354 if ( socket_test() < 0)
356 if (retry(open_can_dev) < 0)
358 ERROR(interface, "read_can: Socket unavailable");
363 nbytes = read(can_handler.socket, &canfd_frame, CANFD_MTU);
365 if (nbytes == CANFD_MTU)
367 DEBUG(interface, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
369 else if (nbytes == CAN_MTU)
371 DEBUG(interface, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
375 if (errno == ENETDOWN)
376 ERROR(interface, "read_can: %s interface down", can_handler.device);
377 ERROR(interface, "read_can: Error reading CAN bus");
381 /* CAN frame integrity check */
382 if ((size_t)nbytes == CAN_MTU)
383 maxdlen = CAN_MAX_DLEN;
384 else if ((size_t)nbytes == CANFD_MTU)
385 maxdlen = CANFD_MAX_DLEN;
388 ERROR(interface, "read_can: CAN frame incomplete");
392 if (parse_can_frame(can_message, &canfd_frame, maxdlen))
394 ERROR(interface, "read_can: Can't parse the can frame. ID: %i, DLC: %i, DATA: %s",
395 canfd_frame.can_id, canfd_frame.len, canfd_frame.data);
401 /*************************************************************************/
402 /*************************************************************************/
405 /** SECTION: MANAGING EVENTS **/
408 /*************************************************************************/
409 /*************************************************************************/
410 static int on_event(sd_event_source *s, int fd, uint32_t revents, void *userdata);
413 * Get the event loop running.
414 * Will trigger on_event function on EPOLLIN event on socket
416 * Return 0 or positive value on success. Else negative value for failure.
418 static int connect_to_event_loop()
420 sd_event *event_loop;
421 sd_event_source *source;
424 if (can_handler.socket < 0)
426 return can_handler.socket;
429 event_loop = afb_daemon_get_event_loop(interface->daemon);
430 rc = sd_event_add_io(event_loop, &source, can_handler.socket, EPOLLIN, on_event, NULL);
433 close(can_handler.socket);
434 ERROR(interface, "Can't connect CAN bus %s to the event loop", can_handler.device);
437 NOTICE(interface, "Connected CAN bus %s to the event loop", can_handler.device);
445 static void send_event()
451 /* Browse can_events */
452 current = can_events_list;
455 /* Browse event for each can_events no matter what the id */
456 events = current->events;
459 object = create_json_from_openxc_CanMessage(events);
460 afb_event_push(events->afb_event, object);
461 events = events->next;
463 current = current->next;
468 * called on an event on the CAN bus
470 static int on_event(sd_event_source *s, int fd, uint32_t revents, void *userdata)
472 openxc_CanMessage can_message;
474 can_message = openxc_CanMessage_init_default;
476 /* read available data */
477 if ((revents & EPOLLIN) != 0)
479 read_can(&can_message);
483 /* check if error or hangup */
484 if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
486 sd_event_source_unref(s);
488 connect_to_event_loop();
495 * get or create an event handler for the type
497 static event *get_event(uint32_t id, enum type type)
502 /* find the can list by id */
503 list = get_event_list_of_id(id);
505 /* make the new event */
506 event_elt = (event*)calloc(1, sizeof(event));
507 event_elt->next = event_elt;
508 list->events = event_elt;
509 event_elt->name = create_name(id);
510 event_elt->afb_event = afb_daemon_make_event(interface->daemon, event_elt->name);
515 /*************************************************************************/
516 /*************************************************************************/
519 /** SECTION: BINDING VERBS IMPLEMENTATION **/
522 /*************************************************************************/
523 /*************************************************************************/
525 * Returns the type corresponding to the given name
527 static enum type type_of_name(const char *name)
532 for (result = 0 ; (size_t)result < type_size; result++)
533 if (strcmp(type_NAMES[result], name) == 0)
539 * extract a valid type from the request
541 static int get_type_for_req(struct afb_req req, enum type *type)
543 if ((*type = type_of_name(afb_req_value(req, "type"))) != type_INVALID)
545 afb_req_fail(req, "unknown-type", NULL);
549 static int subscribe_unsubscribe_sig(struct afb_req request, int subscribe, struct signal *sig)
551 if (!afb_event_is_valid(sig->event)) {
554 sig->event = afb_daemon_make_event(afbitf->daemon, sig->name);
555 if (!afb_event_is_valid(sig->event)) {
560 if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, sig->event)) < 0) {
567 static int subscribe_unsubscribe_all(struct afb_req request, int subscribe)
571 n = sizeof OBD2_PIDS / sizeof * OBD2_PIDS;
573 for (i = 0 ; i < n ; i++)
574 e += !subscribe_unsubscribe_sig(request, subscribe, &OBD2_PIDS[i]);
578 static int subscribe_unsubscribe_name(struct afb_req request, int subscribe, const char *name)
582 if (0 == strcmp(name, "*"))
583 return subscribe_unsubscribe_all(request, subscribe);
590 return subscribe_unsubscribe_sig(request, subscribe, sig);
593 static void subscribe_unsubscribe(struct afb_req request, int subscribe)
596 struct json_object *args, *a, *x;
598 /* makes the subscription/unsubscription */
599 args = afb_req_json(request);
600 if (args == NULL || !json_object_object_get_ex(args, "event", &a)) {
601 ok = subscribe_unsubscribe_all(request, subscribe);
602 } else if (json_object_get_type(a) != json_type_array) {
603 ok = subscribe_unsubscribe_name(request, subscribe, json_object_get_string(a));
605 n = json_object_array_length(a);
607 for (i = 0 ; i < n ; i++) {
608 x = json_object_array_get_idx(a, i);
609 if (subscribe_unsubscribe_name(request, subscribe, json_object_get_string(x)))
615 /* send the report */
617 afb_req_success(request, NULL, NULL);
619 afb_req_fail(request, "error", NULL);
622 static void subscribe(struct afb_req request)
624 subscribe_unsubscribe(request, 1);
627 static void unsubscribe(struct afb_req request)
629 subscribe_unsubscribe(request, 0);
632 static const struct afb_verb_desc_v1 verbs[]=
634 { .name= "subscribe", .session= AFB_SESSION_NONE, .callback= subscribe, .info= "subscribe to notification of CAN bus messages." },
635 { .name= "unsubscribe", .session= AFB_SESSION_NONE, .callback= unsubscribe, .info= "unsubscribe a previous subscription." },
639 static const struct afb_binding binding_desc = {
640 .type = AFB_BINDING_VERSION_1,
642 .info = "CAN bus service",
648 const struct afb_binding *afbBindingV1Register (const struct afb_binding_interface *itf)
652 return &binding_desc;
655 int afbBindingV1ServiceInit(struct afb_service service)
657 /* Open CAN socket */
659 return connect_to_event_loop();