2 * Copyright (c) 2018 TOYOTA MOTOR CORPORATION
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
23 #include <json-c/json.h>
24 #include "policy_manager.hpp"
29 #define AFB_BINDING_VERSION 2
30 #include <afb/afb-binding.h>
31 #include <systemd/sd-event.h>
37 static const char kPathRolesConfigFile[] = "/etc/roles.json";
38 static const char kPathLayoutsConfigFile[] = "/etc/layouts.json";
40 static const int kInvisibleRoleHistoryNum = 5;
42 static PolicyManager *g_context;
44 static int transitionStateWrapper(sd_event_source *source, void *data)
46 int ret = g_context->transitionState(source, data);
50 static int timerEventWrapper(sd_event_source *source, uint64_t usec, void *data)
52 int ret = g_context->timerEvent(source, usec, data);
58 PolicyManager::PolicyManager()
66 this->p_crr_state = new (StmState);
67 this->p_prv_state = new (StmState);
70 PolicyManager::~PolicyManager()
72 delete this->p_crr_state;
73 delete this->p_prv_state;
76 int PolicyManager::initialize(std::string ecu_name)
81 this->ecu_name = ecu_name;
84 for (int i = StmEvtNoMin; i <= StmEvtNoMax; i++)
86 HMI_DEBUG("event name:%s no:%d", kStmEventName[i], i);
87 this->eventname2no[kStmEventName[i]] = i;
90 for (int i = StmCtgNoMin; i <= StmCtgNoMax; i++)
92 HMI_DEBUG("category name:%s no:%d", kStmCategoryName[i], i);
93 this->categoryname2no[kStmCategoryName[i]] = i;
96 for (int i = StmAreaNoMin; i <= StmAreaNoMax; i++)
98 HMI_DEBUG("area name:%s no:%d", kStmAreaName[i], i);
99 this->areaname2no[kStmAreaName[i]] = i;
103 ret = this->loadRolesConfigFile();
106 HMI_ERROR("Load roles config file Error!!");
110 // Load layouts config
111 ret = this->loadLayoutsConfigFile();
114 HMI_ERROR("Load layouts config file Error!!");
118 // Initialize state which is managed by PolicyManager
119 this->initializeState();
121 // Initialize StateTransitioner
122 stmInitialize(ecu_name.c_str());
125 pm::g_context = this;
130 void PolicyManager::registerCallback(CallbackTable callback)
132 this->callback.onStateTransitioned = callback.onStateTransitioned;
133 this->callback.onError = callback.onError;
136 int PolicyManager::setInputEventData(json_object *json_in)
139 if (nullptr == json_in)
141 HMI_ERROR("Argument is NULL!!");
145 // Get event from json_object
146 const char *event = this->getStringFromJson(json_in, "event");
147 int event_no = StmEvtNoNone;
148 if (nullptr != event)
150 // Convert name to number
151 auto itr = this->eventname2no.find(event);
152 if (this->eventname2no.end() != itr)
154 event_no = this->eventname2no[event];
155 HMI_DEBUG("event(%s:%d)", event, event_no);
159 HMI_ERROR("Invalid event name!!");
165 HMI_ERROR("Event is not set!!");
169 // Get role from json_object
170 const char *role = this->getStringFromJson(json_in, "role");
171 std::string category = "";
172 int category_no = StmCtgNoNone;
175 HMI_DEBUG("role(%s)", role);
177 // Convert role to category
178 auto itr = this->role2category.find(role);
179 if (this->role2category.end() != itr)
181 category = this->role2category[role];
185 itr = this->role2category.find("fallback");
186 if (this->role2category.end() != itr)
188 HMI_DEBUG("Role:%s is not registered in roles config file, fallback as normal app", role);
189 category = this->role2category["fallback"];
195 // Convert name to number
196 category_no = categoryname2no[category];
197 HMI_DEBUG("category(%s:%d)", category.c_str(), category_no);
200 if (StmCtgNoNone == category_no)
205 // Get area from json_object
206 const char *area = this->getStringFromJson(json_in, "area");
207 int area_no = StmAreaNoNone;
208 if ((nullptr != area) && (StmCtgNoNone != category_no))
210 for (const auto &x : this->category2areas[category])
212 if (x == std::string(area))
214 area_no = this->areaname2no[area];
218 if (StmAreaNoNone == area_no)
220 area = this->category2areas[category].front().c_str();
221 area_no = this->areaname2no[area];
223 HMI_DEBUG("area(%s:%d)", area, area_no);
226 // Set event info to the queue
227 EventInfo event_info;
228 int event_id = STM_CREATE_EVENT_ID(event_no, category_no, area_no);
229 event_info.event = event_id;
230 event_info.role = std::string(role);
231 event_info.delay = 0;
232 this->event_info_queue.push(event_info);
237 int PolicyManager::executeStateTransition()
240 EventInfo event_info;
242 // Get event info from queue and delete
243 event_info = this->event_info_queue.front();
244 this->event_info_queue.pop();
246 // Set event info to check policy
247 ret = this->setStateTransitionProcessToSystemd(event_info.event,
253 void PolicyManager::undoState()
255 HMI_DEBUG("Undo State !!!");
260 HMI_DEBUG(">>>>>>>>>> BEFORE UNDO");
261 this->dumpLayerState(this->crr_layers);
263 this->crr_layers = this->prv_layers;
264 this->crr_invisible_role_history = this->prv_invisible_role_history;
266 HMI_DEBUG(">>>>>>>>>> AFTER UNDO");
267 this->dumpLayerState(this->crr_layers);
270 void PolicyManager::initializeState()
272 this->initializeModeState();
273 this->initializeLayerState();
276 void PolicyManager::initializeModeState()
279 init_car_ele.state = "none";
280 init_car_ele.changed = false;
282 for (int i = StmCarElementNoMin; i <= StmCarElementNoMax; i++)
284 const char *car_ele_name = kStmCarElementName[i];
285 this->crr_car_elements[car_ele_name] = init_car_ele;
288 this->prv_car_elements = this->crr_car_elements;
291 void PolicyManager::initializeLayerState()
294 LayoutState init_layout;
295 init_area.name = kStmAreaName[StmAreaNoNone];
296 init_area.category = kStmCategoryName[StmCtgNoNone];
298 init_layout.name = kStmLayoutName[StmLayoutNoNone];
299 init_layout.area_list.push_back(init_area);
301 for (int i = StmLayerNoMin; i <= StmLayerNoMax; i++)
303 const char *layer_name = kStmLayerName[i];
304 this->crr_layers[layer_name].name = layer_name;
305 this->crr_layers[layer_name].layout_state = init_layout;
306 this->crr_layers[layer_name].changed = false;
309 this->prv_layers = this->crr_layers;
312 void PolicyManager::addStateToJson(const char *name, bool changed,
313 std::string state, json_object **json_out)
315 if ((nullptr == name) || (nullptr == json_out))
317 HMI_ERROR("Invalid argument!!!");
321 json_object_object_add(*json_out, "name", json_object_new_string(name));
322 json_object_object_add(*json_out, "state", json_object_new_string(state.c_str()));
323 json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
326 void PolicyManager::addStateToJson(const char *layer_name, bool changed,
327 AreaList area_list, json_object **json_out)
329 if ((nullptr == layer_name) || (nullptr == json_out))
331 HMI_ERROR("Invalid argument!!!");
335 json_object *json_areas = json_object_new_array();
336 json_object *json_tmp;
337 for (const auto &as : area_list)
339 json_tmp = json_object_new_object();
340 json_object_object_add(json_tmp, "name", json_object_new_string(as.name.c_str()));
341 json_object_object_add(json_tmp, "role", json_object_new_string(as.role.c_str()));
342 json_object_array_add(json_areas, json_tmp);
345 json_object_object_add(*json_out, "name", json_object_new_string(layer_name));
346 json_object_object_add(*json_out, "changed", json_object_new_boolean(changed));
347 json_object_object_add(*json_out, "areas", json_areas);
350 void PolicyManager::updateState(int event_id)
352 this->updateModeState();
353 this->updateLayer(event_id);
356 void PolicyManager::updateModeState()
359 std::string car_state;
362 // Store previous layers
363 this->prv_car_elements = this->crr_car_elements;
365 // Update car elements
366 HMI_DEBUG(">>> CAR ELEMENTS");
367 for (int car_ele_no = StmCarElementNoMin;
368 car_ele_no <= StmCarElementNoMax; car_ele_no++)
370 const char *car_ele_name = kStmCarElementName[car_ele_no];
372 car_state_no = this->p_crr_state->car_element[car_ele_no].state;
373 car_state = kStmCarElementStateNameList[car_ele_no][car_state_no];
374 changed = (this->p_crr_state->car_element[car_ele_no].changed) ? true : false;
376 this->crr_car_elements[car_ele_name].state = car_state;
377 this->crr_car_elements[car_ele_name].changed = changed;
379 HMI_DEBUG(">>> >>> NAME: %s", car_ele_name);
380 HMI_DEBUG(">>> >>> >>> STATE:%s", car_state.c_str());
381 HMI_DEBUG(">>> >>> >>> CHANGED:%s", (changed) ? "true" : "false");
385 void PolicyManager::updateLayer(int event_id)
387 for (int layer_no = StmLayerNoMin;
388 layer_no <= StmLayerNoMax; layer_no++)
390 HMI_DEBUG(">>> LAYER:%s CHANGED:%d LAYOUT:%s",
391 kStmLayerName[layer_no], this->p_crr_state->layer[layer_no].changed,
392 kStmLayoutName[this->p_crr_state->layer[layer_no].state]);
395 // Store previous layers
396 this->prv_layers = this->crr_layers;
398 // Store previous role history
399 this->prv_invisible_role_history = this->crr_invisible_role_history;
402 for (int layer_no = StmLayerNoMin;
403 layer_no <= StmLayerNoMax; layer_no++)
405 const char *layer_name = kStmLayerName[layer_no];
407 // If restriction mode is changed to mode2 on,
408 // store current state for state of restriction mode off
409 if (this->changedRestrictionModeTo2On() ||
410 this->changedAccelPedalOffToOn()) // Control by Accel
411 // this->changedLightstatusBrakeOnToOff()) // Control by Brake
413 HMI_DEBUG("Store current state for state of restriction mode off");
414 this->prv_layers_car_stop[layer_name] = this->crr_layers[layer_name];
417 // This layer is changed?
418 int changed = this->p_crr_state->layer[layer_no].changed;
421 HMI_DEBUG(">>>>>>>>>> Update layout of layer:%s", layer_name);
423 // Get current layout name of this layer
424 int crr_layout_state_no = this->p_crr_state->layer[layer_no].state;
425 std::string crr_layout_name = std::string(kStmLayoutName[crr_layout_state_no]);
427 LayoutState crr_layout_state;
428 changed = this->updateLayout(event_id, layer_no,
429 crr_layout_name, crr_layout_state);
431 // Update current layout of this layer
432 this->crr_layers[layer_name].layout_state = crr_layout_state;
436 int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
437 std::string req_ctg = kStmCategoryName[category_no];
438 std::string req_role = this->req_role_list[event_id];
439 for (const auto &ctg : this->layer2categories[layer_name])
443 // If layer is not changed and requested role is in this layer,
444 // push requested role to history stack
445 // because the application which has this role have been started
446 HMI_DEBUG("Add requested role to history "
447 "because the application which has this role have been started");
448 this->pushInvisibleRoleHistory(req_ctg, req_role);
453 // Update changed flag
454 this->crr_layers[layer_name].changed = (changed) ? true : false;
457 // Erase role for the event_id from list
458 this->req_role_list.erase(event_id);
460 HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (BEFORE)");
461 this->dumpLayerState(this->prv_layers);
463 HMI_DEBUG(">>>>>>>>>> DUMP LAYERS (AFTER)");
464 this->dumpLayerState(this->crr_layers);
466 this->dumpInvisibleRoleHistory();
469 int PolicyManager::updateLayout(int event_id, int layer_no,
470 std::string crr_layout_name, LayoutState &crr_layout_state)
474 int event_no = STM_GET_EVENT_FROM_ID(event_id);
475 int category_no = STM_GET_CATEGORY_FROM_ID(event_id);
476 int area_no = STM_GET_AREA_FROM_ID(event_id);
478 std::string req_evt = kStmEventName[event_no];
479 std::string req_ctg = kStmCategoryName[category_no];
480 std::string req_area = kStmAreaName[area_no];
481 std::string req_role = this->req_role_list[event_id];
483 const char *layer_name = kStmLayerName[layer_no];
485 // Get previous layout name of this layer
486 LayoutState prv_layout_state = this->prv_layers[layer_name].layout_state;
487 std::string prv_layout_name = prv_layout_state.name;
489 if (this->changedRestrictionMode2OnToOther() ||
490 this->changedAccelPedalOnToOff()) // Control by Accel
491 // this->changedLightstatusBrakeOffToOn()) // Control by Brake
493 // If restriction mode is changed from mode2 -> mode1,
494 // restore state of restriction mode off
495 HMI_DEBUG("Restriction mode is changed from mode2 -> mode1, so restore state of restriction mode off");
496 crr_layout_state = this->prv_layers_car_stop[layer_name].layout_state;
497 crr_layout_name = crr_layout_state.name;
498 if ((prv_layout_name == crr_layout_name) &&
499 (kStmAreaName[StmAreaNoNone] == crr_layout_name))
505 // If the roles which is exist in previous layout is not in current,
506 // push to role history
507 for (const auto &prv_as : prv_layout_state.area_list)
509 for (const auto &crr_as : crr_layout_state.area_list)
511 if (prv_as.role == crr_as.role)
515 this->pushInvisibleRoleHistory(prv_as.category, prv_as.role);
519 else if ((prv_layout_name == crr_layout_name) &&
520 (kStmLayoutName[StmLayoutNoNone] == crr_layout_name))
522 // If previous and current layout are none
523 // Copy previous layout state for current
524 crr_layout_state = prv_layout_state;
529 crr_layout_state = prv_layout_state;
532 HMI_DEBUG("-- layout name previous:%s current:%s",
533 prv_layout_name.c_str(), crr_layout_name.c_str());
534 if (prv_layout_name == crr_layout_name)
536 HMI_DEBUG("---- Previous layout is same with current");
540 // If previous layout is NOT same with current,
541 // current areas is set with default value
542 HMI_DEBUG("---- Previous layout is NOT same with current");
543 crr_layout_state.name = this->default_layouts[crr_layout_name].name;
544 crr_layout_state.category_num = this->default_layouts[crr_layout_name].category_num;
545 crr_layout_state.area_list = this->default_layouts[crr_layout_name].area_list;
548 // Create candidate list
549 std::map<std::string, AreaList> cand_list;
550 // for (int ctg_no = StmCtgNoMin;
551 // ctg_no <= StmCtgNoMax; ctg_no++)
553 for (const auto &ctg : this->layer2categories[layer_name])
555 // if (ctg_no == StmCtgNoNone)
560 // const char *ctg = kStmCategoryName[ctg_no];
561 HMI_DEBUG("-- Create candidate list for ctg:%s", ctg.c_str());
563 AreaList tmp_cand_list;
564 int candidate_num = 0;
565 int blank_num = crr_layout_state.category_num[ctg];
567 // If requested event is "activate"
568 // and there are requested category and area,
569 // update area with requested role in current layout.
570 bool request_for_this_layer = false;
571 std::string used_role = "";
572 if ((ctg == req_ctg) && ("activate" == req_evt))
574 HMI_DEBUG("---- Requested event is activate");
575 for (AreaState &as : crr_layout_state.area_list)
577 if (as.category == req_ctg)
579 request_for_this_layer = true;
581 if (as.name == req_area)
584 used_role = req_role;
586 HMI_DEBUG("------ Update current layout: area:%s category:%s role:%s",
587 as.name.c_str(), as.category.c_str(), as.role.c_str());
594 // Create candidate list for category from the previous displayed categories
595 for (AreaState area_state : prv_layout_state.area_list)
597 if ((ctg == area_state.category) &&
598 (used_role != area_state.role))
600 // If there is the category
601 // which is same with new category and not used for updating yet,
603 HMI_DEBUG("---- Push previous(category:%s role:%s) to candidate list",
604 area_state.category.c_str(), area_state.role.c_str());
605 tmp_cand_list.push_back(area_state);
610 // If NOT updated by requested area:
611 // there is not requested area in new layout,
612 // so push requested role to candidate list
613 if (request_for_this_layer && ("" == used_role))
615 HMI_DEBUG("---- Push request(area:%s category:%s role:%s) to candidate list",
616 req_area.c_str(), req_ctg.c_str(), req_role.c_str());
617 AreaState area_state;
618 area_state.name = req_area;
619 area_state.category = req_ctg;
620 area_state.role = req_role;
621 tmp_cand_list.push_back(area_state);
625 HMI_DEBUG("---- blank_num:%d candidate_num:%d", blank_num, candidate_num);
627 // Compare number of candidate/blank,
628 // And remove role in order of the oldest as necessary
629 if (candidate_num < blank_num)
631 // Refer history stack
632 // and add to the top of tmp_cand_list in order to the newest
633 while (candidate_num != blank_num)
635 AreaState area_state;
636 area_state.name = kStmAreaName[StmAreaNoNone];
637 area_state.category = ctg;
638 area_state.role = this->popInvisibleRoleHistory(ctg);
639 if ("" == area_state.role)
641 HMI_ERROR("There is no role in history stack!!");
643 tmp_cand_list.push_back(area_state);
644 HMI_DEBUG("------ Add role:%s to candidate list",
645 area_state.role.c_str());
649 else if (candidate_num > blank_num)
651 // Remove the oldest role from candidate list
652 while (candidate_num != blank_num)
654 std::string removed_role = tmp_cand_list.begin()->role;
655 HMI_DEBUG("------ Remove the oldest role:%s from candidate list",
656 removed_role.c_str());
657 tmp_cand_list.erase(tmp_cand_list.begin());
660 // Push removed data to history stack
661 this->pushInvisibleRoleHistory(ctg, removed_role);
663 // Remove from current layout
664 for (AreaState &as : crr_layout_state.area_list)
666 if (as.role == removed_role)
674 { // (candidate_num == blank_num)
678 cand_list[ctg] = tmp_cand_list;
682 HMI_DEBUG("-- Update areas by using candidate list");
683 for (AreaState &as : crr_layout_state.area_list)
685 HMI_DEBUG("---- Check area:%s category:%s role:%s",
686 as.name.c_str(), as.category.c_str(), as.role.c_str());
689 HMI_DEBUG("------ Update this area with role:%s",
690 cand_list[as.category].begin()->role.c_str());
691 as.role = cand_list[as.category].begin()->role;
692 cand_list[as.category].erase(cand_list[as.category].begin());
699 void PolicyManager::createOutputInformation(json_object **json_out)
701 json_object *json_tmp;
703 // Create car element information
707 // "parking_brake": {
708 // "changed": <bool>,
709 // "state": <const char*>
713 json_object *json_car_ele = json_object_new_array();
714 const char *car_ele_name;
715 for (int car_ele_no = StmCarElementNoMin;
716 car_ele_no <= StmCarElementNoMax; car_ele_no++)
718 car_ele_name = kStmCarElementName[car_ele_no];
719 json_tmp = json_object_new_object();
720 this->addStateToJson(car_ele_name,
721 this->crr_car_elements[car_ele_name].changed,
722 this->crr_car_elements[car_ele_name].state,
724 json_object_array_add(json_car_ele, json_tmp);
726 json_object_object_add(*json_out, "car_elements", json_car_ele);
728 // Create layout information
733 // "changed": <bool>,
736 // "name":<const char*>,
737 // "role":<const char*>
744 json_object *json_layer = json_object_new_array();
745 const char *layer_name;
746 for (int layer_no = StmLayerNoMin;
747 layer_no <= StmLayerNoMax; layer_no++)
749 layer_name = kStmLayerName[layer_no];
750 json_tmp = json_object_new_object();
751 this->addStateToJson(layer_name,
752 this->crr_layers[layer_name].changed,
753 this->crr_layers[layer_name].layout_state.area_list,
755 json_object_array_add(json_layer, json_tmp);
757 json_object_object_add(*json_out, "layers", json_layer);
760 void PolicyManager::controlTimerEvent()
762 // for ALS2018 (RestrictionMode = Running and after 3sec)
763 // if (this->p_crr_state->car_element[StmCarElementNoRunning].changed)
765 // if (StmRunningNoRun == this->p_crr_state->car_element[StmCarElementNoRunning].state)
767 // // Set delay event(restriction mode on)
768 // this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOn,
771 // else if (StmRunningNoStop ==
772 // this->p_crr_state->car_element[StmCarElementNoRunning].state)
774 // // Stop timer for restriction on event
775 // if (this->event_source_list.find(StmEvtNoRestrictionModeOn) !=
776 // this->event_source_list.end())
778 // HMI_DEBUG("Stop timer for restriction on");
779 // sd_event_source *event_source = this->event_source_list[StmEvtNoRestrictionModeOn];
780 // int ret = sd_event_source_set_enabled(event_source, SD_EVENT_OFF);
783 // HMI_ERROR("Failed to stop timer");
787 // // Set event(restriction mode off)
788 // this->setStateTransitionProcessToSystemd(StmEvtNoRestrictionModeOff, 0, "");
793 int PolicyManager::transitionState(sd_event_source *source, void *data)
795 HMI_DEBUG(">>>>>>>>>> START STATE TRANSITION");
797 int event_id = *((int *)data);
799 int event_no, category_no, area_no;
800 event_no = STM_GET_EVENT_FROM_ID(event_id);
801 category_no = STM_GET_CATEGORY_FROM_ID(event_id);
802 area_no = STM_GET_AREA_FROM_ID(event_id);
803 HMI_DEBUG(">>>>>>>>>> EVENT:%s CATEGORY:%s AREA:%s",
804 kStmEventName[event_no],
805 kStmCategoryName[category_no],
806 kStmAreaName[area_no]);
808 // Store current state
809 *(this->p_prv_state) = *(this->p_crr_state);
812 int ret = stmTransitionState(event_id, this->p_crr_state);
815 HMI_ERROR("Failed transition state");
816 if (nullptr != this->callback.onError)
818 json_object *json_out = json_object_new_object();
819 json_object_object_add(json_out, "message",
820 json_object_new_string("Failed to transition state"));
821 json_object_object_add(json_out, "event",
822 json_object_new_string(kStmEventName[event_no]));
823 json_object_object_add(json_out, "role",
824 json_object_new_string(this->req_role_list[event_id].c_str()));
825 json_object_object_add(json_out, "area",
826 json_object_new_string(kStmAreaName[area_no]));
827 this->callback.onError(json_out);
828 json_object_put(json_out);
833 // Update state which is managed by PolicyManager
834 this->updateState(event_id);
836 // Create output information for ResourceManager
837 json_object *json_out = json_object_new_object();
838 this->createOutputInformation(&json_out);
840 // Notify changed state
841 if (nullptr != this->callback.onStateTransitioned)
843 this->callback.onStateTransitioned(json_out);
846 // Start/Stop timer events
847 this->controlTimerEvent();
849 // Release json_object
850 json_object_put(json_out);
855 // Destroy sd_event_source object
856 sd_event_source_unref(source);
858 // Remove event source from list
859 if (this->event_source_list.find(event_id) != this->event_source_list.end())
861 this->event_source_list.erase(event_id);
864 HMI_DEBUG(">>>>>>>>>> FINISH STATE TRANSITION");
868 int PolicyManager::timerEvent(sd_event_source *source, uint64_t usec, void *data)
872 int ret = this->transitionState(source, data);
876 int PolicyManager::setStateTransitionProcessToSystemd(int event_id, uint64_t delay_ms, std::string role)
878 struct sd_event_source *event_source;
879 HMI_DEBUG("event_id:0x%x delay:%d role:%s", event_id, delay_ms, role.c_str());
883 int ret = sd_event_add_defer(afb_daemon_get_event_loop(), &event_source,
884 &pm::transitionStateWrapper, new int(event_id));
887 HMI_ERROR("Faild to sd_event_add_defer: errno:%d", ret);
894 struct timespec time_spec;
895 clock_gettime(CLOCK_BOOTTIME, &time_spec);
897 // Calculate timer fired time
898 uint64_t usec = (time_spec.tv_sec * 1000000) + (time_spec.tv_nsec / 1000) + (delay_ms * 1000);
901 int ret = sd_event_add_time(afb_daemon_get_event_loop(), &event_source,
902 CLOCK_BOOTTIME, usec, 1,
903 &pm::timerEventWrapper, new int(event_id));
906 HMI_ERROR("Faild to sd_event_add_time: errno:%d", ret);
910 // Store event source
911 this->event_source_list[event_id] = event_source;
912 // Store requested role
913 this->req_role_list[event_id] = role;
917 bool PolicyManager::changedRestrictionModeTo2On()
919 // TODO: If possible thie process should be include in zipc stm in the future
920 if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
921 (StmRestrictionModeSttNoOn != this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
922 (StmRestrictionModeSttNoOn == this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
929 bool PolicyManager::changedRestrictionMode2OnToOther()
931 // TODO: If possible thie process should be include in zipc stm in the future
932 if (this->p_crr_state->car_element[StmCarElementNoRestrictionMode].changed &&
933 (StmRestrictionModeSttNoOn == this->p_prv_state->car_element[StmCarElementNoRestrictionMode].state) &&
934 (StmRestrictionModeSttNoOn != this->p_crr_state->car_element[StmCarElementNoRestrictionMode].state))
941 // bool PolicyManager::changedLightstatusBrakeOffToOn()
943 // // TODO: For master
944 // // If possible thie process should be include in zipc stm in the future
945 // if (("master" == this->ecu_name) &&
946 // this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
947 // (StmLightstatusBrakeSttNoOff == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
948 // (StmLightstatusBrakeSttNoOn == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
955 // bool PolicyManager::changedLightstatusBrakeOnToOff()
957 // // TODO: For master
958 // // If possible thie process should be include in zipc stm in the future
959 // if (("master" == this->ecu_name) &&
960 // this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].changed &&
961 // (StmLightstatusBrakeSttNoOn == this->p_prv_state->car_element[StmCarElementNoLightstatusBrake].state) &&
962 // (StmLightstatusBrakeSttNoOff == this->p_crr_state->car_element[StmCarElementNoLightstatusBrake].state))
969 bool PolicyManager::changedAccelPedalOffToOn()
972 // If possible thie process should be include in zipc stm in the future
973 if (("master" == this->ecu_name) &&
974 this->p_crr_state->car_element[StmCarElementNoAccelPedal].changed &&
975 (StmAccelPedalSttNoOff == this->p_prv_state->car_element[StmCarElementNoAccelPedal].state) &&
976 (StmAccelPedalSttNoOn == this->p_crr_state->car_element[StmCarElementNoAccelPedal].state))
983 bool PolicyManager::changedAccelPedalOnToOff()
986 // If possible thie process should be include in zipc stm in the future
987 if (("master" == this->ecu_name) &&
988 this->p_crr_state->car_element[StmCarElementNoAccelPedal].changed &&
989 (StmAccelPedalSttNoOn == this->p_prv_state->car_element[StmCarElementNoAccelPedal].state) &&
990 (StmAccelPedalSttNoOff == this->p_crr_state->car_element[StmCarElementNoAccelPedal].state))
997 int PolicyManager::loadRolesConfigFile()
999 std::string file_name;
1001 // Get afm application installed dir
1002 char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1003 HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1005 if (!afm_app_install_dir)
1007 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1011 file_name = std::string(afm_app_install_dir) + std::string(pm::kPathRolesConfigFile);
1014 // Load roles config file
1015 json_object *json_obj;
1016 int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
1019 HMI_ERROR("Could not open %s, so use default role information", pm::kPathRolesConfigFile);
1020 json_obj = json_tokener_parse(kDefaultRolesConfig);
1022 HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1025 json_object *json_cfg;
1026 if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
1028 HMI_ERROR("Parse Error!!");
1032 int num_ecu = json_object_array_length(json_cfg);
1033 HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);
1035 const char* c_ecu_name;
1036 json_object *json_ecu;
1037 for (int i = 0; i < num_ecu; i++)
1039 json_ecu= json_object_array_get_idx(json_cfg, i);
1041 c_ecu_name = this->getStringFromJson(json_ecu, "name");
1042 if (nullptr == c_ecu_name)
1044 HMI_ERROR("Parse Error!!");
1048 if (std::string(c_ecu_name) == this->ecu_name)
1060 HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
1065 json_object *json_roles;
1066 if (!json_object_object_get_ex(json_ecu, "roles", &json_roles))
1068 HMI_ERROR("Parse Error!!");
1072 int len = json_object_array_length(json_roles);
1073 HMI_DEBUG("json_cfg len:%d", len);
1074 HMI_DEBUG("json_cfg dump:%s", json_object_get_string(json_roles));
1076 json_object *json_tmp;
1077 const char *category;
1081 for (int i = 0; i < len; i++)
1083 json_tmp = json_object_array_get_idx(json_roles, i);
1085 category = this->getStringFromJson(json_tmp, "category");
1086 roles = this->getStringFromJson(json_tmp, "role");
1087 areas = this->getStringFromJson(json_tmp, "area");
1088 layer = this->getStringFromJson(json_tmp, "layer");
1090 if ((nullptr == category) || (nullptr == roles) ||
1091 (nullptr == areas) || (nullptr == layer))
1093 HMI_ERROR("Parse Error!!");
1097 // Parse roles by '|'
1098 std::vector<std::string> vct_roles;
1099 vct_roles = this->parseString(std::string(roles), '|');
1101 // Parse areas by '|'
1103 vct_areas = this->parseString(std::string(areas), '|');
1105 // Set role, category, areas
1106 for (auto itr = vct_roles.begin(); itr != vct_roles.end(); ++itr)
1108 this->role2category[*itr] = std::string(category);
1110 this->category2role[category] = std::string(roles);
1111 this->category2areas[category] = vct_areas;
1112 this->layer2categories[layer].push_back(category);
1114 // TODO: For run-by-default applications, set history in advance
1115 const char *auto_started_roles;
1116 auto_started_roles = this->getStringFromJson(json_tmp, "auto_started_roles");
1117 if (nullptr != auto_started_roles)
1119 std::vector<std::string> vct_auto_started_roles;
1120 vct_auto_started_roles =
1121 this->parseString(std::string(auto_started_roles), '|');
1123 for (auto itr = vct_auto_started_roles.end() - 1;
1124 itr >= vct_auto_started_roles.begin(); --itr)
1126 this->pushInvisibleRoleHistory(category, *itr);
1132 HMI_DEBUG("Check role2category");
1133 for (const auto &x : this->role2category)
1135 HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
1138 HMI_DEBUG("Check category2role");
1139 for (const auto &x : this->category2role)
1141 HMI_DEBUG("key:%s, val:%s", x.first.c_str(), x.second.c_str());
1144 HMI_DEBUG("Check category2areas");
1145 for (const auto &x : this->category2areas)
1147 for (const auto &y : x.second)
1149 HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
1153 HMI_DEBUG("Check layer2categories");
1154 for (const auto &x : this->layer2categories)
1156 for (const auto &y : x.second)
1158 HMI_DEBUG("key:%s, val:%s", x.first.c_str(), y.c_str());
1164 int PolicyManager::loadLayoutsConfigFile()
1168 // Get afm application installed dir
1169 char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
1170 HMI_DEBUG("afm_app_install_dir:%s", afm_app_install_dir);
1172 std::string file_name;
1173 if (!afm_app_install_dir)
1175 HMI_ERROR("AFM_APP_INSTALL_DIR is not defined");
1179 file_name = std::string(afm_app_install_dir) + std::string(pm::kPathLayoutsConfigFile);
1182 // Load states config file
1183 json_object *json_obj;
1184 int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
1187 HMI_DEBUG("Could not open %s, so use default layout information", pm::kPathLayoutsConfigFile);
1188 json_obj = json_tokener_parse(kDefaultLayoutsConfig);
1190 HMI_DEBUG("json_obj dump:%s", json_object_get_string(json_obj));
1193 json_object *json_cfg;
1194 if (!json_object_object_get_ex(json_obj, "ecus", &json_cfg))
1196 HMI_ERROR("Parse Error!!");
1200 int num_ecu = json_object_array_length(json_cfg);
1201 HMI_DEBUG("json_cfg(ecus) len:%d", num_ecu);
1203 const char* c_ecu_name;
1204 json_object *json_ecu;
1205 for (int i = 0; i < num_ecu; i++)
1207 json_ecu= json_object_array_get_idx(json_cfg, i);
1209 c_ecu_name = this->getStringFromJson(json_ecu, "name");
1210 if (nullptr == c_ecu_name)
1212 HMI_ERROR("Parse Error!!");
1216 if (std::string(c_ecu_name) == this->ecu_name)
1228 HMI_ERROR("Areas for ecu:%s is NOT exist!!", this->ecu_name.c_str());
1233 HMI_DEBUG("Perse layouts");
1234 json_object *json_layouts;
1235 if (!json_object_object_get_ex(json_ecu, "layouts", &json_layouts))
1237 HMI_ERROR("Parse Error!!");
1241 int len = json_object_array_length(json_layouts);
1242 HMI_DEBUG("json_layouts len:%d", len);
1243 HMI_DEBUG("json_layouts dump:%s", json_object_get_string(json_layouts));
1247 const char *category;
1248 for (int i = 0; i < len; i++)
1250 json_object *json_tmp = json_object_array_get_idx(json_layouts, i);
1252 layout = this->getStringFromJson(json_tmp, "name");
1253 if (nullptr == layout)
1255 HMI_ERROR("Parse Error!!");
1258 HMI_DEBUG("> layout:%s", layout);
1260 json_object *json_area_array;
1261 if (!json_object_object_get_ex(json_tmp, "areas", &json_area_array))
1263 HMI_ERROR("Parse Error!!");
1267 int len_area = json_object_array_length(json_area_array);
1268 HMI_DEBUG("json_area_array len:%d", len_area);
1269 HMI_DEBUG("json_area_array dump:%s", json_object_get_string(json_area_array));
1271 LayoutState layout_state;
1272 AreaState area_state;
1273 std::map<std::string, int> category_num;
1274 for (int ctg_no = StmCtgNoMin;
1275 ctg_no <= StmCtgNoMax; ctg_no++)
1277 const char *ctg_name = kStmCategoryName[ctg_no];
1278 category_num[ctg_name] = 0;
1281 for (int j = 0; j < len_area; j++)
1283 json_object *json_area = json_object_array_get_idx(json_area_array, j);
1286 const char *area = this->getStringFromJson(json_area, "name");
1287 if (nullptr == area)
1289 HMI_ERROR("Parse Error!!");
1292 area_state.name = std::string(area);
1293 HMI_DEBUG(">> area:%s", area);
1295 // Get app attribute of the area
1296 category = this->getStringFromJson(json_area, "category");
1297 if (nullptr == category)
1299 HMI_ERROR("Parse Error!!");
1302 area_state.category = std::string(category);
1303 category_num[category]++;
1304 HMI_DEBUG(">>> category:%s", category);
1306 role = this->getStringFromJson(json_area, "role");
1307 if (nullptr != role)
1309 // Role is NOT essential here
1310 area_state.role = std::string(role);
1314 area_state.role = std::string("");
1316 HMI_DEBUG(">>> role:%s", role);
1318 layout_state.area_list.push_back(area_state);
1321 layout_state.name = layout;
1322 layout_state.category_num = category_num;
1323 this->default_layouts[layout] = layout_state;
1326 // initialize for none layout
1327 LayoutState none_layout_state;
1328 memset(&none_layout_state, 0, sizeof(none_layout_state));
1329 none_layout_state.name = "none";
1330 this->default_layouts["none"] = none_layout_state;
1333 for (auto itr_layout = this->default_layouts.begin();
1334 itr_layout != this->default_layouts.end(); ++itr_layout)
1336 HMI_DEBUG(">>> layout:%s", itr_layout->first.c_str());
1338 for (auto itr_area = itr_layout->second.area_list.begin();
1339 itr_area != itr_layout->second.area_list.end(); ++itr_area)
1341 HMI_DEBUG(">>> >>> area :%s", itr_area->name.c_str());
1342 HMI_DEBUG(">>> >>> category:%s", itr_area->category.c_str());
1343 HMI_DEBUG(">>> >>> role :%s", itr_area->role.c_str());
1347 // Release json_object
1348 json_object_put(json_obj);
1353 void PolicyManager::pushInvisibleRoleHistory(std::string category, std::string role)
1355 auto i = std::remove_if(this->crr_invisible_role_history[category].begin(),
1356 this->crr_invisible_role_history[category].end(),
1357 [role](std::string x) { return (role == x); });
1359 if (this->crr_invisible_role_history[category].end() != i)
1361 this->crr_invisible_role_history[category].erase(i);
1364 this->crr_invisible_role_history[category].push_back(role);
1366 if (pm::kInvisibleRoleHistoryNum < crr_invisible_role_history[category].size())
1368 this->crr_invisible_role_history[category].erase(
1369 this->crr_invisible_role_history[category].begin());
1373 std::string PolicyManager::popInvisibleRoleHistory(std::string category)
1376 if (crr_invisible_role_history[category].empty())
1382 role = this->crr_invisible_role_history[category].back();
1383 this->crr_invisible_role_history[category].pop_back();
1388 const char *PolicyManager::getStringFromJson(json_object *obj, const char *key)
1391 if (!json_object_object_get_ex(obj, key, &tmp))
1393 HMI_DEBUG("Not found key \"%s\"", key);
1397 return json_object_get_string(tmp);
1400 int PolicyManager::inputJsonFilie(const char *file, json_object **obj)
1402 const int input_size = 128;
1405 HMI_DEBUG("Input file: %s", file);
1408 FILE *fp = fopen(file, "rb");
1411 HMI_ERROR("Could not open file");
1416 struct json_tokener *tokener = json_tokener_new();
1417 enum json_tokener_error json_error;
1418 char buffer[input_size];
1422 size_t len = fread(buffer, sizeof(char), input_size, fp);
1423 *obj = json_tokener_parse_ex(tokener, buffer, len);
1424 if (nullptr != *obj)
1426 HMI_DEBUG("File input is success");
1431 json_error = json_tokener_get_error(tokener);
1432 if ((json_tokener_continue != json_error) || (input_size > len))
1434 HMI_ERROR("Failed to parse file (byte:%d err:%s)",
1435 (input_size * block_cnt), json_tokener_error_desc(json_error));
1436 HMI_ERROR("\n%s", buffer);
1446 // Free json_tokener
1447 json_tokener_free(tokener);
1452 void PolicyManager::dumpLayerState(std::unordered_map<std::string, LayerState> &layers)
1454 HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
1455 HMI_DEBUG("|%-15s|%s|%-20s|%-20s|%-20s|%-20s|",
1456 "LAYER", "C", "LAYOUT", "AREA", "CATEGORY", "ROLE");
1457 for (const auto &itr : layers)
1459 LayerState ls = itr.second;
1460 const char* layer = ls.name.c_str();
1461 const char* changed = (ls.changed) ? "T" : "f";
1462 const char* layout = ls.layout_state.name.c_str();
1464 for (const auto &as : ls.layout_state.area_list)
1469 HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
1470 layer, changed, layout,
1471 as.name.c_str(), as.category.c_str(), as.role.c_str());
1474 HMI_DEBUG("|%-15s|%1s|%-20s|%-20s|%-20s|%-20s|",
1475 "", "", "", as.name.c_str(), as.category.c_str(), as.role.c_str());
1478 HMI_DEBUG("-------------------------------------------------------------------------------------------------------");
1481 void PolicyManager::dumpInvisibleRoleHistory()
1483 HMI_DEBUG(">>>>>>>>>> DUMP INVISIBLE ROLE HISTORY ( category [older > newer] )");
1484 for (int ctg_no = StmCtgNoMin; ctg_no <= StmCtgNoMax; ctg_no++)
1486 if (ctg_no == StmCtgNoNone)
1489 std::string category = std::string(kStmCategoryName[ctg_no]);
1491 std::string str = category + " [ ";
1492 for (const auto &i : this->crr_invisible_role_history[category])
1496 HMI_DEBUG("%s", str.c_str());
1500 std::vector<std::string> PolicyManager::parseString(std::string str, char delimiter)
1502 // Parse string by delimiter
1503 std::vector<std::string> vct;
1504 std::stringstream ss{str};
1506 while (std::getline(ss, buf, delimiter))
1510 // Delete space and push back to vector
1511 vct.push_back(this->deleteSpace(buf));
1517 std::string PolicyManager::deleteSpace(std::string str)
1519 std::string ret = str;
1521 while ((pos = ret.find_first_of(" ")) != std::string::npos)
1528 const char *PolicyManager::kDefaultRolesConfig = "{ \
1531 \"category\": \"homescreen\", \
1532 \"role\": \"homescreen\", \
1533 \"area\": \"fullscreen\", \
1536 \"category\": \"map\", \
1537 \"role\": \"map\", \
1538 \"area\": \"normal.full | split.main\", \
1541 \"category\": \"general\", \
1542 \"role\": \"launcher | poi | browser | sdl | mixer | radio | hvac | debug | phone | video | music\", \
1543 \"area\": \"normal.full\", \
1546 \"category\": \"system\", \
1547 \"role\": \"settings | dashboard\", \
1548 \"area\": \"normal.full\", \
1551 \"category\": \"software_keyboard\", \
1552 \"role\": \"software_keyboard\", \
1553 \"area\": \"software_keyboard\", \
1556 \"category\": \"restriction\", \
1557 \"role\": \"restriction\", \
1558 \"area\": \"restriction.normal | restriction.split.main | restriction.split.sub\", \
1561 \"category\": \"pop_up\", \
1562 \"role\": \"pop_up\", \
1563 \"area\": \"on_screen\", \
1566 \"category\": \"system_alert\", \
1567 \"role\": \"system_alert\", \
1568 \"area\": \"on_screen\", \
1573 const char *PolicyManager::kDefaultLayoutsConfig = "{ \
1576 \"name\": \"homescreen\", \
1577 \"layer\": \"far_homescreen\", \
1580 \"name\": \"fullscreen\", \
1581 \"category\": \"homescreen\" \
1586 \"name\": \"map.normal\", \
1587 \"layer\": \"apps\", \
1590 \"name\": \"normal.full\", \
1591 \"category\": \"map\" \
1596 \"name\": \"map.split\", \
1597 \"layer\": \"apps\", \
1600 \"name\": \"split.main\", \
1601 \"category\": \"map\" \
1604 \"name\": \"split.sub\", \
1605 \"category\": \"splitable\" \
1610 \"name\": \"map.fullscreen\", \
1611 \"layer\": \"apps\", \
1614 \"name\": \"fullscreen\", \
1615 \"category\": \"map\" \
1620 \"name\": \"splitable.normal\", \
1621 \"layer\": \"apps\", \
1624 \"name\": \"normal.full\", \
1625 \"category\": \"splitable\" \
1630 \"name\": \"splitable.split\", \
1631 \"layer\": \"apps\", \
1634 \"name\": \"split.main\", \
1635 \"category\": \"splitable\" \
1638 \"name\": \"split.sub\", \
1639 \"category\": \"splitable\" \
1644 \"name\": \"general.normal\", \
1645 \"layer\": \"apps\", \
1648 \"name\": \"normal.full\", \
1649 \"category\": \"general\" \
1654 \"name\": \"system.normal\", \
1655 \"layer\": \"apps\", \
1658 \"name\": \"normal.full\", \
1659 \"category\": \"system\" \
1664 \"name\": \"software_keyboard\", \
1665 \"layer\": \"near_homescreen\", \
1668 \"name\": \"software_keyboard\", \
1669 \"category\": \"software_keyboard\" \
1674 \"name\": \"restriction.normal\", \
1675 \"layer\": \"restriction\", \
1678 \"name\": \"restriction.normal\", \
1679 \"category\": \"restriction\" \
1684 \"name\": \"restriction.split.main\", \
1685 \"layer\": \"restriction\", \
1688 \"name\": \"restriction.split.main\", \
1689 \"category\": \"restriction\" \
1694 \"name\": \"restriction.split.sub\", \
1695 \"layer\": \"restriction\", \
1698 \"name\": \"restriction.split.sub\", \
1699 \"category\": \"restriction\" \
1704 \"name\": \"pop_up\", \
1705 \"layer\": \"on_screen\", \
1708 \"name\": \"on_screen\", \
1709 \"category\": \"pop_up\" \
1714 \"name\": \"system_alert\", \
1715 \"layer\": \"on_screen\", \
1718 \"name\": \"on_screen\", \
1719 \"category\": \"system_alert\" \