2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Copyright (C) 2016 Konsulko Group
4 * Author "Romain Forlot"
6 * Author "Scott Murray <scott.murray@konsulko.com>"
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/ioctl.h>
30 #include <linux/can.h>
33 #include <json-c/json.h>
35 #define AFB_BINDING_VERSION 2
36 #define RED "/sys/class/leds/blinkm-3-9-red/brightness"
37 #define BLUE "/sys/class/leds/blinkm-3-9-blue/brightness"
38 #define GREEN "/sys/class/leds/blinkm-3-9-green/brightness"
39 #include <afb/afb-binding.h>
41 #define CAN_DEV "vcan0"
47 static const struct afb_binding_interface *interface;
48 static struct afb_event event;
50 /*****************************************************************************************/
51 /*****************************************************************************************/
54 /** SECTION: UTILITY FUNCTIONS **/
57 /*****************************************************************************************/
58 /*****************************************************************************************/
61 * @brief Retry a function 3 times
63 * @param int function(): function that return an int wihtout any parameter
65 * @ return : 0 if ok, -1 if failed
68 static int retry( int(*func)())
83 /*****************************************************************************************/
84 /*****************************************************************************************/
87 /** SECTION: HANDLE CAN DEVICE **/
90 /*****************************************************************************************/
91 /*****************************************************************************************/
93 // Initialize CAN hvac array that will be sent trough the socket
98 { "LeftTemperature", 21 },
99 { "RightTemperature", 21 },
100 { "Temperature", 21 },
107 // Holds RGB combinations for each temperature
109 const int temperature;
111 } degree_colours[] = {
119 {22, {104, 0, 116} },
120 {23, {116, 0, 102} },
134 struct sockaddr_can txAddress;
137 static struct can_handler can_handler = { .socket = -1, .simulation = false, .send_msg = "SENDING CAN FRAME"};
139 static int open_can_dev_helper()
143 AFB_DEBUG("CAN Handler socket : %d", can_handler.socket);
144 close(can_handler.socket);
146 can_handler.socket = socket(PF_CAN, SOCK_RAW, CAN_RAW);
147 if (can_handler.socket < 0)
149 AFB_ERROR("socket could not be created");
153 // Attempts to open a socket to CAN bus
154 strcpy(ifr.ifr_name, CAN_DEV);
155 if(ioctl(can_handler.socket, SIOCGIFINDEX, &ifr) < 0)
157 AFB_ERROR("ioctl failed");
161 can_handler.txAddress.can_family = AF_CAN;
162 can_handler.txAddress.can_ifindex = ifr.ifr_ifindex;
164 // And bind it to txAddress
165 if (bind(can_handler.socket, (struct sockaddr *)&can_handler.txAddress, sizeof(can_handler.txAddress)) < 0)
167 AFB_ERROR("bind failed");
173 close(can_handler.socket);
174 can_handler.socket = -1;
179 static int open_can_dev()
181 int rc = retry(open_can_dev_helper);
184 AFB_ERROR("Open of interface %s failed. Falling back to simulation mode", CAN_DEV);
185 can_handler.socket = 0;
186 can_handler.simulation = true;
187 can_handler.send_msg = "FAKE CAN FRAME";
193 // Get original get temperature function from cpp hvacplugin code
194 static uint8_t to_can_temp(uint8_t value)
196 int result = ((0xF0 - 0x10) / 15) * (value - 15) + 0x10;
202 return (uint8_t)result;
205 static uint8_t read_temp_left_zone()
207 return hvac_values[0].value;
210 static uint8_t read_temp_right_zone()
212 return hvac_values[1].value;
215 static uint8_t read_temp_left_led()
217 return hvac_values[5].value;
220 static uint8_t read_temp_right_led()
222 return hvac_values[6].value;
225 static uint8_t read_temp()
227 return (uint8_t)(((int)read_temp_left_zone() + (int)read_temp_right_zone()) >> 1);
230 static uint8_t read_fanspeed()
232 return hvac_values[3].value;
236 * @brief Writing to LED for both temperature sliders
239 static int temp_write_led()
241 int rc = 0, red_flag, blue_flag, green_flag, red_value, green_value, blue_value;
245 // /sys/class/leds/blinkm-3-9-red/brightness
246 FILE* r = fopen(RED, "w");
248 AFB_ERROR("Unable to open RED path for writing");
252 // /sys/class/leds/blinkm-3-9-green/brightness
253 FILE* g = fopen(GREEN, "w");
255 AFB_ERROR("Unable to open GREEN path for writing");
259 // /sys/class/leds/blinkm-3-9-blue/brightness
260 FILE* b = fopen(BLUE, "w");
262 AFB_ERROR("Unable to open BLUE path for writing");
266 if (red_flag || green_flag || blue_flag)
271 left_temp = read_temp_left_led() - 15;
272 right_temp = read_temp_right_led() - 15;
274 // Calculates average colour value taken from the temperature toggles
275 red_value = (degree_colours[left_temp].rgb[0] + degree_colours[right_temp].rgb[0]) / 2;
276 green_value = (degree_colours[left_temp].rgb[1] + degree_colours[right_temp].rgb[1]) / 2;
277 blue_value = (degree_colours[left_temp].rgb[2] + degree_colours[right_temp].rgb[2]) / 2;
279 // Writes to LED file the specific colour
280 fprintf(r, "%d", red_value);
281 fprintf(g, "%d", green_value);
282 fprintf(b, "%d", blue_value);
291 * @brief Get temperature of left toggle in HVAC system
293 * @param struct afb_req : an afb request structure
296 static void temp_left_zone_led(struct afb_req request)
298 int i = 5, rc, x, changed;
300 struct json_object *query, *val;
301 uint8_t values[sizeof hvac_values / sizeof *hvac_values];
302 uint8_t saves[sizeof hvac_values / sizeof *hvac_values];
304 AFB_WARNING("In temp_left_zone_led.");
306 query = afb_req_json(request);
308 /* records initial values */
309 AFB_WARNING("Records initial values");
310 values[i] = saves[i] = hvac_values[i].value;
313 if (json_object_object_get_ex(query, hvac_values[i].name, &val))
315 AFB_WARNING("Value of values[i] = %d", values[i]);
316 AFB_WARNING("We got it. Tests if it is an int or double.");
317 if (json_object_is_type(val, json_type_int)) {
318 x = json_object_get_int(val);
319 AFB_WARNING("We get an int: %d",x);
321 else if (json_object_is_type(val, json_type_double)) {
322 d = json_object_get_double(val);
324 AFB_WARNING("We get a double: %f => %d",d,x);
327 afb_req_fail_f(request, "bad-request",
328 "argument '%s' isn't integer or double", hvac_values[i].name);
331 if (x < 0 || x > 255)
333 afb_req_fail_f(request, "bad-request",
334 "argument '%s' is out of bounds", hvac_values[i].name);
337 if (values[i] != x) {
338 values[i] = (uint8_t)x;
340 AFB_WARNING("%s changed to %d", hvac_values[i].name,x);
344 AFB_WARNING("%s not found in query!",hvac_values[i].name);
349 hvac_values[i].value = values[i]; // update structure at line 102
350 AFB_WARNING("WRITE_LED: value: %d", hvac_values[i].value);
351 rc = temp_write_led();
353 afb_req_success(request, NULL, NULL);
354 else if (retry(temp_write_led)) {
355 /* restore initial values */
356 hvac_values[i].value = saves[i];
357 afb_req_fail(request, "error", "I2C error");
363 * @brief Get temperature of right toggle in HVAC system
365 * @param struct afb_req : an afb request structure
368 static void temp_right_zone_led(struct afb_req request)
370 int i = 6, rc, x, changed;
372 struct json_object *query, *val;
373 uint8_t values[sizeof hvac_values / sizeof *hvac_values];
374 uint8_t saves[sizeof hvac_values / sizeof *hvac_values];
376 AFB_WARNING("In temp_right_zone_led.");
378 query = afb_req_json(request);
380 /* records initial values */
381 AFB_WARNING("Records initial values");
382 values[i] = saves[i] = hvac_values[i].value;
385 if (json_object_object_get_ex(query, hvac_values[i].name, &val))
387 AFB_WARNING("Value of values[i] = %d", values[i]);
388 AFB_WARNING("We got it. Tests if it is an int or double.");
389 if (json_object_is_type(val, json_type_int)) {
390 x = json_object_get_int(val);
391 AFB_WARNING("We get an int: %d",x);
393 else if (json_object_is_type(val, json_type_double)) {
394 d = json_object_get_double(val);
396 AFB_WARNING("We get a double: %f => %d",d,x);
399 afb_req_fail_f(request, "bad-request",
400 "argument '%s' isn't integer or double", hvac_values[i].name);
403 if (x < 0 || x > 255)
405 afb_req_fail_f(request, "bad-request",
406 "argument '%s' is out of bounds", hvac_values[i].name);
409 if (values[i] != x) {
410 values[i] = (uint8_t)x;
412 AFB_WARNING("%s changed to %d", hvac_values[i].name,x);
416 AFB_WARNING("%s not found in query!", hvac_values[i].name);
421 hvac_values[i].value = values[i]; // update structure at line 102
422 AFB_WARNING("WRITE_LED: value: %d", hvac_values[i].value);
423 rc = temp_write_led();
425 afb_req_success(request, NULL, NULL);
426 else if (retry(temp_write_led)) {
427 /* restore initial values */
428 hvac_values[i].value = saves[i];
429 afb_req_fail(request, "error", "I2C error");
434 static int write_can()
436 struct can_frame txCanFrame;
439 rc = can_handler.socket;
442 // Hardcoded can_id and dlc (data lenght code)
443 txCanFrame.can_id = 0x30;
444 txCanFrame.can_dlc = 8;
445 txCanFrame.data[0] = to_can_temp(read_temp_left_zone());
446 txCanFrame.data[1] = to_can_temp(read_temp_right_zone());
447 txCanFrame.data[2] = to_can_temp(read_temp());
448 txCanFrame.data[3] = 0xf0;
449 txCanFrame.data[4] = read_fanspeed();
450 txCanFrame.data[5] = 1;
451 txCanFrame.data[6] = 0;
452 txCanFrame.data[7] = 0;
454 AFB_DEBUG("%s: %d %d [%02x %02x %02x %02x %02x %02x %02x %02x]\n",
455 can_handler.send_msg,
456 txCanFrame.can_id, txCanFrame.can_dlc,
457 txCanFrame.data[0], txCanFrame.data[1], txCanFrame.data[2], txCanFrame.data[3],
458 txCanFrame.data[4], txCanFrame.data[5], txCanFrame.data[6], txCanFrame.data[7]);
460 if(!can_handler.simulation)
462 rc = (int)sendto(can_handler.socket, &txCanFrame, sizeof(struct can_frame), 0,
463 (struct sockaddr*)&can_handler.txAddress, sizeof(can_handler.txAddress));
466 AFB_ERROR("Sending CAN frame failed.");
472 AFB_ERROR("socket not initialized. Attempt to reopen can device socket.");
478 /*****************************************************************************************/
479 /*****************************************************************************************/
482 /** SECTION: BINDING VERBS IMPLEMENTATION **/
485 /*****************************************************************************************/
486 /*****************************************************************************************/
489 * @brief Get fan speed HVAC system
491 * @param struct afb_req : an afb request structure
494 static void get_fanspeed(struct afb_req request)
496 json_object *ret_json;
497 uint8_t fanspeed = read_fanspeed();
499 ret_json = json_object_new_object();
500 json_object_object_add(ret_json, "FanSpeed", json_object_new_int(fanspeed));
502 afb_req_success(request, ret_json, NULL);
506 * @brief Read Consign right zone temperature for HVAC system
508 * @param struct afb_req : an afb request structure
511 static void get_temp_right_zone(struct afb_req request)
513 json_object *ret_json;
514 uint8_t temp = read_temp_right_zone();
516 ret_json = json_object_new_object();
517 json_object_object_add(ret_json, "RightTemperature", json_object_new_int(temp));
519 afb_req_success(request, ret_json, NULL);
523 * @brief Read Consign left zone temperature for HVAC system
525 * @param struct afb_req : an afb request structure
528 static void get_temp_left_zone(struct afb_req request)
530 json_object *ret_json;
531 uint8_t temp = read_temp_left_zone();
533 ret_json = json_object_new_object();
534 json_object_object_add(ret_json, "LeftTemperature", json_object_new_int(temp));
536 afb_req_success(request, ret_json, NULL);
540 * @brief Read all values
542 * @param struct afb_req : an afb request structure
545 static void get(struct afb_req request)
547 AFB_DEBUG("Getting all values");
548 json_object *ret_json;
550 ret_json = json_object_new_object();
551 json_object_object_add(ret_json, "LeftTemperature", json_object_new_int(read_temp_left_zone()));
552 json_object_object_add(ret_json, "RightTemperature", json_object_new_int(read_temp_right_zone()));
553 json_object_object_add(ret_json, "FanSpeed", json_object_new_int(read_fanspeed()));
555 afb_req_success(request, ret_json, NULL);
559 * @brief Set a component value using a json object retrieved from request
561 * @param struct afb_req : an afb request structure
564 static void set(struct afb_req request)
566 int i, rc, x, changed;
568 struct json_object *query, *val;
569 uint8_t values[sizeof hvac_values / sizeof *hvac_values];
570 uint8_t saves[sizeof hvac_values / sizeof *hvac_values];
572 /* records initial values */
573 AFB_DEBUG("Records initial values");
574 i = (int)(sizeof hvac_values / sizeof *hvac_values);
577 values[i] = saves[i] = hvac_values[i].value;
580 /* Loop getting arguments */
581 query = afb_req_json(request);
583 i = (int)(sizeof hvac_values / sizeof *hvac_values);
584 AFB_DEBUG("Looping for args. i: %d", i);
588 AFB_DEBUG("Searching... query: %s, i: %d, comp: %s", json_object_to_json_string(query), i, hvac_values[i].name);
589 if (json_object_object_get_ex(query, hvac_values[i].name, &val))
591 AFB_DEBUG("We got it. Tests if it is an int or double.");
592 if (json_object_is_type(val, json_type_int)) {
593 x = json_object_get_int(val);
594 AFB_DEBUG("We get an int: %d",x);
596 else if (json_object_is_type(val, json_type_double)) {
597 d = json_object_get_double(val);
599 AFB_DEBUG("We get a double: %f => %d",d,x);
602 afb_req_fail_f(request, "bad-request",
603 "argument '%s' isn't integer or double", hvac_values[i].name);
606 if (x < 0 || x > 255)
608 afb_req_fail_f(request, "bad-request",
609 "argument '%s' is out of bounds", hvac_values[i].name);
612 if (values[i] != x) {
613 values[i] = (uint8_t)x;
615 AFB_DEBUG("%s changed to %d",hvac_values[i].name,x);
619 AFB_DEBUG("%s not found in query!",hvac_values[i].name);
623 /* attemps to set new values */
624 AFB_DEBUG("Diff: %d", changed);
627 i = (int)(sizeof hvac_values / sizeof *hvac_values);
630 hvac_values[i].value = values[i];
634 afb_req_success(request, NULL, NULL);
635 else if (retry(write_can)) {
636 /* restore initial values */
637 i = (int)(sizeof hvac_values / sizeof *hvac_values);
640 hvac_values[i].value = saves[i];
642 afb_req_fail(request, "error", "CAN error");
646 afb_req_success(request, NULL, "No changes");
650 int bindingServicePreInit(struct afb_service service)
652 return open_can_dev();
655 int bindingServiceInit(struct afb_service service)
657 event = afb_daemon_make_event("language");
658 if(afb_daemon_require_api("identity", 1))
660 return afb_service_call_sync("identity", "subscribe", NULL, NULL);
663 void onEvent(const char *event_name, struct json_object *object)
665 json_object *args, *language = json_object_new_object();
666 json_object *id_evt_name, *current_identity;
668 AFB_NOTICE("Event '%s' received: %s", event_name,
669 json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
671 if (json_object_object_get_ex(object, "eventName", &id_evt_name) &&
672 !strcmp(json_object_get_string(id_evt_name), "login") &&
673 !afb_service_call_sync("identity", "get", NULL, ¤t_identity)) {
674 json_object *response;
675 if (! json_object_object_get_ex(current_identity, "response", &response) || ! json_object_object_get_ex(response, "graphPreferredLanguage", &language)) {
676 language = json_object_new_string("en_US");
678 afb_event_broadcast(event, language);
682 // TODO: Have to change session management flag to AFB_SESSION_CHECK to use token auth
683 static const struct afb_verb_v2 _afb_verbs_v2_hvac[]= {
685 .verb = "get_temp_left_zone",
686 .callback = get_temp_left_zone,
688 .info = "Get the left zone temperature",
689 .session = AFB_SESSION_NONE_V2
692 .verb = "get_temp_right_zone",
693 .callback = get_temp_right_zone,
695 .info = "Get the right zone temperature",
696 .session = AFB_SESSION_NONE_V2
699 .verb = "get_fanspeed",
700 .callback = get_fanspeed,
702 .info = "Read fan speed",
703 .session = AFB_SESSION_NONE_V2
709 .info = "Read all speed",
710 .session = AFB_SESSION_NONE_V2
716 .info = "Set a HVAC component value",
717 .session = AFB_SESSION_NONE_V2
720 .verb = "temp_left_zone_led",
721 .callback = temp_left_zone_led,
723 .info = "Turn on LED on left temperature zone",
724 .session = AFB_SESSION_NONE_V2
727 .verb = "temp_right_zone_led",
728 .callback = temp_right_zone_led,
730 .info = "Turn on LED on left temperature zone",
731 .session = AFB_SESSION_NONE_V2
743 const struct afb_binding_v2 afbBindingV2 = {
745 .specification = NULL,
746 .info = "HVAC service",
747 .verbs = _afb_verbs_v2_hvac,
748 .preinit = bindingServicePreInit,
749 .init = bindingServiceInit,