From f87f95a278542e3a9aa91b178dd5586ca05d5c49 Mon Sep 17 00:00:00 2001 From: ola567 Date: Thu, 29 Feb 2024 23:54:47 +0100 Subject: [PATCH 01/71] init commit --- tools/sensors_data_display_api/main.py | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 tools/sensors_data_display_api/main.py diff --git a/tools/sensors_data_display_api/main.py b/tools/sensors_data_display_api/main.py new file mode 100644 index 00000000..54b08a6a --- /dev/null +++ b/tools/sensors_data_display_api/main.py @@ -0,0 +1,2 @@ +if __name__ == '__main__': + pass From 57877a7901c199e68abad6b5997d67c38d595a8b Mon Sep 17 00:00:00 2001 From: ola567 Date: Thu, 7 Mar 2024 22:35:15 +0100 Subject: [PATCH 02/71] draft of gui and simple simulation --- tools/sensors_data_display_api/data_reader.py | 47 +++++++ tools/sensors_data_display_api/gui.py | 121 ++++++++++++++++++ tools/sensors_data_display_api/main.py | 5 +- .../sensors_data_display_api/requirements.txt | Bin 0 -> 24 bytes 4 files changed, 172 insertions(+), 1 deletion(-) create mode 100644 tools/sensors_data_display_api/data_reader.py create mode 100644 tools/sensors_data_display_api/gui.py create mode 100644 tools/sensors_data_display_api/requirements.txt diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py new file mode 100644 index 00000000..cba3c7dc --- /dev/null +++ b/tools/sensors_data_display_api/data_reader.py @@ -0,0 +1,47 @@ +import tkinter as tk +import threading +import time + + +class DataReader: + def __init__(self, gui): + self.gui = gui + self.data = 0 + + def read_data(self): + while True: + self.data += 1 + self.gui.update_data_label(self.data) + time.sleep(1) + + +class GUI(tk.Tk): + def __init__(self): + super().__init__() + + self.title("Odczyt danych") + self.geometry("200x100") + + self.label = tk.Label(self, text="Dane:") + self.label.pack() + + self.data_label = tk.Label(self, text="") + self.data_label.pack() + + self.data_reader = DataReader(self) + self.start_reading() + + def start_reading(self): + self.data_reader_thread = threading.Thread(target=self.data_reader.start_reading) + self.data_reader_thread.start() + + def update_data_label(self, data): + self.data_label.config(text=str(data)) + + def stop_reading(self): + self.data_reader.stop_reading() + self.data_reader_thread.join() + +if __name__ == "__main__": + app = GUI() + app.mainloop() diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py new file mode 100644 index 00000000..838b820e --- /dev/null +++ b/tools/sensors_data_display_api/gui.py @@ -0,0 +1,121 @@ +import threading +import tkinter as tk + +from data_reader import DataReader + + +class App(tk.Tk): + def __init__(self): + super().__init__() + + # set properties of the window + self.title("Engine") + self.window_width = 600 + self.window_height = 600 + self.screen_width = self.winfo_screenwidth() + self.screen_height = self.winfo_screenheight() + self.padding = 10 + + center_x = int(self.screen_width / 2 - self.window_width / 2) + center_y = int(self.screen_height / 2 - self.window_height / 2) + + self.geometry(f'{self.window_width}x{self.window_height}+{center_x}+{center_y}') + # self.configure(background='#B9B4C7') + + # variables + label_width = 20 + text_width = 50 + text_height = 1 + + # measurements + temperature_up_frame = tk.Frame(self) + temperature_up_label = tk.Label(temperature_up_frame, text='Temperature up:', width=label_width) + self.temperature_up = tk.Label(temperature_up_frame, text='0') + self.temperature_up.config(state=tk.DISABLED) + + temperature_down_frame = tk.Frame(self) + temperature_down_label = tk.Label(temperature_down_frame, text='Temperature down:', width=label_width) + self.temperature_down = tk.Label(temperature_down_frame, text='0', width=label_width) + self.temperature_down.config(state=tk.DISABLED) + + temperature_middle_frame = tk.Frame(self) + temperature_middle_label = tk.Label(temperature_middle_frame, text='Temperature middle:', width=label_width) + self.temperature_middle = tk.Label(temperature_middle_frame, width=label_width, text='0') + self.temperature_middle.config(state=tk.DISABLED) + + tank_pressure_frame = tk.Frame(self) + tank_pressure_label = tk.Label(tank_pressure_frame, text='Tank pressure', width=label_width) + self.tank_pressure = tk.Label(tank_pressure_frame, width=label_width, text='0') + self.tank_pressure.config(state=tk.DISABLED) + + jet_pressure_frame = tk.Frame(self) + jet_pressure_label = tk.Label(jet_pressure_frame, text='Jet pressure', width=label_width) + self.jet_pressure = tk.Label(jet_pressure_frame, width=label_width, text='0') + self.jet_pressure.config(state=tk.DISABLED) + + pressure_difference_frame = tk.Frame(self) + pressure_difference_label = tk.Label(pressure_difference_frame, text='Pressure difference:', width=label_width) + self.pressure_difference = tk.Label(pressure_difference_frame, width=label_width, text='0') + self.pressure_difference.config(state=tk.DISABLED) + + # buttons + button_frame = tk.Frame(self) + start_saving_button = tk.Button(button_frame, text="Start saving data", command=lambda: self.start_saving()) + stop_saving_button = tk.Button(button_frame, text="Stop saving data", command=lambda: self.stop_saving()) + launch_rocket_button = tk.Button(button_frame, text="Launch rocket", command=lambda: self.launch_rocket()) + exit_button = tk.Button(button_frame, text="Exit", command=lambda: self.exit()) + + # pack on screen + temperature_up_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + temperature_up_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.temperature_up.pack(side=tk.LEFT, pady=self.padding, fill='both') + + temperature_down_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + temperature_down_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.temperature_down.pack(side=tk.LEFT, pady=self.padding, fill='both') + + temperature_middle_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + temperature_middle_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.temperature_middle.pack(side=tk.LEFT, pady=self.padding, fill='both') + + tank_pressure_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + tank_pressure_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.tank_pressure.pack(side=tk.LEFT, pady=self.padding, fill='both') + + jet_pressure_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + jet_pressure_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.jet_pressure.pack(side=tk.LEFT, pady=self.padding, fill='both') + + pressure_difference_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + pressure_difference_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.pressure_difference.pack(side=tk.LEFT, pady=self.padding, fill='both') + + button_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + start_saving_button.pack(side=tk.TOP, pady=self.padding, fill='both') + stop_saving_button.pack(side=tk.TOP, pady=self.padding, fill='both') + launch_rocket_button.pack(side=tk.TOP, pady=self.padding, fill='both') + exit_button.pack(side=tk.TOP, pady=self.padding, fill='both') + + self.data_reader = DataReader(gui=self) + self.read_data() + + def read_data(self): + data_reader_thread = threading.Thread(target=self.data_reader.read_data) + data_reader_thread.start() + + def update_data_label(self, data): + # self.temperature_up.delete(0, tk.END) + # self.temperature_up.insert(tk.END, data) + self.temperature_up.config(text=str(data)) + + def start_saving(self): + pass + + def stop_saving(self): + pass + + def launch_rocket(self): + pass + + def exit(self): + self.destroy() diff --git a/tools/sensors_data_display_api/main.py b/tools/sensors_data_display_api/main.py index 54b08a6a..ffbf2a86 100644 --- a/tools/sensors_data_display_api/main.py +++ b/tools/sensors_data_display_api/main.py @@ -1,2 +1,5 @@ +from gui import App + if __name__ == '__main__': - pass + app = App() + app.mainloop() diff --git a/tools/sensors_data_display_api/requirements.txt b/tools/sensors_data_display_api/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..32047118968fd0a980de431c92c5b0235672c17f GIT binary patch literal 24 ccmezWuY@6+!4?P&81xtnf!Kh7mw}4`08+{XTL1t6 literal 0 HcmV?d00001 From b0a8c2dcef40fcb190a5e644bcfecff9a2b7ad32 Mon Sep 17 00:00:00 2001 From: ola567 Date: Sat, 9 Mar 2024 16:57:25 +0100 Subject: [PATCH 03/71] gui improvements --- tools/sensors_data_display_api/gui.py | 75 ++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 13 deletions(-) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 838b820e..88f00f8e 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -14,7 +14,7 @@ def __init__(self): self.window_height = 600 self.screen_width = self.winfo_screenwidth() self.screen_height = self.winfo_screenheight() - self.padding = 10 + self.padding = 5 center_x = int(self.screen_width / 2 - self.window_width / 2) center_y = int(self.screen_height / 2 - self.window_height / 2) @@ -24,8 +24,7 @@ def __init__(self): # variables label_width = 20 - text_width = 50 - text_height = 1 + button_padding = 2 # measurements temperature_up_frame = tk.Frame(self) @@ -58,14 +57,37 @@ def __init__(self): self.pressure_difference = tk.Label(pressure_difference_frame, width=label_width, text='0') self.pressure_difference.config(state=tk.DISABLED) + main_valve_frame = tk.Frame(self) + main_valve_label = tk.Label(main_valve_frame, text='Main valve:', width=label_width) + self.main_valve = tk.Label(main_valve_frame, width=label_width, text='not given') + self.main_valve.config(state=tk.DISABLED) + + vent_frame = tk.Frame(self) + vent_label = tk.Label(vent_frame, text='Vent:', width=label_width) + self.vent = tk.Label(vent_frame, width=label_width, text='not given') + self.vent.config(state=tk.DISABLED) + # buttons - button_frame = tk.Frame(self) - start_saving_button = tk.Button(button_frame, text="Start saving data", command=lambda: self.start_saving()) - stop_saving_button = tk.Button(button_frame, text="Stop saving data", command=lambda: self.stop_saving()) - launch_rocket_button = tk.Button(button_frame, text="Launch rocket", command=lambda: self.launch_rocket()) - exit_button = tk.Button(button_frame, text="Exit", command=lambda: self.exit()) + start_stop_saving_button_frame = tk.Frame(self) + start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.start_saving()) + stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.stop_saving()) + + main_valve_button_frame = tk.Frame(self) + main_valve_set_1_button = tk.Button(main_valve_button_frame, text="Main valve: set 1", command=lambda: self.set_main_valve(value=1)) + main_valve_set_0_button = tk.Button(main_valve_button_frame, text="Main valve: set 0", command=lambda: self.set_main_valve(value=0)) + + vent_button_frame = tk.Frame(self) + vent_set_1_button = tk.Button(vent_button_frame, text="Vent: set 1", command=lambda: self.set_vent(value=1)) + vent_set_0_button = tk.Button(vent_button_frame, text="Vent: set 0", command=lambda: self.set_vent(value=0)) + + launch_rocket_button_frame = tk.Frame(self) + launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Launch rocket", command=lambda: self.launch_rocket()) + stop_launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Stop launch rocket", command=lambda: self.stop_launch_rocket()) + + exit_button = tk.Button(self, text="Exit", command=lambda: self.exit()) # pack on screen + # pack measurements temperature_up_frame.pack(side=tk.TOP, pady=self.padding, fill='both') temperature_up_label.pack(side=tk.LEFT, pady=self.padding, fill='both') self.temperature_up.pack(side=tk.LEFT, pady=self.padding, fill='both') @@ -90,11 +112,32 @@ def __init__(self): pressure_difference_label.pack(side=tk.LEFT, pady=self.padding, fill='both') self.pressure_difference.pack(side=tk.LEFT, pady=self.padding, fill='both') - button_frame.pack(side=tk.TOP, pady=self.padding, fill='both') - start_saving_button.pack(side=tk.TOP, pady=self.padding, fill='both') - stop_saving_button.pack(side=tk.TOP, pady=self.padding, fill='both') - launch_rocket_button.pack(side=tk.TOP, pady=self.padding, fill='both') - exit_button.pack(side=tk.TOP, pady=self.padding, fill='both') + main_valve_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + main_valve_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.main_valve.pack(side=tk.LEFT, pady=self.padding, fill='both') + + vent_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + vent_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.vent.pack(side=tk.LEFT, pady=self.padding, fill='both') + + # pack buttons + main_valve_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') + main_valve_set_1_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + main_valve_set_0_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + + vent_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') + vent_set_1_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + vent_set_0_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + + start_stop_saving_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') + start_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + stop_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + + launch_rocket_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') + launch_rocket_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + stop_launch_rocket_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + + exit_button.pack(side=tk.TOP, fill='both') self.data_reader = DataReader(gui=self) self.read_data() @@ -117,5 +160,11 @@ def stop_saving(self): def launch_rocket(self): pass + def set_main_valve(self, value): + pass + + def set_vent(self, value): + pass + def exit(self): self.destroy() From a0028027dca14b0334e543634b3c38396da73058 Mon Sep 17 00:00:00 2001 From: ola567 Date: Sun, 10 Mar 2024 09:55:17 +0100 Subject: [PATCH 04/71] remove unnecesary lines --- tools/sensors_data_display_api/data_reader.py | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index cba3c7dc..ac82cda7 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -13,35 +13,3 @@ def read_data(self): self.data += 1 self.gui.update_data_label(self.data) time.sleep(1) - - -class GUI(tk.Tk): - def __init__(self): - super().__init__() - - self.title("Odczyt danych") - self.geometry("200x100") - - self.label = tk.Label(self, text="Dane:") - self.label.pack() - - self.data_label = tk.Label(self, text="") - self.data_label.pack() - - self.data_reader = DataReader(self) - self.start_reading() - - def start_reading(self): - self.data_reader_thread = threading.Thread(target=self.data_reader.start_reading) - self.data_reader_thread.start() - - def update_data_label(self, data): - self.data_label.config(text=str(data)) - - def stop_reading(self): - self.data_reader.stop_reading() - self.data_reader_thread.join() - -if __name__ == "__main__": - app = GUI() - app.mainloop() From 1fe9be7184bf5bc0aae6743eb0a19e08d4f59fac Mon Sep 17 00:00:00 2001 From: ola567 Date: Thu, 14 Mar 2024 07:10:42 +0100 Subject: [PATCH 05/71] changes --- tools/sensors_data_display_api/data_reader.py | 68 ++++++++- tools/sensors_data_display_api/gui.py | 2 - .../some_ip_header.py | 74 ++++++++++ tools/sensors_data_display_api/someip.json | 129 ++++++++++++++++++ tools/sensors_data_display_api/test.py | 49 +++++++ 5 files changed, 314 insertions(+), 8 deletions(-) create mode 100644 tools/sensors_data_display_api/some_ip_header.py create mode 100644 tools/sensors_data_display_api/someip.json create mode 100644 tools/sensors_data_display_api/test.py diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index ac82cda7..5d7d677d 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -1,15 +1,71 @@ -import tkinter as tk -import threading +import json +import logging import time +import socket + +from some_ip_header import SomeIPHeader class DataReader: def __init__(self, gui): self.gui = gui self.data = 0 + with open('someip.json') as f: + self.config = json.load(f) + self.lookup_table = self._prepare_lookup_table() + + def _prepare_lookup_table(self): + lookup_table = {} + for key, value in self.config['req_events'].items(): + service_id = value.get('service_id') + method_id = value.get('event_id') + lookup_table[(service_id, method_id)] = key + return lookup_table def read_data(self): - while True: - self.data += 1 - self.gui.update_data_label(self.data) - time.sleep(1) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + try: + sock.bind(('127.0.0.1', 10101)) + except: + logging.critical("Port is taken") + try: + while True: + data = sock.recv(150) + if len(data) == 0: + break + some_ip_header = SomeIPHeader() + some_ip_header.read(data) + + # get service_id, method_id and payload + service_id = some_ip_header.service_id + method_id = some_ip_header.methode_id + payload = some_ip_header.payload + + # get data type + data_type = self.lookup_table.get((service_id, method_id)) + if data_type is not None: + if data_type == 'PC_APP/newTempEvent_1': + # temperature up + temperature_up = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.temperature_up.config(text=str(temperature_up)) + elif data_type == 'PC_APP/newTempEvent_2': + # temperature down + temperature_down = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.temperature_down.config(text=str(temperature_down)) + elif data_type == 'PC_APP/newTempEvent_3': + # temperature middle + temperature_middle = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.temperature_middle.config(text=str(temperature_middle)) + elif data_type == 'PC_APP/newPressEvent': + # tank pressure + tank_pressure = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.tank_pressure.config(text=str(tank_pressure)) + elif data_type == 'PC_APP/servoStatusEvent': + # main valve + main_valve = payload.decode('UTF-8', errors='ignore') + self.gui.main_valve.config(text=main_valve) + else: + print("No data") + + except KeyboardInterrupt: + time.sleep(0.5) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 88f00f8e..f440754e 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -147,8 +147,6 @@ def read_data(self): data_reader_thread.start() def update_data_label(self, data): - # self.temperature_up.delete(0, tk.END) - # self.temperature_up.insert(tk.END, data) self.temperature_up.config(text=str(data)) def start_saving(self): diff --git a/tools/sensors_data_display_api/some_ip_header.py b/tools/sensors_data_display_api/some_ip_header.py new file mode 100644 index 00000000..b17d841e --- /dev/null +++ b/tools/sensors_data_display_api/some_ip_header.py @@ -0,0 +1,74 @@ +from ctypes import sizeof, c_uint16, c_uint8, c_uint32, c_uint64 + + +class SomeIPHeader: + def __str__(self) -> str: + return f""" + service_id:{self.service_id} + method_id:{self.methode_id} + lenght:{self.length} + msg_type:{self.msg_typ} + payload:{self.raw_payload}""" + + def __init__(self, service_id=None, methode_id=None, msg_typ=0x01) -> None: + self.raw_payload = None + self.service_id = service_id + self.methode_id = methode_id + self.payload = [] + self.length = 0x0008 + self.client_id = 0x0001 + self.session = 0x0001 + self.msg_typ = msg_typ + self.msg_return = 0x00 + + def read(self, hex) -> None: + self.service_id = int.from_bytes(hex[0:2], byteorder="big", signed=False) + self.methode_id = int.from_bytes(hex[2:4], byteorder="big", signed=False) + self.length = int.from_bytes(hex[4:8], byteorder="big", signed=False) + self.msg_typ = hex[14] + self.raw_payload = hex[16:] + + def set_payload(self, payload) -> None: + self.payload = payload + self.length = 0x8 + len(payload) + + def get_some_ip_data(self): + res = [] + temp_res = [] + size = 0 + for item in self.payload: + if (item <= 255): + size = size + 1 + temp_res.append(item.to_bytes(sizeof(c_uint8), byteorder="little")) + else: + size = size + 2 + temp_res.append(item.to_bytes(sizeof(c_uint16), byteorder="little")) + self.length = 0x8 + size + res.append(self.service_id.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(self.methode_id.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(self.length.to_bytes(sizeof(c_uint32), byteorder="big")) + res.append(self.client_id.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(self.session.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(0x01.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(0x01.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(self.msg_typ.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(self.msg_return.to_bytes(sizeof(c_uint8), byteorder="big")) + for item in temp_res: + res.append(item) + + return res + + def get_some_ip_data_payload(self, payload): + res = [] + self.length = 0x8 + len(payload) + res.append(self.service_id.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(self.methode_id.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(self.length.to_bytes(sizeof(c_uint32), byteorder="big")) + res.append(self.client_id.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(self.session.to_bytes(sizeof(c_uint16), byteorder="big")) + res.append(0x01.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(0x01.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(self.msg_typ.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(self.msg_return.to_bytes(sizeof(c_uint8), byteorder="big")) + res.append(payload) + return res diff --git a/tools/sensors_data_display_api/someip.json b/tools/sensors_data_display_api/someip.json new file mode 100644 index 00000000..51427bd4 --- /dev/null +++ b/tools/sensors_data_display_api/someip.json @@ -0,0 +1,129 @@ +{ + "service_id": 1, + "interface": [ + { + "ip": "127.0.0.1", + "port": 10101 + } + ], + "pub_methods": {}, + "pub_event": {}, + "req_methods": { + "PC_APP/setServoValue": { + "service_id": 515, + "method_id": 1 + }, + "PC_APP/readServoValue": { + "service_id": 515, + "method_id": 2 + }, + "PC_APP/startPrime": { + "service_id": 516, + "method_id": 3 + }, + "PC_APP/onPrime": { + "service_id": 516, + "method_id": 1 + }, + "PC_APP/offPrime": { + "service_id": 516, + "method_id": 2 + }, + "PC_APP/LoggerStart": { + "service_id": 517, + "method_id": 1 + }, + "PC_APP/LoggerStop": { + "service_id": 517, + "method_id": 2 + }, + "PC_APP/EngineStart": { + "service_id": 518, + "method_id": 1 + }, + "PC_APP/EngineSetMode": { + "service_id": 518, + "method_id": 2 + }, + "PC_APP/diagMethodRequestJob": { + "service_id": 513, + "method_id": 1 + }, + "PC_APP/diagMethodRequestRead": { + "service_id": 513, + "method_id": 2 + }, + "PC_APP/diagMethodRequestWrite": { + "service_id": 513, + "method_id": 3 + } + }, + "req_events": { + "PC_APP/servoStatusEvent": { + "service_id": 515, + "event_id": 32769 + }, + "PC_APP/newTempEvent_1": { + "service_id": 514, + "event_id": 32769 + }, + "PC_APP/newTempEvent_2": { + "service_id": 514, + "event_id": 32770 + }, + "PC_APP/newTempEvent_3": { + "service_id": 514, + "event_id": 32771 + }, + "PC_APP/newTempEvent_4": { + "service_id": 514, + "event_id": 32772 + }, + "PC_APP/newPressEvent": { + "service_id": 514, + "event_id": 32773 + }, + "PC_APP/newDPressEvent": { + "service_id": 514, + "event_id": 32774 + }, + "PC_APP/primeStatusEvent": { + "service_id": 516, + "event_id": 32769 + }, + "PC_APP/newDTCEvent": { + "service_id": 513, + "event_id": 32769 + }, + "PC_APP/currentMode": { + "service_id": 518, + "event_id": 32769 + } + }, + "db": { + "515": { + "ip": "192.168.10.101", + "port": 1515 + }, + "516": { + "ip": "192.168.10.101", + "port": 1516 + }, + "517": { + "ip": "192.168.10.101", + "port": 1517 + }, + "518": { + "ip": "192.168.10.101", + "port": 1518 + }, + "513": { + "ip": "192.168.10.101", + "port": 1513 + }, + "514": { + "ip": "192.168.10.101", + "port": 1514 + } + } +} \ No newline at end of file diff --git a/tools/sensors_data_display_api/test.py b/tools/sensors_data_display_api/test.py new file mode 100644 index 00000000..3f2a555f --- /dev/null +++ b/tools/sensors_data_display_api/test.py @@ -0,0 +1,49 @@ +import socket +import struct +import random +import time + +from some_ip_header import SomeIPHeader + + +first = True +HOST = "127.0.0.1" +PORT = 10101 + +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + while True: + hdr = SomeIPHeader(0x01, 0x8002) + payload = struct.pack('f', random.uniform(20, 25)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + hdr = SomeIPHeader(0x01, 0x8001) + payload = struct.pack('f', random.uniform(0, 15)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + hdr = SomeIPHeader(0x01, 0x8003) + payload = struct.pack('f', random.uniform(0, 3.3)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + hdr = SomeIPHeader(0x01, 0x8004) + payload = struct.pack('f', random.uniform(0, 3.3)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + hdr = SomeIPHeader(0x01, 0x8005) + payload = struct.pack('f', random.uniform(0, 3.3)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + hdr = SomeIPHeader(0x01, 0x8006) + payload = struct.pack('f', random.uniform(0, 10000)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + hdr = SomeIPHeader(0x01, 0x8007) + payload = struct.pack('f', random.uniform(0, 20)) + "28-062018f00883".encode("UTF-8") + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + payload = struct.pack('f', random.uniform(0, 20)) + "28-3c29e381356d".encode("UTF-8") + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + payload = struct.pack('f', random.uniform(0, 20)) + ("28-3c01e076e761".encode("UTF-8")) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + time.sleep(0.1) From e10b7cfa9d90c935e9f86831231326b60c24fa67 Mon Sep 17 00:00:00 2001 From: ola567 Date: Thu, 14 Mar 2024 08:01:49 +0100 Subject: [PATCH 06/71] changes --- tools/sensors_data_display_api/Data.py | 15 ++++ tools/sensors_data_display_api/data_reader.py | 83 ++++++++++--------- tools/sensors_data_display_api/gui.py | 22 ++--- tools/sensors_data_display_api/test.py | 3 +- 4 files changed, 74 insertions(+), 49 deletions(-) create mode 100644 tools/sensors_data_display_api/Data.py diff --git a/tools/sensors_data_display_api/Data.py b/tools/sensors_data_display_api/Data.py new file mode 100644 index 00000000..91e59101 --- /dev/null +++ b/tools/sensors_data_display_api/Data.py @@ -0,0 +1,15 @@ +class Data: + def __init__(self): + self.temperature_up = None + self.temperature_middle = None + self.temperature_down = None + self.tank_pressure = None + self.jet_pressure = None + self.pressure_difference = None + self.main_valve = None + self.vent_frame = None + + def is_None(self): + if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None or self.main_valve is None: + return True + return False diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index 5d7d677d..e0e2d3ad 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -25,47 +25,56 @@ def _prepare_lookup_table(self): def read_data(self): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: try: - sock.bind(('127.0.0.1', 10101)) + sock.bind(('127.0.0.1', 12345)) except: logging.critical("Port is taken") + sock.listen() + conn, addr = sock.accept() try: - while True: - data = sock.recv(150) - if len(data) == 0: - break - some_ip_header = SomeIPHeader() - some_ip_header.read(data) + with conn: + while True: + if self.gui.stop_reading: + break + data = sock.recv(150) + if len(data) == 0: + break + some_ip_header = SomeIPHeader() + some_ip_header.read(data) - # get service_id, method_id and payload - service_id = some_ip_header.service_id - method_id = some_ip_header.methode_id - payload = some_ip_header.payload - - # get data type - data_type = self.lookup_table.get((service_id, method_id)) - if data_type is not None: - if data_type == 'PC_APP/newTempEvent_1': - # temperature up - temperature_up = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.temperature_up.config(text=str(temperature_up)) - elif data_type == 'PC_APP/newTempEvent_2': - # temperature down - temperature_down = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.temperature_down.config(text=str(temperature_down)) - elif data_type == 'PC_APP/newTempEvent_3': - # temperature middle - temperature_middle = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.temperature_middle.config(text=str(temperature_middle)) - elif data_type == 'PC_APP/newPressEvent': - # tank pressure - tank_pressure = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.tank_pressure.config(text=str(tank_pressure)) - elif data_type == 'PC_APP/servoStatusEvent': - # main valve - main_valve = payload.decode('UTF-8', errors='ignore') - self.gui.main_valve.config(text=main_valve) - else: - print("No data") + # get service_id, method_id and payload + service_id = some_ip_header.service_id + method_id = some_ip_header.methode_id + payload = some_ip_header.payload + # get data type + data_type = self.lookup_table.get((service_id, method_id)) + if data_type is not None: + if data_type == 'PC_APP/newTempEvent_1': + # temperature up + temperature_up = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.data_to_save.temperature_up = temperature_up + self.gui.temperature_up.config(text=str(temperature_up)) + elif data_type == 'PC_APP/newTempEvent_2': + # temperature down + temperature_down = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.data_to_save.temperature_down = temperature_down + self.gui.temperature_down.config(text=str(temperature_down)) + elif data_type == 'PC_APP/newTempEvent_3': + # temperature middle + temperature_middle = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.data_to_save.temperature_middle = temperature_middle + self.gui.temperature_middle.config(text=str(temperature_middle)) + elif data_type == 'PC_APP/newPressEvent': + # tank pressure + tank_pressure = int.from_bytes(payload, byteorder="big", signed=False) + self.gui.data_to_save.tank_pressure = tank_pressure + self.gui.tank_pressure.config(text=str(tank_pressure)) + elif data_type == 'PC_APP/servoStatusEvent': + # main valve + main_valve = payload.decode('UTF-8', errors='ignore') + self.gui.data_to_save.main_valve = main_valve + self.gui.main_valve.config(text=main_valve) + else: + print("No data") except KeyboardInterrupt: time.sleep(0.5) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index f440754e..b65f824c 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -1,6 +1,7 @@ import threading import tkinter as tk +from Data import Data from data_reader import DataReader @@ -25,6 +26,9 @@ def __init__(self): # variables label_width = 20 button_padding = 2 + self.stop_reading = False + self.data_reader_thread = None + self.data_to_save = Data() # measurements temperature_up_frame = tk.Frame(self) @@ -69,8 +73,8 @@ def __init__(self): # buttons start_stop_saving_button_frame = tk.Frame(self) - start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.start_saving()) - stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.stop_saving()) + start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.save_to_file(start_stop=True)) + stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.save_to_file(start_stop=False)) main_valve_button_frame = tk.Frame(self) main_valve_set_1_button = tk.Button(main_valve_button_frame, text="Main valve: set 1", command=lambda: self.set_main_valve(value=1)) @@ -143,16 +147,10 @@ def __init__(self): self.read_data() def read_data(self): - data_reader_thread = threading.Thread(target=self.data_reader.read_data) - data_reader_thread.start() + self.data_reader_thread = threading.Thread(target=self.data_reader.read_data) + self.data_reader_thread.start() - def update_data_label(self, data): - self.temperature_up.config(text=str(data)) - - def start_saving(self): - pass - - def stop_saving(self): + def save_to_file(self, start_stop: bool): pass def launch_rocket(self): @@ -165,4 +163,6 @@ def set_vent(self, value): pass def exit(self): + self.stop_reading = True + self.data_reader_thread.join() self.destroy() diff --git a/tools/sensors_data_display_api/test.py b/tools/sensors_data_display_api/test.py index 3f2a555f..34715f09 100644 --- a/tools/sensors_data_display_api/test.py +++ b/tools/sensors_data_display_api/test.py @@ -8,9 +8,10 @@ first = True HOST = "127.0.0.1" -PORT = 10101 +PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + sock.connect((HOST, PORT)) while True: hdr = SomeIPHeader(0x01, 0x8002) payload = struct.pack('f', random.uniform(20, 25)) From 8eee2483cdb0f37ba017d5b164345776b5de7569 Mon Sep 17 00:00:00 2001 From: ola567 Date: Sun, 17 Mar 2024 22:40:00 +0100 Subject: [PATCH 07/71] changes --- tools/sensors_data_display_api/data_reader.py | 91 +++++++++---------- tools/sensors_data_display_api/test.py | 14 +-- 2 files changed, 51 insertions(+), 54 deletions(-) diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index e0e2d3ad..1d38e65a 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -1,5 +1,6 @@ import json import logging +import struct import time import socket @@ -28,53 +29,49 @@ def read_data(self): sock.bind(('127.0.0.1', 12345)) except: logging.critical("Port is taken") - sock.listen() - conn, addr = sock.accept() - try: - with conn: - while True: - if self.gui.stop_reading: - break - data = sock.recv(150) - if len(data) == 0: - break - some_ip_header = SomeIPHeader() - some_ip_header.read(data) + while True: + if self.gui.stop_reading: + break + data = sock.recv(150) + if len(data) == 0: + break + some_ip_header = SomeIPHeader() + some_ip_header.read(data) - # get service_id, method_id and payload - service_id = some_ip_header.service_id - method_id = some_ip_header.methode_id - payload = some_ip_header.payload + # get service_id, method_id and payload + service_id = some_ip_header.service_id + method_id = some_ip_header.methode_id + payload = some_ip_header.raw_payload - # get data type - data_type = self.lookup_table.get((service_id, method_id)) - if data_type is not None: - if data_type == 'PC_APP/newTempEvent_1': - # temperature up - temperature_up = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.data_to_save.temperature_up = temperature_up - self.gui.temperature_up.config(text=str(temperature_up)) - elif data_type == 'PC_APP/newTempEvent_2': - # temperature down - temperature_down = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.data_to_save.temperature_down = temperature_down - self.gui.temperature_down.config(text=str(temperature_down)) - elif data_type == 'PC_APP/newTempEvent_3': - # temperature middle - temperature_middle = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.data_to_save.temperature_middle = temperature_middle - self.gui.temperature_middle.config(text=str(temperature_middle)) - elif data_type == 'PC_APP/newPressEvent': - # tank pressure - tank_pressure = int.from_bytes(payload, byteorder="big", signed=False) - self.gui.data_to_save.tank_pressure = tank_pressure - self.gui.tank_pressure.config(text=str(tank_pressure)) - elif data_type == 'PC_APP/servoStatusEvent': - # main valve - main_valve = payload.decode('UTF-8', errors='ignore') - self.gui.data_to_save.main_valve = main_valve - self.gui.main_valve.config(text=main_valve) - else: - print("No data") - except KeyboardInterrupt: + # get data type + data_type = self.lookup_table.get((service_id, method_id)) + print(f'service_id: {service_id}, method_id: {method_id}, payload: {payload}, data_ty[e: {data_type}') + if data_type is not None: + if data_type == 'PC_APP/newTempEvent_1': + # temperature up + temperature_up = struct.unpack('f', payload)[0] + self.gui.data_to_save.temperature_up = temperature_up + self.gui.temperature_up.config(text=str(temperature_up)) + elif data_type == 'PC_APP/newTempEvent_2': + # temperature down + temperature_down = struct.unpack('f', payload)[0] + self.gui.data_to_save.temperature_down = temperature_down + self.gui.temperature_down.config(text=str(temperature_down)) + elif data_type == 'PC_APP/newTempEvent_3': + # temperature middle + temperature_middle = struct.unpack('f', payload)[0] + self.gui.data_to_save.temperature_middle = temperature_middle + self.gui.temperature_middle.config(text=str(temperature_middle)) + elif data_type == 'PC_APP/newPressEvent': + # tank pressure + tank_pressure = struct.unpack('f', payload)[0] + self.gui.data_to_save.tank_pressure = tank_pressure + self.gui.tank_pressure.config(text=str(tank_pressure)) + elif data_type == 'PC_APP/servoStatusEvent': + # main valve + main_valve = payload.decode('UTF-8', errors='ignore') + self.gui.data_to_save.main_valve = main_valve + self.gui.main_valve.config(text=main_valve) + else: + print("No data") time.sleep(0.5) diff --git a/tools/sensors_data_display_api/test.py b/tools/sensors_data_display_api/test.py index 34715f09..ce6f5f80 100644 --- a/tools/sensors_data_display_api/test.py +++ b/tools/sensors_data_display_api/test.py @@ -13,31 +13,31 @@ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.connect((HOST, PORT)) while True: - hdr = SomeIPHeader(0x01, 0x8002) + hdr = SomeIPHeader(514, 32769) payload = struct.pack('f', random.uniform(20, 25)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(0x01, 0x8001) + hdr = SomeIPHeader(514, 0x8001) payload = struct.pack('f', random.uniform(0, 15)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(0x01, 0x8003) + hdr = SomeIPHeader(514, 0x8003) payload = struct.pack('f', random.uniform(0, 3.3)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(0x01, 0x8004) + hdr = SomeIPHeader(515, 0x8004) payload = struct.pack('f', random.uniform(0, 3.3)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(0x01, 0x8005) + hdr = SomeIPHeader(513, 0x8005) payload = struct.pack('f', random.uniform(0, 3.3)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(0x01, 0x8006) + hdr = SomeIPHeader(514, 0x8006) payload = struct.pack('f', random.uniform(0, 10000)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(0x01, 0x8007) + hdr = SomeIPHeader(514, 0x8007) payload = struct.pack('f', random.uniform(0, 20)) + "28-062018f00883".encode("UTF-8") msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) From 393167ea224c3d3e54c3175fc307e6f3c0cd9d5e Mon Sep 17 00:00:00 2001 From: ola567 Date: Sun, 17 Mar 2024 23:19:18 +0100 Subject: [PATCH 08/71] changes --- .../{Data.py => data.py} | 4 +- tools/sensors_data_display_api/data_reader.py | 8 ++-- tools/sensors_data_display_api/gui.py | 44 ++++++++++++++++--- tools/sensors_data_display_api/test.py | 16 ++++--- 4 files changed, 55 insertions(+), 17 deletions(-) rename tools/sensors_data_display_api/{Data.py => data.py} (87%) diff --git a/tools/sensors_data_display_api/Data.py b/tools/sensors_data_display_api/data.py similarity index 87% rename from tools/sensors_data_display_api/Data.py rename to tools/sensors_data_display_api/data.py index 91e59101..790fd49d 100644 --- a/tools/sensors_data_display_api/Data.py +++ b/tools/sensors_data_display_api/data.py @@ -7,9 +7,9 @@ def __init__(self): self.jet_pressure = None self.pressure_difference = None self.main_valve = None - self.vent_frame = None + self.vent = None def is_None(self): - if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None or self.main_valve is None: + if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None: return True return False diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index 1d38e65a..0c119301 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -51,22 +51,22 @@ def read_data(self): # temperature up temperature_up = struct.unpack('f', payload)[0] self.gui.data_to_save.temperature_up = temperature_up - self.gui.temperature_up.config(text=str(temperature_up)) + self.gui.temperature_up.config(text=str(round(temperature_up, 2))) elif data_type == 'PC_APP/newTempEvent_2': # temperature down temperature_down = struct.unpack('f', payload)[0] self.gui.data_to_save.temperature_down = temperature_down - self.gui.temperature_down.config(text=str(temperature_down)) + self.gui.temperature_down.config(text=str(round(temperature_down, 2))) elif data_type == 'PC_APP/newTempEvent_3': # temperature middle temperature_middle = struct.unpack('f', payload)[0] self.gui.data_to_save.temperature_middle = temperature_middle - self.gui.temperature_middle.config(text=str(temperature_middle)) + self.gui.temperature_middle.config(text=str(round(temperature_middle, 2))) elif data_type == 'PC_APP/newPressEvent': # tank pressure tank_pressure = struct.unpack('f', payload)[0] self.gui.data_to_save.tank_pressure = tank_pressure - self.gui.tank_pressure.config(text=str(tank_pressure)) + self.gui.tank_pressure.config(text=str(round(tank_pressure, 2))) elif data_type == 'PC_APP/servoStatusEvent': # main valve main_valve = payload.decode('UTF-8', errors='ignore') diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index b65f824c..68b213e5 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -1,7 +1,9 @@ +import csv +import datetime import threading import tkinter as tk -from Data import Data +from data import Data from data_reader import DataReader @@ -27,7 +29,9 @@ def __init__(self): label_width = 20 button_padding = 2 self.stop_reading = False + self.saving = False self.data_reader_thread = None + self.saving_thread = None self.data_to_save = Data() # measurements @@ -73,8 +77,8 @@ def __init__(self): # buttons start_stop_saving_button_frame = tk.Frame(self) - start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.save_to_file(start_stop=True)) - stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.save_to_file(start_stop=False)) + start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.start_save_to_file()) + stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.stop_save_to_file()) main_valve_button_frame = tk.Frame(self) main_valve_set_1_button = tk.Button(main_valve_button_frame, text="Main valve: set 1", command=lambda: self.set_main_valve(value=1)) @@ -150,8 +154,38 @@ def read_data(self): self.data_reader_thread = threading.Thread(target=self.data_reader.read_data) self.data_reader_thread.start() - def save_to_file(self, start_stop: bool): - pass + def start_save_to_file(self): + self.saving = True + self.saving_thread = threading.Thread(target=self._save_to_file) + self.saving_thread.start() + + def stop_save_to_file(self): + self.saving = False + self.saving_thread.join() + + def _save_to_file(self): + timestamp = datetime.datetime.now() + filename = f"data_{timestamp.hour}_{timestamp.minute}_{timestamp.second}.csv" + with open(file=filename, mode='w', encoding='UTF-8') as csvFile: + writer = csv.writer(csvFile, delimiter=";") + writer.writerow(['TIMESTAMP', 'TEMPERATURE_UP', 'TEMPERATURE_DOWN', 'TEMPERATURE_MIDDLE', 'TANK_PRESSURE', 'JET_PRESSURE', 'PRESSURE_DIFFERENCE', 'MAIN_VALVE', 'VENT']) + start = datetime.datetime.now() + while self.saving: + if self.data_to_save.is_None() is False: + timestamp = datetime.datetime.now() - start + with open(filename, 'a', encoding='UTF-8', newline='') as csvFile: + writer = csv.writer(csvFile, delimiter=";") + writer.writerow([timestamp, self.data_to_save.temperature_up, self.data_to_save.temperature_down, self.data_to_save.temperature_middle, + self.data_to_save.tank_pressure, self.data_to_save.jet_pressure, self.data_to_save.pressure_difference, + self.data_to_save.main_valve, self.data_to_save.vent]) + self.data_to_save.temperature_up = None + self.data_to_save.temperature_down = None + self.data_to_save.temperature_middle = None + self.data_to_save.tank_pressure = None + self.data_to_save.jet_pressure = None + self.data_to_save.pressure_difference = None + self.data_to_save.main_valve = None + self.data_to_save.vent = None def launch_rocket(self): pass diff --git a/tools/sensors_data_display_api/test.py b/tools/sensors_data_display_api/test.py index ce6f5f80..076f7cf9 100644 --- a/tools/sensors_data_display_api/test.py +++ b/tools/sensors_data_display_api/test.py @@ -13,20 +13,24 @@ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.connect((HOST, PORT)) while True: + # temperature up hdr = SomeIPHeader(514, 32769) payload = struct.pack('f', random.uniform(20, 25)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(514, 0x8001) - payload = struct.pack('f', random.uniform(0, 15)) + # temperature down + hdr = SomeIPHeader(514, 32770) + payload = struct.pack('f', random.uniform(10, 15)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(514, 0x8003) - payload = struct.pack('f', random.uniform(0, 3.3)) + # temperature middle + hdr = SomeIPHeader(514, 32771) + payload = struct.pack('f', random.uniform(1, 3.3)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(515, 0x8004) - payload = struct.pack('f', random.uniform(0, 3.3)) + # tank pressure + hdr = SomeIPHeader(514, 32773) + payload = struct.pack('f', random.uniform(1, 3.3)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) hdr = SomeIPHeader(513, 0x8005) From ba25227643df949897067075bcbe234daff58379 Mon Sep 17 00:00:00 2001 From: ola567 Date: Mon, 18 Mar 2024 07:52:33 +0100 Subject: [PATCH 09/71] changes --- tools/sensors_data_display_api/gui.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 68b213e5..7aaf934b 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -100,14 +100,14 @@ def __init__(self): temperature_up_label.pack(side=tk.LEFT, pady=self.padding, fill='both') self.temperature_up.pack(side=tk.LEFT, pady=self.padding, fill='both') - temperature_down_frame.pack(side=tk.TOP, pady=self.padding, fill='both') - temperature_down_label.pack(side=tk.LEFT, pady=self.padding, fill='both') - self.temperature_down.pack(side=tk.LEFT, pady=self.padding, fill='both') - temperature_middle_frame.pack(side=tk.TOP, pady=self.padding, fill='both') temperature_middle_label.pack(side=tk.LEFT, pady=self.padding, fill='both') self.temperature_middle.pack(side=tk.LEFT, pady=self.padding, fill='both') + temperature_down_frame.pack(side=tk.TOP, pady=self.padding, fill='both') + temperature_down_label.pack(side=tk.LEFT, pady=self.padding, fill='both') + self.temperature_down.pack(side=tk.LEFT, pady=self.padding, fill='both') + tank_pressure_frame.pack(side=tk.TOP, pady=self.padding, fill='both') tank_pressure_label.pack(side=tk.LEFT, pady=self.padding, fill='both') self.tank_pressure.pack(side=tk.LEFT, pady=self.padding, fill='both') From 968ce390674badd8b4dddc650a929778a3375e84 Mon Sep 17 00:00:00 2001 From: ola567 Date: Mon, 18 Mar 2024 08:04:41 +0100 Subject: [PATCH 10/71] changes --- tools/sensors_data_display_api/gui.py | 2 +- tools/sensors_data_display_api/test.py | 21 +++++---------------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 7aaf934b..4dfa266f 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -37,7 +37,7 @@ def __init__(self): # measurements temperature_up_frame = tk.Frame(self) temperature_up_label = tk.Label(temperature_up_frame, text='Temperature up:', width=label_width) - self.temperature_up = tk.Label(temperature_up_frame, text='0') + self.temperature_up = tk.Label(temperature_up_frame, text='0', width=label_width) self.temperature_up.config(state=tk.DISABLED) temperature_down_frame = tk.Frame(self) diff --git a/tools/sensors_data_display_api/test.py b/tools/sensors_data_display_api/test.py index 076f7cf9..d2d42f33 100644 --- a/tools/sensors_data_display_api/test.py +++ b/tools/sensors_data_display_api/test.py @@ -12,7 +12,9 @@ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.connect((HOST, PORT)) + i = 0 while True: + i += 1 # temperature up hdr = SomeIPHeader(514, 32769) payload = struct.pack('f', random.uniform(20, 25)) @@ -33,22 +35,9 @@ payload = struct.pack('f', random.uniform(1, 3.3)) msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(513, 0x8005) - payload = struct.pack('f', random.uniform(0, 3.3)) - msg = b''.join(hdr.get_some_ip_data_payload(payload)) - sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(514, 0x8006) - payload = struct.pack('f', random.uniform(0, 10000)) - msg = b''.join(hdr.get_some_ip_data_payload(payload)) - sock.sendto(msg, (HOST, PORT)) - hdr = SomeIPHeader(514, 0x8007) - payload = struct.pack('f', random.uniform(0, 20)) + "28-062018f00883".encode("UTF-8") - msg = b''.join(hdr.get_some_ip_data_payload(payload)) - sock.sendto(msg, (HOST, PORT)) - payload = struct.pack('f', random.uniform(0, 20)) + "28-3c29e381356d".encode("UTF-8") - msg = b''.join(hdr.get_some_ip_data_payload(payload)) - sock.sendto(msg, (HOST, PORT)) - payload = struct.pack('f', random.uniform(0, 20)) + ("28-3c01e076e761".encode("UTF-8")) + # main valve + hdr = SomeIPHeader(515, 32769) + payload = f"test{i}".encode("UTF-8") msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) time.sleep(0.1) From 74f1889b1b7c043c3e508edf7ad2c368cf0a0aa1 Mon Sep 17 00:00:00 2001 From: ola567 Date: Mon, 18 Mar 2024 08:05:47 +0100 Subject: [PATCH 11/71] changes --- tools/sensors_data_display_api/data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/sensors_data_display_api/data.py b/tools/sensors_data_display_api/data.py index 790fd49d..b6e650fd 100644 --- a/tools/sensors_data_display_api/data.py +++ b/tools/sensors_data_display_api/data.py @@ -10,6 +10,6 @@ def __init__(self): self.vent = None def is_None(self): - if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None: + if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None or self.main_valve is None: return True return False From 99f12dad70231fefddf755681ec3b26264251229 Mon Sep 17 00:00:00 2001 From: ola567 Date: Mon, 18 Mar 2024 08:52:24 +0100 Subject: [PATCH 12/71] changes --- tools/sensors_data_display_api/gui.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 4dfa266f..63b67075 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -198,5 +198,6 @@ def set_vent(self, value): def exit(self): self.stop_reading = True + self.saving = False self.data_reader_thread.join() self.destroy() From f52b3a3a649c129a288faa19996ff332f1e7f871 Mon Sep 17 00:00:00 2001 From: ola567 Date: Sat, 23 Mar 2024 14:01:16 +0100 Subject: [PATCH 13/71] changes --- tools/sensors_data_display_api/gui.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 63b67075..51f8805a 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -77,7 +77,7 @@ def __init__(self): # buttons start_stop_saving_button_frame = tk.Frame(self) - start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.start_save_to_file()) + self.start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.start_save_to_file()) stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.stop_save_to_file()) main_valve_button_frame = tk.Frame(self) @@ -138,7 +138,7 @@ def __init__(self): vent_set_0_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) start_stop_saving_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') - start_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + self.start_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) stop_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) launch_rocket_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') @@ -156,11 +156,13 @@ def read_data(self): def start_save_to_file(self): self.saving = True + self.start_saving_button.config(state=tk.DISABLED) self.saving_thread = threading.Thread(target=self._save_to_file) self.saving_thread.start() def stop_save_to_file(self): self.saving = False + self.start_saving_button.config(state=tk.NORMAL) self.saving_thread.join() def _save_to_file(self): @@ -171,7 +173,9 @@ def _save_to_file(self): writer.writerow(['TIMESTAMP', 'TEMPERATURE_UP', 'TEMPERATURE_DOWN', 'TEMPERATURE_MIDDLE', 'TANK_PRESSURE', 'JET_PRESSURE', 'PRESSURE_DIFFERENCE', 'MAIN_VALVE', 'VENT']) start = datetime.datetime.now() while self.saving: + print("SAVING....") if self.data_to_save.is_None() is False: + print("SAVED") timestamp = datetime.datetime.now() - start with open(filename, 'a', encoding='UTF-8', newline='') as csvFile: writer = csv.writer(csvFile, delimiter=";") @@ -186,6 +190,8 @@ def _save_to_file(self): self.data_to_save.pressure_difference = None self.data_to_save.main_valve = None self.data_to_save.vent = None + else: + print("NOT SAVED") def launch_rocket(self): pass From b8faba4db015d9f860af09aaa8a6debcc1ddc75e Mon Sep 17 00:00:00 2001 From: Mateusz Date: Wed, 17 Apr 2024 08:19:14 +0200 Subject: [PATCH 14/71] fix data type and delay --- tools/sensors_data_display_api/data_reader.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index 0c119301..ca78fb57 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -26,7 +26,7 @@ def _prepare_lookup_table(self): def read_data(self): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: try: - sock.bind(('127.0.0.1', 12345)) + sock.bind(('192.168.10.100', 10001)) except: logging.critical("Port is taken") while True: @@ -45,26 +45,26 @@ def read_data(self): # get data type data_type = self.lookup_table.get((service_id, method_id)) - print(f'service_id: {service_id}, method_id: {method_id}, payload: {payload}, data_ty[e: {data_type}') + print(f'service_id: {service_id}, method_id: {method_id}, payload: {payload}, data_type: {data_type}') if data_type is not None: if data_type == 'PC_APP/newTempEvent_1': # temperature up - temperature_up = struct.unpack('f', payload)[0] + temperature_up = float(struct.unpack(' Date: Wed, 17 Apr 2024 10:53:10 +0200 Subject: [PATCH 15/71] kill threads with app+ set ip,port from config --- tools/sensors_data_display_api/data_reader.py | 6 ++++-- tools/sensors_data_display_api/gui.py | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index ca78fb57..98d109fc 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -11,9 +11,11 @@ class DataReader: def __init__(self, gui): self.gui = gui self.data = 0 - with open('someip.json') as f: + with open('someip.json',encoding='UTF-8') as f: self.config = json.load(f) self.lookup_table = self._prepare_lookup_table() + self.ip = self.config["interface"][0].get('ip') + self.port = self.config["interface"][0].get("port") def _prepare_lookup_table(self): lookup_table = {} @@ -26,7 +28,7 @@ def _prepare_lookup_table(self): def read_data(self): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: try: - sock.bind(('192.168.10.100', 10001)) + sock.bind((self.ip,self.port)) except: logging.critical("Port is taken") while True: diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 51f8805a..5f1fdea3 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -151,13 +151,13 @@ def __init__(self): self.read_data() def read_data(self): - self.data_reader_thread = threading.Thread(target=self.data_reader.read_data) + self.data_reader_thread = threading.Thread(target=self.data_reader.read_data,daemon= True) self.data_reader_thread.start() def start_save_to_file(self): self.saving = True self.start_saving_button.config(state=tk.DISABLED) - self.saving_thread = threading.Thread(target=self._save_to_file) + self.saving_thread = threading.Thread(target=self._save_to_file,daemon=True) self.saving_thread.start() def stop_save_to_file(self): From c9c36adbc300afc5861caa55213ce4a196c2d887 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Wed, 17 Apr 2024 15:19:49 +0200 Subject: [PATCH 16/71] Init tests --- .gitignore | 5 +- tools/sensors_data_display_api/data.py | 16 +++---- tools/sensors_data_display_api/data_reader.py | 4 +- .../some_ip_header.py | 13 +++--- .../sensors_data_display_api/tests/runTest.sh | 3 ++ .../tests/test_data.py | 23 ++++++++++ .../tests/test_data_reader.py | 9 ++++ .../tests/test_gui.py | 8 ++++ .../tests/test_someiphdr.py | 46 +++++++++++++++++++ 9 files changed, 109 insertions(+), 18 deletions(-) create mode 100755 tools/sensors_data_display_api/tests/runTest.sh create mode 100644 tools/sensors_data_display_api/tests/test_data.py create mode 100644 tools/sensors_data_display_api/tests/test_data_reader.py create mode 100644 tools/sensors_data_display_api/tests/test_gui.py create mode 100644 tools/sensors_data_display_api/tests/test_someiphdr.py diff --git a/.gitignore b/.gitignore index d0d70aee..3b78ae97 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ bazel-* -.vscode \ No newline at end of file +.vscode +.pyc +__pycache__ +.coverage \ No newline at end of file diff --git a/tools/sensors_data_display_api/data.py b/tools/sensors_data_display_api/data.py index b6e650fd..c9b25a4c 100644 --- a/tools/sensors_data_display_api/data.py +++ b/tools/sensors_data_display_api/data.py @@ -1,13 +1,13 @@ class Data: def __init__(self): - self.temperature_up = None - self.temperature_middle = None - self.temperature_down = None - self.tank_pressure = None - self.jet_pressure = None - self.pressure_difference = None - self.main_valve = None - self.vent = None + self.temperature_up:float = None + self.temperature_middle:float = None + self.temperature_down:float = None + self.tank_pressure:float = None + self.jet_pressure:float = None + self.pressure_difference:float = None + self.main_valve:int = None + self.vent:int = None def is_None(self): if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None or self.main_valve is None: diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index 98d109fc..773049f8 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -8,10 +8,10 @@ class DataReader: - def __init__(self, gui): + def __init__(self, gui,filename = "someip.json"): self.gui = gui self.data = 0 - with open('someip.json',encoding='UTF-8') as f: + with open(filename, encoding='UTF-8') as f: self.config = json.load(f) self.lookup_table = self._prepare_lookup_table() self.ip = self.config["interface"][0].get('ip') diff --git a/tools/sensors_data_display_api/some_ip_header.py b/tools/sensors_data_display_api/some_ip_header.py index b17d841e..19e87cdb 100644 --- a/tools/sensors_data_display_api/some_ip_header.py +++ b/tools/sensors_data_display_api/some_ip_header.py @@ -1,6 +1,5 @@ from ctypes import sizeof, c_uint16, c_uint8, c_uint32, c_uint64 - class SomeIPHeader: def __str__(self) -> str: return f""" @@ -21,12 +20,12 @@ def __init__(self, service_id=None, methode_id=None, msg_typ=0x01) -> None: self.msg_typ = msg_typ self.msg_return = 0x00 - def read(self, hex) -> None: - self.service_id = int.from_bytes(hex[0:2], byteorder="big", signed=False) - self.methode_id = int.from_bytes(hex[2:4], byteorder="big", signed=False) - self.length = int.from_bytes(hex[4:8], byteorder="big", signed=False) - self.msg_typ = hex[14] - self.raw_payload = hex[16:] + def read(self, hex_data) -> None: + self.service_id = int.from_bytes(hex_data[0:2], byteorder="big", signed=False) + self.methode_id = int.from_bytes(hex_data[2:4], byteorder="big", signed=False) + self.length = int.from_bytes(hex_data[4:8], byteorder="big", signed=False) + self.msg_typ = hex_data[14] + self.raw_payload = hex_data[16:] def set_payload(self, payload) -> None: self.payload = payload diff --git a/tools/sensors_data_display_api/tests/runTest.sh b/tools/sensors_data_display_api/tests/runTest.sh new file mode 100755 index 00000000..29a57c48 --- /dev/null +++ b/tools/sensors_data_display_api/tests/runTest.sh @@ -0,0 +1,3 @@ +python3-coverage run -m unittest discover -s . + +python3-coverage report -m \ No newline at end of file diff --git a/tools/sensors_data_display_api/tests/test_data.py b/tools/sensors_data_display_api/tests/test_data.py new file mode 100644 index 00000000..fbe8ceca --- /dev/null +++ b/tools/sensors_data_display_api/tests/test_data.py @@ -0,0 +1,23 @@ +import unittest +import sys +from pathlib import Path + +sys.path.append(str(Path(__file__).resolve().parent.parent)) + +from data import Data + +class TestDataClass(unittest.TestCase): + def test_is_none(self): + data = Data() + self.assertTrue(data.is_None()) + data.jet_pressure = 12.2 + self.assertTrue(data.is_None()) + data.temperature_down=1 + data.temperature_middle=1 + data.temperature_up=1 + data.tank_pressure=1 + data.jet_pressure=1 + data.pressure_difference=1 + data.main_valve=1 + data.vent=1 + self.assertFalse(data.is_None()) diff --git a/tools/sensors_data_display_api/tests/test_data_reader.py b/tools/sensors_data_display_api/tests/test_data_reader.py new file mode 100644 index 00000000..ae65edd8 --- /dev/null +++ b/tools/sensors_data_display_api/tests/test_data_reader.py @@ -0,0 +1,9 @@ +import unittest +from data_reader import DataReader + +import sys +from pathlib import Path + +sys.path.append(str(Path(__file__).resolve().parent.parent)) + + diff --git a/tools/sensors_data_display_api/tests/test_gui.py b/tools/sensors_data_display_api/tests/test_gui.py new file mode 100644 index 00000000..fc99be33 --- /dev/null +++ b/tools/sensors_data_display_api/tests/test_gui.py @@ -0,0 +1,8 @@ +import unittest + +from gui import App + +import sys +from pathlib import Path + +sys.path.append(str(Path(__file__).resolve().parent.parent)) diff --git a/tools/sensors_data_display_api/tests/test_someiphdr.py b/tools/sensors_data_display_api/tests/test_someiphdr.py new file mode 100644 index 00000000..642dbfd3 --- /dev/null +++ b/tools/sensors_data_display_api/tests/test_someiphdr.py @@ -0,0 +1,46 @@ +import unittest +import sys +from pathlib import Path + +# Dodanie katalogu nadrzędnego do ścieżki +sys.path.append(str(Path(__file__).resolve().parent.parent)) + +from some_ip_header import SomeIPHeader + +class TestSomeIpHeader(unittest.TestCase): + def test_constructor(self): + hdr = SomeIPHeader(0x22,0x23,0x1) + self.assertEqual(hdr.service_id,0x22) + self.assertEqual(hdr.methode_id,0x23) + self.assertEqual(hdr.msg_typ,0x1) + self.assertEqual(hdr.payload,[]) + self.assertEqual(hdr.length,0x8) + self.assertEqual(hdr.client_id,0x1) + self.assertEqual(hdr.session,0x1) + self.assertEqual(hdr.msg_return,0x0) + self.assertEqual(str(hdr),""" + service_id:34 + method_id:35 + lenght:8 + msg_type:1 + payload:None""") + + def test_set_payload(self): + hdr = SomeIPHeader(0x01,0x01) + payload = [0,1,2,3,4] + hdr.set_payload(payload) + self.assertEqual(hdr.payload,payload) + self.assertEqual(hdr.length,0x8+len(payload)) + def test_read(self): + hdr = SomeIPHeader() + hex_data=b'\x00\x01\x00\x01\x00\x00\x00\x10\x00\x01\x00\x01\x01\x01\x01\x00\x12\x13' + hdr.read(hex_data) + self.assertEqual(hdr.service_id,0x01) + self.assertEqual(hdr.methode_id,0x01) + self.assertEqual(hdr.length,0x10) + self.assertEqual(hdr.msg_typ,0x1) + self.assertEqual(hdr.raw_payload,b"\x12\x13") + def test_get_some_ip_data(self): + data = b'\x00"\x00#\x00\x00\x00\x08\x00\x01\x00\x01\x01\x01\x01\x00' + hdr = SomeIPHeader(0x22,0x23,0x1) + self.assertEqual(b"".join(hdr.get_some_ip_data()),data) From e66d53bb4c61185af49e7d0d333dc9e2d1293938 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Wed, 17 Apr 2024 16:32:23 +0200 Subject: [PATCH 17/71] fix --- tools/sensors_data_display_api/data_reader.py | 2 +- tools/sensors_data_display_api/test.py | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index 773049f8..d3c2310e 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -66,7 +66,7 @@ def read_data(self): self.gui.temperature_middle.config(text=str(round(temperature_middle, 2))) elif data_type == 'PC_APP/newPressEvent': # tank pressure - tank_pressure = float(struct.unpack(' Date: Wed, 17 Apr 2024 17:59:04 +0200 Subject: [PATCH 18/71] finish tests --- tools/sensors_data_display_api/gui.py | 8 ++-- .../tests/someip.json | 41 +++++++++++++++++++ .../tests/test_data_reader.py | 12 ++++++ .../tests/test_gui.py | 35 ++++++++++++++++ .../tests/test_someiphdr.py | 13 ++++++ 5 files changed, 105 insertions(+), 4 deletions(-) create mode 100644 tools/sensors_data_display_api/tests/someip.json diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 5f1fdea3..3161a320 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -2,6 +2,7 @@ import datetime import threading import tkinter as tk +import logging from data import Data from data_reader import DataReader @@ -173,9 +174,9 @@ def _save_to_file(self): writer.writerow(['TIMESTAMP', 'TEMPERATURE_UP', 'TEMPERATURE_DOWN', 'TEMPERATURE_MIDDLE', 'TANK_PRESSURE', 'JET_PRESSURE', 'PRESSURE_DIFFERENCE', 'MAIN_VALVE', 'VENT']) start = datetime.datetime.now() while self.saving: - print("SAVING....") + logging.info("SAVING....") if self.data_to_save.is_None() is False: - print("SAVED") + logging.info("SAVED") timestamp = datetime.datetime.now() - start with open(filename, 'a', encoding='UTF-8', newline='') as csvFile: writer = csv.writer(csvFile, delimiter=";") @@ -191,7 +192,7 @@ def _save_to_file(self): self.data_to_save.main_valve = None self.data_to_save.vent = None else: - print("NOT SAVED") + logging.info("NOT SAVED") def launch_rocket(self): pass @@ -205,5 +206,4 @@ def set_vent(self, value): def exit(self): self.stop_reading = True self.saving = False - self.data_reader_thread.join() self.destroy() diff --git a/tools/sensors_data_display_api/tests/someip.json b/tools/sensors_data_display_api/tests/someip.json new file mode 100644 index 00000000..fbdc2bd3 --- /dev/null +++ b/tools/sensors_data_display_api/tests/someip.json @@ -0,0 +1,41 @@ +{ + "service_id": 1, + "interface": [ + { + "ip": "127.0.0.1", + "port": 10101 + } + ], + "pub_methods": {}, + "pub_event": {}, + "req_methods": { + "PC_APP/setServoValue": { + "service_id": 515, + "method_id": 1 + }, + "PC_APP/readServoValue": { + "service_id": 515, + "method_id": 2 + } + }, + "req_events": { + "PC_APP/servoStatusEvent": { + "service_id": 515, + "event_id": 32769 + }, + "PC_APP/newTempEvent_1": { + "service_id": 514, + "event_id": 32769 + } + }, + "db": { + "515": { + "ip": "192.168.10.101", + "port": 1515 + }, + "514": { + "ip": "192.168.10.101", + "port": 1514 + } + } +} \ No newline at end of file diff --git a/tools/sensors_data_display_api/tests/test_data_reader.py b/tools/sensors_data_display_api/tests/test_data_reader.py index ae65edd8..ff1fd195 100644 --- a/tools/sensors_data_display_api/tests/test_data_reader.py +++ b/tools/sensors_data_display_api/tests/test_data_reader.py @@ -1,5 +1,6 @@ import unittest from data_reader import DataReader +from unittest.mock import MagicMock, patch import sys from pathlib import Path @@ -7,3 +8,14 @@ sys.path.append(str(Path(__file__).resolve().parent.parent)) +class TestDataReader(unittest.TestCase): + def test_init(self): + dr = DataReader(None,"someip.json") + self.assertEqual(dr.data,0) + self.assertEqual(dr.ip,"127.0.0.1") + self.assertEqual(dr.port,10101) + def test_prepere_lookup_table(self): + dr = DataReader(None,"someip.json") + data = {(515, 32769): 'PC_APP/servoStatusEvent', + (514, 32769): 'PC_APP/newTempEvent_1'} + self.assertEqual(dr.lookup_table, data) \ No newline at end of file diff --git a/tools/sensors_data_display_api/tests/test_gui.py b/tools/sensors_data_display_api/tests/test_gui.py index fc99be33..4fbfd615 100644 --- a/tools/sensors_data_display_api/tests/test_gui.py +++ b/tools/sensors_data_display_api/tests/test_gui.py @@ -1,8 +1,43 @@ import unittest from gui import App +import logging import sys from pathlib import Path +import tkinter as tk +from unittest.mock import MagicMock sys.path.append(str(Path(__file__).resolve().parent.parent)) + +logging.disable(60) + +class TestAppInitialization(unittest.TestCase): + + def setUp(self): + self.app = App() + + def test_window_properties(self): + self.assertEqual(self.app.title(), "Engine") + self.assertEqual(self.app.window_width, 600) + self.assertEqual(self.app.window_height, 600) + + def test_elements_existence(self): + self.assertIsNotNone(self.app.temperature_up) + self.assertIsNotNone(self.app.temperature_down) + self.assertIsNotNone(self.app.temperature_middle) + self.assertIsNotNone(self.app.tank_pressure) + self.assertIsNotNone(self.app.jet_pressure) + self.assertIsNotNone(self.app.pressure_difference) + self.assertIsNotNone(self.app.main_valve) + self.assertIsNotNone(self.app.vent) + self.assertIsNotNone(self.app.start_saving_button) + + def test_start_to_save_file(self): + self.app.start_save_to_file() + self.assertTrue(self.app.saving_thread.is_alive()) + + def test_stop_save_to_file(self): + self.app.start_save_to_file() + self.app.stop_save_to_file() + self.assertFalse(self.app.saving_thread.is_alive()) diff --git a/tools/sensors_data_display_api/tests/test_someiphdr.py b/tools/sensors_data_display_api/tests/test_someiphdr.py index 642dbfd3..7d89a3bb 100644 --- a/tools/sensors_data_display_api/tests/test_someiphdr.py +++ b/tools/sensors_data_display_api/tests/test_someiphdr.py @@ -1,6 +1,7 @@ import unittest import sys from pathlib import Path +import struct # Dodanie katalogu nadrzędnego do ścieżki sys.path.append(str(Path(__file__).resolve().parent.parent)) @@ -44,3 +45,15 @@ def test_get_some_ip_data(self): data = b'\x00"\x00#\x00\x00\x00\x08\x00\x01\x00\x01\x01\x01\x01\x00' hdr = SomeIPHeader(0x22,0x23,0x1) self.assertEqual(b"".join(hdr.get_some_ip_data()),data) + def test_get_some_ip_data2(self): + data = b'\x00"\x00#\x00\x00\x00\n\x00\x01\x00\x01\x01\x01\x01\x00{\x00' + payload = struct.pack('H',123) + hdr = SomeIPHeader(0x22,0x23,0x1) + hdr.set_payload(payload) + self.assertEqual(b"".join(hdr.get_some_ip_data()),data) + def test_get_some_ip_data_payload(self): + data = b'\x00"\x00#\x00\x00\x00\n\x00\x01\x00\x01\x01\x01\x01\x00{\x00' + payload = struct.pack('H',123) + hdr = SomeIPHeader(0x22,0x23,0x1) + hdr.set_payload(payload) + self.assertEqual(b"".join(hdr.get_some_ip_data_payload(payload)),data) From 2cb271810357c9487178d92ba4a077582d9a548f Mon Sep 17 00:00:00 2001 From: ola567 Date: Wed, 17 Apr 2024 18:55:58 +0200 Subject: [PATCH 19/71] disable stop saaving button --- tools/sensors_data_display_api/gui.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 3161a320..3578175a 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -79,7 +79,7 @@ def __init__(self): # buttons start_stop_saving_button_frame = tk.Frame(self) self.start_saving_button = tk.Button(start_stop_saving_button_frame, text="Start saving data", command=lambda: self.start_save_to_file()) - stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.stop_save_to_file()) + self.stop_saving_button = tk.Button(start_stop_saving_button_frame, text="Stop saving data", command=lambda: self.stop_save_to_file()) main_valve_button_frame = tk.Frame(self) main_valve_set_1_button = tk.Button(main_valve_button_frame, text="Main valve: set 1", command=lambda: self.set_main_valve(value=1)) @@ -140,7 +140,8 @@ def __init__(self): start_stop_saving_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') self.start_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) - stop_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + self.stop_saving_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) + self.stop_saving_button.config(state=tk.DISABLED) launch_rocket_button_frame.pack(side=tk.TOP, pady=button_padding, fill='both') launch_rocket_button.pack(side=tk.LEFT, pady=button_padding, fill='both', expand=True) @@ -152,18 +153,20 @@ def __init__(self): self.read_data() def read_data(self): - self.data_reader_thread = threading.Thread(target=self.data_reader.read_data,daemon= True) + self.data_reader_thread = threading.Thread(target=self.data_reader.read_data, daemon=True) self.data_reader_thread.start() def start_save_to_file(self): self.saving = True self.start_saving_button.config(state=tk.DISABLED) - self.saving_thread = threading.Thread(target=self._save_to_file,daemon=True) + self.stop_saving_button.config(state=tk.NORMAL) + self.saving_thread = threading.Thread(target=self._save_to_file, daemon=True) self.saving_thread.start() def stop_save_to_file(self): self.saving = False self.start_saving_button.config(state=tk.NORMAL) + self.stop_saving_button.config(state=tk.DISABLED) self.saving_thread.join() def _save_to_file(self): From 6a445091fd5feb9580154ced54c0a1e51a70f19d Mon Sep 17 00:00:00 2001 From: ola567 Date: Wed, 17 Apr 2024 20:50:43 +0200 Subject: [PATCH 20/71] change saving to file --- tools/sensors_data_display_api/data.py | 21 ++++++++++--------- tools/sensors_data_display_api/data_reader.py | 9 ++++++-- tools/sensors_data_display_api/gui.py | 15 ++++++++----- tools/sensors_data_display_api/test.py | 6 ++++++ .../tests/test_data.py | 6 +++--- 5 files changed, 37 insertions(+), 20 deletions(-) diff --git a/tools/sensors_data_display_api/data.py b/tools/sensors_data_display_api/data.py index c9b25a4c..ee726d04 100644 --- a/tools/sensors_data_display_api/data.py +++ b/tools/sensors_data_display_api/data.py @@ -1,15 +1,16 @@ class Data: def __init__(self): - self.temperature_up:float = None - self.temperature_middle:float = None - self.temperature_down:float = None - self.tank_pressure:float = None - self.jet_pressure:float = None - self.pressure_difference:float = None - self.main_valve:int = None - self.vent:int = None + self.temperature_up: float = None + self.temperature_middle: float = None + self.temperature_down: float = None + self.tank_pressure: float = None + self.pressure_difference: float = None + self.main_valve: int = None + # not given as for now + self.jet_pressure: float = None + self.vent: int = None - def is_None(self): - if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None or self.main_valve is None: + def is_none(self): + if self.temperature_up is None or self.temperature_middle is None or self.temperature_down is None or self.tank_pressure is None or self.main_valve is None or self.pressure_difference is None: return True return False diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index d3c2310e..3bae30eb 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -8,7 +8,7 @@ class DataReader: - def __init__(self, gui,filename = "someip.json"): + def __init__(self, gui, filename="someip.json"): self.gui = gui self.data = 0 with open(filename, encoding='UTF-8') as f: @@ -28,7 +28,7 @@ def _prepare_lookup_table(self): def read_data(self): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: try: - sock.bind((self.ip,self.port)) + sock.bind((self.ip, self.port)) except: logging.critical("Port is taken") while True: @@ -74,6 +74,11 @@ def read_data(self): main_valve = payload.decode('UTF-8', errors='ignore') self.gui.data_to_save.main_valve = main_valve self.gui.main_valve.config(text=main_valve) + elif data_type == 'PC_APP/newDPressEvent': + # pressure difference + pressure_difference = float(struct.unpack('f', payload)[0]) + self.gui.data_to_save.pressure_difference = pressure_difference + self.gui.pressure_difference.config(text=str(round(pressure_difference, 2))) else: print("No data") time.sleep(0.01) diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/gui.py index 3578175a..898722b9 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/gui.py @@ -1,6 +1,7 @@ import csv import datetime import threading +import time import tkinter as tk import logging @@ -34,6 +35,7 @@ def __init__(self): self.data_reader_thread = None self.saving_thread = None self.data_to_save = Data() + self.collection_time = 10 # measurements temperature_up_frame = tk.Frame(self) @@ -173,16 +175,19 @@ def _save_to_file(self): timestamp = datetime.datetime.now() filename = f"data_{timestamp.hour}_{timestamp.minute}_{timestamp.second}.csv" with open(file=filename, mode='w', encoding='UTF-8') as csvFile: - writer = csv.writer(csvFile, delimiter=";") + writer = csv.writer(csvFile, delimiter=",") writer.writerow(['TIMESTAMP', 'TEMPERATURE_UP', 'TEMPERATURE_DOWN', 'TEMPERATURE_MIDDLE', 'TANK_PRESSURE', 'JET_PRESSURE', 'PRESSURE_DIFFERENCE', 'MAIN_VALVE', 'VENT']) - start = datetime.datetime.now() + start = time.time() while self.saving: logging.info("SAVING....") - if self.data_to_save.is_None() is False: + collection_time_difference = time.time() - start + logging.info(f"Collection time difference: {collection_time_difference}") + if (self.data_to_save.is_none() is False) or collection_time_difference > self.collection_time: logging.info("SAVED") - timestamp = datetime.datetime.now() - start + timestamp = datetime.datetime.now() + start = time.time() with open(filename, 'a', encoding='UTF-8', newline='') as csvFile: - writer = csv.writer(csvFile, delimiter=";") + writer = csv.writer(csvFile, delimiter=",") writer.writerow([timestamp, self.data_to_save.temperature_up, self.data_to_save.temperature_down, self.data_to_save.temperature_middle, self.data_to_save.tank_pressure, self.data_to_save.jet_pressure, self.data_to_save.pressure_difference, self.data_to_save.main_valve, self.data_to_save.vent]) diff --git a/tools/sensors_data_display_api/test.py b/tools/sensors_data_display_api/test.py index 4eb280d7..7a20c446 100644 --- a/tools/sensors_data_display_api/test.py +++ b/tools/sensors_data_display_api/test.py @@ -42,4 +42,10 @@ payload = f"test{i}".encode("UTF-8") msg = b''.join(hdr.get_some_ip_data_payload(payload)) sock.sendto(msg, (HOST, PORT)) + # pressure difference + hdr = SomeIPHeader(514, 32774) + payload = struct.pack('f', random.uniform(20, 25)) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + sock.sendto(msg, (HOST, PORT)) + time.sleep(0.1) diff --git a/tools/sensors_data_display_api/tests/test_data.py b/tools/sensors_data_display_api/tests/test_data.py index fbe8ceca..ba10c10b 100644 --- a/tools/sensors_data_display_api/tests/test_data.py +++ b/tools/sensors_data_display_api/tests/test_data.py @@ -9,9 +9,9 @@ class TestDataClass(unittest.TestCase): def test_is_none(self): data = Data() - self.assertTrue(data.is_None()) + self.assertTrue(data.is_none()) data.jet_pressure = 12.2 - self.assertTrue(data.is_None()) + self.assertTrue(data.is_none()) data.temperature_down=1 data.temperature_middle=1 data.temperature_up=1 @@ -20,4 +20,4 @@ def test_is_none(self): data.pressure_difference=1 data.main_valve=1 data.vent=1 - self.assertFalse(data.is_None()) + self.assertFalse(data.is_none()) From 32cb63a6291c5d493c5a8f7ee053d9b21f4d3411 Mon Sep 17 00:00:00 2001 From: ola567 Date: Wed, 17 Apr 2024 22:49:30 +0200 Subject: [PATCH 21/71] changes --- .../{gui.py => app.py} | 20 +++++++++++++------ tools/sensors_data_display_api/data_sender.py | 19 ++++++++++++++++++ tools/sensors_data_display_api/main.py | 2 +- .../some_ip_header.py | 1 + .../tests/test_gui.py | 2 +- 5 files changed, 36 insertions(+), 8 deletions(-) rename tools/sensors_data_display_api/{gui.py => app.py} (93%) create mode 100644 tools/sensors_data_display_api/data_sender.py diff --git a/tools/sensors_data_display_api/gui.py b/tools/sensors_data_display_api/app.py similarity index 93% rename from tools/sensors_data_display_api/gui.py rename to tools/sensors_data_display_api/app.py index 898722b9..79842e52 100644 --- a/tools/sensors_data_display_api/gui.py +++ b/tools/sensors_data_display_api/app.py @@ -3,10 +3,12 @@ import threading import time import tkinter as tk +from tkinter import messagebox import logging from data import Data from data_reader import DataReader +from data_sender import DataSender class App(tk.Tk): @@ -36,6 +38,7 @@ def __init__(self): self.saving_thread = None self.data_to_save = Data() self.collection_time = 10 + self.data_sender = DataSender() # measurements temperature_up_frame = tk.Frame(self) @@ -92,8 +95,8 @@ def __init__(self): vent_set_0_button = tk.Button(vent_button_frame, text="Vent: set 0", command=lambda: self.set_vent(value=0)) launch_rocket_button_frame = tk.Frame(self) - launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Launch rocket", command=lambda: self.launch_rocket()) - stop_launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Stop launch rocket", command=lambda: self.stop_launch_rocket()) + launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Launch rocket", command=lambda: self.launch_rocket(value=1)) + stop_launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Stop launch rocket", command=lambda: self.launch_rocket(value=0)) exit_button = tk.Button(self, text="Exit", command=lambda: self.exit()) @@ -202,14 +205,19 @@ def _save_to_file(self): else: logging.info("NOT SAVED") - def launch_rocket(self): - pass + def launch_rocket(self, value): + if value == 1: + result = messagebox.askyesno('Launch rocket', 'Are you sure you want to launch rocket?') + if result: + self.data_sender.send_data(value=value, service_id=518, method_id=1) + else: + self.data_sender.send_data(value=value, service_id=518, method_id=1) def set_main_valve(self, value): - pass + self.data_sender.send_data(value=value, service_id=515, method_id=1) def set_vent(self, value): - pass + self.data_sender.send_data(value=value, service_id=515, method_id=3) def exit(self): self.stop_reading = True diff --git a/tools/sensors_data_display_api/data_sender.py b/tools/sensors_data_display_api/data_sender.py new file mode 100644 index 00000000..fe19e735 --- /dev/null +++ b/tools/sensors_data_display_api/data_sender.py @@ -0,0 +1,19 @@ +import socket +import struct + +from some_ip_header import SomeIPHeader + + +class DataSender: + def __init__(self): + self.receiver_host = '127.0.0.1' + self.receiver_port = 10101 + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.socket.connect((self.receiver_host, self.receiver_port)) + + def send_data(self, value: int, service_id: int, method_id: int): + hdr = SomeIPHeader(service_id, method_id) + payload = struct.pack('H', value) + msg = b''.join(hdr.get_some_ip_data_payload(payload)) + self.socket.sendto(msg, (self.receiver_host, self.receiver_port)) + print("DATA SENT") diff --git a/tools/sensors_data_display_api/main.py b/tools/sensors_data_display_api/main.py index ffbf2a86..ceac8dad 100644 --- a/tools/sensors_data_display_api/main.py +++ b/tools/sensors_data_display_api/main.py @@ -1,4 +1,4 @@ -from gui import App +from app import App if __name__ == '__main__': app = App() diff --git a/tools/sensors_data_display_api/some_ip_header.py b/tools/sensors_data_display_api/some_ip_header.py index 19e87cdb..5fcb0c7e 100644 --- a/tools/sensors_data_display_api/some_ip_header.py +++ b/tools/sensors_data_display_api/some_ip_header.py @@ -1,5 +1,6 @@ from ctypes import sizeof, c_uint16, c_uint8, c_uint32, c_uint64 + class SomeIPHeader: def __str__(self) -> str: return f""" diff --git a/tools/sensors_data_display_api/tests/test_gui.py b/tools/sensors_data_display_api/tests/test_gui.py index 4fbfd615..3ebaf9e6 100644 --- a/tools/sensors_data_display_api/tests/test_gui.py +++ b/tools/sensors_data_display_api/tests/test_gui.py @@ -1,6 +1,6 @@ import unittest -from gui import App +from app import App import logging import sys From 7bf008dd226d01cb64eafca685891a8096cf5b1a Mon Sep 17 00:00:00 2001 From: Mateusz Date: Thu, 18 Apr 2024 11:31:43 +0200 Subject: [PATCH 22/71] fix config --- tools/sensors_data_display_api/data_reader.py | 2 +- tools/sensors_data_display_api/someip.json | 76 ++++++++++++------- 2 files changed, 51 insertions(+), 27 deletions(-) diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index 3bae30eb..c469b3bd 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -64,7 +64,7 @@ def read_data(self): temperature_middle = float(struct.unpack(' Date: Tue, 7 May 2024 10:11:32 +0200 Subject: [PATCH 23/71] test1 --- .github/workflows/python_syntax.yaml | 56 ++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 .github/workflows/python_syntax.yaml diff --git a/.github/workflows/python_syntax.yaml b/.github/workflows/python_syntax.yaml new file mode 100644 index 00000000..829b1397 --- /dev/null +++ b/.github/workflows/python_syntax.yaml @@ -0,0 +1,56 @@ +name: Python Pylint Analysis + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + pylint-analysis: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pylint + + - name: Run pylint and count errors + id: pylint + run: | + # Lista folderów, w których przeprowadzana jest analiza Pylint + folders=("tools") + + total_errors=0 + + for folder in "${folders[@]}"; do + find "$folder" -type f -name "*.py" | while read -r file; do + errors=$(pylint --output-format=text "$file" | grep -c '^\*\*\*') + total_errors=$((total_errors + errors)) + done + done + + echo "::set-output name=total_errors::$total_errors" + + - name: Display total errors + run: | + echo "Total errors: ${{ steps.pylint.outputs.total_errors }}" + + - name: Check for errors and return error if any + run: | + total_errors=${{ steps.pylint.outputs.total_errors }} + if [ "$total_errors" -gt 0 ]; then + echo "Errors found. Exiting with status code 1." + exit 1 + fi From 43574db35efc628baa9a7deeeeadb5477f8413e1 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Fri, 12 Jan 2024 21:08:11 +0100 Subject: [PATCH 24/71] SOMEIP_DATABASE: adding json parser - Added methods support and events - Added job to build cpus --- .github/workflows/build_cpu.yaml | 43 ++++++++ .github/workflows/build_cpu_linux.yaml | 42 ++++++++ apps/example/config/BUILD | 5 + apps/example/config/out.json | 67 +++++++++++++ apps/example/main2.cc | 19 ++++ communication-core/database/BUILD | 17 ---- communication-core/database/Idatabase.h | 34 ------- communication-core/database/app_element.h | 91 ----------------- communication-core/database/database.cc | 38 ------- communication-core/database/database.h | 38 ------- .../database/database_element.h | 31 ------ communication-core/database/event_element.h | 37 ------- communication-core/database/method_element.h | 36 ------- .../database/net_interface_element.h | 61 ------------ .../database/req_event_element.h | 30 ------ communication-core/database/service_element.h | 52 ---------- communication-core/json-parser/BUILD | 12 ++- .../json-parser/database_json_parser.h | 65 +++++++++--- communication-core/json-parser/json_parser.cc | 2 +- communication-core/json-parser/json_parser.h | 2 +- communication-core/someip-database/BUILD | 0 communication-core/someip-database/code/BUILD | 53 ++++++++++ .../someip-database/code/config_db.cc | 41 ++++++++ .../someip-database/code/config_db.h | 46 +++++++++ .../someip-database/code/config_db_parser.h | 99 +++++++++++++++++++ .../code/config_someip_provide.h | 15 +++ .../someip-database/code/database.cc | 63 ++++++++++++ .../someip-database/code/database.h | 42 ++++++++ .../someip-database/code/database_parser.h | 95 ++++++++++++++++++ .../someip-database/code/endpoint.h | 34 +++++++ .../someip-database/code/interface.h | 38 +++++++ .../someip-database/code/service.h | 39 ++++++++ communication-core/someip-database/test/BUILD | 24 +++++ .../test/config_db_parser_test.cc | 82 +++++++++++++++ .../test/database_parser_test.cc | 62 ++++++++++++ .../someip-database/test/resource/BUILD | 8 ++ .../test/resource/app_someip1.json | 33 +++++++ .../test/resource/app_someip2.json | 35 +++++++ deployment | 2 +- diag/base/controller/BUILD | 3 - diag/base/controller/diag_controller.cc | 57 ++++++----- diag/base/controller/diag_controller.h | 12 ++- diag/base/controller/diag_transfer.h | 8 +- diag/base/controller/idiag_controller.h | 10 +- diag/base/data/BUILD | 1 - diag/base/data/parser.cc | 12 +-- diag/base/data/parser.h | 6 +- diag/base/factories/BUILD | 1 - diag/base/factories/diag_data_factory.cc | 48 +++++---- diag/base/factories/diag_data_factory.h | 10 +- diag/base/tests/test_diag_data_factory.cc | 16 +-- diag/base/tests/test_parser.cc | 24 ++--- diag/dtc/factories/BUILD | 1 - 53 files changed, 1154 insertions(+), 588 deletions(-) create mode 100644 .github/workflows/build_cpu.yaml create mode 100644 .github/workflows/build_cpu_linux.yaml create mode 100644 apps/example/config/BUILD create mode 100644 apps/example/config/out.json create mode 100644 apps/example/main2.cc delete mode 100644 communication-core/database/BUILD delete mode 100644 communication-core/database/Idatabase.h delete mode 100644 communication-core/database/app_element.h delete mode 100644 communication-core/database/database.cc delete mode 100644 communication-core/database/database.h delete mode 100644 communication-core/database/database_element.h delete mode 100644 communication-core/database/event_element.h delete mode 100644 communication-core/database/method_element.h delete mode 100644 communication-core/database/net_interface_element.h delete mode 100644 communication-core/database/req_event_element.h delete mode 100644 communication-core/database/service_element.h create mode 100644 communication-core/someip-database/BUILD create mode 100644 communication-core/someip-database/code/BUILD create mode 100644 communication-core/someip-database/code/config_db.cc create mode 100644 communication-core/someip-database/code/config_db.h create mode 100644 communication-core/someip-database/code/config_db_parser.h create mode 100644 communication-core/someip-database/code/config_someip_provide.h create mode 100644 communication-core/someip-database/code/database.cc create mode 100644 communication-core/someip-database/code/database.h create mode 100644 communication-core/someip-database/code/database_parser.h create mode 100644 communication-core/someip-database/code/endpoint.h create mode 100644 communication-core/someip-database/code/interface.h create mode 100644 communication-core/someip-database/code/service.h create mode 100644 communication-core/someip-database/test/BUILD create mode 100644 communication-core/someip-database/test/config_db_parser_test.cc create mode 100644 communication-core/someip-database/test/database_parser_test.cc create mode 100644 communication-core/someip-database/test/resource/BUILD create mode 100755 communication-core/someip-database/test/resource/app_someip1.json create mode 100755 communication-core/someip-database/test/resource/app_someip2.json diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml new file mode 100644 index 00000000..3002c588 --- /dev/null +++ b/.github/workflows/build_cpu.yaml @@ -0,0 +1,43 @@ +name: Build deployments (BeagleBone config) + +on: + pull_request: + types: [labeled, synchronize] + push: + branches: + - master + +jobs: + build: + + runs-on: ubuntu-latest + steps: + - name: check lable + id: pr-labels + uses: joerick/pr-labels-action@v1.0.8 + + - name: Checkout Repository + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + uses: actions/checkout@v2 + with: + submodules: 'true' + ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} + - name: Install bazel + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + run: | + sudo apt install apt-transport-https curl gnupg + sudo add-apt-repository ppa:ubuntu-toolchain-r/ppa -y + sudo apt update + sudo apt install g++-13 gcc-13 + curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg + sudo mv bazel.gpg /etc/apt/trusted.gpg.d/ + echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list + sudo apt update && sudo apt install bazel-5.4.1 + + - name: Run build engine computer + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + run: | + bazel build --config=bbb //deployment/cpu/ec:pkg + + + \ No newline at end of file diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml new file mode 100644 index 00000000..42eba72f --- /dev/null +++ b/.github/workflows/build_cpu_linux.yaml @@ -0,0 +1,42 @@ +name: Build deployments (Linux config) + +on: + pull_request: + types: [labeled, synchronize] + push: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: check lable + id: pr-labels + uses: joerick/pr-labels-action@v1.0.8 + + - name: Checkout Repository + if: contains(steps.pr-labels.outputs.labels, 'check') + uses: actions/checkout@v2 + with: + submodules: 'true' + ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} + + - name: Install bazel + if: contains(steps.pr-labels.outputs.labels, 'check') + run: | + sudo apt install apt-transport-https curl gnupg + sudo add-apt-repository ppa:ubuntu-toolchain-r/ppa -y + sudo apt update + sudo apt install g++-13 gcc-13 + curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg + sudo mv bazel.gpg /etc/apt/trusted.gpg.d/ + echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list + sudo apt update && sudo apt install bazel-5.4.1 + + - name: Run build engine computer + if: contains(steps.pr-labels.outputs.labels, 'check') + run: | + bazel build //deployment/cpu/ec:pkg + + \ No newline at end of file diff --git a/apps/example/config/BUILD b/apps/example/config/BUILD new file mode 100644 index 00000000..5e12dbbc --- /dev/null +++ b/apps/example/config/BUILD @@ -0,0 +1,5 @@ +filegroup( + name = "json", + srcs = ["out.json"], + visibility = ["//apps/example:__subpackages__"], +) \ No newline at end of file diff --git a/apps/example/config/out.json b/apps/example/config/out.json new file mode 100644 index 00000000..81d9dccf --- /dev/null +++ b/apps/example/config/out.json @@ -0,0 +1,67 @@ +{ + "name": "mainApp", + "service_id": 2, + "interface": { + "ip": "192.168.1.3", + "ipc": "SIMBA.DIAG.0x0103", + "port": 1003 + }, + "req_events": [ + { + "name": "engineApp/pressure", + "service_id": 1, + "event_id": 1 + }, + { + "name": "engineApp/deltaPress", + "service_id": 1, + "event_id": 2 + } + ], + "pub_events": { + "mainApp/status": { + "event_id": 4, + "subscribers": [ + { + "service_id": 1 + }, + { + "service_id": 3 + } + ] + } + }, + "req_methods": { + "engineApp/startEngine": { + "service_id": 1, + "method_id": 1 + }, + "engineApp/startTank": { + "service_id": 1, + "method_id": 2 + } + }, + "pub_methods": [ + { + "method_id": 2, + "name": "callGSE" + } + ], + "db": { + "1": { + "name": "app1", + "ip": "", + "ipc": "SIMBA.DIAG.0x0101", + "port": 0 + }, + "3": { + "name": "app2", + "ip": "192.168.11.22", + "ipc": "", + "port": 5055 + } + }, + "conf": { + "lvl": "Debug" + } +} \ No newline at end of file diff --git a/apps/example/main2.cc b/apps/example/main2.cc new file mode 100644 index 00000000..4d80663a --- /dev/null +++ b/apps/example/main2.cc @@ -0,0 +1,19 @@ +/** + * @file main2.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-01-12 + * + * @copyright Copyright (c) 2024 + * + */ +#include "communication-core/database/database.h" +#include "communication-core/json-parser/database_json_parser.h" +int main(int argc, char const *argv[]) { + simba::database::Database db{}; + + simba::database::json::DatabaseJsonParser::LoadJson( + db, "apps/example/config/out.json"); + return 0; +} diff --git a/communication-core/database/BUILD b/communication-core/database/BUILD deleted file mode 100644 index 4345698d..00000000 --- a/communication-core/database/BUILD +++ /dev/null @@ -1,17 +0,0 @@ -cc_library( - name = "DatabaseLib", - srcs = ["database.cc"], - hdrs = [ - "Idatabase.h", - "database.h", - "database_element.h", - "req_event_element.h", - "event_element.h", - "method_element.h", - "net_interface_element.h", - "service_element.h", - "app_element.h" - ], - visibility = ["//communication-core:__subpackages__"], - deps = ["//core"], -) diff --git a/communication-core/database/Idatabase.h b/communication-core/database/Idatabase.h deleted file mode 100644 index 219b91a0..00000000 --- a/communication-core/database/Idatabase.h +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @file database.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief This file define interface for database - * @version 0.1 - * @date 2023-10-23 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_IDATABASE_H_ -#define COMMUNICATION_CORE_DATABASE_IDATABASE_H_ -#include -#include - -#include "communication-core/database/database_element.h" -#include "core/results/result.h" - -namespace simba { -namespace database { -class IDatabase { - private: - public: - virtual simba::core::Result GetService( - const std::uint16_t service_id) = 0; - virtual bool ServiceExist(const std::uint16_t service_id) = 0; - virtual void AddService(const std::uint16_t service_id, - const DatabaseElement& element) = 0; - virtual DatabaseElement CreatDatabaseElement(const std::string& ip, - const int16_t port) = 0; -}; -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_IDATABASE_H_ diff --git a/communication-core/database/app_element.h b/communication-core/database/app_element.h deleted file mode 100644 index a64727b7..00000000 --- a/communication-core/database/app_element.h +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file app_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-10 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_APP_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_APP_ELEMENT_H_ - -#include -#include - -#include "database/event_element.h" -#include "database/method_element.h" -#include "database/net_interface_element.h" -#include "database/req_event_element.h" -#include "unordered_map" - -namespace simba { -namespace database { -namespace objects { -class AppElement { - private: - std::string name; - NetInterfaceElement net_interface; - std::unordered_map pub_methods; - std::unordered_map req_events; - std::unordered_map pub_events; - std::unordered_map db; - std::unordered_map conf; - - public: - AppElement( - const std::string& app_name, - const NetInterfaceElement& net_interface_element, - const std::unordered_map& pub_methods_map, - const std::unordered_map& req_events_map, - const std::unordered_map& pub_events_map, - const std::unordered_map& db_map, - const std::unordered_map& conf_map) - : name(app_name), - net_interface(net_interface_element), - pub_methods(pub_methods_map), - req_events(req_events_map), - pub_events(pub_events_map), - db(db_map), - conf(conf_map) {} - ~AppElement() = default; - friend std::ostream& operator<<(std::ostream& os, - const AppElement& app_element); -}; - -std::ostream& operator<<(std::ostream& os, const AppElement& app_element) { - os << "App Name: " << app_element.name << "\n"; - os << "Net Interface: " << app_element.net_interface << "\n"; - - os << "Pub Methods:\n"; - for (const auto& entry : app_element.pub_methods) { - os << " " << entry.first << ": " << entry.second << "\n"; - } - - os << "Req Events:\n"; - for (const auto& entry : app_element.req_events) { - os << " " << entry.first << ": " << entry.second << "\n"; - } - - os << "Pub Events:\n"; - for (const auto& entry : app_element.pub_events) { - os << " " << entry.first << ": " << entry.second << "\n"; - } - - os << "Database Methods:\n"; - for (const auto& entry : app_element.db) { - os << " " << entry.first << ": " << entry.second << "\n"; - } - - os << "Configuration:\n"; - for (const auto& entry : app_element.conf) { - os << " " << entry.first << ": " << entry.second << "\n"; - } - - return os; -} -} // namespace objects -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_APP_ELEMENT_H_ diff --git a/communication-core/database/database.cc b/communication-core/database/database.cc deleted file mode 100644 index bdca4674..00000000 --- a/communication-core/database/database.cc +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file database.cc - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-11-13 - * - * @copyright Copyright (c) 2023 - * - */ -#include "database.h" -namespace simba { -namespace database { -simba::core::Result Database::GetService( - const std::uint16_t service_id) { - auto obj = this->db.find(service_id); - if (obj == this->db.end()) { - return simba::core::Result{}; - } - return simba::core::Result{obj->second}; -} -bool Database::ServiceExist(const std::uint16_t service_id) { - const auto obj = this->db.find(service_id); - return obj != this->db.end(); -} -void Database::AddService(const std::uint16_t service_id, - const DatabaseElement& element) { - if (this->ServiceExist(service_id)) { - return; - } - this->db.insert({service_id, element}); -} -DatabaseElement Database::CreatDatabaseElement(const std::string& ip, - const int16_t port) { - return DatabaseElement{ip, port}; -} -} // namespace database -} // namespace simba diff --git a/communication-core/database/database.h b/communication-core/database/database.h deleted file mode 100644 index 5f9c6e52..00000000 --- a/communication-core/database/database.h +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file database.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief This file define database for router - * @version 0.1 - * @date 2023-10-23 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_DATABASE_H_ -#define COMMUNICATION_CORE_DATABASE_DATABASE_H_ -#include -#include -#include - -#include "communication-core/database/Idatabase.h" -#include "communication-core/database/database_element.h" -namespace simba { -namespace database { -class Database : public IDatabase { - private: - std::unordered_map db{}; - - public: - simba::core::Result GetService( - const std::uint16_t service_id) override; - bool ServiceExist(const std::uint16_t service_id) override; - void AddService(const std::uint16_t service_id, - const DatabaseElement& element) override; - DatabaseElement CreatDatabaseElement(const std::string& ip, - const int16_t port) override; - - public: -}; -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_DATABASE_H_ diff --git a/communication-core/database/database_element.h b/communication-core/database/database_element.h deleted file mode 100644 index 12f4656b..00000000 --- a/communication-core/database/database_element.h +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file database_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief this file define database element - * @version 0.1 - * @date 2023-10-23 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_DATABASE_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_DATABASE_ELEMENT_H_ -#include -#include -namespace simba { -namespace database { -class DatabaseElement { - private: - const std::string ip_; - const uint16_t port_; - - public: - DatabaseElement(const std::string& ip, const uint16_t port) - : ip_{ip}, port_{port} {} - const inline std::string GetIp() { return ip_; } - const inline uint16_t GetPort() { return port_; } - ~DatabaseElement() = default; -}; -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_DATABASE_ELEMENT_H_ diff --git a/communication-core/database/event_element.h b/communication-core/database/event_element.h deleted file mode 100644 index d31f3e59..00000000 --- a/communication-core/database/event_element.h +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @file events_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-12-11 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_EVENT_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_EVENT_ELEMENT_H_ -#include - -#include - -#include "database/service_element.h" - -namespace simba { -namespace database { -namespace objects { -class EventElement { - private: - const uint16_t event_id_; - std::vector client_lists_{}; - - public: - explicit EventElement(const uint16_t& event_id) : event_id_{event_id} {} - void AddService(const ServiceElement& item) { client_lists_.push_back(item); } - const std::vector& GetLists() const { - return this->client_lists_; - } -}; -} // namespace objects -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_EVENT_ELEMENT_H_ diff --git a/communication-core/database/method_element.h b/communication-core/database/method_element.h deleted file mode 100644 index 3bc55efc..00000000 --- a/communication-core/database/method_element.h +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @file method_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-12-11 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_METHOD_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_METHOD_ELEMENT_H_ -#include - -#include - -#include "database/service_element.h" - -namespace simba { -namespace database { -namespace objects { -class MethodElement { - private: - const uint16_t method_id_; - const ServiceElement service_; - - public: - MethodElement(const uint16_t& method_id, const ServiceElement& service) - : method_id_{method_id}, service_{service} {} - uint16_t GetMethodId() const { return method_id_; } - ServiceElement GetService() const { return service_; } -}; -} // namespace objects -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_METHOD_ELEMENT_H_ diff --git a/communication-core/database/net_interface_element.h b/communication-core/database/net_interface_element.h deleted file mode 100644 index 3d06c514..00000000 --- a/communication-core/database/net_interface_element.h +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @file service_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-12-11 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_NET_INTERFACE_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_NET_INTERFACE_ELEMENT_H_ -#include - -#include - -namespace simba { -namespace database { -namespace objects { -class NetInterfaceElement { - private: - const uint16_t service_id_; - const std::string ip_address_; - const std::string ipc_address_; - const uint16_t port_; - - public: - uint16_t GetServiceId() const { return this->service_id_; } - std::string GetIpAddress() const { return this->ip_address_; } - std::string GetIpcAddress() const { return this->ipc_address_; } - uint16_t GetPort() const { return this->port_; } - /** - * @brief Construct a new Net Interface Element object - * - * @param service_id client or service id number - * @param ip_address ip address - * @param port ip port or 0 if ipc - */ - NetInterfaceElement(const uint16_t& service_id, const std::string& ip_address, - const uint16_t& port, const std::string& ipc_address) - : service_id_{service_id}, - ip_address_{ip_address}, - ipc_address_{ipc_address}, - port_{port} {} - NetInterfaceElement(const uint16_t& service_id, - const std::string& ipc_address) - : service_id_{service_id}, - ip_address_{""}, - ipc_address_{ipc_address}, - port_{0x00} {} - NetInterfaceElement(const uint16_t& service_id, const std::string& ip_address, - const uint16_t& port) - : service_id_{service_id}, - ip_address_{ip_address}, - ipc_address_{""}, - port_{port} {} -}; -} // namespace objects -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_NET_INTERFACE_ELEMENT_H_ diff --git a/communication-core/database/req_event_element.h b/communication-core/database/req_event_element.h deleted file mode 100644 index d7c030cb..00000000 --- a/communication-core/database/req_event_element.h +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @file req_event_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-10 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_REQ_EVENT_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_REQ_EVENT_ELEMENT_H_ -#include - -namespace simba { -namespace database { -namespace objects { -class ReqEventElement { - private: - const uint16_t event_id_; - const uint16_t service_id; - - public: - ReqEventElement(const uint16_t& event_id, const uint16_t& service_id) - : event_id_{event_id}, service_id{service_id} {} -}; -} // namespace objects -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_REQ_EVENT_ELEMENT_H_ diff --git a/communication-core/database/service_element.h b/communication-core/database/service_element.h deleted file mode 100644 index de7e1404..00000000 --- a/communication-core/database/service_element.h +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file service_element.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-12-11 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_DATABASE_SERVICE_ELEMENT_H_ -#define COMMUNICATION_CORE_DATABASE_SERVICE_ELEMENT_H_ -#include - -#include - -namespace simba { -namespace database { -namespace objects { -class ServiceElement { - private: - const uint16_t service_id_; - const std::string ip_address_; - const uint16_t port_; - - public: - uint16_t GetServiceId() const { return this->service_id_; } - std::string GetIpAddress() const { return this->ip_address_; } - uint16_t GetPort() const { return this->port_; } - /** - * @brief Construct a new Service Element object - * - * @param service_id client or service id number - * @param ip_address ip address or ipc address - * @param port ip port or 0 if ipc - */ - ServiceElement(const uint16_t& service_id, const std::string& ip_address, - const uint16_t& port) - : service_id_{service_id}, ip_address_{ip_address}, port_{port} {} - /** - * @brief Construct a new Service Element object - * - * @param service_id client or service id number - * @param ip_address ipc address - */ - ServiceElement(const uint16_t& service_id, const std::string& ip_address) - : service_id_{service_id}, ip_address_{ip_address}, port_{0x00} {} -}; -} // namespace objects -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_DATABASE_SERVICE_ELEMENT_H_ diff --git a/communication-core/json-parser/BUILD b/communication-core/json-parser/BUILD index a8dab9c3..cd2b21ed 100644 --- a/communication-core/json-parser/BUILD +++ b/communication-core/json-parser/BUILD @@ -1,7 +1,15 @@ cc_library( name = "JsonParser", - srcs = ["json_parser.cc"], - hdrs = ["database_json_parser.h", "Ijson_parser.h", "json_parser.h"], + # srcs = ["json_parser.cc"], + hdrs = [ + # "Ijson_parser.h", + "database_json_parser.h", + # "json_parser.h", + ], + visibility = [ + "//apps:__subpackages__", + "//mw:__subpackages__", + ], deps = [ "//communication-core/database:DatabaseLib", "@com_json//:json", diff --git a/communication-core/json-parser/database_json_parser.h b/communication-core/json-parser/database_json_parser.h index 79644ffe..7aeb1582 100644 --- a/communication-core/json-parser/database_json_parser.h +++ b/communication-core/json-parser/database_json_parser.h @@ -25,30 +25,67 @@ class DatabaseJsonParser { /* data */ public: template - static void LoadJson(Database& db, // NOLINT + static void LoadJson(Database& db, // NOLINT const std::string& path_to_json) { // NOLINT std::ifstream f(path_to_json); if (!f.is_open()) { return; } nlohmann::json data = nlohmann::json::parse(f); - nlohmann::json remote_lists = data.at("remote"); - if (!remote_lists.is_array()) { - return; + ParseReqMethods(db, data); + ParsePubMethods(db, data); + ParseDb(db, data); + ParsePubEvent(db, data); + ParseReqEvent(db, data); + } + template + static void ParseReqMethods(Database& db, // NOLINT + const nlohmann::json& data) { // NOLINT + auto reqs_methods = data["req_methods"]; + for (auto& [key, val] : reqs_methods.items()) { + db.AddReqMethodsElement( + key, db.CreatReqMethodElement(val["method_id"], val["service_id"])); + } + } + template + static void ParsePubMethods(Database& db, // NOLINT + const nlohmann::json& data) { // NOLINT + auto reqs_methods = data["pub_methods"]; + for (auto& [key, val] : reqs_methods.items()) { + db.AddPubMethodElement(val["name"], + static_cast(val["method_id"])); + } + } + template + static void ParseDb(Database& db, const nlohmann::json& data) { // NOLINT + auto reqs_methods = data["db"]; + for (auto& [key, val] : reqs_methods.items()) { + db.AddDbElement( + static_cast(std::stoi(key)), + db.CreatDbElement((val["ip"].size() == 0) ? val["ipc"] : val["ip"], + static_cast(val["port"]))); } - for (auto obj : remote_lists) { - try { - const uint16_t service_id = obj["id"]; - const std::string ip = obj["ip"]; - const uint16_t port = obj["port"]; - const auto item = db.CreatDatabaseElement(ip, port); - db.AddService(service_id, item); - } catch (...) { - continue; - } + } + template + static void ParsePubEvent(Database& db, // NOLINT + const nlohmann::json& data) { // NOLINT + auto reqs_methods = data["pub_events"]; + for (auto& [key, val] : reqs_methods.items()) { + std::cout << "key: " << key << ", value:" << val << '\n'; } } + template + static void ParseReqEvent(Database& db, // NOLINT + const nlohmann::json& data) { // NOLINT + auto reqs_methods = data["req_events"]; + for (auto& [key, val] : reqs_methods.items()) { + // std::cout << "key: " << key << ", value:" << val << '\n'; + db.AddReqMethodsElement( + val["name"], + db.CreatReqMethodElement(val["event_id"], val["service_id"])); + } + } DatabaseJsonParser(/* args */); ~DatabaseJsonParser(); }; diff --git a/communication-core/json-parser/json_parser.cc b/communication-core/json-parser/json_parser.cc index 61e98224..d26699ec 100644 --- a/communication-core/json-parser/json_parser.cc +++ b/communication-core/json-parser/json_parser.cc @@ -8,7 +8,7 @@ * @copyright Copyright (c) 2024 * */ -#include "json_parser.h" +#include "communication-core/json-parser/json_parser.h" #include #include diff --git a/communication-core/json-parser/json_parser.h b/communication-core/json-parser/json_parser.h index 99e9b66d..a03bfa59 100644 --- a/communication-core/json-parser/json_parser.h +++ b/communication-core/json-parser/json_parser.h @@ -13,7 +13,7 @@ #include #include -#include "json-parser/Ijson_parser.h" +#include "communication-core/json-parser/Ijson_parser.h" namespace simba { namespace database { diff --git a/communication-core/someip-database/BUILD b/communication-core/someip-database/BUILD new file mode 100644 index 00000000..e69de29b diff --git a/communication-core/someip-database/code/BUILD b/communication-core/someip-database/code/BUILD new file mode 100644 index 00000000..91286b43 --- /dev/null +++ b/communication-core/someip-database/code/BUILD @@ -0,0 +1,53 @@ +cc_library( + name = "someip_database_lib", + srcs = ["database.cc"], + hdrs = [ + "database.h", + "endpoint.h", + "interface.h", + "service.h", + ], + visibility = ["//visibility:public"], + deps = [ + "//core/common:common_types", + ], +) + +cc_library( + name = "someip_database_parser_lib", + srcs = [], + hdrs = [ + "database_parser.h", + ], + visibility = ["//visibility:public"], + deps = [ + "//communication-core/someip-database/code:someip_database_lib", + "//core/common:common_types", + "@com_json//:json", + ], +) + +cc_library( + name = "config_database_lib_p", + srcs = ["config_db.cc"], + hdrs = ["config_db.h"], + visibility = ["//communication-core/someip-database:__subpackages__"], + deps = [ + "//communication-core/someip-database/code:someip_database_lib", + "//core/common:common_types", + ], +) + +cc_library( + name = "config_database_parser_lib", + srcs = [], + hdrs = [ + "config_db_parser.h", + ], + visibility = ["//visibility:public"], + deps = [ + "//communication-core/someip-database/code:config_database_lib_p", + "//core/common:common_types", + "@com_json//:json", + ], +) diff --git a/communication-core/someip-database/code/config_db.cc b/communication-core/someip-database/code/config_db.cc new file mode 100644 index 00000000..60f1fbcb --- /dev/null +++ b/communication-core/someip-database/code/config_db.cc @@ -0,0 +1,41 @@ +/** + * @file config_db.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-03 + * + * @copyright Copyright (c) 2024 + * + */ +#include "communication-core/someip-database/code/config_db.h" +namespace simba { +namespace com { +namespace someip { +namespace objects { +core::ErrorCode ConfigDb::InsertObject(const std::string& key, + const Endpoint& item) noexcept { + if (this->item_list.find(key) != this->item_list.end()) { + return core::ErrorCode::kError; + } + + this->item_list.insert({key, item}); + return core::ErrorCode::kOk; +} + +std::optional ConfigDb::FindObject( + const std::string& key) const noexcept { + const auto obj = this->item_list.find(key); + if (obj == this->item_list.end()) { + return {}; + } + return obj->second; +} + +ConfigDb::ConfigDb(/* args */) {} + +ConfigDb::~ConfigDb() {} +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba diff --git a/communication-core/someip-database/code/config_db.h b/communication-core/someip-database/code/config_db.h new file mode 100644 index 00000000..8dc30dfd --- /dev/null +++ b/communication-core/someip-database/code/config_db.h @@ -0,0 +1,46 @@ +/** + * @file config_db.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-03 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_DB_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_DB_H_ + +#include +#include +#include + +#include "communication-core/someip-database/code/endpoint.h" + +#include "core/common/error_code.h" + +namespace simba { +namespace com { +namespace someip { +namespace objects { + +class ConfigDb { + private: + std::unordered_map item_list{}; + + + public: + core::ErrorCode InsertObject(const std::string& key, + const Endpoint& item) noexcept; + std::optional FindObject(const std::string& key) const noexcept; + + + ConfigDb(/* args */); + ~ConfigDb(); +}; +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba + +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_DB_H_ diff --git a/communication-core/someip-database/code/config_db_parser.h b/communication-core/someip-database/code/config_db_parser.h new file mode 100644 index 00000000..8834ef0d --- /dev/null +++ b/communication-core/someip-database/code/config_db_parser.h @@ -0,0 +1,99 @@ +/** + * @file config_db_parser.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-04 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_DB_PARSER_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_DB_PARSER_H_ + +#include +#include + +#include "communication-core/someip-database/code/config_db.h" +#include "communication-core/someip-database/code/endpoint.h" +#include "core/common/error_code.h" +#include "nlohmann/json.hpp" +namespace simba { +namespace com { +namespace someip { +namespace json { + +class ConfigDbParser { + public: + static core::ErrorCode ParseJsonObject(std::shared_ptr db, + const nlohmann::json& obj) noexcept { + auto res = ParseReqMethods(db, obj); + if (res == core::ErrorCode::kOk) { + res = ParseProvideMethods(db, obj); + } + if (res == core::ErrorCode::kOk) { + res = ParsePubEvent(db, obj); + } + if (res == core::ErrorCode::kOk) { + res = ParseReqEvent(db, obj); + } + + return res; + } + + static core::ErrorCode ParseProvideMethods( + std::shared_ptr db, + const nlohmann::json& obj) noexcept { + auto list = obj["pub_methods"]; + for (auto& [key, val] : list.items()) { + db->InsertObject(key, ParseObj(val)); + } + return core::ErrorCode::kOk; + } + + static core::ErrorCode ParseReqMethods(std::shared_ptr db, + const nlohmann::json& obj) noexcept { + auto list = obj["req_methods"]; + for (auto& [key, val] : list.items()) { + db->InsertObject(key, ParseObj(val)); + } + return core::ErrorCode::kOk; + } + + static core::ErrorCode ParseReqEvent(std::shared_ptr db, + const nlohmann::json& obj) noexcept { + auto list = obj["req_events"]; + for (auto& [key, val] : list.items()) { + db->InsertObject(key, ParseObj(val)); + } + return core::ErrorCode::kOk; + } + static core::ErrorCode ParsePubEvent(std::shared_ptr db, + const nlohmann::json& obj) noexcept { + auto list = obj["pub_event"]; + for (auto& [key, val] : list.items()) { + db->InsertObject(key, ParseObj(val)); + } + return core::ErrorCode::kOk; + } + static objects::Endpoint ParseObj(const nlohmann::json& obj) noexcept { + uint16_t method_id = 0; + uint16_t service_id = 0; + if (obj.contains("method_id")) { + method_id = obj["method_id"]; + } + if (obj.contains("event_id")) { + method_id = obj["event_id"]; + } + if (obj.contains("service_id")) { + service_id = obj["service_id"]; + } + return objects::Endpoint{service_id, method_id}; + } +}; + +} // namespace json +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_DB_PARSER_H_ diff --git a/communication-core/someip-database/code/config_someip_provide.h b/communication-core/someip-database/code/config_someip_provide.h new file mode 100644 index 00000000..1e2cbeed --- /dev/null +++ b/communication-core/someip-database/code/config_someip_provide.h @@ -0,0 +1,15 @@ +/** + * @file config_someip_provide.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-04 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_SOMEIP_PROVIDE_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_SOMEIP_PROVIDE_H_ + + +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_CONFIG_SOMEIP_PROVIDE_H_ diff --git a/communication-core/someip-database/code/database.cc b/communication-core/someip-database/code/database.cc new file mode 100644 index 00000000..f5f5de2d --- /dev/null +++ b/communication-core/someip-database/code/database.cc @@ -0,0 +1,63 @@ +/** + * @file database.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-24 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "communication-core/someip-database/code/database.h" + +#include +namespace simba { +namespace com { +namespace someip { +namespace objects { +core::ErrorCode DataBase::InsertService(const uint16_t service_id, + const Interface& inf) noexcept { + if (list.find(service_id) != list.end()) { + return core::ErrorCode::kError; + } + this->list.insert({service_id, inf}); + return core::ErrorCode::kOk; +} +std::optional DataBase::FindService( + const uint16_t service_id) const noexcept { + const auto obj = list.find(service_id); + if (obj == list.end()) { + return {}; + } + + return obj->second; +} + +core::ErrorCode DataBase::InstertEvent(const uint16_t event_id, + const uint16_t client_id) noexcept { + auto obj = this->event_map.find(event_id); + if (obj == this->event_map.end()) { + this->event_map.insert({event_id, std::vector{client_id}}); + return core::ErrorCode::kOk; + } + if (std::find(obj->second.begin(), obj->second.end(), client_id) == + obj->second.end()) { + obj->second.push_back(client_id); + return core::ErrorCode::kOk; + } + return core::ErrorCode::kError; +} +std::optional> DataBase::FindEventClient( + const uint16_t event_id) const noexcept { + auto obj = this->event_map.find(event_id); + if (obj == this->event_map.end()) { + return {}; + } else { + return obj->second; + } +} +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba diff --git a/communication-core/someip-database/code/database.h b/communication-core/someip-database/code/database.h new file mode 100644 index 00000000..f4e6260f --- /dev/null +++ b/communication-core/someip-database/code/database.h @@ -0,0 +1,42 @@ +/** + * @file database.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_DATABASE_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_DATABASE_H_ +#include +#include +#include +#include "communication-core/someip-database/code/interface.h" +#include "communication-core/someip-database/code/service.h" +#include "core/common/error_code.h" +namespace simba { +namespace com { +namespace someip { +namespace objects { +class DataBase { + private: + std::unordered_map list{}; + std::unordered_map> event_map{}; + public: + core::ErrorCode InsertService(const uint16_t service_id, + const Interface& inf) noexcept; + std::optional FindService( + const uint16_t service_id) const noexcept; + + core::ErrorCode InstertEvent(const uint16_t event_id, const uint16_t client_id) noexcept; + std::optional> FindEventClient(const uint16_t event_id) const noexcept; +}; + +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba + +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_DATABASE_H_ diff --git a/communication-core/someip-database/code/database_parser.h b/communication-core/someip-database/code/database_parser.h new file mode 100644 index 00000000..0ebda2ac --- /dev/null +++ b/communication-core/someip-database/code/database_parser.h @@ -0,0 +1,95 @@ +/** + * @file database_parser.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-25 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_DATABASE_PARSER_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_DATABASE_PARSER_H_ +#include +#include +#include +#include + +#include "communication-core/someip-database/code/database.h" +#include "communication-core/someip-database/code/interface.h" +#include "core/common/error_code.h" +#include "nlohmann/json.hpp" + +namespace simba { +namespace com { +namespace someip { +namespace json { +class DataBaseParser { + public: + static core::ErrorCode ParseJsonObject(std::shared_ptr db, + const nlohmann::json& obj) noexcept { + core::ErrorCode flag = core::ErrorCode::kOk; + if (DataBaseParser::ValidateDb(obj) != core::ErrorCode::kOk) { + return core::ErrorCode::kError; + } + auto list = obj.at("db"); + for (auto& [key, val] : list.items()) { + if (DataBaseParser::ValidateItem(val) == core::ErrorCode::kOk) { + std::string ip = val.at("ip"); + uint16_t port = static_cast(val.at("port")); + if (db->InsertService(static_cast(std::stoi(key)), + objects::Interface{ip, port}) != + core::ErrorCode::kOk) { + flag = core::ErrorCode::kError; + } + } else { + flag = core::ErrorCode::kError; + } + } + if (flag == core::ErrorCode::kOk) { + flag = ParseEventClients(std::move(db), obj); + } + return flag; + } + + private: + static core::ErrorCode ValidateDb(const nlohmann::json& obj) noexcept { + if (!obj.contains("db")) { + return core::ErrorCode::kError; + } + return core::ErrorCode::kOk; + } + static core::ErrorCode ValidateItem(const nlohmann::json& obj) noexcept { + if (!obj.contains("ip")) { + return core::ErrorCode::kError; + } + if (!obj.contains("port")) { + return core::ErrorCode::kError; + } + if (!obj.at("ip").is_string()) { + return core::ErrorCode::kError; + } + if (!obj.at("port").is_number_unsigned()) { + return core::ErrorCode::kError; + } + return core::ErrorCode::kOk; + } + static core::ErrorCode ParseEventClients( + std::shared_ptr db, const nlohmann::json& obj) { + auto list = obj["pub_event"]; + for (auto& [key, val] : list.items()) { + const uint16_t event_id = val["event_id"]; + const std::vector list2 = val["subscribers"]; + for (const auto& val : list2) { + db->InstertEvent(event_id, val); + } + } + return core::ErrorCode::kOk; + } +}; + +} // namespace json +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_DATABASE_PARSER_H_ diff --git a/communication-core/someip-database/code/endpoint.h b/communication-core/someip-database/code/endpoint.h new file mode 100644 index 00000000..a72311f0 --- /dev/null +++ b/communication-core/someip-database/code/endpoint.h @@ -0,0 +1,34 @@ +/** + * @file endpoint.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_ENDPOINT_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_ENDPOINT_H_ +#include + +namespace simba { +namespace com { +namespace someip { +namespace objects { +class Endpoint { + protected: + const uint16_t service_id_; + const uint16_t endpoint_id_; + + public: + Endpoint(const uint16_t service_id, const uint16_t endpoint_id) + : service_id_{service_id}, endpoint_id_{endpoint_id} {} + uint16_t GetServiceId() const { return service_id_; } + uint16_t GetEndpointId() const { return endpoint_id_; } +}; +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_ENDPOINT_H_ diff --git a/communication-core/someip-database/code/interface.h b/communication-core/someip-database/code/interface.h new file mode 100644 index 00000000..f80e1cb1 --- /dev/null +++ b/communication-core/someip-database/code/interface.h @@ -0,0 +1,38 @@ +/** + * @file interface.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_INTERFACE_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_INTERFACE_H_ + +#include +#include + +namespace simba { +namespace com { +namespace someip { +namespace objects { +class Interface { + private: + const uint16_t port_; + const std::string ip_; + + public: + Interface(const std::string& ip, const uint16_t port) + : port_{port}, ip_{ip} {} + + uint16_t GetPort() const { return this->port_; } + std::string GetIp() const { return this->ip_; } +}; +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba + +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_INTERFACE_H_ diff --git a/communication-core/someip-database/code/service.h b/communication-core/someip-database/code/service.h new file mode 100644 index 00000000..e32ccd49 --- /dev/null +++ b/communication-core/someip-database/code/service.h @@ -0,0 +1,39 @@ +/** + * @file service.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_SERVICE_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_SERVICE_H_ +#include +#include + +#include "communication-core/someip-database/code/interface.h" +namespace simba { +namespace com { +namespace someip { +namespace objects { +class Service { + private: + const uint16_t service_id_; + std::vector interfaces_; + + public: + Service(const uint16_t service_id, const std::vector& interfaces) + : service_id_{service_id}, interfaces_{interfaces} {} + uint16_t GetServiceId() const { return service_id_; } + const std::vector& GetInterfacesList() const { + return interfaces_; + } +}; +} // namespace objects +} // namespace someip +} // namespace com +} // namespace simba + +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_SERVICE_H_ diff --git a/communication-core/someip-database/test/BUILD b/communication-core/someip-database/test/BUILD new file mode 100644 index 00000000..69a79f70 --- /dev/null +++ b/communication-core/someip-database/test/BUILD @@ -0,0 +1,24 @@ +cc_test( + name = "database_parser_test", + srcs = ["database_parser_test.cc"], + data = ["//communication-core/someip-database/test/resource:files"], + visibility = [], + deps = [ + "//communication-core/someip-database/code:someip_database_parser_lib", + "@com_json//:json", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "config_db_parser_test", + srcs = ["config_db_parser_test.cc"], + data = ["//communication-core/someip-database/test/resource:files"], + visibility = [], + deps = [ + "//communication-core/someip-database/code:config_database_parser_lib", + "@com_json//:json", + "@com_google_googletest//:gtest_main", + ], +) + diff --git a/communication-core/someip-database/test/config_db_parser_test.cc b/communication-core/someip-database/test/config_db_parser_test.cc new file mode 100644 index 00000000..75096e71 --- /dev/null +++ b/communication-core/someip-database/test/config_db_parser_test.cc @@ -0,0 +1,82 @@ +/** + * @file config_db_parser_test.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-04 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "communication-core/someip-database/code/config_db_parser.h" + +#include + +#include +#include + +#include "communication-core/someip-database/code/config_db.h" +#include "core/common/error_code.h" +#include "nlohmann/json.hpp" + +TEST(DataBaseParser, Parsing) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip1.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::ConfigDbParser::ParseJsonObject(db, obj)); +} + +TEST(DataBaseParser, ParsingAndFindReqMethod) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip1.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::ConfigDbParser::ParseJsonObject(db, obj)); + EXPECT_TRUE(db->FindObject("ExampleApp/exampleMethod").has_value()); + const auto r = db->FindObject("ExampleApp/exampleMethod"); + EXPECT_EQ(10, r.value().GetEndpointId()); + EXPECT_EQ(15, r.value().GetServiceId()); +} + +TEST(DataBaseParser, ParsingAndFindPubMethod) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip2.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::ConfigDbParser::ParseJsonObject(db, obj)); + EXPECT_TRUE(db->FindObject("ExampleApp/exampleMethod").has_value()); + EXPECT_TRUE(db->FindObject("ExampleApp/exampleMethod2").has_value()); + const auto r = db->FindObject("ExampleApp/exampleMethod"); + EXPECT_EQ(10, r.value().GetEndpointId()); + EXPECT_EQ(0, r.value().GetServiceId()); +} + +TEST(DataBaseParser, ParsingAndFindReqEvent) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip1.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::ConfigDbParser::ParseJsonObject(db, obj)); + EXPECT_TRUE(db->FindObject("ExampleApp/exampleEvent").has_value()); + const auto r = db->FindObject("ExampleApp/exampleEvent"); + EXPECT_EQ(32769, r.value().GetEndpointId()); + EXPECT_EQ(15, r.value().GetServiceId()); +} +TEST(DataBaseParser, ParsingAndFindPubEvent) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip2.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::ConfigDbParser::ParseJsonObject(db, obj)); + EXPECT_TRUE(db->FindObject("ExampleApp/exampleEvent").has_value()); + const auto r = db->FindObject("ExampleApp/exampleEvent"); + EXPECT_EQ(32769, r.value().GetEndpointId()); + EXPECT_EQ(0, r.value().GetServiceId()); +} diff --git a/communication-core/someip-database/test/database_parser_test.cc b/communication-core/someip-database/test/database_parser_test.cc new file mode 100644 index 00000000..8bd1fdf0 --- /dev/null +++ b/communication-core/someip-database/test/database_parser_test.cc @@ -0,0 +1,62 @@ +/** + * @file database_parser_test.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-02-25 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "communication-core/someip-database/code/database_parser.h" + +#include + +#include +#include + +#include "communication-core/someip-database/code/database.h" +#include "core/common/error_code.h" +#include "nlohmann/json.hpp" + +TEST(DataBaseParser, Parsing) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip1.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::DataBaseParser::ParseJsonObject(db, obj)); +} + +TEST(DataBaseParser, GiveCorrectFileWhileFindServiceReturnPositive) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip1.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::DataBaseParser::ParseJsonObject(db, obj)); + EXPECT_TRUE(db->FindService(15).has_value()); + EXPECT_EQ(0, db->FindService(15).value().GetPort()); + EXPECT_EQ("SIMBA.SOMEIP.15", db->FindService(15).value().GetIp()); +} + +TEST(DataBaseParser, GiveCorrectFileWhileFindServiceReturnNegative) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip1.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::DataBaseParser::ParseJsonObject(db, obj)); + EXPECT_FALSE(db->FindService(30).has_value()); +} + +TEST(DataBaseParser, GiveCorrectFileWhileFindEventReturnPositive) { + std::ifstream f( + "communication-core/someip-database/test/resource/app_someip2.json"); + auto db = std::make_shared(); + auto obj = nlohmann::json::parse(f); + EXPECT_EQ(simba::core::ErrorCode::kOk, + simba::com::someip::json::DataBaseParser::ParseJsonObject(db, obj)); + EXPECT_TRUE(db->FindEventClient(32769).has_value()); +} diff --git a/communication-core/someip-database/test/resource/BUILD b/communication-core/someip-database/test/resource/BUILD new file mode 100644 index 00000000..4a470406 --- /dev/null +++ b/communication-core/someip-database/test/resource/BUILD @@ -0,0 +1,8 @@ +filegroup( + name = "files", + srcs = [ + "app_someip1.json", + "app_someip2.json", + ], + visibility = ["//communication-core/someip-database/test:__subpackages__"], +) diff --git a/communication-core/someip-database/test/resource/app_someip1.json b/communication-core/someip-database/test/resource/app_someip1.json new file mode 100755 index 00000000..31f7eef4 --- /dev/null +++ b/communication-core/someip-database/test/resource/app_someip1.json @@ -0,0 +1,33 @@ +{ + "service_id": 258, + "interface": [ + { + "ip": "SIMBA.SOMEIP.258", + "port": 0 + }, + { + "ip": "192.168.10.101", + "port": 1011 + } + ], + "pub_methods": {}, + "pub_event": {}, + "req_methods": { + "ExampleApp/exampleMethod": { + "service_id": 15, + "method_id": 10 + } + }, + "req_events": { + "ExampleApp/exampleEvent": { + "service_id": 15, + "event_id": 32769 + } + }, + "db": { + "15": { + "ip": "SIMBA.SOMEIP.15", + "port": 0 + } + } +} \ No newline at end of file diff --git a/communication-core/someip-database/test/resource/app_someip2.json b/communication-core/someip-database/test/resource/app_someip2.json new file mode 100755 index 00000000..9953dff6 --- /dev/null +++ b/communication-core/someip-database/test/resource/app_someip2.json @@ -0,0 +1,35 @@ +{ + "service_id": 15, + "interface": [ + { + "ip": "SIMBA.SOMEIP.15", + "port": 0 + }, + { + "ip": "192.168.10.101", + "port": 1011 + } + ], + "pub_methods": { + "ExampleApp/exampleMethod": { + "method_id": 10 + }, + "ExampleApp/exampleMethod2": { + "method_id": 100 + } + }, + "pub_event": { + "ExampleApp/exampleEvent": { + "event_id": 32769, + "subscribers": [10] + } + }, + "req_methods": {}, + "req_events": {}, + "db": { + "258": { + "ip": "SIMBA.SOMEIP.258", + "port": 0 + } + } +} \ No newline at end of file diff --git a/deployment b/deployment index 569bbd3e..d58a9544 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 569bbd3e8130b51b4e018c14453528a11f3cbee7 +Subproject commit d58a9544ab96da5f2c4fda6f3704bbc8f43d53f6 diff --git a/diag/base/controller/BUILD b/diag/base/controller/BUILD index 12ad3e9b..f1e28581 100644 --- a/diag/base/controller/BUILD +++ b/diag/base/controller/BUILD @@ -5,7 +5,6 @@ cc_library( deps = [ "//communication-core/someip-controller:transfer_lib", "//core/common:common_types", - "//core/results:results_lib", ], ) @@ -14,7 +13,6 @@ cc_library( hdrs = ["idiag_controller.h"], deps = [ "//core/common:common_types", - "//core/results:results_lib", ], ) @@ -31,7 +29,6 @@ cc_library( "//communication-core/sockets:socket_interface", "//core/common:common_types", "//core/logger:Logger", - "//core/results:results_lib", "//diag/base/controller:diag_transfer", "//diag/base/controller:idiag_controller", "//diag/base/data:diag_parser", diff --git a/diag/base/controller/diag_controller.cc b/diag/base/controller/diag_controller.cc index 308bb426..f0320f83 100644 --- a/diag/base/controller/diag_controller.cc +++ b/diag/base/controller/diag_controller.cc @@ -11,13 +11,13 @@ #include "diag/base/controller/diag_controller.h" #include +#include #include #include #include "communication-core/sockets/socket_config.h" #include "core/common/error_code.h" #include "core/logger/Logger.h" -#include "core/results/result.h" #include "diag/base/data/data_structure.h" #include "diag/base/data/parser.h" #include "diag/base/factories/diag_data_factory.h" @@ -70,10 +70,10 @@ void DiagController::RxCallback(const std::string& ip, const std::uint16_t& port, std::vector payload) { const auto data_r = diag::Parser::GetStructure(payload); - if (!data_r.HasValue()) { + if (!data_r.has_value()) { return; } - const auto data = data_r.Value(); + const auto data = data_r.value(); if (data.GetServiceID() != this->service_id_) { return; } @@ -103,16 +103,16 @@ void DiagController::Request(const data::DataStructure req) { } const auto result = obj->second(req.GetPayload()); - if (result.HasValue()) { + if (result.has_value()) { const auto res_t = DiagDataFactory::CreateResponse( req.GetSenderID(), req.GetDiagID() >> 0x2, this->service_id_, - req.GetTransferID(), result.Value()); - if (!res_t.HasValue()) { + req.GetTransferID(), result.value()); + if (!res_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the answer"); return; } - if (this->Send(res_t.Value()) != core::ErrorCode::kOk) { + if (this->Send(res_t.value()) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send response to: SIMBA.DIAG." + std::to_string(req.GetSenderID())); @@ -124,11 +124,11 @@ void DiagController::Request(const data::DataStructure req) { simba::core::ErrorCode DiagController::Send(const data::DataStructure& req) { const auto buffer_t = Parser::GetBuffer(req); - if (!buffer_t.HasValue()) { + if (!buffer_t.has_value()) { AppLogger::Error("[DIAG_CONTROLLER] An error occurred while parsing"); return core::ErrorCode::kError; } - const auto buffer = buffer_t.Value(); + const auto buffer = buffer_t.value(); if (this->socket_driver != nullptr) { return this->socket_driver->Transmit( "SIMBA.DIAG." + std::to_string(req.GetServiceID()), 0, buffer); @@ -156,12 +156,12 @@ void DiagController::Response(const data::DataStructure req) { void DiagController::SendError(const data::DataStructure req) { const auto res_t = diag::DiagDataFactory::CreateResponse( req.GetSenderID(), 0x3F, this->service_id_, req.GetTransferID(), {}); - if (!res_t.HasValue()) { + if (!res_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the answer"); return; } - const auto res = res_t.Value(); + const auto res = res_t.value(); if (this->Send(res) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send error response to: SIMBA.DIAG." + @@ -169,22 +169,22 @@ void DiagController::SendError(const data::DataStructure req) { } } -simba::core::Result> DiagController::Read( +std::optional> DiagController::Read( const uint16_t service_id, const uint8_t diag_id) { const auto t_id = this->GetTransferId(); const auto req_t = DiagDataFactory::CreateReadRequest( service_id, diag_id, this->service_id_, t_id, {}); - if (!req_t.HasValue()) { + if (!req_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the Read request"); - return simba::core::Result>{}; + return std::optional>{}; } auto transfer = std::make_shared(t_id); - if (this->Send(req_t.Value()) != core::ErrorCode::kOk) { + if (this->Send(req_t.value()) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send Read request to: SIMBA.DIAG." + - std::to_string(req_t.Value().GetServiceID())); - return simba::core::Result>{}; + std::to_string(req_t.value().GetServiceID())); + return std::optional>{}; } this->transfer_list.push_back(transfer); const auto result = transfer->GetPayloadAsc(); @@ -201,16 +201,16 @@ simba::core::ErrorCode DiagController::Write( const auto t_id = this->GetTransferId(); const auto req_t = DiagDataFactory::CreateWriteRequest( service_id, diag_id, this->service_id_, t_id, payload); - if (!req_t.HasValue()) { + if (!req_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the Read request"); return core::ErrorCode::kError; } auto transfer = std::make_shared(t_id); - if (this->Send(req_t.Value()) != core::ErrorCode::kOk) { + if (this->Send(req_t.value()) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send Write request to: SIMBA.DIAG." + - std::to_string(req_t.Value().GetServiceID())); + std::to_string(req_t.value().GetServiceID())); return core::ErrorCode::kConnectionError; } this->transfer_list.push_back(transfer); @@ -219,29 +219,29 @@ simba::core::ErrorCode DiagController::Write( [transfer](std::shared_ptr t) { return t->GetTransferID() == transfer->GetTransferID(); }); - if (result.HasValue()) { + if (result.has_value()) { return core::ErrorCode::kOk; } else { return core::ErrorCode::kError; } } -simba::core::Result> DiagController::Job( +std::optional> DiagController::Job( const uint16_t service_id, const uint8_t diag_id, const std::vector payload) { const auto t_id = this->GetTransferId(); const auto req_t = DiagDataFactory::CreateJobRequest( service_id, diag_id, this->service_id_, t_id, payload); - if (!req_t.HasValue()) { + if (!req_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the Read request"); - return simba::core::Result>{}; + return std::optional>{}; } auto transfer = std::make_shared(t_id); - if (this->Send(req_t.Value()) != core::ErrorCode::kOk) { + if (this->Send(req_t.value()) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send Job request to: SIMBA.DIAG." + - std::to_string(req_t.Value().GetSenderID())); - return simba::core::Result>{}; + std::to_string(req_t.value().GetSenderID())); + return std::optional>{}; } this->transfer_list.push_back(transfer); const auto result = transfer->GetPayloadAsc(); @@ -254,8 +254,7 @@ simba::core::Result> DiagController::Job( DiagController::DiagController(const uint16_t service_id, std::unique_ptr soc) - : service_id_{service_id}, socket_driver{std::move(soc)} { - } + : service_id_{service_id}, socket_driver{std::move(soc)} {} const uint16_t DiagController::GetTransferId() { return this->transfer_id++; } diff --git a/diag/base/controller/diag_controller.h b/diag/base/controller/diag_controller.h index aabddcd6..0a1be5bd 100644 --- a/diag/base/controller/diag_controller.h +++ b/diag/base/controller/diag_controller.h @@ -12,13 +12,13 @@ #define DIAG_BASE_CONTROLLER_DIAG_CONTROLLER_H_ #include #include +#include #include #include #include #include "communication-core/sockets/Isocket.h" #include "core/common/error_code.h" -#include "core/results/result.h" #include "diag/base/controller/diag_transfer.h" #include "diag/base/controller/idiag_controller.h" #include "diag/base/data/data_structure.h" @@ -64,17 +64,19 @@ class DiagController : public IDiagController { simba::core::ErrorCode AddMethod(const uint8_t diag_id, DiagMethod callback, const DiagMethodType method_type) override; simba::core::ErrorCode Init() override; - simba::core::Result> Read( + std::optional> Read( const uint16_t service_id, const uint8_t diag_id) override; simba::core::ErrorCode Write(const uint16_t service_id, const uint8_t diag_id, const std::vector payload) override; - simba::core::Result> Job( + std::optional> Job( const uint16_t service_id, const uint8_t diag_id, const std::vector payload) override; DiagController(const uint16_t service_id, std::unique_ptr soc); - ~DiagController() { this->callback_list.erase(this->callback_list.begin(), - this->callback_list.end());} + ~DiagController() { + this->callback_list.erase(this->callback_list.begin(), + this->callback_list.end()); + } }; } // namespace diag } // namespace simba diff --git a/diag/base/controller/diag_transfer.h b/diag/base/controller/diag_transfer.h index 4b862b06..9018d9a0 100644 --- a/diag/base/controller/diag_transfer.h +++ b/diag/base/controller/diag_transfer.h @@ -27,16 +27,16 @@ class DiagTransfer : public com::someip::data::Transfer { explicit DiagTransfer(const uint16_t transfer_id) : com::someip::data::Transfer{transfer_id} {} - simba::core::Result> GetPayloadAsc() { + std::optional> GetPayloadAsc() { std::unique_lock lk(cv_m); if (!cv.wait_for(lk, std::chrono::seconds{2}, [this]() { return this->IsRespond() || this->error; })) { - return simba::core::Result>{}; + return {}; } if (!this->error) { - return simba::core::Result>{response}; + return response; } else { - return simba::core::Result>{}; + return {}; } } diff --git a/diag/base/controller/idiag_controller.h b/diag/base/controller/idiag_controller.h index 56422926..0a92544e 100644 --- a/diag/base/controller/idiag_controller.h +++ b/diag/base/controller/idiag_controller.h @@ -11,14 +11,14 @@ #ifndef DIAG_BASE_CONTROLLER_IDIAG_CONTROLLER_H_ #define DIAG_BASE_CONTROLLER_IDIAG_CONTROLLER_H_ #include +#include #include #include "core/common/error_code.h" -#include "core/results/result.h" namespace simba { namespace diag { -using DiagMethod = std::function>( +using DiagMethod = std::function>( const std::vector payload)>; enum DiagMethodType { WRITE = 0x00, READ = 0x01, JOB = 0x02 }; @@ -29,12 +29,12 @@ class IDiagController { const uint8_t diag_id, DiagMethod callback, const DiagMethodType method_type) = 0; virtual simba::core::ErrorCode Init() = 0; - virtual simba::core::Result> Read( - const uint16_t service_id, const uint8_t diag_id) = 0; + virtual std::optional> Read(const uint16_t service_id, + const uint8_t diag_id) = 0; virtual simba::core::ErrorCode Write(const uint16_t service_id, const uint8_t diag_id, const std::vector payload) = 0; - virtual simba::core::Result> Job( + virtual std::optional> Job( const uint16_t service_id, const uint8_t diag_id, const std::vector payload) = 0; virtual ~IDiagController() {} diff --git a/diag/base/data/BUILD b/diag/base/data/BUILD index 29f30847..e0bcb825 100644 --- a/diag/base/data/BUILD +++ b/diag/base/data/BUILD @@ -11,7 +11,6 @@ cc_library( hdrs = ["parser.h"], visibility = ["//visibility:public"], deps = [ - "//core/results:results_lib", "//diag/base/data:diag_data_structure", ], ) diff --git a/diag/base/data/parser.cc b/diag/base/data/parser.cc index 00370bea..988eda29 100644 --- a/diag/base/data/parser.cc +++ b/diag/base/data/parser.cc @@ -17,7 +17,7 @@ namespace diag { namespace { static constexpr size_t base_header_size = 0x08; } -core::Result Parser::GetStructure( +std::optional Parser::GetStructure( const std::vector& buffer) { if (buffer.size() >= base_header_size) { const uint16_t s_id = (buffer[0] << 8) + buffer[1]; @@ -27,12 +27,12 @@ core::Result Parser::GetStructure( data::DataStructure res{s_id, diag_id, send_id, transfer_id}; res.SetPayload( std::vector{buffer.begin() + base_header_size, buffer.end()}); - return core::Result{res}; + return res; } else { - return core::Result{}; + return {}; } } -core::Result> Parser::GetBuffer( +std::optional> Parser::GetBuffer( const data::DataStructure& data) { std::vector res{}; res.push_back(static_cast((data.GetServiceID() & 0XFF00) >> 8)); @@ -46,9 +46,9 @@ core::Result> Parser::GetBuffer( const auto vec = data.GetPayload(); res.insert(res.end(), vec.begin(), vec.end()); if (res.size() < 260) { - return core::Result{res}; + return res; } else { - return core::Result>{}; + return {}; } } diff --git a/diag/base/data/parser.h b/diag/base/data/parser.h index 0b449d4f..e3982e77 100644 --- a/diag/base/data/parser.h +++ b/diag/base/data/parser.h @@ -11,17 +11,17 @@ #ifndef DIAG_BASE_DATA_PARSER_H_ #define DIAG_BASE_DATA_PARSER_H_ #include +#include #include -#include "core/results/result.h" #include "diag/base/data/data_structure.h" namespace simba { namespace diag { class Parser { public: - static core::Result GetStructure( + static std::optional GetStructure( const std::vector& buffer); - static core::Result> GetBuffer( + static std::optional> GetBuffer( const data::DataStructure& data); }; } // namespace diag diff --git a/diag/base/factories/BUILD b/diag/base/factories/BUILD index 9e0a194e..89e007ec 100644 --- a/diag/base/factories/BUILD +++ b/diag/base/factories/BUILD @@ -4,7 +4,6 @@ cc_library( hdrs = ["diag_data_factory.h"], visibility = ["//visibility:public"], deps = [ - "//core/results:results_lib", "//diag/base/data:diag_data_structure", ], ) diff --git a/diag/base/factories/diag_data_factory.cc b/diag/base/factories/diag_data_factory.cc index 0c752e5f..42a5b111 100644 --- a/diag/base/factories/diag_data_factory.cc +++ b/diag/base/factories/diag_data_factory.cc @@ -14,63 +14,69 @@ #include namespace simba { namespace diag { -simba::core::Result DiagDataFactory::CreateReadRequest( +std::optional DiagDataFactory::CreateReadRequest( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload) { if (diag_id > 0x3F) { - return simba::core::Result{}; + return {}; } - data::DataStructure res{service_id, static_cast(((diag_id & 0x3F) << 0x02) | static_cast(0x01U)), + data::DataStructure res{service_id, + static_cast(((diag_id & 0x3F) << 0x02) | + static_cast(0x01U)), sender_id, transfer_id}; res.SetPayload(payload); - return simba::core::Result{res}; + return res; } -simba::core::Result -DiagDataFactory::CreateWriteRequest(const std::uint16_t service_id, - const std::uint8_t diag_id, - const std::uint16_t sender_id, - const std::uint16_t transfer_id, - const std::vector& payload) { +std::optional DiagDataFactory::CreateWriteRequest( + const std::uint16_t service_id, const std::uint8_t diag_id, + const std::uint16_t sender_id, const std::uint16_t transfer_id, + const std::vector& payload) { if (diag_id > 0x3F) { - return simba::core::Result{}; + return {}; } - data::DataStructure res{service_id, static_cast(((diag_id & 0x3F) << 0x02) | static_cast(0x00U)), + data::DataStructure res{service_id, + static_cast(((diag_id & 0x3F) << 0x02) | + static_cast(0x00U)), sender_id, transfer_id}; res.SetPayload(payload); - return simba::core::Result{res}; + return res; } -simba::core::Result DiagDataFactory::CreateResponse( +std::optional DiagDataFactory::CreateResponse( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload) { if (diag_id > 0x3F) { - return simba::core::Result{}; + return {}; } - data::DataStructure res{service_id, static_cast(((diag_id & 0x3F) << 0x02) | static_cast(0x03U)), + data::DataStructure res{service_id, + static_cast(((diag_id & 0x3F) << 0x02) | + static_cast(0x03U)), sender_id, transfer_id}; res.SetPayload(payload); - return simba::core::Result{res}; + return res; } -simba::core::Result DiagDataFactory::CreateJobRequest( +std::optional DiagDataFactory::CreateJobRequest( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload) { if (diag_id > 0x3F) { - return simba::core::Result{}; + return {}; } - data::DataStructure res{service_id, static_cast(((diag_id & 0x3F) << 0x02) | static_cast(0x02U)), + data::DataStructure res{service_id, + static_cast(((diag_id & 0x3F) << 0x02) | + static_cast(0x02U)), sender_id, transfer_id}; res.SetPayload(payload); - return simba::core::Result{res}; + return res; } } // namespace diag } // namespace simba diff --git a/diag/base/factories/diag_data_factory.h b/diag/base/factories/diag_data_factory.h index 01b2ff2d..1355484b 100644 --- a/diag/base/factories/diag_data_factory.h +++ b/diag/base/factories/diag_data_factory.h @@ -11,26 +11,26 @@ #ifndef DIAG_BASE_FACTORIES_DIAG_DATA_FACTORY_H_ #define DIAG_BASE_FACTORIES_DIAG_DATA_FACTORY_H_ #include +#include -#include "core/results/result.h" #include "diag/base/data/data_structure.h" namespace simba { namespace diag { class DiagDataFactory { public: - static simba::core::Result CreateReadRequest( + static std::optional CreateReadRequest( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload); - static simba::core::Result CreateWriteRequest( + static std::optional CreateWriteRequest( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload); - static simba::core::Result CreateResponse( + static std::optional CreateResponse( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload); - static simba::core::Result CreateJobRequest( + static std::optional CreateJobRequest( const std::uint16_t service_id, const std::uint8_t diag_id, const std::uint16_t sender_id, const std::uint16_t transfer_id, const std::vector& payload); diff --git a/diag/base/tests/test_diag_data_factory.cc b/diag/base/tests/test_diag_data_factory.cc index 50b40f93..e214399a 100644 --- a/diag/base/tests/test_diag_data_factory.cc +++ b/diag/base/tests/test_diag_data_factory.cc @@ -16,25 +16,25 @@ TEST(DIAG_DAT_FACTORY, CreateReadRequest) { auto sut = simba::diag::DiagDataFactory::CreateReadRequest(0x01, 0x01, 0x01, 0x01, {}); - ASSERT_TRUE(sut.HasValue()); - ASSERT_EQ(sut.Value().GetDiagID() & 0b11, 0x01); + ASSERT_TRUE(sut.has_value()); + ASSERT_EQ(sut.value().GetDiagID() & 0b11, 0x01); } TEST(DIAG_DAT_FACTORY, CreateWriteRequest) { auto sut = simba::diag::DiagDataFactory::CreateWriteRequest(0x01, 0x01, 0x01, 0x01, {}); - ASSERT_TRUE(sut.HasValue()); - ASSERT_EQ(sut.Value().GetDiagID() & 0b11, 0x00); + ASSERT_TRUE(sut.has_value()); + ASSERT_EQ(sut.value().GetDiagID() & 0b11, 0x00); } TEST(DIAG_DAT_FACTORY, CreateResponse) { auto sut = simba::diag::DiagDataFactory::CreateResponse(0x01, 0x01, 0x01, 0x01, {}); - ASSERT_TRUE(sut.HasValue()); - ASSERT_EQ(sut.Value().GetDiagID() & 0b11, 0x03); + ASSERT_TRUE(sut.has_value()); + ASSERT_EQ(sut.value().GetDiagID() & 0b11, 0x03); } TEST(DIAG_DAT_FACTORY, CreateJobRequest) { auto sut = simba::diag::DiagDataFactory::CreateJobRequest(0x01, 0x01, 0x01, 0x01, {}); - ASSERT_TRUE(sut.HasValue()); - ASSERT_EQ(sut.Value().GetDiagID() & 0b11, 0x02); + ASSERT_TRUE(sut.has_value()); + ASSERT_EQ(sut.value().GetDiagID() & 0b11, 0x02); } diff --git a/diag/base/tests/test_parser.cc b/diag/base/tests/test_parser.cc index 0b7280b1..fb8e8db8 100644 --- a/diag/base/tests/test_parser.cc +++ b/diag/base/tests/test_parser.cc @@ -19,8 +19,8 @@ TEST(PARSER, GetBuffer_without_payload) { simba::diag::data::DataStructure obj{0x1111, 0x01, 0x02, 0x00}; const auto res = simba::diag::Parser::GetBuffer(obj); - EXPECT_TRUE(res.HasValue()); - const auto sut = res.Value(); + EXPECT_TRUE(res.has_value()); + const auto sut = res.value(); EXPECT_EQ(expected.size(), sut.size()); for (uint8_t i = 0; i < expected.size(); i++) { EXPECT_EQ(expected[i], sut[i]); @@ -35,8 +35,8 @@ TEST(PARSER, GetBuffer_with_payload) { simba::diag::data::DataStructure obj{0x1111, 0x01, 0x02, 0x00}; obj.SetPayload(elements); const auto res = simba::diag::Parser::GetBuffer(obj); - ASSERT_TRUE(res.HasValue()); - const auto sut = res.Value(); + ASSERT_TRUE(res.has_value()); + const auto sut = res.value(); EXPECT_EQ(expected.size(), sut.size()); for (uint8_t i = 0; i < expected.size(); i++) { EXPECT_EQ(expected[i], sut[i]); @@ -50,8 +50,8 @@ TEST(PARSER, GetStructure_without_payload) { simba::diag::data::DataStructure expected_obj{0x1111, 0x01, 0x02, 0x00}; const auto res = simba::diag::Parser::GetStructure(src); - ASSERT_TRUE(res.HasValue()); - const auto sut = res.Value(); + ASSERT_TRUE(res.has_value()); + const auto sut = res.value(); EXPECT_EQ(expected_obj.GetServiceID(), sut.GetServiceID()); EXPECT_EQ(expected_obj.GetDiagID(), sut.GetDiagID()); @@ -65,8 +65,8 @@ TEST(PARSER, GetStructure_with_payload) { simba::diag::data::DataStructure expected_obj{0x1111, 0x01, 0x02, 0x00}; expected_obj.SetPayload(elements); const auto res = simba::diag::Parser::GetStructure(src); - ASSERT_TRUE(res.HasValue()); - const auto sut = res.Value(); + ASSERT_TRUE(res.has_value()); + const auto sut = res.value(); EXPECT_EQ(expected_obj.GetServiceID(), sut.GetServiceID()); EXPECT_EQ(expected_obj.GetDiagID(), sut.GetDiagID()); @@ -81,10 +81,10 @@ TEST(PARSER, DoubleTest) { simba::diag::data::DataStructure expected_obj{0x1111, 0x01, 0x02, 0x00}; expected_obj.SetPayload(elements); const auto res = simba::diag::Parser::GetBuffer(expected_obj); - ASSERT_TRUE(res.HasValue()); - const auto res2 = simba::diag::Parser::GetStructure(res.Value()); - ASSERT_TRUE(res2.HasValue()); - const auto sut = res2.Value(); + ASSERT_TRUE(res.has_value()); + const auto res2 = simba::diag::Parser::GetStructure(res.value()); + ASSERT_TRUE(res2.has_value()); + const auto sut = res2.value(); EXPECT_EQ(expected_obj.GetServiceID(), sut.GetServiceID()); EXPECT_EQ(expected_obj.GetDiagID(), sut.GetDiagID()); EXPECT_EQ(expected_obj.GetPayload().size(), sut.GetPayload().size()); diff --git a/diag/dtc/factories/BUILD b/diag/dtc/factories/BUILD index 76293989..7c2d216d 100644 --- a/diag/dtc/factories/BUILD +++ b/diag/dtc/factories/BUILD @@ -4,7 +4,6 @@ cc_library( hdrs = ["dtc_msg_factory.hpp"], visibility = ["//visibility:public"], deps = [ - "//core/results:results_lib", "//diag/dtc/data:diag_dtc_data_structure" ], ) From 1727ce6786c2a1273fdda7b4f95971c7d3ee1412 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Tue, 5 Mar 2024 22:27:55 +0100 Subject: [PATCH 25/71] Update submodule --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index d58a9544..fe8edfd1 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit d58a9544ab96da5f2c4fda6f3704bbc8f43d53f6 +Subproject commit fe8edfd181d7038904db21e44194a6212a86eff7 From 68d8b65a7ac01bba5e971e0583b3e36304a4d908 Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Thu, 7 Mar 2024 10:44:25 +0100 Subject: [PATCH 26/71] Makr fix gpio driver (#42) * small_gpio_fix test fix deps cycle * fix. --- apps/example/BUILD | 1 + apps/example/router.cc | 4 + apps/example/router.h | 2 + communication-core/network-data/BUILD | 2 +- communication-core/someip-controller/BUILD | 4 +- communication-core/someip/BUILD | 1 + core/application/application_common.cc | 1 + core/application/application_common.h | 1 + core/common/BUILD | 4 +- core/gpio/BUILD | 7 +- core/gpio/GPIO_digital_driver.cpp | 87 ++++++++++++---------- core/gpio/GPIO_digital_driver.h | 59 ++++++++++++--- core/gpio/IGPIO_digital_driver.h | 13 +--- diag/dtc/controller/I_dtc_controller.hpp | 2 +- diag/dtc/controller/dtc_controller.cpp | 2 +- diag/dtc/controller/dtc_controller.hpp | 2 +- diag/dtc/specification/frame.md | 12 +++ mw/diag/dtc/service/BUILD | 3 +- mw/diag/dtc/service/dtcService.h | 1 - 19 files changed, 141 insertions(+), 67 deletions(-) diff --git a/apps/example/BUILD b/apps/example/BUILD index c8fc1bdb..1b8e2663 100644 --- a/apps/example/BUILD +++ b/apps/example/BUILD @@ -9,6 +9,7 @@ cc_binary( deps = [ "//core/application:simba_application", "@untar", + "//core/gpio:gpio_drivers" ], ) diff --git a/apps/example/router.cc b/apps/example/router.cc index 46f02db4..2fc5a3b7 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -20,6 +20,9 @@ core::ErrorCode Router::Run(std::stop_token token) { AppLogger::Info("AppLogger::Info"); AppLogger::Warning("AppLogger::Warning"); AppLogger::Error("AppLogger::Error"); + this->gpio_.setValue(21, 1); + std::this_thread::sleep_for(std::chrono::seconds{1}); + this->gpio_.setValue(21, 0); std::this_thread::sleep_for(std::chrono::seconds{1}); } @@ -28,6 +31,7 @@ core::ErrorCode Router::Run(std::stop_token token) { core::ErrorCode Router::Initialize( const std::unordered_map& parms) { + this->gpio_.initializePin(21, core::gpio::direction_t::OUT); return core::ErrorCode::kOk; } } // namespace router diff --git a/apps/example/router.h b/apps/example/router.h index bdb056cd..ce706171 100644 --- a/apps/example/router.h +++ b/apps/example/router.h @@ -14,6 +14,7 @@ #include #include "core/application/application_no_ipc.h" +#include "core/gpio/GPIO_digital_driver.h" namespace simba { namespace router { class Router : public core::ApplicationNoIPC{ @@ -34,6 +35,7 @@ class Router : public core::ApplicationNoIPC{ public: ~Router() = default; + core::gpio::GpioDigitalDriver gpio_; }; } // namespace router diff --git a/communication-core/network-data/BUILD b/communication-core/network-data/BUILD index 417b6c8d..19704e23 100644 --- a/communication-core/network-data/BUILD +++ b/communication-core/network-data/BUILD @@ -2,7 +2,7 @@ cc_library( name = "interfaces", hdrs = ["iframe.h"], visibility = ["//communication-core:__subpackages__"], - deps = ["//core"], + deps = ["//core/common:common_types"], ) cc_library( diff --git a/communication-core/someip-controller/BUILD b/communication-core/someip-controller/BUILD index fcb3de3d..ce284237 100644 --- a/communication-core/someip-controller/BUILD +++ b/communication-core/someip-controller/BUILD @@ -8,7 +8,8 @@ cc_library( "//communication-core/someip:someip_header", "//communication-core/someip:someip_types", "//communication-core/someip/factory:someip_message_factory", - "//core", + "//core/common:common_types", + "//core/results:results_lib" ], ) @@ -38,7 +39,6 @@ cc_library( "//communication-core/someip:someip_types", "//communication-core/someip/factory:someip_header_factory", "//communication-core/someip/factory:someip_message_factory", - "//core", "//communication-core/someip-controller:transfer_lib", ], ) diff --git a/communication-core/someip/BUILD b/communication-core/someip/BUILD index 6ab71438..d16d9392 100644 --- a/communication-core/someip/BUILD +++ b/communication-core/someip/BUILD @@ -17,5 +17,6 @@ cc_library( deps = [ "//communication-core/network-data:network_data_structure", "//communication-core/network-data:network_data_type", + "//core/common:common_converter" ], ) diff --git a/core/application/application_common.cc b/core/application/application_common.cc index aec3f10e..349017ca 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -13,6 +13,7 @@ #include #include #include +#include #include "boost/algorithm/string.hpp" #include "core/application/parm.h" diff --git a/core/application/application_common.h b/core/application/application_common.h index 5859226c..b971d5aa 100644 --- a/core/application/application_common.h +++ b/core/application/application_common.h @@ -24,6 +24,7 @@ namespace core { class ApplicationCommon : public IApplication { protected: std::stop_source source; + /** * @brief This is pre-run function only for creting new application * interfacess diff --git a/core/common/BUILD b/core/common/BUILD index e58e59bf..6b584361 100644 --- a/core/common/BUILD +++ b/core/common/BUILD @@ -9,7 +9,9 @@ cc_library( cc_library( name = "common_converter", hdrs = ["endianess_converter.h"], - visibility = ["//core:__subpackages__"], + visibility = [ + "//core:__subpackages__", + "//communication-core:__subpackages__"], ) cc_library( diff --git a/core/gpio/BUILD b/core/gpio/BUILD index 191cde1f..6143c16c 100644 --- a/core/gpio/BUILD +++ b/core/gpio/BUILD @@ -8,8 +8,13 @@ cc_library( name = "gpio_drivers", srcs = ["GPIO_digital_driver.cpp"], hdrs = ["GPIO_digital_driver.h"], - visibility = ["//core:__subpackages__"], + visibility = [ + "//core:__subpackages__", + "//mw:__subpackages__", + "//apps:__subpackages__"], deps = [ ":gpio_interface", + "//core/common:common_types", + "//core/logger:Logger" ], ) \ No newline at end of file diff --git a/core/gpio/GPIO_digital_driver.cpp b/core/gpio/GPIO_digital_driver.cpp index d71a246a..5919cf3a 100644 --- a/core/gpio/GPIO_digital_driver.cpp +++ b/core/gpio/GPIO_digital_driver.cpp @@ -12,63 +12,86 @@ #include #include "GPIO_digital_driver.h" +#include "core/logger/Logger.h" namespace simba { namespace core { namespace gpio { -GpioDigitalDriver::GpioDigitalDriver() { -} +GpioDigitalDriver::GpioDigitalDriver() {} -std::string GpioDigitalDriver::getEndpointPath -(uint8_t pinNumber, std::string endpoint) { - return this->path+std::to_string(pinNumber)+"/"+endpoint; +GpioDigitalDriver::~GpioDigitalDriver() { + for (auto pin : this->registered_pins.getPins()) { + if (!this->unregisterPin(pin.number)) { + AppLogger::Error("Cant close gpio file"); + } + } } -core::ErrorCode GpioDigitalDriver::setValue(uint8_t pinNumber , uint8_t value) { +core::ErrorCode GpioDigitalDriver::unregisterPin(uint8_t pinNumber) { std::ofstream file; - file.open(this->getEndpointPath(pinNumber, "value")); + file.open(this->path+"/unexport"); if (!file.is_open()) { return core::ErrorCode::kError; } - if (this->getDirection(pinNumber) != OUT) { - return core::ErrorCode::kConnectionError; - } - file << value; + file << std::to_string(pinNumber); file.close(); return core::ErrorCode::kOk; } -core::ErrorCode GpioDigitalDriver::setDirection -(uint8_t pinNumber , direction_t direction) { +core::ErrorCode GpioDigitalDriver::initializePin(uint8_t pinNumber, direction_t direction) { std::ofstream file; - file.open(this->getEndpointPath(pinNumber, "direction")); + file.open(this->path+"/export"); if (!file.is_open()) { + AppLogger::Error("Cant export pin"); + return core::ErrorCode::kError; + } + file << std::to_string(pinNumber); + file.close(); + if (this->setDirection(pinNumber, direction) != core::ErrorCode::kOk) { + AppLogger::Error("cant set direction"); + return core::ErrorCode::kError; + } + this->registered_pins.AddPin(pinNumber, direction); + return core::ErrorCode::kOk; +} + + +std::string GpioDigitalDriver::getEndpointPath(uint8_t pinNumber, std::string endpoint) { + return this->path+"/gpio"+std::to_string(pinNumber)+"/"+endpoint; +} + +core::ErrorCode GpioDigitalDriver::setValue(uint8_t pinNumber , uint8_t value) { + if ( this->registered_pins.getPinDirection(pinNumber) != direction_t::OUT ) { return core::ErrorCode::kInitializeError; } - if (direction == IN) { - file << "in"; - } else { - file << "out"; + std::ofstream file; + file.open(this->getEndpointPath(pinNumber, "value")); + if (!file.is_open()) { + AppLogger::Error("error"); + return core::ErrorCode::kError; } + file << std::to_string(value); file.close(); + return core::ErrorCode::kOk; } -core::ErrorCode GpioDigitalDriver::setActivePinLow(uint8_t pinNumber, - bool value) { +core::ErrorCode GpioDigitalDriver::setDirection(uint8_t pinNumber , direction_t direction) { std::ofstream file; - file.open(this->getEndpointPath(pinNumber, "active_low")); + file.open(this->getEndpointPath(pinNumber, "direction")); if (!file.is_open()) { return core::ErrorCode::kInitializeError; } - if (this->getDirection(pinNumber) != IN) { - return core::ErrorCode::kConnectionError; - } - file << value; + file << (direction == direction_t::IN ? "in" : "out"); file.close(); + this->registered_pins.SetDirection(pinNumber, direction); + return ErrorCode::kOk; } uint8_t GpioDigitalDriver::getValue(uint8_t pinNumber) { + if (this->registered_pins.getPinDirection(pinNumber)!= direction_t::IN) { + return ErrorCode::kError; + } std::ifstream file; file.open(this->getEndpointPath(pinNumber, "value")); if (!file.is_open()) { @@ -84,7 +107,7 @@ direction_t GpioDigitalDriver::getDirection(uint8_t pinNumber) { std::ifstream file; file.open(this->getEndpointPath(pinNumber, "direction")); if (!file.is_open()) { - return; + return OUT; } uint8_t direction; file >> direction; @@ -92,18 +115,6 @@ direction_t GpioDigitalDriver::getDirection(uint8_t pinNumber) { return static_cast(direction); } -bool GpioDigitalDriver::getActivePinLow(uint8_t pinNumber) { - std::ifstream file; - file.open(this->getEndpointPath(pinNumber, "active_low")); - if (!file.is_open()) { - return; - } - bool active; - file >> active; - file.close(); - return active; -} - } // namespace gpio } // namespace core } // namespace simba diff --git a/core/gpio/GPIO_digital_driver.h b/core/gpio/GPIO_digital_driver.h index 28c506a1..ca2ebea5 100644 --- a/core/gpio/GPIO_digital_driver.h +++ b/core/gpio/GPIO_digital_driver.h @@ -15,15 +15,61 @@ #include #include +#include namespace simba { namespace core { namespace gpio { +struct Pin{ + uint16_t number; + direction_t direction_; +}; +class Pins{ + private: + std::vector pins; + + public: + std::vector getPins() { + return this->pins; + } + core::ErrorCode AddPin(uint16_t pinNumber, direction_t direction) { + this->pins.push_back(Pin(pinNumber, direction)); + } + bool pinIsRegistered(uint16_t pinNumber) { + for (auto pin : this->pins) { + if (pin.number == pinNumber) { + return true; + } + } + return false; + } + direction_t getPinDirection(uint16_t pinNumber) { + for (auto pin : this->pins) { + if (pin.number == pinNumber) { + return pin.direction_; + } + } + return direction_t::ERROR; + } + ErrorCode SetDirection(uint16_t pinNumber, direction_t direction) { + for (auto pin : this->pins) { + if (pin.number == pinNumber) { + pin.direction_ = direction; + return ErrorCode::kOk; + } + } + return ErrorCode::kConnectionError; + } +}; + + class GpioDigitalDriver:IgpioDigitalDriver{ public: GpioDigitalDriver(); + ~GpioDigitalDriver(); + core::ErrorCode initializePin(uint8_t pinNumber, direction_t direction) override; /** * @brief Set the pin Value * @@ -48,13 +94,6 @@ class GpioDigitalDriver:IgpioDigitalDriver{ * @param value * @return core::ErrorCode */ - core::ErrorCode setActivePinLow(uint8_t pinNumber, bool value) override; - /** - * @brief Get the pin Value - * - * @param pinNumber - * @return uint8_t - */ uint8_t getValue(uint8_t pinNumber) override; /** * @brief Get the pin Direction @@ -70,12 +109,12 @@ class GpioDigitalDriver:IgpioDigitalDriver{ * @return true * @return false */ - bool getActivePinLow(uint8_t pinNumber) override; - private: std::string getEndpointPath(uint8_t pinNumber, std::string endpoint); + core::ErrorCode unregisterPin(uint8_t pinNumber); + const std::string path = "/sys/class/gpio"; - const std::string path = "/sys/class/gpio/gpio"; + Pins registered_pins; }; } // namespace gpio } // namespace core diff --git a/core/gpio/IGPIO_digital_driver.h b/core/gpio/IGPIO_digital_driver.h index 17b77dc0..3b4ae9f3 100644 --- a/core/gpio/IGPIO_digital_driver.h +++ b/core/gpio/IGPIO_digital_driver.h @@ -24,12 +24,16 @@ namespace gpio { enum direction_t{ IN, OUT, + ERROR, }; class IgpioDigitalDriver{ public: IgpioDigitalDriver() {} + + virtual core::ErrorCode initializePin(uint8_t pinNumber, direction_t direction) = 0; + /** * @brief Set the output Pin Value * @@ -47,14 +51,6 @@ class IgpioDigitalDriver{ virtual core::ErrorCode setDirection(uint8_t pinNumber, direction_t direction) = 0; - /** - * @brief Set the base value Pin to activate - * - * @param pinNumber - * @param value - */ - virtual core::ErrorCode setActivePinLow(uint8_t pinNumber, bool value) = 0; - /** * @brief read Pin Value * @@ -69,7 +65,6 @@ class IgpioDigitalDriver{ * @return direction_t */ virtual direction_t getDirection(uint8_t pinNumber) = 0; - virtual bool getActivePinLow(uint8_t pinNumber) = 0; }; } // namespace gpio } // namespace core diff --git a/diag/dtc/controller/I_dtc_controller.hpp b/diag/dtc/controller/I_dtc_controller.hpp index 6de3bb50..ff991566 100644 --- a/diag/dtc/controller/I_dtc_controller.hpp +++ b/diag/dtc/controller/I_dtc_controller.hpp @@ -28,7 +28,7 @@ class IDtcController{ virtual void Init(std::shared_ptr config) = 0; virtual core::ErrorCode RegisterError(const uint16_t &dtc_error_id, - const uint8_t &dtc_status, const std::vector &payload) = 0; + const std::vector &payload, const uint8_t &dtc_status) = 0; }; } // namespace dtc diff --git a/diag/dtc/controller/dtc_controller.cpp b/diag/dtc/controller/dtc_controller.cpp index f7308ea1..4b8462c6 100644 --- a/diag/dtc/controller/dtc_controller.cpp +++ b/diag/dtc/controller/dtc_controller.cpp @@ -23,7 +23,7 @@ void DtcController::Init( } core::ErrorCode DtcController::RegisterError(const uint16_t &dtc_error_id, -const uint8_t &dtc_status, const std::vector &payload) { + const std::vector &payload, const uint8_t &dtc_status) { DtcHeader hdr{dtc_error_id, dtc_status}; std::vector data = this->factory_.GetBuffer( std::make_shared(hdr), payload); diff --git a/diag/dtc/controller/dtc_controller.hpp b/diag/dtc/controller/dtc_controller.hpp index 93079be5..1bd15875 100644 --- a/diag/dtc/controller/dtc_controller.hpp +++ b/diag/dtc/controller/dtc_controller.hpp @@ -34,7 +34,7 @@ class DtcController:public IDtcController{ * @return core::ErrorCode */ core::ErrorCode RegisterError(const uint16_t &dtc_error_id, - const uint8_t &dtc_status, const std::vector &payload) override; + const std::vector &payload, const uint8_t &dtc_status) override; void Init(std::shared_ptr config) override; private: diff --git a/diag/dtc/specification/frame.md b/diag/dtc/specification/frame.md index bccd8d06..f62375ca 100644 --- a/diag/dtc/specification/frame.md +++ b/diag/dtc/specification/frame.md @@ -7,3 +7,15 @@ | length | 1 | Długość pola "payload" [uint8_t] (bajty) | | payload | 0-255 | dodatkowe dane opcjonalnie w celu przekazania jakiś danych [std::vector] | + +## dtc_status +| status | desc | +| --- | --- | +| 0x00 | idk | + + +## błędy + +| DTC_id | name | desc | payload | +| --- | --- | --- | +| 0x0000 | error Read file | | uint16_t service_id ( if known, else 0x0000), std::string file_name | \ No newline at end of file diff --git a/mw/diag/dtc/service/BUILD b/mw/diag/dtc/service/BUILD index a36576d8..bea4b2e1 100644 --- a/mw/diag/dtc/service/BUILD +++ b/mw/diag/dtc/service/BUILD @@ -3,7 +3,8 @@ cc_library( deps = [ "//mw/diag/dtc/database:dtc_db", "//mw/diag/dtc/database:dtc_db_element", - "//core", + "//core/logger:Logger", + "//core/application:simba_application", "//diag/dtc/factories:diag_dtc_msg_factory", "//communication-core/sockets:socket_interface", "//communication-core/sockets:socket_ipc", diff --git a/mw/diag/dtc/service/dtcService.h b/mw/diag/dtc/service/dtcService.h index 44b749d7..49aa3a5b 100644 --- a/mw/diag/dtc/service/dtcService.h +++ b/mw/diag/dtc/service/dtcService.h @@ -26,7 +26,6 @@ #include "communication-core/sockets/ipc_socket.h" #include "communication-core/sockets/socket_config.h" #include "core/application/application_mw.h" -#include "core/application/application_factory.h" #include "core/logger/ILogger.h" #include "diag/dtc/factories/dtc_msg_factory.hpp" #include "diag/base/data/data_structure.h" From e92d7cfd3c9e5152f78930c9c59ea83138073009 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Fri, 8 Mar 2024 13:33:28 +0100 Subject: [PATCH 27/71] init --- communication-core/network-data/BUILD | 13 ++++-- mw/gpio_server/BUILD | 12 ++++++ mw/gpio_server/Readme.md | 20 +++++++++ mw/gpio_server/controller/BUILD | 11 +++++ mw/gpio_server/controller/gpio_controller.cpp | 31 +++++++++++++ mw/gpio_server/controller/gpio_controller.hpp | 41 ++++++++++++++++++ mw/gpio_server/data/BUILD | 10 +++++ mw/gpio_server/data/header.cpp | 32 ++++++++++++++ mw/gpio_server/data/header.hpp | 43 +++++++++++++++++++ mw/gpio_server/gpio_mw.cpp | 0 mw/gpio_server/gpio_mw.hpp | 36 ++++++++++++++++ mw/gpio_server/tests/BUILD | 9 ++++ mw/gpio_server/tests/test_header.cpp | 35 +++++++++++++++ 13 files changed, 290 insertions(+), 3 deletions(-) create mode 100644 mw/gpio_server/BUILD create mode 100644 mw/gpio_server/Readme.md create mode 100644 mw/gpio_server/controller/BUILD create mode 100644 mw/gpio_server/controller/gpio_controller.cpp create mode 100644 mw/gpio_server/controller/gpio_controller.hpp create mode 100644 mw/gpio_server/data/BUILD create mode 100644 mw/gpio_server/data/header.cpp create mode 100644 mw/gpio_server/data/header.hpp create mode 100644 mw/gpio_server/gpio_mw.cpp create mode 100644 mw/gpio_server/gpio_mw.hpp create mode 100644 mw/gpio_server/tests/BUILD create mode 100644 mw/gpio_server/tests/test_header.cpp diff --git a/communication-core/network-data/BUILD b/communication-core/network-data/BUILD index 19704e23..864e2d8d 100644 --- a/communication-core/network-data/BUILD +++ b/communication-core/network-data/BUILD @@ -13,7 +13,8 @@ cc_library( "//communication-core:__subpackages__", "//diag/dtc/data:__subpackages__", "//mw/diag/dtc:__subpackages__", - "//diag/exec/data:__subpackages__" + "//diag/exec/data:__subpackages__", + "//mw:__subpackages__", ], deps = [":interfaces"], ) @@ -21,6 +22,12 @@ cc_library( cc_library( name = "network_data_type", hdrs = ["network_data_type.h"], - visibility = ["//communication-core:__subpackages__"], - deps = [":interfaces"], + visibility = [ + "//communication-core:__subpackages__", + "//mw:__subpackages__", + ], + deps = [ + ":interfaces", + "//core/common:common_converter", + ], ) diff --git a/mw/gpio_server/BUILD b/mw/gpio_server/BUILD new file mode 100644 index 00000000..f8003175 --- /dev/null +++ b/mw/gpio_server/BUILD @@ -0,0 +1,12 @@ +cc_binary( + name = "gpio_service", + srcs = [ + "gpio_mw.cpp", + "gpio_mw.hpp" + ], + deps = [ + "//core/gpio:gpio_drivers", + "//mw/gpio_server/data:gpio_hdr", + "//core/application:simba_application", + ], +) \ No newline at end of file diff --git a/mw/gpio_server/Readme.md b/mw/gpio_server/Readme.md new file mode 100644 index 00000000..280401f5 --- /dev/null +++ b/mw/gpio_server/Readme.md @@ -0,0 +1,20 @@ +# GPIO MW Service + +## Frame +| name | size | desc | +| --- | --- | --- | +| service_id | uint16_t | client id | +| pin_id | uint16_t | nadane id konkretnego pinu | +| value | uint8_t | wartość do ustawienia pinu (0/1)(LOW/HIGH) | + + +## Config + +{ + "pins":{ + :{ + "pin":33, + "direction":"out", + } + } +} \ No newline at end of file diff --git a/mw/gpio_server/controller/BUILD b/mw/gpio_server/controller/BUILD new file mode 100644 index 00000000..338f0e59 --- /dev/null +++ b/mw/gpio_server/controller/BUILD @@ -0,0 +1,11 @@ +cc_library( + name = "gpio_controller", + deps = [ + "//mw/gpio_server/data:gpio_hdr", + "//communication-core/sockets:socket_ipc", + "//core/gpio:gpio_drivers", + "//core/logger:Logger", + ], + srcs = ["gpio_controller.cpp"], + hdrs = ["gpio_controller.hpp"], +) \ No newline at end of file diff --git a/mw/gpio_server/controller/gpio_controller.cpp b/mw/gpio_server/controller/gpio_controller.cpp new file mode 100644 index 00000000..28746842 --- /dev/null +++ b/mw/gpio_server/controller/gpio_controller.cpp @@ -0,0 +1,31 @@ +/** + * @file gpio_controller.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "gpio_controller.hpp" + +namespace simba { +namespace gpio { + +void GPIOController::Init(uint16_t service_id) { + this->service_id = service_id; +} + +void GPIOController::SetPinValue(uint16_t pinID, uint8_t value) { + static gpio::Header hdr(this->service_id, pinID, value); + this->sock_.Transmit("SIMBA.GPIO", 0, hdr.GetBuffor()); +} + +uint8_t GPIOController::GetPinValue(uint16_t pinID) { +} + + +} // namespace gpio +} // namespace simba diff --git a/mw/gpio_server/controller/gpio_controller.hpp b/mw/gpio_server/controller/gpio_controller.hpp new file mode 100644 index 00000000..d1051895 --- /dev/null +++ b/mw/gpio_server/controller/gpio_controller.hpp @@ -0,0 +1,41 @@ +/** + * @file gpio_controller.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_GPIO_SERVER_CONTROLLER_GPIO_CONTROLLER_HPP_ +#define MW_GPIO_SERVER_CONTROLLER_GPIO_CONTROLLER_HPP_ + +#include +#include +#include + +#include "communication-core/sockets/ipc_socket.h" +#include "core/gpio/GPIO_digital_driver.h" +#include "mw/gpio_server/data/header.hpp" +#include "core/logger/Logger.h" + +namespace simba { +namespace gpio { + +class GPIOController { + private: + com::soc::IpcSocket sock_; + uint16_t service_id; + public: + void SetPinValue(uint16_t pinID, uint8_t value); + uint8_t GetPinValue(uint16_t pinID); + void Init(uint16_t service_id); +}; + +} // namespace gpio +} // namespace simba + + +#endif // MW_GPIO_SERVER_CONTROLLER_GPIO_CONTROLLER_HPP_ diff --git a/mw/gpio_server/data/BUILD b/mw/gpio_server/data/BUILD new file mode 100644 index 00000000..10efab1f --- /dev/null +++ b/mw/gpio_server/data/BUILD @@ -0,0 +1,10 @@ +cc_library( + name = "gpio_hdr", + srcs = ["header.cpp"], + hdrs = ["header.hpp"], + deps = [ + "//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type", + ], + visibility = ["//visibility:public"], +) \ No newline at end of file diff --git a/mw/gpio_server/data/header.cpp b/mw/gpio_server/data/header.cpp new file mode 100644 index 00000000..33c0abfc --- /dev/null +++ b/mw/gpio_server/data/header.cpp @@ -0,0 +1,32 @@ +/** + * @file header.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "header.hpp" +#include + +namespace simba { +namespace gpio { + +Header::Header(uint16_t service_id, uint16_t pin_id, uint8_t value){ + this->service_id = service_id; + this->pin_id = pin_id; + this->value = value; + this->SetData(); +} + +void Header::SetData() { + this->AddData(&service_id); + this->AddData(&pin_id); + this->AddData(&value); +} + +} // gpio +} // simba diff --git a/mw/gpio_server/data/header.hpp b/mw/gpio_server/data/header.hpp new file mode 100644 index 00000000..c25162b3 --- /dev/null +++ b/mw/gpio_server/data/header.hpp @@ -0,0 +1,43 @@ +/** + * @file header.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_GPIO_SERVER_DATA_HEADER_HPP_ +#define MW_GPIO_SERVER_DATA_HEADER_HPP_ + +#include + +#include "communication-core/network-data/network_data_structure.h" +#include "communication-core/network-data/network_data_type.h" + + +namespace simba { +namespace gpio { + +class Header : public com::core::network::NetworkDataStructure { + private: + com::core::network::uint16_t service_id; + com::core::network::uint16_t pin_id; + com::core::network::uint8_t value; + void SetData(); + public: + uint16_t GetServiceID() { return this->service_id.Get(); } + uint16_t GetPinID() { return this->pin_id.Get(); } + uint8_t GetValue() { return this->value.Get(); } + Header(uint16_t service_id, uint16_t pin_id, uint8_t value); +}; + +} // namespace gpio +} // namespace simba + + + + +#endif // MW_GPIO_SERVER_DATA_HEADER_HPP_ diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp new file mode 100644 index 00000000..e69de29b diff --git a/mw/gpio_server/gpio_mw.hpp b/mw/gpio_server/gpio_mw.hpp new file mode 100644 index 00000000..d5c9ef7d --- /dev/null +++ b/mw/gpio_server/gpio_mw.hpp @@ -0,0 +1,36 @@ +/** + * @file gpio_mw.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_GPIO_SERVER_GPIO_MW_HPP_ +#define MW_GPIO_SERVER_GPIO_MW_HPP_ + +#include "core/gpio/GPIO_digital_driver.h" +#include "communication-core/sockets/ipc_socket.h" + +namespace simba { +namespace mw { + +class GPIOMWService{ + private: + com::soc::IpcSocket sock_; + core::gpio::GpioDigitalDriver gpio_; + void RxCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data); + public: + +}; + +} +} + + + +#endif // MW_GPIO_SERVER_GPIO_MW_HPP_ diff --git a/mw/gpio_server/tests/BUILD b/mw/gpio_server/tests/BUILD new file mode 100644 index 00000000..0b80c7c2 --- /dev/null +++ b/mw/gpio_server/tests/BUILD @@ -0,0 +1,9 @@ +cc_test( + name = "data_structure", + srcs = ["test_header.cpp"], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//mw/gpio_server/data:gpio_hdr" + ] +) diff --git a/mw/gpio_server/tests/test_header.cpp b/mw/gpio_server/tests/test_header.cpp new file mode 100644 index 00000000..fcff9342 --- /dev/null +++ b/mw/gpio_server/tests/test_header.cpp @@ -0,0 +1,35 @@ +/** + * @file test_header.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#include + +#include "mw/gpio_server/data/header.hpp" + +TEST(GPIO_DATA_STRUCTURE, CONSTRUCTOR_CHECK) { + uint16_t service_id = 0x1111; + uint16_t pin_id = 0x11; + uint8_t value = 0x1; +simba::gpio::Header hdr{service_id, pin_id, value}; +EXPECT_EQ(hdr.GetServiceID(), service_id); +EXPECT_EQ(hdr.GetPinID(), pin_id); +EXPECT_EQ(hdr.GetValue(), value); +} + + +TEST(GPIO_MSG_FACTORY,CHECK_BUFFOR) { + simba::gpio::Header hdr(12,12,1); + auto data=hdr.GetBuffor(); + simba::gpio::Header hdr2(0x00,0x00,0x0); + hdr2.SetBuffor(data); + EXPECT_EQ(hdr.GetServiceID(),hdr2.GetServiceID()); + EXPECT_EQ(hdr.GetPinID(),hdr2.GetPinID()); + EXPECT_EQ(hdr.GetValue(),hdr2.GetValue()); +} \ No newline at end of file From 9394d2fbc3817b48fc435318c4a8227076bb0d1e Mon Sep 17 00:00:00 2001 From: Mateusz Date: Fri, 8 Mar 2024 15:17:58 +0100 Subject: [PATCH 28/71] basic_change_value_with_res_toTest --- core/gpio/GPIO_digital_driver.cpp | 5 +- core/gpio/GPIO_digital_driver.h | 1 + mw/gpio_server/BUILD | 1 + mw/gpio_server/Readme.md | 7 +- mw/gpio_server/controller/gpio_controller.cpp | 32 ++++++- mw/gpio_server/controller/gpio_controller.hpp | 4 +- mw/gpio_server/data/BUILD | 10 ++- mw/gpio_server/data/resHeader.cpp | 29 +++++++ mw/gpio_server/data/resHeader.hpp | 41 +++++++++ mw/gpio_server/gpio_mw.cpp | 84 +++++++++++++++++++ mw/gpio_server/gpio_mw.hpp | 25 ++++-- mw/gpio_server/tests/BUILD | 5 +- mw/gpio_server/tests/test_header.cpp | 14 ++-- mw/gpio_server/tests/test_resHeader.cpp | 31 +++++++ 14 files changed, 269 insertions(+), 20 deletions(-) create mode 100644 mw/gpio_server/data/resHeader.cpp create mode 100644 mw/gpio_server/data/resHeader.hpp create mode 100644 mw/gpio_server/tests/test_resHeader.cpp diff --git a/core/gpio/GPIO_digital_driver.cpp b/core/gpio/GPIO_digital_driver.cpp index 5919cf3a..7879db31 100644 --- a/core/gpio/GPIO_digital_driver.cpp +++ b/core/gpio/GPIO_digital_driver.cpp @@ -73,7 +73,10 @@ core::ErrorCode GpioDigitalDriver::setValue(uint8_t pinNumber , uint8_t value) { } file << std::to_string(value); file.close(); - return core::ErrorCode::kOk; + if (this->getValue(pinNumber) != value) { + return core::ErrorCode::kOk; + } + return core::ErrorCode::kError; } core::ErrorCode GpioDigitalDriver::setDirection(uint8_t pinNumber , direction_t direction) { diff --git a/core/gpio/GPIO_digital_driver.h b/core/gpio/GPIO_digital_driver.h index ca2ebea5..09bf17e4 100644 --- a/core/gpio/GPIO_digital_driver.h +++ b/core/gpio/GPIO_digital_driver.h @@ -35,6 +35,7 @@ class Pins{ } core::ErrorCode AddPin(uint16_t pinNumber, direction_t direction) { this->pins.push_back(Pin(pinNumber, direction)); + return core::ErrorCode::kOk; } bool pinIsRegistered(uint16_t pinNumber) { for (auto pin : this->pins) { diff --git a/mw/gpio_server/BUILD b/mw/gpio_server/BUILD index f8003175..d66ba93b 100644 --- a/mw/gpio_server/BUILD +++ b/mw/gpio_server/BUILD @@ -8,5 +8,6 @@ cc_binary( "//core/gpio:gpio_drivers", "//mw/gpio_server/data:gpio_hdr", "//core/application:simba_application", + "//core/json:simba_json", ], ) \ No newline at end of file diff --git a/mw/gpio_server/Readme.md b/mw/gpio_server/Readme.md index 280401f5..73055c65 100644 --- a/mw/gpio_server/Readme.md +++ b/mw/gpio_server/Readme.md @@ -1,12 +1,17 @@ # GPIO MW Service -## Frame +## Frame REQ | name | size | desc | | --- | --- | --- | | service_id | uint16_t | client id | | pin_id | uint16_t | nadane id konkretnego pinu | | value | uint8_t | wartość do ustawienia pinu (0/1)(LOW/HIGH) | +## Frame RES +| name | size | desc | +| --- | --- | --- | +| pin_id | uint16_t | | +| value | uint8_t | | ## Config diff --git a/mw/gpio_server/controller/gpio_controller.cpp b/mw/gpio_server/controller/gpio_controller.cpp index 28746842..dd2cb5fb 100644 --- a/mw/gpio_server/controller/gpio_controller.cpp +++ b/mw/gpio_server/controller/gpio_controller.cpp @@ -9,7 +9,13 @@ * */ +#include +#include +#include +#include + #include "gpio_controller.hpp" +#include "mw/gpio_server/data/resHeader.hpp" namespace simba { namespace gpio { @@ -18,9 +24,31 @@ void GPIOController::Init(uint16_t service_id) { this->service_id = service_id; } -void GPIOController::SetPinValue(uint16_t pinID, uint8_t value) { +std::optional> GPIOController::ReceiveData(std::string path, uint8_t buffer_size) { + int sockrc; + struct sockaddr_un servaddr; + sockrc = socket(AF_UNIX, SOCK_DGRAM, 0); + servaddr.sun_family = AF_UNIX; + strncpy(servaddr.sun_path, ("/run/"+path).c_str(), sizeof(servaddr.sun_path)-1); + bind(sockrc, (const struct sockaddr *)&servaddr, sizeof(servaddr)); + std::vector buffer(buffer_size); + recvfrom(sockrc, buffer.data(), buffer.size(), MSG_WAITALL, NULL, NULL); + close(sockrc); + return std::optional>(buffer); +} + +core::ErrorCode GPIOController::SetPinValue(uint16_t pinID, uint8_t value) { static gpio::Header hdr(this->service_id, pinID, value); - this->sock_.Transmit("SIMBA.GPIO", 0, hdr.GetBuffor()); + gpio::ResHeader resHdr(0, 0); + this->sock_.Transmit("SIMBA.GPIO.SET", 0, hdr.GetBuffor()); + auto data = this->ReceiveData("SIMBA.GPIO.SET."+std::to_string(this->service_id), 3); + if (data.has_value()) { + resHdr.SetBuffor(data.value()); + } + if (resHdr.GetValue() == value) { + return core::ErrorCode::kOk; + } + return core::ErrorCode::kError; } uint8_t GPIOController::GetPinValue(uint16_t pinID) { diff --git a/mw/gpio_server/controller/gpio_controller.hpp b/mw/gpio_server/controller/gpio_controller.hpp index d1051895..b816776a 100644 --- a/mw/gpio_server/controller/gpio_controller.hpp +++ b/mw/gpio_server/controller/gpio_controller.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include "communication-core/sockets/ipc_socket.h" #include "core/gpio/GPIO_digital_driver.h" @@ -28,8 +29,9 @@ class GPIOController { private: com::soc::IpcSocket sock_; uint16_t service_id; + std::optional> ReceiveData(std::string path, uint8_t buffer_size); public: - void SetPinValue(uint16_t pinID, uint8_t value); + core::ErrorCode SetPinValue(uint16_t pinID, uint8_t value); uint8_t GetPinValue(uint16_t pinID); void Init(uint16_t service_id); }; diff --git a/mw/gpio_server/data/BUILD b/mw/gpio_server/data/BUILD index 10efab1f..46433a11 100644 --- a/mw/gpio_server/data/BUILD +++ b/mw/gpio_server/data/BUILD @@ -1,7 +1,13 @@ cc_library( name = "gpio_hdr", - srcs = ["header.cpp"], - hdrs = ["header.hpp"], + srcs = [ + "header.cpp", + "resHeader.cpp", + ], + hdrs = [ + "header.hpp", + "resHeader.hpp" + ], deps = [ "//communication-core/network-data:network_data_structure", "//communication-core/network-data:network_data_type", diff --git a/mw/gpio_server/data/resHeader.cpp b/mw/gpio_server/data/resHeader.cpp new file mode 100644 index 00000000..1b2d007a --- /dev/null +++ b/mw/gpio_server/data/resHeader.cpp @@ -0,0 +1,29 @@ +/** + * @file resHeader.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ +#include "resHeader.hpp" +#include + +namespace simba { +namespace gpio { + +ResHeader::ResHeader(uint16_t pin_id, uint8_t value){ + this->pin_id = pin_id; + this->value = value; + this->SetData(); +} + +void ResHeader::SetData() { + this->AddData(&pin_id); + this->AddData(&value); +} + +} // gpio +} // simba diff --git a/mw/gpio_server/data/resHeader.hpp b/mw/gpio_server/data/resHeader.hpp new file mode 100644 index 00000000..1d050c84 --- /dev/null +++ b/mw/gpio_server/data/resHeader.hpp @@ -0,0 +1,41 @@ +/** + * @file resHeader.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_GPIO_SERVER_DATA_RESHEADER_HPP_ +#define MW_GPIO_SERVER_DATA_RESHEADER_HPP_ + +#include + +#include "communication-core/network-data/network_data_structure.h" +#include "communication-core/network-data/network_data_type.h" + + +namespace simba { +namespace gpio { + +class ResHeader : public com::core::network::NetworkDataStructure { + private: + com::core::network::uint16_t pin_id; + com::core::network::uint8_t value; + void SetData(); + public: + uint16_t GetPinID() { return this->pin_id.Get(); } + uint8_t GetValue() { return this->value.Get(); } + ResHeader(uint16_t pin_id, uint8_t value); +}; + +} // namespace gpio +} // namespace simba + + + + +#endif // MW_GPIO_SERVER_DATA_RESHEADER_HPP_ diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp index e69de29b..a27ffb2b 100644 --- a/mw/gpio_server/gpio_mw.cpp +++ b/mw/gpio_server/gpio_mw.cpp @@ -0,0 +1,84 @@ +/** + * @file gpio_mw.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include +#include + +#include "gpio_mw.hpp" +#include "mw/gpio_server/data/header.hpp" +#include "mw/gpio_server/data/resHeader.hpp" +#include "core/json/json_parser.h" +#include "core/gpio/IGPIO_digital_driver.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace mw { + +void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data) { + if (data.size() <= 0) { + return; + } + gpio::Header hdr(0, 0, 0); + hdr.SetBuffor(data); + auto it = this->config.find(hdr.GetPinID()); + if (it == this->config.end()) { + AppLogger::Warning("Unknown pin with ID: "+std::to_string(hdr.GetPinID())); + return; + } + if (it->second.direction != core::gpio::direction_t::OUT) { + AppLogger::Warning("Try to set IN pin value, ID: "+std::to_string(hdr.GetPinID())); + } + if (this->gpio_driver_.getValue(it->second.pinNum) != hdr.GetValue()) { + if (this->gpio_driver_.setValue(it->second.pinNum, hdr.GetValue()) == core::ErrorCode::kOk) { + gpio::ResHeader resHdr(hdr.GetPinID(), hdr.GetValue()); + this->sock_.Transmit("SIMBA.GPIO.SET."+std::to_string(hdr.GetServiceID()), 0, resHdr.GetBuffor()); + } else { + gpio::ResHeader resHdr(hdr.GetPinID(), !hdr.GetValue()); + this->sock_.Transmit("SIMBA.GPIO.SET."+std::to_string(hdr.GetServiceID()), 0, resHdr.GetBuffor()); + } + } +} + +core::ErrorCode GPIOMWService::Run(std::stop_token token) { + while (true) { + this->gpio_driver_.setValue(21, 0); + this->gpio_driver_.setValue(22, 1); + std::this_thread::sleep_for(std::chrono::seconds(1)); + this->gpio_driver_.setValue(21, 1); + this->gpio_driver_.setValue(22, 0); + std::this_thread::sleep_for(std::chrono::seconds(1)); + } +} + +core::ErrorCode GPIOMWService::Initialize( + const std::unordered_map& parms) { + this->sock_.Init({"SIMBA.GPIO.SET", 0, 0}); + this->sock_.SetRXCallback(std::bind(&GPIOMWService::RxCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + this->InitializePins(); + this->sock_.StartRXThread(); +} +void GPIOMWService::InitializePins() { + // TODO (matikrajek42@gmail.com) READ config file // NOLINT + this->config.insert({1, GpioConf{21, core::gpio::direction_t::OUT}}); + this->config.insert({2, GpioConf{22, core::gpio::direction_t::OUT}}); + this->config.insert({3, GpioConf{23, core::gpio::direction_t::OUT}}); + this->config.insert({4, GpioConf{24, core::gpio::direction_t::OUT}}); + + for (auto pin : this->config) { + this->gpio_driver_.initializePin(pin.second.pinNum, pin.second.direction); + } +} + + +} // namespace mw +} // namespace simba diff --git a/mw/gpio_server/gpio_mw.hpp b/mw/gpio_server/gpio_mw.hpp index d5c9ef7d..a0d532c4 100644 --- a/mw/gpio_server/gpio_mw.hpp +++ b/mw/gpio_server/gpio_mw.hpp @@ -12,24 +12,39 @@ #ifndef MW_GPIO_SERVER_GPIO_MW_HPP_ #define MW_GPIO_SERVER_GPIO_MW_HPP_ +#include +#include +#include + #include "core/gpio/GPIO_digital_driver.h" #include "communication-core/sockets/ipc_socket.h" +#include "core/application/application_mw.h" namespace simba { namespace mw { -class GPIOMWService{ +struct GpioConf{ + uint16_t pinNum; + core::gpio::direction_t direction; +}; + +class GPIOMWService : public simba::core::ApplicationMW { private: com::soc::IpcSocket sock_; - core::gpio::GpioDigitalDriver gpio_; + core::gpio::GpioDigitalDriver gpio_driver_; + std::unordered_map config; void RxCallback(const std::string& ip, const std::uint16_t& port, - const std::vector data); + const std::vector data); + void InitializePins(); public: + core::ErrorCode Run(std::stop_token token) final; + core::ErrorCode Initialize( + const std::unordered_map& parms) final; }; -} -} +} // namespace mw +} // namespace simba diff --git a/mw/gpio_server/tests/BUILD b/mw/gpio_server/tests/BUILD index 0b80c7c2..7f16cfb4 100644 --- a/mw/gpio_server/tests/BUILD +++ b/mw/gpio_server/tests/BUILD @@ -1,6 +1,9 @@ cc_test( name = "data_structure", - srcs = ["test_header.cpp"], + srcs = [ + "test_header.cpp", + "test_resHeader.cpp", + ], visibility = ["//visibility:public"], deps=[ "@com_google_googletest//:gtest_main", diff --git a/mw/gpio_server/tests/test_header.cpp b/mw/gpio_server/tests/test_header.cpp index fcff9342..0e010ee8 100644 --- a/mw/gpio_server/tests/test_header.cpp +++ b/mw/gpio_server/tests/test_header.cpp @@ -24,12 +24,12 @@ EXPECT_EQ(hdr.GetValue(), value); } -TEST(GPIO_MSG_FACTORY,CHECK_BUFFOR) { - simba::gpio::Header hdr(12,12,1); - auto data=hdr.GetBuffor(); - simba::gpio::Header hdr2(0x00,0x00,0x0); +TEST(GPIO_MSG_FACTORY, CHECK_BUFFOR) { + simba::gpio::Header hdr(12, 12, 1); + auto data = hdr.GetBuffor(); + simba::gpio::Header hdr2(0x00, 0x00, 0x0); hdr2.SetBuffor(data); - EXPECT_EQ(hdr.GetServiceID(),hdr2.GetServiceID()); - EXPECT_EQ(hdr.GetPinID(),hdr2.GetPinID()); - EXPECT_EQ(hdr.GetValue(),hdr2.GetValue()); + EXPECT_EQ(hdr.GetServiceID(), hdr2.GetServiceID()); + EXPECT_EQ(hdr.GetPinID(), hdr2.GetPinID()); + EXPECT_EQ(hdr.GetValue(), hdr2.GetValue()); } \ No newline at end of file diff --git a/mw/gpio_server/tests/test_resHeader.cpp b/mw/gpio_server/tests/test_resHeader.cpp new file mode 100644 index 00000000..daa9b298 --- /dev/null +++ b/mw/gpio_server/tests/test_resHeader.cpp @@ -0,0 +1,31 @@ +/** + * @file test_resHeader.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ +#include + +#include "mw/gpio_server/data/resHeader.hpp" + +TEST(GPIO_ResDATA_STRUCTURE, CONSTRUCTOR_CHECK) { + uint16_t pin_id = 0x11; + uint8_t value = 0x1; +simba::gpio::ResHeader hdr{pin_id, value}; +EXPECT_EQ(hdr.GetPinID(), pin_id); +EXPECT_EQ(hdr.GetValue(), value); +} + + +TEST(GPIO_RES_MSG_FACTORY, CHECK_BUFFOR) { + simba::gpio::ResHeader hdr(12, 1); + auto data = hdr.GetBuffor(); + simba::gpio::ResHeader hdr2(0x00, 0x0); + hdr2.SetBuffor(data); + EXPECT_EQ(hdr.GetPinID(), hdr2.GetPinID()); + EXPECT_EQ(hdr.GetValue(), hdr2.GetValue()); +} \ No newline at end of file From 1bb163592397bd82de4f290158e72f914da17d6e Mon Sep 17 00:00:00 2001 From: Mateusz Date: Fri, 8 Mar 2024 19:11:37 +0100 Subject: [PATCH 29/71] . --- apps/example/BUILD | 2 +- apps/example/router.cc | 12 ++--- apps/example/router.h | 4 +- mw/gpio_server/BUILD | 17 +++++-- mw/gpio_server/controller/BUILD | 3 ++ mw/gpio_server/controller/gpio_controller.cpp | 31 ++---------- mw/gpio_server/controller/gpio_controller.hpp | 10 ++-- mw/gpio_server/data/BUILD | 2 - mw/gpio_server/data/resHeader.cpp | 29 ----------- mw/gpio_server/data/resHeader.hpp | 41 ---------------- mw/gpio_server/gpio_mw.cpp | 48 +++++++++++-------- mw/gpio_server/gpio_mw.hpp | 1 + mw/gpio_server/main.cpp | 17 +++++++ mw/gpio_server/tests/test_header.cpp | 16 ++++++- 14 files changed, 97 insertions(+), 136 deletions(-) delete mode 100644 mw/gpio_server/data/resHeader.cpp delete mode 100644 mw/gpio_server/data/resHeader.hpp create mode 100644 mw/gpio_server/main.cpp diff --git a/apps/example/BUILD b/apps/example/BUILD index 1b8e2663..de9de4cd 100644 --- a/apps/example/BUILD +++ b/apps/example/BUILD @@ -9,7 +9,7 @@ cc_binary( deps = [ "//core/application:simba_application", "@untar", - "//core/gpio:gpio_drivers" + "//mw/gpio_server/controller:gpio_controller", ], ) diff --git a/apps/example/router.cc b/apps/example/router.cc index 2fc5a3b7..6a09b926 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -19,19 +19,17 @@ core::ErrorCode Router::Run(std::stop_token token) { AppLogger::Debug("AppLogger::Debug"); AppLogger::Info("AppLogger::Info"); AppLogger::Warning("AppLogger::Warning"); - AppLogger::Error("AppLogger::Error"); - this->gpio_.setValue(21, 1); - std::this_thread::sleep_for(std::chrono::seconds{1}); - this->gpio_.setValue(21, 0); - std::this_thread::sleep_for(std::chrono::seconds{1}); + this->gpio_.SetPinValue(1, gpio::Value::HIGH); + std::this_thread::sleep_for(std::chrono::seconds(1)); + this->gpio_.SetPinValue(1, gpio::Value::LOW); + std::this_thread::sleep_for(std::chrono::seconds(1)); } - return core::ErrorCode::kOk; } core::ErrorCode Router::Initialize( const std::unordered_map& parms) { - this->gpio_.initializePin(21, core::gpio::direction_t::OUT); + this->gpio_.Init(12); return core::ErrorCode::kOk; } } // namespace router diff --git a/apps/example/router.h b/apps/example/router.h index ce706171..df78f74e 100644 --- a/apps/example/router.h +++ b/apps/example/router.h @@ -14,11 +14,12 @@ #include #include "core/application/application_no_ipc.h" -#include "core/gpio/GPIO_digital_driver.h" +#include "mw/gpio_server/controller/gpio_controller.hpp" namespace simba { namespace router { class Router : public core::ApplicationNoIPC{ protected: + gpio::GPIOController gpio_; /** * @brief This function is called to launch the application * @@ -35,7 +36,6 @@ class Router : public core::ApplicationNoIPC{ public: ~Router() = default; - core::gpio::GpioDigitalDriver gpio_; }; } // namespace router diff --git a/mw/gpio_server/BUILD b/mw/gpio_server/BUILD index d66ba93b..3de22557 100644 --- a/mw/gpio_server/BUILD +++ b/mw/gpio_server/BUILD @@ -1,13 +1,24 @@ -cc_binary( - name = "gpio_service", +cc_library( + name = "gpio_service_lib", srcs = [ "gpio_mw.cpp", - "gpio_mw.hpp" ], + hdrs=[ + "gpio_mw.hpp" + ], deps = [ "//core/gpio:gpio_drivers", "//mw/gpio_server/data:gpio_hdr", "//core/application:simba_application", "//core/json:simba_json", ], +) + +cc_binary( + name = "gpio_service", + deps = [":gpio_service_lib"], + srcs = ["main.cpp"], + visibility = [ + "//deployment:__subpackages__", + ], ) \ No newline at end of file diff --git a/mw/gpio_server/controller/BUILD b/mw/gpio_server/controller/BUILD index 338f0e59..be70fef6 100644 --- a/mw/gpio_server/controller/BUILD +++ b/mw/gpio_server/controller/BUILD @@ -8,4 +8,7 @@ cc_library( ], srcs = ["gpio_controller.cpp"], hdrs = ["gpio_controller.hpp"], + visibility = [ + "//apps:__subpackages__", + ], ) \ No newline at end of file diff --git a/mw/gpio_server/controller/gpio_controller.cpp b/mw/gpio_server/controller/gpio_controller.cpp index dd2cb5fb..079c587e 100644 --- a/mw/gpio_server/controller/gpio_controller.cpp +++ b/mw/gpio_server/controller/gpio_controller.cpp @@ -15,7 +15,6 @@ #include #include "gpio_controller.hpp" -#include "mw/gpio_server/data/resHeader.hpp" namespace simba { namespace gpio { @@ -24,34 +23,14 @@ void GPIOController::Init(uint16_t service_id) { this->service_id = service_id; } -std::optional> GPIOController::ReceiveData(std::string path, uint8_t buffer_size) { - int sockrc; - struct sockaddr_un servaddr; - sockrc = socket(AF_UNIX, SOCK_DGRAM, 0); - servaddr.sun_family = AF_UNIX; - strncpy(servaddr.sun_path, ("/run/"+path).c_str(), sizeof(servaddr.sun_path)-1); - bind(sockrc, (const struct sockaddr *)&servaddr, sizeof(servaddr)); - std::vector buffer(buffer_size); - recvfrom(sockrc, buffer.data(), buffer.size(), MSG_WAITALL, NULL, NULL); - close(sockrc); - return std::optional>(buffer); +core::ErrorCode GPIOController::SetPinValue(uint16_t pinID, Value value) { + gpio::Header hdr(this->service_id, pinID, value); + return this->sock_.Transmit("SIMBA.GPIO.SET", 0, hdr.GetBuffor()); } -core::ErrorCode GPIOController::SetPinValue(uint16_t pinID, uint8_t value) { - static gpio::Header hdr(this->service_id, pinID, value); - gpio::ResHeader resHdr(0, 0); - this->sock_.Transmit("SIMBA.GPIO.SET", 0, hdr.GetBuffor()); - auto data = this->ReceiveData("SIMBA.GPIO.SET."+std::to_string(this->service_id), 3); - if (data.has_value()) { - resHdr.SetBuffor(data.value()); - } - if (resHdr.GetValue() == value) { - return core::ErrorCode::kOk; - } - return core::ErrorCode::kError; -} +Value GPIOController::GetPinValue(uint16_t pinID) { -uint8_t GPIOController::GetPinValue(uint16_t pinID) { + return Value::HIGH; } diff --git a/mw/gpio_server/controller/gpio_controller.hpp b/mw/gpio_server/controller/gpio_controller.hpp index b816776a..5a9e01cd 100644 --- a/mw/gpio_server/controller/gpio_controller.hpp +++ b/mw/gpio_server/controller/gpio_controller.hpp @@ -25,14 +25,18 @@ namespace simba { namespace gpio { +enum Value{ + LOW = 0, + HIGH = 1, +}; + class GPIOController { private: com::soc::IpcSocket sock_; uint16_t service_id; - std::optional> ReceiveData(std::string path, uint8_t buffer_size); public: - core::ErrorCode SetPinValue(uint16_t pinID, uint8_t value); - uint8_t GetPinValue(uint16_t pinID); + core::ErrorCode SetPinValue(uint16_t pinID, Value value); + Value GetPinValue(uint16_t pinID); void Init(uint16_t service_id); }; diff --git a/mw/gpio_server/data/BUILD b/mw/gpio_server/data/BUILD index 46433a11..dd2bb9b8 100644 --- a/mw/gpio_server/data/BUILD +++ b/mw/gpio_server/data/BUILD @@ -2,11 +2,9 @@ cc_library( name = "gpio_hdr", srcs = [ "header.cpp", - "resHeader.cpp", ], hdrs = [ "header.hpp", - "resHeader.hpp" ], deps = [ "//communication-core/network-data:network_data_structure", diff --git a/mw/gpio_server/data/resHeader.cpp b/mw/gpio_server/data/resHeader.cpp deleted file mode 100644 index 1b2d007a..00000000 --- a/mw/gpio_server/data/resHeader.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @file resHeader.cpp - * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief - * @version 0.1 - * @date 2024-03-08 - * - * @copyright Copyright (c) 2024 - * - */ -#include "resHeader.hpp" -#include - -namespace simba { -namespace gpio { - -ResHeader::ResHeader(uint16_t pin_id, uint8_t value){ - this->pin_id = pin_id; - this->value = value; - this->SetData(); -} - -void ResHeader::SetData() { - this->AddData(&pin_id); - this->AddData(&value); -} - -} // gpio -} // simba diff --git a/mw/gpio_server/data/resHeader.hpp b/mw/gpio_server/data/resHeader.hpp deleted file mode 100644 index 1d050c84..00000000 --- a/mw/gpio_server/data/resHeader.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file resHeader.hpp - * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief - * @version 0.1 - * @date 2024-03-08 - * - * @copyright Copyright (c) 2024 - * - */ - -#ifndef MW_GPIO_SERVER_DATA_RESHEADER_HPP_ -#define MW_GPIO_SERVER_DATA_RESHEADER_HPP_ - -#include - -#include "communication-core/network-data/network_data_structure.h" -#include "communication-core/network-data/network_data_type.h" - - -namespace simba { -namespace gpio { - -class ResHeader : public com::core::network::NetworkDataStructure { - private: - com::core::network::uint16_t pin_id; - com::core::network::uint8_t value; - void SetData(); - public: - uint16_t GetPinID() { return this->pin_id.Get(); } - uint8_t GetValue() { return this->value.Get(); } - ResHeader(uint16_t pin_id, uint8_t value); -}; - -} // namespace gpio -} // namespace simba - - - - -#endif // MW_GPIO_SERVER_DATA_RESHEADER_HPP_ diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp index a27ffb2b..0078d020 100644 --- a/mw/gpio_server/gpio_mw.cpp +++ b/mw/gpio_server/gpio_mw.cpp @@ -11,19 +11,22 @@ #include #include #include +#include #include "gpio_mw.hpp" #include "mw/gpio_server/data/header.hpp" -#include "mw/gpio_server/data/resHeader.hpp" #include "core/json/json_parser.h" #include "core/gpio/IGPIO_digital_driver.h" #include "core/logger/Logger.h" +using json = nlohmann::json; + namespace simba { namespace mw { void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, const std::vector data) { + AppLogger::Debug("Receive change pin command"); if (data.size() <= 0) { return; } @@ -38,25 +41,16 @@ void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, AppLogger::Warning("Try to set IN pin value, ID: "+std::to_string(hdr.GetPinID())); } if (this->gpio_driver_.getValue(it->second.pinNum) != hdr.GetValue()) { - if (this->gpio_driver_.setValue(it->second.pinNum, hdr.GetValue()) == core::ErrorCode::kOk) { - gpio::ResHeader resHdr(hdr.GetPinID(), hdr.GetValue()); - this->sock_.Transmit("SIMBA.GPIO.SET."+std::to_string(hdr.GetServiceID()), 0, resHdr.GetBuffor()); - } else { - gpio::ResHeader resHdr(hdr.GetPinID(), !hdr.GetValue()); - this->sock_.Transmit("SIMBA.GPIO.SET."+std::to_string(hdr.GetServiceID()), 0, resHdr.GetBuffor()); + AppLogger::Info("set pin to position:"+std::to_string(hdr.GetValue())); + if (this->gpio_driver_.setValue(it->second.pinNum, hdr.GetValue()) != core::ErrorCode::kOk) { + AppLogger::Warning("pin state not change"); } } } core::ErrorCode GPIOMWService::Run(std::stop_token token) { - while (true) { - this->gpio_driver_.setValue(21, 0); - this->gpio_driver_.setValue(22, 1); - std::this_thread::sleep_for(std::chrono::seconds(1)); - this->gpio_driver_.setValue(21, 1); - this->gpio_driver_.setValue(22, 0); - std::this_thread::sleep_for(std::chrono::seconds(1)); - } + this->SleepMainThread(); + return core::ErrorCode::kOk; } core::ErrorCode GPIOMWService::Initialize( @@ -66,14 +60,26 @@ core::ErrorCode GPIOMWService::Initialize( std::placeholders::_2, std::placeholders::_3)); this->InitializePins(); this->sock_.StartRXThread(); + return core::ErrorCode::kOk; } void GPIOMWService::InitializePins() { - // TODO (matikrajek42@gmail.com) READ config file // NOLINT - this->config.insert({1, GpioConf{21, core::gpio::direction_t::OUT}}); - this->config.insert({2, GpioConf{22, core::gpio::direction_t::OUT}}); - this->config.insert({3, GpioConf{23, core::gpio::direction_t::OUT}}); - this->config.insert({4, GpioConf{24, core::gpio::direction_t::OUT}}); - + std::ifstream file("/opt/gpio/etc/config.json"); + if (!file.is_open()) { + AppLogger::Warning("file not found"); + return; + } + nlohmann::json data = nlohmann::json::parse(file); + if (!data.contains("gpio")) { + AppLogger::Warning("cant find config file"); + return; + } + for (const auto& gpio : data["gpio"]) { + uint16_t pin_id = static_cast(data.at("id")); + uint16_t pin_num = static_cast(data.at("num")); + core::gpio::direction_t direction = data["out"] ? + core::gpio::direction_t::OUT : core::gpio::direction_t::IN; + AppLogger::Error(std::to_string(pin_id)+":"+std::to_string(pin_num)); + } for (auto pin : this->config) { this->gpio_driver_.initializePin(pin.second.pinNum, pin.second.direction); } diff --git a/mw/gpio_server/gpio_mw.hpp b/mw/gpio_server/gpio_mw.hpp index a0d532c4..6077bb8c 100644 --- a/mw/gpio_server/gpio_mw.hpp +++ b/mw/gpio_server/gpio_mw.hpp @@ -19,6 +19,7 @@ #include "core/gpio/GPIO_digital_driver.h" #include "communication-core/sockets/ipc_socket.h" #include "core/application/application_mw.h" +#include "nlohmann/json.hpp" namespace simba { namespace mw { diff --git a/mw/gpio_server/main.cpp b/mw/gpio_server/main.cpp new file mode 100644 index 00000000..1adab758 --- /dev/null +++ b/mw/gpio_server/main.cpp @@ -0,0 +1,17 @@ +/** + * @file main.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ +#include "mw/gpio_server/gpio_mw.hpp" +#include "core/application/application_factory.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/mw/gpio_server/tests/test_header.cpp b/mw/gpio_server/tests/test_header.cpp index 0e010ee8..75f0225b 100644 --- a/mw/gpio_server/tests/test_header.cpp +++ b/mw/gpio_server/tests/test_header.cpp @@ -10,6 +10,7 @@ */ #include +#include #include "mw/gpio_server/data/header.hpp" @@ -21,9 +22,22 @@ simba::gpio::Header hdr{service_id, pin_id, value}; EXPECT_EQ(hdr.GetServiceID(), service_id); EXPECT_EQ(hdr.GetPinID(), pin_id); EXPECT_EQ(hdr.GetValue(), value); + service_id = 12; + pin_id = 1; + value = 0; +simba::gpio::Header hdr2{service_id, pin_id, value}; +EXPECT_EQ(hdr2.GetServiceID(), service_id); +EXPECT_EQ(hdr2.GetPinID(), pin_id); +EXPECT_EQ(hdr2.GetValue(), value); + service_id = 7; + pin_id = 5; + value = 0; +simba::gpio::Header hdr3{service_id, pin_id, value}; +EXPECT_EQ(hdr3.GetServiceID(), service_id); +EXPECT_EQ(hdr3.GetPinID(), pin_id); +EXPECT_EQ(hdr3.GetValue(), value); } - TEST(GPIO_MSG_FACTORY, CHECK_BUFFOR) { simba::gpio::Header hdr(12, 12, 1); auto data = hdr.GetBuffor(); From edbc61b812d18e4e1c020242390620f3524be294 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Fri, 8 Mar 2024 20:22:29 +0100 Subject: [PATCH 30/71] fix --- deployment | 2 +- mw/gpio_server/controller/gpio_controller.cpp | 1 - mw/gpio_server/data/header.cpp | 6 ++-- mw/gpio_server/gpio_mw.cpp | 16 ++++++---- mw/gpio_server/tests/BUILD | 1 - mw/gpio_server/tests/test_header.cpp | 2 +- mw/gpio_server/tests/test_resHeader.cpp | 31 ------------------- 7 files changed, 15 insertions(+), 44 deletions(-) delete mode 100644 mw/gpio_server/tests/test_resHeader.cpp diff --git a/deployment b/deployment index fe8edfd1..58c59329 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit fe8edfd181d7038904db21e44194a6212a86eff7 +Subproject commit 58c59329b5f800b49edb1e2e786068c9f96b6890 diff --git a/mw/gpio_server/controller/gpio_controller.cpp b/mw/gpio_server/controller/gpio_controller.cpp index 079c587e..159e82c6 100644 --- a/mw/gpio_server/controller/gpio_controller.cpp +++ b/mw/gpio_server/controller/gpio_controller.cpp @@ -29,7 +29,6 @@ core::ErrorCode GPIOController::SetPinValue(uint16_t pinID, Value value) { } Value GPIOController::GetPinValue(uint16_t pinID) { - return Value::HIGH; } diff --git a/mw/gpio_server/data/header.cpp b/mw/gpio_server/data/header.cpp index 33c0abfc..1ab05501 100644 --- a/mw/gpio_server/data/header.cpp +++ b/mw/gpio_server/data/header.cpp @@ -15,7 +15,7 @@ namespace simba { namespace gpio { -Header::Header(uint16_t service_id, uint16_t pin_id, uint8_t value){ +Header::Header(uint16_t service_id, uint16_t pin_id, uint8_t value) { this->service_id = service_id; this->pin_id = pin_id; this->value = value; @@ -28,5 +28,5 @@ void Header::SetData() { this->AddData(&value); } -} // gpio -} // simba +} // namespace gpio +} // namespace simba diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp index 0078d020..bd91537d 100644 --- a/mw/gpio_server/gpio_mw.cpp +++ b/mw/gpio_server/gpio_mw.cpp @@ -26,7 +26,6 @@ namespace mw { void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, const std::vector data) { - AppLogger::Debug("Receive change pin command"); if (data.size() <= 0) { return; } @@ -41,7 +40,7 @@ void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, AppLogger::Warning("Try to set IN pin value, ID: "+std::to_string(hdr.GetPinID())); } if (this->gpio_driver_.getValue(it->second.pinNum) != hdr.GetValue()) { - AppLogger::Info("set pin to position:"+std::to_string(hdr.GetValue())); + AppLogger::Debug("set pin to position:"+std::to_string(hdr.GetValue())); if (this->gpio_driver_.setValue(it->second.pinNum, hdr.GetValue()) != core::ErrorCode::kOk) { AppLogger::Warning("pin state not change"); } @@ -74,11 +73,16 @@ void GPIOMWService::InitializePins() { return; } for (const auto& gpio : data["gpio"]) { - uint16_t pin_id = static_cast(data.at("id")); - uint16_t pin_num = static_cast(data.at("num")); - core::gpio::direction_t direction = data["out"] ? + std::cout<< gpio["id"] <<":"<< gpio["num"] <(gpio["id"]); + uint16_t pin_num = static_cast(gpio["num"]); + const std::string direct = gpio.at("direction"); + core::gpio::direction_t direction = direct == "out" ? core::gpio::direction_t::OUT : core::gpio::direction_t::IN; - AppLogger::Error(std::to_string(pin_id)+":"+std::to_string(pin_num)); + this->config.insert({ + pin_id, { + pin_num, direction} + }); } for (auto pin : this->config) { this->gpio_driver_.initializePin(pin.second.pinNum, pin.second.direction); diff --git a/mw/gpio_server/tests/BUILD b/mw/gpio_server/tests/BUILD index 7f16cfb4..65954555 100644 --- a/mw/gpio_server/tests/BUILD +++ b/mw/gpio_server/tests/BUILD @@ -2,7 +2,6 @@ cc_test( name = "data_structure", srcs = [ "test_header.cpp", - "test_resHeader.cpp", ], visibility = ["//visibility:public"], deps=[ diff --git a/mw/gpio_server/tests/test_header.cpp b/mw/gpio_server/tests/test_header.cpp index 75f0225b..3cff87ce 100644 --- a/mw/gpio_server/tests/test_header.cpp +++ b/mw/gpio_server/tests/test_header.cpp @@ -46,4 +46,4 @@ TEST(GPIO_MSG_FACTORY, CHECK_BUFFOR) { EXPECT_EQ(hdr.GetServiceID(), hdr2.GetServiceID()); EXPECT_EQ(hdr.GetPinID(), hdr2.GetPinID()); EXPECT_EQ(hdr.GetValue(), hdr2.GetValue()); -} \ No newline at end of file +} diff --git a/mw/gpio_server/tests/test_resHeader.cpp b/mw/gpio_server/tests/test_resHeader.cpp deleted file mode 100644 index daa9b298..00000000 --- a/mw/gpio_server/tests/test_resHeader.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file test_resHeader.cpp - * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief - * @version 0.1 - * @date 2024-03-08 - * - * @copyright Copyright (c) 2024 - * - */ -#include - -#include "mw/gpio_server/data/resHeader.hpp" - -TEST(GPIO_ResDATA_STRUCTURE, CONSTRUCTOR_CHECK) { - uint16_t pin_id = 0x11; - uint8_t value = 0x1; -simba::gpio::ResHeader hdr{pin_id, value}; -EXPECT_EQ(hdr.GetPinID(), pin_id); -EXPECT_EQ(hdr.GetValue(), value); -} - - -TEST(GPIO_RES_MSG_FACTORY, CHECK_BUFFOR) { - simba::gpio::ResHeader hdr(12, 1); - auto data = hdr.GetBuffor(); - simba::gpio::ResHeader hdr2(0x00, 0x0); - hdr2.SetBuffor(data); - EXPECT_EQ(hdr.GetPinID(), hdr2.GetPinID()); - EXPECT_EQ(hdr.GetValue(), hdr2.GetValue()); -} \ No newline at end of file From 374350a5417dd67fdb10b91d9d596cf8d13a0350 Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Sun, 10 Mar 2024 22:50:03 +0100 Subject: [PATCH 31/71] Makr remove result fix core dep (#43) * remove Result and //core import * fix dtc+exec hdr, add exec controller to mw --- communication-core/network-data/BUILD | 1 + communication-core/someip-controller/BUILD | 2 - .../someip-controller/Isomeip_controller.h | 6 +-- .../someip-controller/someip_controller.cc | 43 +++++++++---------- .../someip-controller/someip_controller.h | 4 +- .../someip-controller/transfer.h | 14 +++--- communication-core/someip/factory/BUILD | 3 -- core/BUILD | 1 - core/application/BUILD | 3 +- core/application/application_common.cc | 12 +++++- core/application/application_common.h | 5 ++- core/application/application_mw.cc | 16 ++++--- core/common/BUILD | 7 ++- core/json/BUILD | 1 - core/json/json_parser.cc | 16 +++---- core/json/json_parser.h | 16 +++---- core/logger/BUILD | 1 - core/logger/logger_factory.cc | 6 +-- core/logger/logger_factory.h | 4 +- core/results/BUILD | 10 ----- core/results/result.h | 40 ----------------- diag/base/controller/diag_controller.cc | 8 ++-- diag/dtc/data/BUILD | 1 + diag/dtc/data/dtc_header.cpp | 13 +++--- diag/dtc/data/dtc_header.hpp | 14 ++++-- diag/dtc/tests/BUILD | 4 +- diag/dtc/tests/test_dtc_msg_factory.cpp | 3 +- diag/exec/controller/BUILD | 3 +- diag/exec/controller/exec_controller.cpp | 38 ++++++++-------- diag/exec/controller/exec_controller.hpp | 16 +++---- diag/exec/data/BUILD | 1 + diag/exec/data/exec_header.cpp | 14 +++--- diag/exec/data/exec_header.hpp | 13 ++++-- diag/exec/factories/exec_msg_factory.cpp | 6 +-- diag/exec/tests/BUILD | 19 ++++++++ diag/exec/tests/exec_data_factory.cc | 23 ++++++++++ diag/exec/tests/exec_structure.cc | 20 +++++++++ mw/diag/ota/code/service/BUILD | 2 +- mw/diag/ota/code/service/ota_service.cc | 3 +- mw/em/code/services/em/BUILD | 1 - mw/em/code/services/em/em_service.cc | 36 ++++++++-------- mw/em/code/services/em/em_service.h | 4 +- mw/logger/code/application/dlt_service.cc | 18 ++++---- mw/logger/code/data/BUILD | 2 +- mw/logger/code/data/dlt_frame.h | 5 +-- mw/logger/code/data/dlt_log_type.h | 12 +++--- mw/logger/code/data/idlt_frame.h | 4 +- 47 files changed, 267 insertions(+), 227 deletions(-) delete mode 100644 core/results/BUILD delete mode 100644 core/results/result.h create mode 100644 diag/exec/tests/BUILD create mode 100644 diag/exec/tests/exec_data_factory.cc create mode 100644 diag/exec/tests/exec_structure.cc diff --git a/communication-core/network-data/BUILD b/communication-core/network-data/BUILD index 864e2d8d..95b5dfae 100644 --- a/communication-core/network-data/BUILD +++ b/communication-core/network-data/BUILD @@ -24,6 +24,7 @@ cc_library( hdrs = ["network_data_type.h"], visibility = [ "//communication-core:__subpackages__", + "//diag:__subpackages__", "//mw:__subpackages__", ], deps = [ diff --git a/communication-core/someip-controller/BUILD b/communication-core/someip-controller/BUILD index ce284237..cb05470a 100644 --- a/communication-core/someip-controller/BUILD +++ b/communication-core/someip-controller/BUILD @@ -9,7 +9,6 @@ cc_library( "//communication-core/someip:someip_types", "//communication-core/someip/factory:someip_message_factory", "//core/common:common_types", - "//core/results:results_lib" ], ) @@ -20,7 +19,6 @@ cc_library( "//core:__subpackages__", "//diag:__subpackages__", ], - deps = ["//core/results:results_lib"], ) cc_library( diff --git a/communication-core/someip-controller/Isomeip_controller.h b/communication-core/someip-controller/Isomeip_controller.h index ffadb888..7c12afe3 100644 --- a/communication-core/someip-controller/Isomeip_controller.h +++ b/communication-core/someip-controller/Isomeip_controller.h @@ -14,19 +14,19 @@ #include #include #include +#include #include "core/common/error_code.h" -#include "core/results/result.h" #include "communication-core/someip/message_code.h" namespace simba { namespace com { namespace someip { -using SomeIPMethod = std::function, com::core::data::MessageCode>>( const std::vector payload)>; class ISomeIpController { public: - virtual simba::core::Result> Request( + virtual std::optional> Request( const uint16_t service_id, const uint16_t method_id, const std::vector payload) = 0; virtual bool RequestNoResponse(const uint16_t service_id, diff --git a/communication-core/someip-controller/someip_controller.cc b/communication-core/someip-controller/someip_controller.cc index cb414770..3172da9f 100644 --- a/communication-core/someip-controller/someip_controller.cc +++ b/communication-core/someip-controller/someip_controller.cc @@ -16,22 +16,21 @@ #include "communication-core/someip/message_code.h" #include "communication-core/someip/message_type.h" #include "communication-core/someip/someip_header.h" -#include "core/results/result.h" namespace simba { namespace com { namespace someip { -simba::core::Result> SomeIpController::Request( +std::optional> SomeIpController::Request( const uint16_t service_id, const uint16_t method_id, const std::vector payload) { const auto service_data = db_.GetService(service_id); - if (!service_data.HasValue()) { + if (!service_data.has_value()) { AppLogger::Error("[SOMEIPCONTROLLER] Service_id: " + std::to_string(service_id) + " not found!"); - return simba::core::Result>{}; + return {}; } else { AppLogger::Error( "[SOMEIPCONTROLLER] Service_id: " + std::to_string(service_id) + - " ip = " + service_data.Value().GetIp()); + " ip = " + service_data.value().GetIp()); } const auto transfer = GetTransferID(); auto req = header_factory.CreateRequest(service_id, method_id); @@ -39,8 +38,8 @@ simba::core::Result> SomeIpController::Request( auto trans = this->AddTransfer(transfer); AppLogger::Debug("Sending to: " + std::to_string(req->GetServiceID()) + " From " + std::to_string(req->GetClientID())); - if (this->socket_->Transmit(service_data.Value().GetIp(), - service_data.Value().GetPort(), + if (this->socket_->Transmit(service_data.value().GetIp(), + service_data.value().GetPort(), req_payload) != simba::core::ErrorCode::kOk) { std::remove_if( this->transfers.begin(), transfers.end(), @@ -50,7 +49,7 @@ simba::core::Result> SomeIpController::Request( AppLogger::Error( "[SOMEIPCONTROLLER] Request to :" + std::to_string(service_id) + " method_id: " + std::to_string(method_id) + " No connection"); - return simba::core::Result>{}; + return {}; } const auto res = trans->GetPayloadAsc(); auto vec = trans->GetPayload(); @@ -59,13 +58,13 @@ simba::core::Result> SomeIpController::Request( [trans](std::shared_ptr tr) { return tr->GetTransferID() == trans->GetTransferID(); }); - if (res.HasValue()) { - return simba::core::Result>{vec}; + if (res.has_value()) { + return std::optional>{vec}; } else { AppLogger::Error( "[SOMEIPCONTROLLER] Request to :" + std::to_string(service_id) + " : " + std::to_string(method_id) + " Timeout"); - return simba::core::Result>{}; + return {}; } } @@ -73,7 +72,7 @@ bool SomeIpController::RequestNoResponse(const uint16_t service_id, const uint16_t method_id, const std::vector payload) { const auto service_data = db_.GetService(service_id); - if (!service_data.HasValue()) { + if (!service_data.has_value()) { AppLogger::Error("[SOMEIPCONTROLLER] Service_id: " + std::to_string(service_id) + " not found!"); return false; @@ -84,11 +83,11 @@ bool SomeIpController::RequestNoResponse(const uint16_t service_id, msg_factory.GetBuffor(req, this->service_id_, transfer, payload); auto trans = this->AddTransfer(transfer); - this->socket_->Transmit(service_data.Value().GetIp(), - service_data.Value().GetPort(), req_payload); + this->socket_->Transmit(service_data.value().GetIp(), + service_data.value().GetPort(), req_payload); const auto res = trans->GetACK(); - if (res.HasValue()) { - return res.Value(); + if (res.has_value()) { + return res.value(); } else { AppLogger::Error( "[SOMEIPCONTROLLER] Request to :" + std::to_string(service_id) + " : " + @@ -167,19 +166,19 @@ void SomeIpController::MethodCalled( const auto res = obj->second(data); - if (!res.HasValue()) { + if (!res.has_value()) { AppLogger::Info("[SOMEIPCONTROLLER] Socket Send Respons No Value"); // TODO(any) : implemnet error kNOK } - if (res.Value().second != com::core::data::MessageCode::kEOk) { + if (res.value().second != com::core::data::MessageCode::kEOk) { AppLogger::Info("[SOMEIPCONTROLLER] Socket Send Respons No OK"); // TODO(any) : implemnet error } else { if (header->GetMessageType() == com::core::data::MessageType::kRequest) { header->SetMessageType(core::data::MessageType::kResponse); header->SetReturnCode(core::data::MessageCode::kEOk); - this->SendResponse(header, res.Value().first); + this->SendResponse(header, res.value().first); AppLogger::Info("[SOMEIPCONTROLLER] Socket Send Respons"); } } @@ -207,14 +206,14 @@ void SomeIpController::SendResponse( std::vector data) { const auto service_id = header->GetClientID(); const auto service_data = db_.GetService(service_id); - if (!service_data.HasValue()) { + if (!service_data.has_value()) { AppLogger::Error("[SOMEIPCONTROLLER] (" + std::string(__func__) + ") Service_id: " + std::to_string(service_id) + " not found!"); } - this->socket_->Transmit(service_data.Value().GetIp(), - service_data.Value().GetPort(), + this->socket_->Transmit(service_data.value().GetIp(), + service_data.value().GetPort(), msg_factory.GetBuffor(header, header->GetClientID(), header->GetSessionID(), data)); } diff --git a/communication-core/someip-controller/someip_controller.h b/communication-core/someip-controller/someip_controller.h index 4af0c739..9f4ee4b8 100644 --- a/communication-core/someip-controller/someip_controller.h +++ b/communication-core/someip-controller/someip_controller.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "communication-core/database/database.h" #include "communication-core/sockets/Isocket.h" @@ -30,7 +31,6 @@ #include "communication-core/someip/factory/someip_message_factory.h" #include "core/common/error_code.h" #include "core/logger/Logger.h" -#include "core/results/result.h" #include "memory" namespace simba { @@ -73,7 +73,7 @@ class SomeIpController : public ISomeIpController { std::vector data); public: - simba::core::Result> Request( + std::optional> Request( const uint16_t service_id, const uint16_t method_id, const std::vector payload) override; diff --git a/communication-core/someip-controller/transfer.h b/communication-core/someip-controller/transfer.h index 6e267f34..caabc5e7 100644 --- a/communication-core/someip-controller/transfer.h +++ b/communication-core/someip-controller/transfer.h @@ -17,8 +17,8 @@ #include #include // NOLINT #include +#include -#include "core/results/result.h" namespace simba { namespace com { namespace someip { @@ -42,22 +42,22 @@ class Transfer { } std::vector GetPayload() const { return this->response; } - simba::core::Result> GetPayloadAsc() { + std::optional> GetPayloadAsc() { std::unique_lock lk(cv_m); if (!cv.wait_for(lk, std::chrono::seconds{2}, [this]() { return this->IsRespond(); })) { - return simba::core::Result>{}; + return {}; } - return simba::core::Result>{response}; + return std::optional>{response}; } - simba::core::Result GetACK() { + std::optional GetACK() { std::unique_lock lk(cv_m); if (!cv.wait_for(lk, std::chrono::seconds{2}, [this]() { return this->IsRespond(); })) { - return simba::core::Result{}; + return {}; } else { - return simba::core::Result{true}; + return std::optional{true}; } } virtual ~Transfer() {} diff --git a/communication-core/someip/factory/BUILD b/communication-core/someip/factory/BUILD index 92ef9652..f533f8e1 100644 --- a/communication-core/someip/factory/BUILD +++ b/communication-core/someip/factory/BUILD @@ -8,7 +8,6 @@ cc_library( deps = [ "//communication-core/someip:someip_header", "//communication-core/someip:someip_types", - "//core", ], ) @@ -23,7 +22,6 @@ cc_library( ":someip_factory_interface", "//communication-core/someip:someip_header", "//communication-core/someip:someip_types", - "//core", ], ) @@ -38,6 +36,5 @@ cc_library( ":someip_factory_interface", "//communication-core/someip:someip_header", "//communication-core/someip:someip_types", - "//core", ], ) diff --git a/core/BUILD b/core/BUILD index 0a09eeb5..6c4163e7 100644 --- a/core/BUILD +++ b/core/BUILD @@ -12,7 +12,6 @@ cc_library( "//core/common:common_converter", "//core/common:common_types", "//core/logger:console_logger", - "//core/results:results_lib", "//core/logger:Logger", ], ) diff --git a/core/application/BUILD b/core/application/BUILD index 3d583c88..6b48898e 100644 --- a/core/application/BUILD +++ b/core/application/BUILD @@ -14,6 +14,8 @@ cc_library( deps = [ "//core/common:common_types", "//core/logger:Logger", + "//diag/exec/controller:diag_exec_controller", + "//core/json:simba_json", "@boost//:algorithm", "@com_json//:json", ], @@ -33,7 +35,6 @@ cc_library( deps = [ ":application", "//communication-core/sockets:socket_ipc", - "//core/json:simba_json", "//diag/base/controller:diag_controller", ], ) diff --git a/core/application/application_common.cc b/core/application/application_common.cc index 349017ca..67ffa886 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -19,6 +19,7 @@ #include "core/application/parm.h" #include "core/logger/Logger.h" #include "core/logger/logger_factory.h" +#include "core/json/json_parser.h" #include "nlohmann/json.hpp" namespace simba { namespace core { @@ -40,6 +41,13 @@ void ApplicationCommon::RunApp(int argc, char const* argv[]) { const std::string app_name = help_path.substr(help_path.find_last_of("/") + 1); parms.insert({"app_name", app_name}); + auto obj = json::JsonParser::Parser("/opt/" + parms.at("app_name") + + "/etc/srp_app.json") + .value(); + auto app_id_ = obj.GetNumber("app_id"); + if (app_id_.has_value()) { + this->exec_.Init(app_id_.value()); + } onRun(parms); parms.clear(); } @@ -119,8 +127,8 @@ ErrorCode ApplicationCommon::CommonConfig( AppLogger::SetParms(app_id, log_level); for (const auto& mode : log_mode) { auto res = logger::LoggerFactory::CreateLogger(mode); - if (res.HasValue()) { - AppLogger::AddLogger(res.Value()); + if (res.has_value()) { + AppLogger::AddLogger(res.value()); } } } diff --git a/core/application/application_common.h b/core/application/application_common.h index b971d5aa..7c2ab5f0 100644 --- a/core/application/application_common.h +++ b/core/application/application_common.h @@ -16,15 +16,16 @@ #include #include // NOLINT #include +#include #include "core/application/Iapplication.h" - +#include "diag/exec/controller/exec_controller.hpp" namespace simba { namespace core { class ApplicationCommon : public IApplication { protected: std::stop_source source; - + diag::exec::ExecController exec_; /** * @brief This is pre-run function only for creting new application * interfacess diff --git a/core/application/application_mw.cc b/core/application/application_mw.cc index 3127be4b..b3ea2a4a 100644 --- a/core/application/application_mw.cc +++ b/core/application/application_mw.cc @@ -41,16 +41,22 @@ ErrorCode ApplicationMW::MwConfig( const std::unordered_map& parms) { auto obj = json::JsonParser::Parser("/opt/" + parms.at("app_name") + "/etc/srp_app.json") - .Value(); + .value(); auto service_id_r = obj.GetNumber("diag_id"); - if (service_id_r.HasValue()) { - if (service_id_r.Value() != 0) { + if (service_id_r.has_value()) { + if (service_id_r.value() != 0) { AppLogger::Info("Application [MW] Service_id: " + - std::to_string(service_id_r.Value())); + std::to_string(service_id_r.value())); this->diag_controller = std::make_unique( - service_id_r.Value(), std::make_unique()); + service_id_r.value(), std::make_unique()); } } + auto app_ = obj.GetNumber("app_id"); + if (app_.has_value()) { + this->exec_.Init(app_.value()); + } else { + return ErrorCode::kError; + } return ErrorCode::kOk; } } // namespace core diff --git a/core/common/BUILD b/core/common/BUILD index 6b584361..d068c2ec 100644 --- a/core/common/BUILD +++ b/core/common/BUILD @@ -11,14 +11,17 @@ cc_library( hdrs = ["endianess_converter.h"], visibility = [ "//core:__subpackages__", - "//communication-core:__subpackages__"], + "//communication-core:__subpackages__", + ], ) cc_library( name = "crc_lib", srcs = ["crc_16.cc"], hdrs = ["crc_16.h"], - visibility = ["//core/common/test:__subpackages__"], + visibility = [ + "//core/common/test:__subpackages__", + ], ) cc_library( diff --git a/core/json/BUILD b/core/json/BUILD index 231bc5bf..d0a02afe 100644 --- a/core/json/BUILD +++ b/core/json/BUILD @@ -4,7 +4,6 @@ cc_library( hdrs = ["json_parser.h"], visibility = ["//visibility:public"], deps = [ - "//core/results:results_lib", "@com_json//:json", ], ) diff --git a/core/json/json_parser.cc b/core/json/json_parser.cc index 70b210de..908ac3d7 100644 --- a/core/json/json_parser.cc +++ b/core/json/json_parser.cc @@ -15,31 +15,31 @@ namespace simba { namespace core { namespace json { -Result JsonParser::Parser(const std::string& path) noexcept { +std::optional JsonParser::Parser(const std::string& path) noexcept { std::ifstream f(path); if (!f.is_open()) { - return core::Result{}; + return {}; } - return core::Result{JsonParser{f}}; + return std::optional{JsonParser{f}}; } JsonParser::JsonParser(std::ifstream& f) { this->obj = nlohmann::json::parse(f); } nlohmann::json JsonParser::GetObject() const { return this->obj; } -Result JsonParser::GetString( +std::optional JsonParser::GetString( const std::string& name) const noexcept { try { if (obj.contains(name)) { if (obj.at(name).is_string()) { const std::string res = obj.at(name); - return Result{res}; + return std::optional{res}; } - return Result{}; + return {}; } else { - return Result{}; + return {}; } } catch (std::exception&) { - return Result{}; + return {}; } } JsonParser::~JsonParser() {} diff --git a/core/json/json_parser.h b/core/json/json_parser.h index e170cb0f..56c563b0 100644 --- a/core/json/json_parser.h +++ b/core/json/json_parser.h @@ -14,8 +14,8 @@ #include #include +#include -#include "core/results/result.h" #include "nlohmann/json.hpp" namespace simba { @@ -26,24 +26,24 @@ class JsonParser { nlohmann::json obj; public: - static Result Parser(const std::string& path) noexcept; + static std::optional Parser(const std::string& path) noexcept; explicit JsonParser(std::ifstream& f); nlohmann::json GetObject() const; - Result GetString(const std::string& name) const noexcept; + std::optional GetString(const std::string& name) const noexcept; template - Result GetNumber(const std::string& name) const noexcept { + std::optional GetNumber(const std::string& name) const noexcept { try { if (obj.contains(name)) { if (obj.at(name).is_number()) { const T res{static_cast(obj.at(name))}; - return Result{res}; + return std::optional{res}; } - return Result{}; + return {}; } else { - return Result{}; + return {}; } } catch (std::exception&) { - return Result{}; + return {}; } } ~JsonParser(); diff --git a/core/logger/BUILD b/core/logger/BUILD index 0bb98fc1..d6ba9562 100644 --- a/core/logger/BUILD +++ b/core/logger/BUILD @@ -23,7 +23,6 @@ cc_library( ":console_logger", ":logger_interface", "//core/common:common_types", - "//core/results:results_lib", "//core/logger:dlt_logger", ], ) diff --git a/core/logger/logger_factory.cc b/core/logger/logger_factory.cc index 50a9349f..c81b1628 100644 --- a/core/logger/logger_factory.cc +++ b/core/logger/logger_factory.cc @@ -27,13 +27,13 @@ std::unordered_map()>> {"kDLT", []() { return std::make_shared(); }}}; } // namespace -Result> LoggerFactory::CreateLogger( + std::optional> LoggerFactory::CreateLogger( const std::string& name) { if (lookup_table.find(name) != lookup_table.end()) { auto obj = (lookup_table.at(name))(); - return Result{obj}; + return std::optional{obj}; } else { - return Result>{}; + return {}; } } } // namespace logger diff --git a/core/logger/logger_factory.h b/core/logger/logger_factory.h index 483ba4ab..20024595 100644 --- a/core/logger/logger_factory.h +++ b/core/logger/logger_factory.h @@ -12,16 +12,16 @@ #define CORE_LOGGER_LOGGER_FACTORY_H_ #include #include +#include #include "core/logger/ILogger.h" -#include "core/results/result.h" namespace simba { namespace core { namespace logger { class LoggerFactory { public: - static Result> CreateLogger(const std::string& name); + static std::optional> CreateLogger(const std::string& name); }; } // namespace logger } // namespace core diff --git a/core/results/BUILD b/core/results/BUILD deleted file mode 100644 index 27002f7d..00000000 --- a/core/results/BUILD +++ /dev/null @@ -1,10 +0,0 @@ -cc_library( - name = "results_lib", - hdrs = ["result.h"], - visibility = [ - "//core:__subpackages__", - "//mw:__subpackages__", - "//diag:__subpackages__", - "//communication-core:__subpackages__", - ], -) diff --git a/core/results/result.h b/core/results/result.h deleted file mode 100644 index ecceda09..00000000 --- a/core/results/result.h +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @file result.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-11-13 - * - * @copyright Copyright (c) 2023 - * - */ - -#ifndef CORE_RESULTS_RESULT_H_ -#define CORE_RESULTS_RESULT_H_ -#include -#include - -namespace simba { -namespace core { -template -class Result { - private: - std::shared_ptr value; - bool was_set{false}; - - public: - Result() { value = nullptr; } - explicit Result(const T& value) { - this->value = std::make_shared(value); - this->was_set = true; - } - bool HasValue() const { return was_set; } - T Value() const { return *this->value.get(); } - void SetValue(const T& value) { - this->value = value; - this->was_set = true; - } -}; -} // namespace core -} // namespace simba -#endif // CORE_RESULTS_RESULT_H_ diff --git a/diag/base/controller/diag_controller.cc b/diag/base/controller/diag_controller.cc index f0320f83..b13272ae 100644 --- a/diag/base/controller/diag_controller.cc +++ b/diag/base/controller/diag_controller.cc @@ -177,14 +177,14 @@ std::optional> DiagController::Read( if (!req_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the Read request"); - return std::optional>{}; + return {}; } auto transfer = std::make_shared(t_id); if (this->Send(req_t.value()) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send Read request to: SIMBA.DIAG." + std::to_string(req_t.value().GetServiceID())); - return std::optional>{}; + return {}; } this->transfer_list.push_back(transfer); const auto result = transfer->GetPayloadAsc(); @@ -234,14 +234,14 @@ std::optional> DiagController::Job( if (!req_t.has_value()) { AppLogger::Error( "[DIAG_CONTROLLER] An error occurred while creating the Read request"); - return std::optional>{}; + return {}; } auto transfer = std::make_shared(t_id); if (this->Send(req_t.value()) != core::ErrorCode::kOk) { AppLogger::Error( "[DIAG_CONTROLLER] Cannot send Job request to: SIMBA.DIAG." + std::to_string(req_t.value().GetSenderID())); - return std::optional>{}; + return {}; } this->transfer_list.push_back(transfer); const auto result = transfer->GetPayloadAsc(); diff --git a/diag/dtc/data/BUILD b/diag/dtc/data/BUILD index 8e208a33..3e0507ed 100644 --- a/diag/dtc/data/BUILD +++ b/diag/dtc/data/BUILD @@ -4,6 +4,7 @@ cc_library( hdrs = ["dtc_header.hpp"], deps=[ "//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type", ], visibility = ["//visibility:public"], ) diff --git a/diag/dtc/data/dtc_header.cpp b/diag/dtc/data/dtc_header.cpp index 8d6775ea..c344a923 100644 --- a/diag/dtc/data/dtc_header.cpp +++ b/diag/dtc/data/dtc_header.cpp @@ -21,21 +21,24 @@ static constexpr uint8_t hdrSize = 0x04; DtcHeader::DtcHeader(const uint16_t &dtc_id, const uint8_t &dtc_status) :dtc_id_(dtc_id), dtc_status_(dtc_status) { this->lenght_ = hdrSize; + this->SetData(); } -DtcHeader::DtcHeader():dtc_id_{0}, dtc_status_{0} {}; +DtcHeader::DtcHeader():dtc_id_{0}, dtc_status_{0} { + this->SetData(); +}; uint16_t DtcHeader::GetDtcID() { - return this->dtc_id_; + return this->dtc_id_.Get(); } uint8_t DtcHeader::GetDtcStatus() { - return this->dtc_status_; + return this->dtc_status_.Get(); } uint8_t DtcHeader::GetLength() { - return this->lenght_; + return this->lenght_.Get(); } void DtcHeader::SetLength(const uint8_t& value) { - this->lenght_ = value + hdrSize; + this->lenght_.Set(value+hdrSize); } } // namespace dtc diff --git a/diag/dtc/data/dtc_header.hpp b/diag/dtc/data/dtc_header.hpp index 9539fab7..b58ea715 100644 --- a/diag/dtc/data/dtc_header.hpp +++ b/diag/dtc/data/dtc_header.hpp @@ -16,6 +16,7 @@ #include #include "communication-core/network-data/network_data_structure.h" +#include "communication-core/network-data/network_data_type.h" namespace simba { namespace diag { @@ -24,10 +25,11 @@ namespace dtc { class DtcHeader : public com::core::network::NetworkDataStructure { private: // numer błędu - const uint16_t dtc_id_; + com::core::network::uint16_t dtc_id_; // flagi błędu - const uint8_t dtc_status_; - uint8_t lenght_; + com::core::network::uint8_t dtc_status_; + com::core::network::uint8_t lenght_; + public: DtcHeader(const uint16_t &dtc_id, const uint8_t &dtc_status); DtcHeader(); @@ -36,6 +38,12 @@ class DtcHeader : public com::core::network::NetworkDataStructure { uint8_t GetDtcStatus(); uint8_t GetLength(); + void SetData() { + this->AddData(&dtc_id_); + this->AddData(&dtc_status_); + this->AddData(&lenght_); + } + /** * @brief Set the Length object * diff --git a/diag/dtc/tests/BUILD b/diag/dtc/tests/BUILD index f3be22ca..9601a2f7 100644 --- a/diag/dtc/tests/BUILD +++ b/diag/dtc/tests/BUILD @@ -10,10 +10,10 @@ cc_test( cc_test( name = "data_factories", - srcs = ["test_data_hdr.cpp"], + srcs = ["test_dtc_msg_factory.cpp"], visibility = ["//visibility:public"], deps=[ "@com_google_googletest//:gtest_main", - "//diag/dtc/data:diag_dtc_data_structure" + "//diag/dtc/factories:diag_dtc_msg_factory" ] ) diff --git a/diag/dtc/tests/test_dtc_msg_factory.cpp b/diag/dtc/tests/test_dtc_msg_factory.cpp index b108b155..fb951baa 100644 --- a/diag/dtc/tests/test_dtc_msg_factory.cpp +++ b/diag/dtc/tests/test_dtc_msg_factory.cpp @@ -20,9 +20,8 @@ TEST(DATA_FACTORIES, DATA_FACTORIES_TEST) { uint8_t status = 0x03; simba::diag::dtc::DtcHeader hdr{id, status}; std::vector data = factory.GetBuffer( - std::make_shared(hdr), payload); + std::make_shared(hdr), {}); auto hdr2 = factory.GetHeader(data); EXPECT_EQ(hdr2->GetDtcID(), hdr.GetDtcID()); EXPECT_EQ(hdr2->GetDtcStatus(), hdr.GetDtcStatus()); - EXPECT_EQ(hdr2->GetLength(), hdr.GetLength()); } diff --git a/diag/exec/controller/BUILD b/diag/exec/controller/BUILD index 0595397d..b5492d3a 100644 --- a/diag/exec/controller/BUILD +++ b/diag/exec/controller/BUILD @@ -4,7 +4,8 @@ cc_library( name = "diag_exec_controller", deps = [ "//diag/exec/factories:diag_exec_factories", - "//communication-core/sockets:socket_ipc" + "//communication-core/sockets:socket_ipc", + "//core/logger:Logger" ], srcs = ["exec_controller.cpp"], hdrs = ["exec_controller.hpp"], diff --git a/diag/exec/controller/exec_controller.cpp b/diag/exec/controller/exec_controller.cpp index 9de34a37..b4e2adb6 100644 --- a/diag/exec/controller/exec_controller.cpp +++ b/diag/exec/controller/exec_controller.cpp @@ -9,36 +9,38 @@ * */ #include "exec_controller.hpp" - +#include "core/logger/Logger.h" +#include "communication-core/sockets/ipc_socket.h" +#include "diag/exec/factories/exec_msg_factory.hpp" namespace simba { namespace diag { namespace exec { - -ExecController::ExecController(u_int16_t service_id): - service_id(service_id), status_(Status::Start_up) { - this->sock_.Init(com::soc::SocketConfig{"SIMBA.DIAG." + - std::to_string(this->service_id), 0, 0}); - this->thread_ = std::jthread(&ExecController::thread_func, this, std::placeholders::_1); +void ExecController::Init(uint16_t service_id) { + this->status_ = Status::Start_up; + this->thread_ = std::jthread([&](std::stop_token stop_token) { + auto factory_ = ExecMsgFactory(); + auto sock_ = com::soc::IpcSocket(); + auto hdr = ExecHeader(service_id, 0, this->status_); + while (!stop_token.stop_requested()) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + auto data = factory_.GetBuffer(std::make_shared(hdr)); + sock_.Transmit("SIMBA.EXE", 0, data); + AppLogger::Info("id: "+ std::to_string(hdr.GetServiceID()) + +" timestamp:"+std::to_string(hdr.GetTimestamp())); + hdr.IncrementTimeStamp(); + } + }); } + void ExecController::SetStatus(Status status) { this->status_ = status; } -void ExecController::thread_func(std::stop_token token) { - auto hdr = std::make_shared( - this->service_id, 0, this->status_); - while (!token.stop_requested()) { - std::vector data = this->factory_.GetBuffer(hdr); - hdr->IncrementTimeStamp(); - this->sock_.Transmit("SIMBA.EXE", 0, data); - std::this_thread::sleep_for(std::chrono::seconds(1)); - } -} +ExecController::ExecController() {} ExecController::~ExecController() { - this->thread_.request_stop(); } diff --git a/diag/exec/controller/exec_controller.hpp b/diag/exec/controller/exec_controller.hpp index 735daba7..8222e09d 100644 --- a/diag/exec/controller/exec_controller.hpp +++ b/diag/exec/controller/exec_controller.hpp @@ -9,15 +9,13 @@ * */ - #ifndef DIAG_EXEC_CONTROLLER_EXEC_CONTROLLER_HPP_ #define DIAG_EXEC_CONTROLLER_EXEC_CONTROLLER_HPP_ #include #include - -#include "communication-core/sockets/ipc_socket.h" -#include "diag/exec/factories/exec_msg_factory.hpp" +#include // NOLINT +#include // NOLINT namespace simba { namespace diag { @@ -36,15 +34,13 @@ enum Status { class ExecController { private: - const uint16_t service_id; - static ExecMsgFactory factory_; - com::soc::IpcSocket sock_; + uint16_t service_id; std::jthread thread_; - std::atomic status_; - void thread_func(std::stop_token token); + Status status_; public: - explicit ExecController(u_int16_t service_id); + void Init(uint16_t service_id); + ExecController(); void SetStatus(Status status); ~ExecController(); }; diff --git a/diag/exec/data/BUILD b/diag/exec/data/BUILD index 0b28bcd4..952b7fc7 100644 --- a/diag/exec/data/BUILD +++ b/diag/exec/data/BUILD @@ -3,6 +3,7 @@ cc_library( name = "diag_exec_header", deps = [ "//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type", ], srcs = ["exec_header.cpp"], hdrs = ["exec_header.hpp"], diff --git a/diag/exec/data/exec_header.cpp b/diag/exec/data/exec_header.cpp index 10578009..9a3d0856 100644 --- a/diag/exec/data/exec_header.cpp +++ b/diag/exec/data/exec_header.cpp @@ -16,20 +16,22 @@ namespace exec { ExecHeader::ExecHeader(const uint16_t &service_id, const uint16_t &time_stamp, uint8_t flags) - :service_id_(service_id), time_stamp_(time_stamp), flags_(flags) {} -ExecHeader::ExecHeader():service_id_{0}, time_stamp_{0} {}; + :service_id_(service_id), time_stamp_(time_stamp), flags_(flags) {this->SetData();} +ExecHeader::ExecHeader():service_id_{0}, time_stamp_{0} { + this->SetData(); +} uint16_t ExecHeader::GetServiceID() const { - return this->service_id_; + return this->service_id_.Get(); } uint16_t ExecHeader::GetTimestamp() const { - return this->time_stamp_; + return this->time_stamp_.Get(); } uint8_t ExecHeader::GetFlags() const { - return this->flags_; + return this->flags_.Get(); } void ExecHeader::IncrementTimeStamp() { - this->time_stamp_+=1; + this->time_stamp_.Set(this->time_stamp_.Get()+1); } } // namespace exec diff --git a/diag/exec/data/exec_header.hpp b/diag/exec/data/exec_header.hpp index 25936b2c..212a93fc 100644 --- a/diag/exec/data/exec_header.hpp +++ b/diag/exec/data/exec_header.hpp @@ -16,6 +16,7 @@ #include #include "communication-core/network-data/network_data_structure.h" +#include "communication-core/network-data/network_data_type.h" namespace simba { namespace diag { @@ -24,14 +25,20 @@ namespace exec { class ExecHeader : public com::core::network::NetworkDataStructure { private: // numer id serwisu - const uint16_t service_id_; + com::core::network::uint16_t service_id_; // timestamp - uint16_t time_stamp_; - uint8_t flags_; + com::core::network::uint32_t time_stamp_; + com::core::network::uint8_t flags_; public: ExecHeader(const uint16_t &service_id, const uint16_t &time_stamp, uint8_t flags); ExecHeader(); + void SetData() { + this->AddData(&service_id_); + this->AddData(&time_stamp_); + this->AddData(&flags_); + } + uint16_t GetServiceID() const; uint16_t GetTimestamp() const; diff --git a/diag/exec/factories/exec_msg_factory.cpp b/diag/exec/factories/exec_msg_factory.cpp index 3806e558..923e9d88 100644 --- a/diag/exec/factories/exec_msg_factory.cpp +++ b/diag/exec/factories/exec_msg_factory.cpp @@ -23,9 +23,9 @@ std::vector ExecMsgFactory::GetBuffer( std::shared_ptr ExecMsgFactory::GetHeader( std::vector raw_data) { - auto header = std::make_shared(); - header->SetBuffor(raw_data); - return header; + auto header = diag::exec::ExecHeader(); + header.SetBuffor(raw_data); + return std::make_shared(header); } } // namespace exec diff --git a/diag/exec/tests/BUILD b/diag/exec/tests/BUILD new file mode 100644 index 00000000..4405244b --- /dev/null +++ b/diag/exec/tests/BUILD @@ -0,0 +1,19 @@ +cc_test( + name = "data_structure", + srcs = ["exec_structure.cc"], + visibility = ["//visibility:public"], + deps = [ + "//diag/exec/data:diag_exec_header", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "diag_data_factory", + srcs = ["exec_data_factory.cc"], + visibility = ["//visibility:public"], + deps = [ + "//diag/exec/factories:diag_exec_factories", + "@com_google_googletest//:gtest_main", + ], +) diff --git a/diag/exec/tests/exec_data_factory.cc b/diag/exec/tests/exec_data_factory.cc new file mode 100644 index 00000000..2110790f --- /dev/null +++ b/diag/exec/tests/exec_data_factory.cc @@ -0,0 +1,23 @@ +/** + * @file test_diag_data_factory.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-01-10 + * + * @copyright Copyright (c) 2024 + * + */ +#include + +#include "diag/exec/factories/exec_msg_factory.hpp" + +TEST(DIAG_DAT_FACTORY, CreateReadRequest) { + auto hdr = simba::diag::exec::ExecHeader(123, 12, 2); + auto sut = simba::diag::exec::ExecMsgFactory(); + auto buf = sut.GetBuffer(std::make_shared(hdr)); + auto hdr2 = sut.GetHeader(buf); + ASSERT_EQ(hdr.GetBuffor(), buf); + ASSERT_EQ(hdr.GetServiceID(), hdr2->GetServiceID()); + ASSERT_EQ(hdr.GetTimestamp(), hdr2->GetTimestamp()); +} diff --git a/diag/exec/tests/exec_structure.cc b/diag/exec/tests/exec_structure.cc new file mode 100644 index 00000000..867ab8d1 --- /dev/null +++ b/diag/exec/tests/exec_structure.cc @@ -0,0 +1,20 @@ +/** + * @file test_data_structure.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-01-10 + * + * @copyright Copyright (c) 2024 + * + */ +#include + +#include "diag/exec/data/exec_header.hpp" + +TEST(DATA_STRUCTURE, CONSTRUCTOR_CHECK) { + simba::diag::exec::ExecHeader hdr(123, 12, 1); + EXPECT_EQ(hdr.GetServiceID(), 123); + EXPECT_EQ(hdr.GetTimestamp(), 12); + EXPECT_EQ(hdr.GetFlags(), 1); +} diff --git a/mw/diag/ota/code/service/BUILD b/mw/diag/ota/code/service/BUILD index f522d1c1..5326902d 100644 --- a/mw/diag/ota/code/service/BUILD +++ b/mw/diag/ota/code/service/BUILD @@ -4,7 +4,7 @@ cc_library( hdrs = ["ota_service.h"], visibility = ["//mw/diag/ota:__subpackages__"], deps = [ - "//core", + "//core/application:simba_application", "//diag/base/controller:diag_controller", "//communication-core/sockets:socket_ipc", ], diff --git a/mw/diag/ota/code/service/ota_service.cc b/mw/diag/ota/code/service/ota_service.cc index c5e04ac5..7ae5f1bf 100644 --- a/mw/diag/ota/code/service/ota_service.cc +++ b/mw/diag/ota/code/service/ota_service.cc @@ -12,7 +12,6 @@ #include "mw/diag/ota/code/service/ota_service.h" #include "communication-core/sockets/ipc_socket.h" -#include "core/results/result.h" #include "diag/base/controller/diag_controller.h" namespace simba { namespace mw { @@ -24,7 +23,7 @@ void OtaService::Run(const std::unordered_map& parms) { diag_controller->AddMethod( 0x01, [this](const std::vector payload) { - return core::Result>{}; + return {}; }, diag::DiagMethodType::WRITE); AppLogger::Info("Application function started"); diff --git a/mw/em/code/services/em/BUILD b/mw/em/code/services/em/BUILD index 12ad5a33..020a997c 100644 --- a/mw/em/code/services/em/BUILD +++ b/mw/em/code/services/em/BUILD @@ -9,7 +9,6 @@ cc_library( deps = [ "//core/json:simba_json", "//core/logger:Logger", - "//core/results:results_lib", # "@boost//:process", ], ) diff --git a/mw/em/code/services/em/em_service.cc b/mw/em/code/services/em/em_service.cc index 6b072cc1..75243faa 100644 --- a/mw/em/code/services/em/em_service.cc +++ b/mw/em/code/services/em/em_service.cc @@ -61,17 +61,17 @@ void EmService::LoadApps() noexcept { if (this->IsSrpApp(p.path().c_str())) { std::string pp{p.path().string() + "/etc/srp_app.json"}; auto res = this->GetAppConfig(pp); - if (res.HasValue()) { - this->app_list.push_back(res.Value()); + if (res.has_value()) { + this->app_list.push_back(res.value()); if (std::find(this->app_level_list.begin(), this->app_level_list.end(), - res.Value().GetStartUpPrio()) == + res.value().GetStartUpPrio()) == this->app_level_list.end()) { - this->app_level_list.push_back(res.Value().GetStartUpPrio()); + this->app_level_list.push_back(res.value().GetStartUpPrio()); } - AppLogger::Info("App: " + res.Value().GetBinPath() + + AppLogger::Info("App: " + res.value().GetBinPath() + " added to boot list with prio: " + - std::to_string(res.Value().GetStartUpPrio())); + std::to_string(res.value().GetStartUpPrio())); } } } @@ -81,9 +81,9 @@ void EmService::LoadApps() noexcept { } } -core::Result EmService::GetAppConfig( +std::optional EmService::GetAppConfig( const std::string& path) noexcept { - auto obj = core::json::JsonParser::Parser(path).Value(); + auto obj = core::json::JsonParser::Parser(path).value(); std::string bin_path{""}; std::string parm{""}; uint8_t prio{0}; @@ -91,8 +91,8 @@ core::Result EmService::GetAppConfig( uint8_t error_count{0}; { auto bin_path_r = obj.GetString("bin_path"); - if (bin_path_r.HasValue()) { - bin_path = bin_path_r.Value(); + if (bin_path_r.has_value()) { + bin_path = bin_path_r.value(); } else { AppLogger::Error("Application from: " + path + ", don't have: bin_path"); error_count++; @@ -100,8 +100,8 @@ core::Result EmService::GetAppConfig( } { auto parm_r = obj.GetString("parms"); - if (parm_r.HasValue()) { - parm = parm_r.Value(); + if (parm_r.has_value()) { + parm = parm_r.value(); } else { AppLogger::Error("Application from: " + path + ", don't have: parms"); error_count++; @@ -109,8 +109,8 @@ core::Result EmService::GetAppConfig( } { auto prio_r = obj.GetNumber("startup_prio"); - if (prio_r.HasValue()) { - prio = prio_r.Value(); + if (prio_r.has_value()) { + prio = prio_r.value(); } else { AppLogger::Error("Application from: " + path + ", don't have: startup_prio"); @@ -119,8 +119,8 @@ core::Result EmService::GetAppConfig( } { auto delay_r = obj.GetNumber("startup_after_delay"); - if (delay_r.HasValue()) { - delay = delay_r.Value(); + if (delay_r.has_value()) { + delay = delay_r.value(); } else { AppLogger::Error("Application from: " + path + ", don't have: startup_after_delay"); @@ -128,9 +128,9 @@ core::Result EmService::GetAppConfig( } } if (error_count != 0) { - return core::Result{}; + return {}; } else { - return core::Result{data::AppConfig{bin_path, parm, prio, delay}}; + return std::optional{data::AppConfig{bin_path, parm, prio, delay}}; } } void EmService::StartApps() noexcept { diff --git a/mw/em/code/services/em/em_service.h b/mw/em/code/services/em/em_service.h index 511b0bdd..7603d800 100644 --- a/mw/em/code/services/em/em_service.h +++ b/mw/em/code/services/em/em_service.h @@ -13,8 +13,8 @@ #include #include #include +#include -#include "core/results/result.h" #include "mw/em/code/services/em/app_config.h" namespace simba { @@ -25,7 +25,7 @@ class EmService { std::vector app_level_list{}; std::vector app_list{}; bool IsSrpApp(const std::string& path) noexcept; - core::Result GetAppConfig(const std::string& path) noexcept; + std::optional GetAppConfig(const std::string& path) noexcept; public: void LoadApps() noexcept; diff --git a/mw/logger/code/application/dlt_service.cc b/mw/logger/code/application/dlt_service.cc index 48b4c1b0..5157393e 100644 --- a/mw/logger/code/application/dlt_service.cc +++ b/mw/logger/code/application/dlt_service.cc @@ -29,7 +29,7 @@ core::ErrorCode DltService::Run(std::stop_token token) { while (!token.stop_requested()) { auto res_v = this->logs.GetWithoutRemove(); auto res = res_v->ParseFrame(); - if (soc.Transmit("231.255.42.99", tx_port, res.Value()) == + if (soc.Transmit("231.255.42.99", tx_port, res.value()) == core::ErrorCode::kOk) { this->logs.Remove(); } @@ -42,35 +42,35 @@ core::ErrorCode DltService::Initialize( const std::unordered_map& parms) { auto obj_r = core::json::JsonParser::Parser("/opt/" + parms.at("app_name") + "/etc/config.json"); - if (!obj_r.HasValue()) { + if (!obj_r.has_value()) { AppLogger::Error("File not found: /opt/" + parms.at("app_name") + "/etc/config.json"); return core::kError; } - auto json_obj = obj_r.Value(); + auto json_obj = obj_r.value(); { auto ip_t = json_obj.GetString("ip"); - if (!ip_t.HasValue()) { + if (!ip_t.has_value()) { AppLogger::Error("Ip not found in config file"); return core::kError; } - ip_ = ip_t.Value(); + ip_ = ip_t.value(); } { auto port_t = json_obj.GetNumber("tx_port"); - if (!port_t.HasValue()) { + if (!port_t.has_value()) { AppLogger::Error("tx port not found in config file"); return core::kError; } - tx_port = port_t.Value(); + tx_port = port_t.value(); } { auto ip_t = json_obj.GetString("ecu_id"); - if (!ip_t.HasValue()) { + if (!ip_t.has_value()) { AppLogger::Error("Ecu id not found in config file"); return core::kError; } - ec_name = ip_t.Value(); + ec_name = ip_t.value(); } AppLogger::Info("Config loaded: ip=" + ip_ + ", port=" + std::to_string(tx_port) + ", name=" + ec_name); diff --git a/mw/logger/code/data/BUILD b/mw/logger/code/data/BUILD index cf3acddb..82d7cb7e 100644 --- a/mw/logger/code/data/BUILD +++ b/mw/logger/code/data/BUILD @@ -8,5 +8,5 @@ cc_library( "idlt_frame.h", ], visibility = ["//mw/logger:__subpackages__"], - deps = ["//core/results:results_lib"], + deps = [], ) diff --git a/mw/logger/code/data/dlt_frame.h b/mw/logger/code/data/dlt_frame.h index aedbaadb..c2962bf7 100644 --- a/mw/logger/code/data/dlt_frame.h +++ b/mw/logger/code/data/dlt_frame.h @@ -15,7 +15,6 @@ #include #include -#include "core/results/result.h" #include "mw/logger/code/data/dlt_log_type.h" #include "mw/logger/code/data/idlt_frame.h" namespace simba { @@ -79,7 +78,7 @@ class DltFrame final : public IDLTFrame { APID = app_id; MSIN = type; } - core::Result> ParseFrame() noexcept override { + std::optional> ParseFrame() noexcept override { LEN += payload.Length(); std::vector res{HTYP, MCNT, static_cast(LEN >> 8U), static_cast(LEN & 0xFFU)}; @@ -95,7 +94,7 @@ class DltFrame final : public IDLTFrame { std::copy(this->CTID.begin(), this->CTID.end(), std::back_inserter(res)); const auto r = payload.ParseArg(); std::copy(r.begin(), r.end(), std::back_inserter(res)); - return core::Result{res}; + return std::optional{res}; } }; } // namespace data diff --git a/mw/logger/code/data/dlt_log_type.h b/mw/logger/code/data/dlt_log_type.h index a5516cbf..df720598 100644 --- a/mw/logger/code/data/dlt_log_type.h +++ b/mw/logger/code/data/dlt_log_type.h @@ -15,12 +15,12 @@ namespace simba { namespace dlt { namespace data { -enum DLTLogType : uint8_t { - kDLTDebug = 0x51, - kDLTInfo = 0x41, - kDLTWarning = 0x31, - kDLTError = 0x21, -}; + enum DLTLogType : uint8_t { + kDLTDebug = 0x51, + kDLTInfo = 0x41, + kDLTWarning = 0x31, + kDLTError = 0x21, + }; } // namespace data } // namespace dlt } // namespace simba diff --git a/mw/logger/code/data/idlt_frame.h b/mw/logger/code/data/idlt_frame.h index 645e51bc..68d04a15 100644 --- a/mw/logger/code/data/idlt_frame.h +++ b/mw/logger/code/data/idlt_frame.h @@ -12,14 +12,14 @@ #define MW_LOGGER_CODE_DATA_IDLT_FRAME_H_ #include #include +#include -#include "core/results/result.h" namespace simba { namespace dlt { namespace data { class IDLTFrame { public: - virtual core::Result> ParseFrame() noexcept = 0; + virtual std::optional> ParseFrame() noexcept = 0; virtual ~IDLTFrame() {} }; } // namespace data From 4b1c56bc588a96758e2f620f5e9eb4b726c5d5b7 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Mon, 11 Mar 2024 13:56:34 +0100 Subject: [PATCH 32/71] Problem with socket hotfix --- communication-core/sockets/ipc_socket.cc | 3 ++- communication-core/sockets/udp_socket.cc | 1 + deployment | 2 +- mw/logger/code/application/dlt_service.cc | 3 ++- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/communication-core/sockets/ipc_socket.cc b/communication-core/sockets/ipc_socket.cc index 67e51af6..50a32868 100644 --- a/communication-core/sockets/ipc_socket.cc +++ b/communication-core/sockets/ipc_socket.cc @@ -40,7 +40,7 @@ simba::core::ErrorCode IpcSocket::Init(const SocketConfig& config) { strcpy(server_sockaddr.sun_path, // NOLINT ("/run/" + config.GetIp()).c_str()); // NOLINT len = sizeof(server_sockaddr); - unlink(config.GetIp().c_str()); + unlink(("/run/" + config.GetIp()).c_str()); return simba::core::ErrorCode::kOk; } @@ -70,6 +70,7 @@ simba::core::ErrorCode IpcSocket::Transmit(const std::string& ip, (struct sockaddr*)&remote, sizeof(remote)); delete[] buffor; if (rc == -1) { + rc = close(client_socket); return simba::core::ErrorCode::kError; } diff --git a/communication-core/sockets/udp_socket.cc b/communication-core/sockets/udp_socket.cc index f7ec757a..68bea7f4 100644 --- a/communication-core/sockets/udp_socket.cc +++ b/communication-core/sockets/udp_socket.cc @@ -63,6 +63,7 @@ simba::core::ErrorCode UdpSocket::Transmit(const std::string& ip, (struct sockaddr*)&remote, sizeof(remote)); delete[] buffor; if (rc == -1) { + rc = close(client_socket); return simba::core::ErrorCode::kError; } rc = close(client_socket); diff --git a/deployment b/deployment index 58c59329..bee66179 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 58c59329b5f800b49edb1e2e786068c9f96b6890 +Subproject commit bee661795412d34fc830ff0c5cee22958c2ddf82 diff --git a/mw/logger/code/application/dlt_service.cc b/mw/logger/code/application/dlt_service.cc index 5157393e..b7fcab85 100644 --- a/mw/logger/code/application/dlt_service.cc +++ b/mw/logger/code/application/dlt_service.cc @@ -35,6 +35,7 @@ core::ErrorCode DltService::Run(std::stop_token token) { } } AppLogger::Info("Stop"); + SleepMainThread(); return core::kOk; } @@ -117,7 +118,7 @@ void DltService::InitIPC() noexcept { simba::dlt::data::DltFrame>( timestamp, this->ec_name, app_id, types, simba::dlt::data::DltString{log_content}); - if (!this->logs.push(r)) { + if (!this->logs.push(std::move(r))) { AppLogger::Error("DLT msg dropped in TX queue!!"); } }); From ab2a4031edb2686e33a40f17b1676177620a8c96 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Mon, 11 Mar 2024 17:38:54 +0100 Subject: [PATCH 33/71] Fix --- communication-core/sockets/ipc_socket.cc | 6 ++---- communication-core/sockets/ipc_socket.h | 2 +- communication-core/sockets/udp_socket.cc | 3 +-- core/application/application_common.cc | 2 +- core/common/wait_queue.h | 3 ++- core/logger/dlt_logger.cc | 4 ++-- deployment | 2 +- mw/logger/code/application/dlt_service.cc | 3 ++- 8 files changed, 12 insertions(+), 13 deletions(-) diff --git a/communication-core/sockets/ipc_socket.cc b/communication-core/sockets/ipc_socket.cc index 50a32868..f175e9ef 100644 --- a/communication-core/sockets/ipc_socket.cc +++ b/communication-core/sockets/ipc_socket.cc @@ -54,14 +54,13 @@ simba::core::ErrorCode IpcSocket::Transmit(const std::string& ip, int client_socket, rc; struct sockaddr_un remote; memset(&remote, 0, sizeof(struct sockaddr_un)); - client_socket = socket(AF_UNIX, SOCK_DGRAM, 0); if (client_socket == -1) { return simba::core::ErrorCode::kError; } remote.sun_family = AF_UNIX; - strcpy(remote.sun_path, ("/run/" +ip).c_str()); // NOLINT + strcpy(remote.sun_path, ("/run/" + ip).c_str()); // NOLINT std::uint8_t* buffor = new std::uint8_t[payload.size()]; std::copy(payload.begin(), payload.end(), buffor); @@ -69,12 +68,11 @@ simba::core::ErrorCode IpcSocket::Transmit(const std::string& ip, rc = sendto(client_socket, buffor, payload.size(), 0, (struct sockaddr*)&remote, sizeof(remote)); delete[] buffor; + close(client_socket); if (rc == -1) { - rc = close(client_socket); return simba::core::ErrorCode::kError; } - rc = close(client_socket); return simba::core::ErrorCode::kOk; } diff --git a/communication-core/sockets/ipc_socket.h b/communication-core/sockets/ipc_socket.h index 67f9d69f..30eab47d 100644 --- a/communication-core/sockets/ipc_socket.h +++ b/communication-core/sockets/ipc_socket.h @@ -32,7 +32,7 @@ class IpcSocket : public ISocket { int server_sock, len, rc; int bytes_rec = 0; struct sockaddr_un server_sockaddr, peer_sock; - char buf[256 * 2]; + std::unique_ptr rx_thred; void Loop(std::stop_token stoken); diff --git a/communication-core/sockets/udp_socket.cc b/communication-core/sockets/udp_socket.cc index 68bea7f4..63db3169 100644 --- a/communication-core/sockets/udp_socket.cc +++ b/communication-core/sockets/udp_socket.cc @@ -62,11 +62,10 @@ simba::core::ErrorCode UdpSocket::Transmit(const std::string& ip, rc = sendto(client_socket, buffor, payload.size(), 0, (struct sockaddr*)&remote, sizeof(remote)); delete[] buffor; + close(client_socket); if (rc == -1) { - rc = close(client_socket); return simba::core::ErrorCode::kError; } - rc = close(client_socket); return simba::core::ErrorCode::kOk; } diff --git a/core/application/application_common.cc b/core/application/application_common.cc index 67ffa886..5c11286b 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -25,7 +25,7 @@ namespace simba { namespace core { void ApplicationCommon::StopApp() { this->source.request_stop(); - exit(1); + // exit(1); } bool ApplicationCommon::FileExist(const std::string& name) { std::ifstream file{name}; diff --git a/core/common/wait_queue.h b/core/common/wait_queue.h index 8e5867a4..5a344bd2 100644 --- a/core/common/wait_queue.h +++ b/core/common/wait_queue.h @@ -13,6 +13,7 @@ #include // NOLINT #include // NOLINT #include +#include namespace simba { namespace core { template @@ -35,7 +36,7 @@ class WaitQueue final { q.pop(); flag = false; } - q.push(obj); + q.push(std::move(obj)); cv.notify_one(); return flag; } diff --git a/core/logger/dlt_logger.cc b/core/logger/dlt_logger.cc index 357b6686..ba717360 100644 --- a/core/logger/dlt_logger.cc +++ b/core/logger/dlt_logger.cc @@ -22,7 +22,7 @@ namespace simba { namespace core { namespace logger { DltLogger::DltLogger(/* args */) { - ipc_soc.Init(com::soc::SocketConfig{"", 0, 0}); + // ipc_soc.Init(com::soc::SocketConfig{"", 0, 0}); this->thread = std::make_unique( [this](std::stop_token token) { this->Loop(token); }); } @@ -38,8 +38,8 @@ void DltLogger::Loop(std::stop_token token) { drop_number++; if (drop_number > 20) { drop_number = 0; - std::cerr << "DLT drop logs!!!" << std::endl; q.Remove(); + std::cerr << "DLT drop logs!!!" << std::endl; } } } diff --git a/deployment b/deployment index bee66179..df3861c9 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit bee661795412d34fc830ff0c5cee22958c2ddf82 +Subproject commit df3861c9cb1ce7ec854847ac99b1902e2d80f6a1 diff --git a/mw/logger/code/application/dlt_service.cc b/mw/logger/code/application/dlt_service.cc index b7fcab85..8f24d4cf 100644 --- a/mw/logger/code/application/dlt_service.cc +++ b/mw/logger/code/application/dlt_service.cc @@ -12,6 +12,7 @@ #include "mw/logger/code/application/dlt_service.h" #include +#include #include #include "communication-core/sockets/socket_config.h" @@ -25,6 +26,7 @@ namespace mw { namespace dlt { core::ErrorCode DltService::Run(std::stop_token token) { + // int i = 0; std::this_thread::sleep_for(std::chrono::seconds{5}); while (!token.stop_requested()) { auto res_v = this->logs.GetWithoutRemove(); @@ -35,7 +37,6 @@ core::ErrorCode DltService::Run(std::stop_token token) { } } AppLogger::Info("Stop"); - SleepMainThread(); return core::kOk; } From 8884e632df4a914036c8f8cf58120115f2f22d55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Ma=C5=84kowski?= <127433424+Michal-Mankowski@users.noreply.github.com> Date: Mon, 11 Mar 2024 20:13:50 +0100 Subject: [PATCH 34/71] i2c dodane (#26) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added action * i2c dodane * poprawiono składnie * nevermind poprawiono składnie znowu * finalne poprawienie składni, może --------- Co-authored-by: Bartosz Śnieg Co-authored-by: Mateusz Krajewski --- core/i2c/BUILD | 7 +++++ core/i2c/i2cdriver.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++ core/i2c/i2cdriver.h | 39 +++++++++++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 core/i2c/BUILD create mode 100644 core/i2c/i2cdriver.cpp create mode 100644 core/i2c/i2cdriver.h diff --git a/core/i2c/BUILD b/core/i2c/BUILD new file mode 100644 index 00000000..a8264f05 --- /dev/null +++ b/core/i2c/BUILD @@ -0,0 +1,7 @@ +cc_library( + name = "i2cdriver", + srcs = ["i2cdriver.cpp"], + hdrs = ["i2cdriver.h"], + deps = ["//core/common:common_types", "//core/results:results_lib"], + visibility = ["//core:__subpackages__"], +) diff --git a/core/i2c/i2cdriver.cpp b/core/i2c/i2cdriver.cpp new file mode 100644 index 00000000..e21efb94 --- /dev/null +++ b/core/i2c/i2cdriver.cpp @@ -0,0 +1,61 @@ +/** + * @file i2cdriver.cpp + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief This file defines I2C driver + * @version 0.1 + * @date 2024-01-14 + * + * @copyright Copyright (c) 2024 + * + */ +#include "i2cdriver.h" +namespace simba { +namespace core { +int32_t I2C::i2c_smbus_access(char read_write, uint8_t command, int size, union i2c_smbus_data *data) { + i2c_smbus_ioctl_data args; + args.read_write = read_write; + args.command = command; + args.size = size; + args.data = data; + return ioctl(this->file, I2C_SMBUS, &args); +} +Result I2C::i2c_smbus_read_byte_data(const uint8_t command) { + union i2c_smbus_data data; + if (i2c_smbus_access(I2C_SMBUS_READ, command, I2C_SMBUS_BYTE_DATA, &data) != 0) { + return Result{}; + } + return Result(0xFF & data.byte); +} +ErrorCode I2C::init(const std::string& path) { + this->file = open(path.c_str(), O_RDWR); + if (this->file < 0) { + return ErrorCode::kError; + } + return ErrorCode::kOk; +} +Result> I2C::Read(const uint8_t address, const uint8_t reg) { + std::vector result; + if (ioctl(this->file, I2C_SLAVE, address) < 0) { + return Result>{}; + } + Result data = i2c_smbus_read_byte_data(reg); + if (!data.HasValue()) { + return Result>{}; + } + while (data.Value() >= 0) { + result.push_back(data.Value()); + data = i2c_smbus_read_byte_data(reg); + } + return Result>{result}; +} +ErrorCode I2C::Write(const uint8_t address, const uint8_t reg, std::vector data) { + if (ioctl(this->file, I2C_SLAVE, address) < 0) { + return ErrorCode::kInitializeError; + } + if (write(file, data.data(), data.size()) != data.size()) { + return ErrorCode::kError; + } + return ErrorCode::kOk; +} +} // namespace core +} // namespace simba diff --git a/core/i2c/i2cdriver.h b/core/i2c/i2cdriver.h new file mode 100644 index 00000000..934aacab --- /dev/null +++ b/core/i2c/i2cdriver.h @@ -0,0 +1,39 @@ +/** + * @file i2cdriver.h + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief This file defines I2C driver + * @version 0.1 + * @date 2024-01-14 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef CORE_I2C_I2CDRIVER_H_ +#define CORE_I2C_I2CDRIVER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "core/common/error_code.h" +#include "core/results/result.h" +namespace simba { +namespace core { +class I2C{ + public: + ErrorCode init(const std::string& path); + Result> Read(const uint8_t address, const uint8_t reg); + ErrorCode Write(const uint8_t address, const uint8_t reg, std::vector data); + private: + int file = -1; + int32_t i2c_smbus_access(char read_write, + uint8_t command, int size, union i2c_smbus_data *data); + Result i2c_smbus_read_byte_data(const uint8_t command); +}; +} // namespace core +} // namespace simba +#endif // CORE_I2C_I2CDRIVER_H_ From 69899773ce85b4358f128c329df2666fa5066d3b Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 12 Mar 2024 12:41:10 +0100 Subject: [PATCH 35/71] I2C driver remove core::Result --- core/i2c/BUILD | 4 +++- core/i2c/i2cdriver.cpp | 23 ++++++++++++----------- core/i2c/i2cdriver.h | 6 +++--- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/core/i2c/BUILD b/core/i2c/BUILD index a8264f05..b2bead0d 100644 --- a/core/i2c/BUILD +++ b/core/i2c/BUILD @@ -2,6 +2,8 @@ cc_library( name = "i2cdriver", srcs = ["i2cdriver.cpp"], hdrs = ["i2cdriver.h"], - deps = ["//core/common:common_types", "//core/results:results_lib"], + deps = [ + "//core/common:common_types", + ], visibility = ["//core:__subpackages__"], ) diff --git a/core/i2c/i2cdriver.cpp b/core/i2c/i2cdriver.cpp index e21efb94..f5509d84 100644 --- a/core/i2c/i2cdriver.cpp +++ b/core/i2c/i2cdriver.cpp @@ -9,6 +9,7 @@ * */ #include "i2cdriver.h" + namespace simba { namespace core { int32_t I2C::i2c_smbus_access(char read_write, uint8_t command, int size, union i2c_smbus_data *data) { @@ -19,12 +20,12 @@ int32_t I2C::i2c_smbus_access(char read_write, uint8_t command, int size, union args.data = data; return ioctl(this->file, I2C_SMBUS, &args); } -Result I2C::i2c_smbus_read_byte_data(const uint8_t command) { +std::optional I2C::i2c_smbus_read_byte_data(const uint8_t command) { union i2c_smbus_data data; if (i2c_smbus_access(I2C_SMBUS_READ, command, I2C_SMBUS_BYTE_DATA, &data) != 0) { - return Result{}; + return{}; } - return Result(0xFF & data.byte); + return std::optional(0xFF & data.byte); } ErrorCode I2C::init(const std::string& path) { this->file = open(path.c_str(), O_RDWR); @@ -33,20 +34,20 @@ ErrorCode I2C::init(const std::string& path) { } return ErrorCode::kOk; } -Result> I2C::Read(const uint8_t address, const uint8_t reg) { +std::optional> I2C::Read(const uint8_t address, const uint8_t reg) { std::vector result; if (ioctl(this->file, I2C_SLAVE, address) < 0) { - return Result>{}; + return {}; } - Result data = i2c_smbus_read_byte_data(reg); - if (!data.HasValue()) { - return Result>{}; + std::optional data = i2c_smbus_read_byte_data(reg); + if (!data.has_value()) { + return {}; } - while (data.Value() >= 0) { - result.push_back(data.Value()); + while (data.value() >= 0) { + result.push_back(data.value()); data = i2c_smbus_read_byte_data(reg); } - return Result>{result}; + return std::optional>{result}; } ErrorCode I2C::Write(const uint8_t address, const uint8_t reg, std::vector data) { if (ioctl(this->file, I2C_SLAVE, address) < 0) { diff --git a/core/i2c/i2cdriver.h b/core/i2c/i2cdriver.h index 934aacab..5335db16 100644 --- a/core/i2c/i2cdriver.h +++ b/core/i2c/i2cdriver.h @@ -19,20 +19,20 @@ #include #include #include +#include #include "core/common/error_code.h" -#include "core/results/result.h" namespace simba { namespace core { class I2C{ public: ErrorCode init(const std::string& path); - Result> Read(const uint8_t address, const uint8_t reg); + std::optional> Read(const uint8_t address, const uint8_t reg); ErrorCode Write(const uint8_t address, const uint8_t reg, std::vector data); private: int file = -1; int32_t i2c_smbus_access(char read_write, uint8_t command, int size, union i2c_smbus_data *data); - Result i2c_smbus_read_byte_data(const uint8_t command); + std::optional i2c_smbus_read_byte_data(const uint8_t command); }; } // namespace core } // namespace simba From eb5f53a85d2c64df15f64a43ceaf2e3cd10fe358 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Tue, 5 Mar 2024 22:34:19 +0100 Subject: [PATCH 36/71] some/ip v 1.0 --- apps/example/BUILD | 35 +- apps/example/router.cc | 19 +- apps/example/router2.cc | 45 ++- communication-core/json-parser/BUILD | 17 - communication-core/json-parser/Ijson_parser.h | 35 -- .../json-parser/database_json_parser.h | 96 ------ communication-core/json-parser/json_parser.cc | 166 --------- communication-core/json-parser/json_parser.h | 45 --- .../network-data/network_data_structure.h | 9 +- .../sockets/udp_multicast_socket.cc | 18 +- communication-core/sockets/udp_socket.cc | 2 +- communication-core/someip-controller/BUILD | 68 ++-- .../someip-controller/Isomeip_controller.h | 46 --- .../someip-controller/callbacks.h | 52 +++ .../someip-controller/controller.cc | 321 ++++++++++++++++++ .../someip-controller/controller.h | 100 ++++++ .../someip-controller/event_proxy.h | 143 ++++++++ .../someip-controller/event_skeleton.h | 103 ++++++ communication-core/someip-controller/iproxy.h | 38 +++ .../someip-controller/iskeleton.h | 35 ++ .../someip-controller/method_proxy.h | 142 ++++++++ .../someip-controller/method_skeleton.h | 67 ++++ .../someip-controller/someip_controller.cc | 222 ------------ .../someip-controller/someip_controller.h | 98 ------ .../someip-controller/transfer.h | 1 + communication-core/someip-database/code/BUILD | 13 + .../someip-database/code/com_config.cc | 45 +++ .../someip-database/code/com_config.h | 39 +++ .../someip-database/code/config_db.cc | 2 +- .../someip-database/code/config_db.h | 2 +- .../someip-database/code/config_db_parser.h | 55 +-- .../someip-database/code/database.cc | 14 + .../someip-database/code/database.h | 17 +- .../someip-database/code/database_parser.h | 63 ++-- .../someip-database/code/interface.h | 6 +- .../someip-database/code/interface_parser.h | 15 + communication-core/someip/BUILD | 14 +- communication-core/someip/factory/BUILD | 2 +- .../someip/factory/Isomeip_header_factory.h | 6 +- .../someip/factory/Isomeip_message_factory.h | 2 - .../someip/factory/someip_header_factory.cc | 10 +- .../someip/factory/someip_header_factory.h | 6 +- .../someip/factory/someip_message_factory.cc | 8 +- .../someip/factory/someip_message_factory.h | 12 +- communication-core/someip/message_code.h | 2 - communication-core/someip/message_type.h | 2 - communication-core/someip/someip_header.cc | 2 - communication-core/someip/someip_header.h | 2 - core/application/BUILD | 10 +- core/application/application_common.cc | 28 +- core/application/application_common.h | 8 +- core/application/application_mw.cc | 1 + deployment | 2 +- mw/gpio_server/gpio_mw.cpp | 1 - mw/logger/code/BUILD | 2 +- 55 files changed, 1425 insertions(+), 889 deletions(-) delete mode 100644 communication-core/json-parser/BUILD delete mode 100644 communication-core/json-parser/Ijson_parser.h delete mode 100644 communication-core/json-parser/database_json_parser.h delete mode 100644 communication-core/json-parser/json_parser.cc delete mode 100644 communication-core/json-parser/json_parser.h delete mode 100644 communication-core/someip-controller/Isomeip_controller.h create mode 100644 communication-core/someip-controller/callbacks.h create mode 100644 communication-core/someip-controller/controller.cc create mode 100644 communication-core/someip-controller/controller.h create mode 100644 communication-core/someip-controller/event_proxy.h create mode 100644 communication-core/someip-controller/event_skeleton.h create mode 100644 communication-core/someip-controller/iproxy.h create mode 100644 communication-core/someip-controller/iskeleton.h create mode 100644 communication-core/someip-controller/method_proxy.h create mode 100644 communication-core/someip-controller/method_skeleton.h delete mode 100644 communication-core/someip-controller/someip_controller.cc delete mode 100644 communication-core/someip-controller/someip_controller.h create mode 100644 communication-core/someip-database/code/com_config.cc create mode 100644 communication-core/someip-database/code/com_config.h create mode 100644 communication-core/someip-database/code/interface_parser.h diff --git a/apps/example/BUILD b/apps/example/BUILD index de9de4cd..40b8d477 100644 --- a/apps/example/BUILD +++ b/apps/example/BUILD @@ -7,24 +7,27 @@ cc_binary( ], visibility = ["//deployment/apps/example:__subpackages__"], deps = [ + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", "//core/application:simba_application", - "@untar", "//mw/gpio_server/controller:gpio_controller", + "@untar", ], ) -# cc_binary( -# name = "router2", -# srcs = [ -# "main.cc", -# "router.h", -# "router2.cc", -# ], -# visibility = ["//deployment/apps/example:__subpackages__"], -# deps = [ -# "//communication-core/sockets:socket_ipc", -# "//core", -# "//diag/base/controller:diag_controller", -# "@untar", -# ], -# ) +cc_binary( + name = "example2", + srcs = [ + "main.cc", + "router.h", + "router2.cc", + ], + visibility = ["//deployment/apps/example2:__subpackages__"], + deps = [ + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", + "//core/application:simba_application", + "//mw/gpio_server/controller:gpio_controller", + "@untar", + ], +) diff --git a/apps/example/router.cc b/apps/example/router.cc index 6a09b926..e40495b6 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -10,11 +10,28 @@ */ #include "apps/example/router.h" +#include +#include + +#include "communication-core/someip-controller/event_proxy.h" +#include "communication-core/someip-controller/method_skeleton.h" #include "core/logger/Logger.h" namespace simba { namespace router { core::ErrorCode Router::Run(std::stop_token token) { + auto proxy_event = std::make_shared( + "ExampleApp/someevent", + [this](const std::vector) { AppLogger::Info("EVENT !!!!!!!"); }); + auto example = std::make_shared( + "ExampleApp/exampleMethod", + [this](const std::vector payload) + -> std::optional> { + return std::vector{0, 1, 2}; + }); + com->Add(example); + com->Add(proxy_event); + proxy_event->StartFindService(); while (true) { AppLogger::Debug("AppLogger::Debug"); AppLogger::Info("AppLogger::Info"); @@ -29,7 +46,7 @@ core::ErrorCode Router::Run(std::stop_token token) { core::ErrorCode Router::Initialize( const std::unordered_map& parms) { - this->gpio_.Init(12); + this->gpio_.Init(12); return core::ErrorCode::kOk; } } // namespace router diff --git a/apps/example/router2.cc b/apps/example/router2.cc index 243b247e..6d44131e 100644 --- a/apps/example/router2.cc +++ b/apps/example/router2.cc @@ -11,35 +11,34 @@ #include #include "apps/example/router.h" -#include "communication-core/sockets/ipc_socket.h" +#include "communication-core/someip-controller/event_skeleton.h" +#include "communication-core/someip-controller/method_proxy.h" #include "core/logger/Logger.h" -#include "diag/base/controller/diag_controller.h" namespace simba { namespace router { -void Router::Run(const std::unordered_map& parms) { - diag::DiagController diag_controller{0x00002, - std::make_unique()}; - diag_controller.Init(); - const auto res = diag_controller.Write(0x0001, 0x01, {0x10, 0x01}); - if (res == core::ErrorCode::kOk) { - AppLogger::Info("OK"); - } else { - AppLogger::Error("NOK"); +core::ErrorCode Router::Run(std::stop_token token) { + auto example = + std::make_shared("ExampleApp2/someproxy"); + auto event_example = + std::make_shared("ExampleApp2/exampleEvent"); + com->Add(example); + com->Add(event_example); + example->StartFindService(); + event_example->SetValue({10, 11, 12, 13, 14, 15}); + while (true) { + // this->gpio_.SetPinValue(5,gpio::Value::HIGH); + std::ignore = example->Get(); + // this->gpio_.SetPinValue(5,gpio::Value::LOW); + std::this_thread::sleep_for(std::chrono::seconds(1)); } - // if(res.HasValue()){ - // std::string pp = ""; - // auto res_p = res.Value(); - // for(auto a : res_p){ - // pp+=std::to_string(a)+","; - // } - // AppLogger::Debug("Payload: "+pp); - // } + return core::ErrorCode::kOk; +} - AppLogger::Debug("Router started"); - this->SleepMainThread(); - // this->logger_->Debug("Router started"); +core::ErrorCode Router::Initialize( + const std::unordered_map& parms) { + this->gpio_.Init(12); + return core::ErrorCode::kOk; } -void Router::Stop() {} } // namespace router } // namespace simba diff --git a/communication-core/json-parser/BUILD b/communication-core/json-parser/BUILD deleted file mode 100644 index cd2b21ed..00000000 --- a/communication-core/json-parser/BUILD +++ /dev/null @@ -1,17 +0,0 @@ -cc_library( - name = "JsonParser", - # srcs = ["json_parser.cc"], - hdrs = [ - # "Ijson_parser.h", - "database_json_parser.h", - # "json_parser.h", - ], - visibility = [ - "//apps:__subpackages__", - "//mw:__subpackages__", - ], - deps = [ - "//communication-core/database:DatabaseLib", - "@com_json//:json", - ], -) diff --git a/communication-core/json-parser/Ijson_parser.h b/communication-core/json-parser/Ijson_parser.h deleted file mode 100644 index 41a14d7e..00000000 --- a/communication-core/json-parser/Ijson_parser.h +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @file Ijson_parser.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-10 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef COMMUNICATION_CORE_JSON_PARSER_IJSON_PARSER_H_ -#define COMMUNICATION_CORE_JSON_PARSER_IJSON_PARSER_H_ -#include -#include - -#include "database/app_element.h" -#include "nlohmann/json.hpp" -#include "unordered_map" - -namespace simba { -namespace database { -namespace json { -class Ijson_parser { - private: - virtual simba::database::objects::AppElement ParseJson( - const nlohmann::json& data) = 0; - - public: - virtual simba::database::objects::AppElement LoadJson( - const std::string& path) = 0; -}; -} // namespace json -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_JSON_PARSER_IJSON_PARSER_H_ diff --git a/communication-core/json-parser/database_json_parser.h b/communication-core/json-parser/database_json_parser.h deleted file mode 100644 index 7aeb1582..00000000 --- a/communication-core/json-parser/database_json_parser.h +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file database_json_parser.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief This file define parser for database - * @version 0.1 - * @date 2023-10-23 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_JSON_PARSER_DATABASE_JSON_PARSER_H_ -#define COMMUNICATION_CORE_JSON_PARSER_DATABASE_JSON_PARSER_H_ -#include -#include -#include -#include - -#include "nlohmann/json.hpp" -// using nlojson = nlohmann::json; -namespace simba { -namespace database { -namespace json { -class DatabaseJsonParser { - private: - /* data */ - public: - template - static void LoadJson(Database& db, // NOLINT - const std::string& path_to_json) { // NOLINT - std::ifstream f(path_to_json); - if (!f.is_open()) { - return; - } - nlohmann::json data = nlohmann::json::parse(f); - ParseReqMethods(db, data); - ParsePubMethods(db, data); - ParseDb(db, data); - ParsePubEvent(db, data); - ParseReqEvent(db, data); - } - template - static void ParseReqMethods(Database& db, // NOLINT - const nlohmann::json& data) { // NOLINT - auto reqs_methods = data["req_methods"]; - for (auto& [key, val] : reqs_methods.items()) { - db.AddReqMethodsElement( - key, db.CreatReqMethodElement(val["method_id"], val["service_id"])); - } - } - template - static void ParsePubMethods(Database& db, // NOLINT - const nlohmann::json& data) { // NOLINT - auto reqs_methods = data["pub_methods"]; - for (auto& [key, val] : reqs_methods.items()) { - db.AddPubMethodElement(val["name"], - static_cast(val["method_id"])); - } - } - template - static void ParseDb(Database& db, const nlohmann::json& data) { // NOLINT - auto reqs_methods = data["db"]; - for (auto& [key, val] : reqs_methods.items()) { - db.AddDbElement( - static_cast(std::stoi(key)), - db.CreatDbElement((val["ip"].size() == 0) ? val["ipc"] : val["ip"], - static_cast(val["port"]))); - } - } - template - static void ParsePubEvent(Database& db, // NOLINT - const nlohmann::json& data) { // NOLINT - auto reqs_methods = data["pub_events"]; - for (auto& [key, val] : reqs_methods.items()) { - std::cout << "key: " << key << ", value:" << val << '\n'; - } - } - template - static void ParseReqEvent(Database& db, // NOLINT - const nlohmann::json& data) { // NOLINT - auto reqs_methods = data["req_events"]; - for (auto& [key, val] : reqs_methods.items()) { - // std::cout << "key: " << key << ", value:" << val << '\n'; - - db.AddReqMethodsElement( - val["name"], - db.CreatReqMethodElement(val["event_id"], val["service_id"])); - } - } - DatabaseJsonParser(/* args */); - ~DatabaseJsonParser(); -}; -} // namespace json -} // namespace database -} // namespace simba - -#endif // COMMUNICATION_CORE_JSON_PARSER_DATABASE_JSON_PARSER_H_ diff --git a/communication-core/json-parser/json_parser.cc b/communication-core/json-parser/json_parser.cc deleted file mode 100644 index d26699ec..00000000 --- a/communication-core/json-parser/json_parser.cc +++ /dev/null @@ -1,166 +0,0 @@ -/** - * @file json_parser.cc - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-10 - * - * @copyright Copyright (c) 2024 - * - */ -#include "communication-core/json-parser/json_parser.h" - -#include -#include -#include - -namespace simba { -namespace database { -namespace json { - -simba::database::objects::AppElement Json_parser::LoadJson( - const std::string& path) { - std::ifstream file(path); - if (file.is_open()) { - nlohmann::json data; - file >> data; - file.close(); - - simba::database::objects::AppElement result = ParseJson(data); - return result; - } else { - // Handle file open error - } -} - -simba::database::objects::AppElement Json_parser::ParseJson( - const nlohmann::json& data) { - std::string name = data["name"]; - simba::database::objects::NetInterfaceElement buffer( - data["service_id"], data["interface"]["ip"], data["interface"]["port"], - data["interface"]["ipc"]); - std::unordered_map pub_methods = - parsePubMethods(data); - std::unordered_map - req_events = parseReqEvents(data); - std::unordered_map - pub_events = parsePubEvents(data); - std::unordered_map db = - parseDb(data); - std::unordered_map conf = parseConfig(data); - simba::database::objects::AppElement results( - name, buffer, pub_methods, req_events, pub_events, db, conf); - - return results; -} - -std::unordered_map Json_parser::parsePubMethods( - const nlohmann::json& json_data) { - std::unordered_map pub_methods; - - auto pub_methods_array = json_data["pub_methods"]; - - for (const auto& method : pub_methods_array) { - uint16_t method_id = method["method_id"]; - std::string name = method["name"]; - - pub_methods[std::to_string(method_id)] = name; - } - - return pub_methods; -} - -std::unordered_map -Json_parser::parseReqEvents(const nlohmann::json& json_data) { - std::unordered_map - req_events; - - auto req_events_array = json_data["req_events"]; - - for (const auto& event : req_events_array) { - u_int16_t event_id = event["event_id"]; - u_int16_t service_id = event["service_id"]; - std::string name = event["name"]; - - simba::database::objects::ReqEventElement event_element(event_id, - service_id); - - req_events.emplace(name, event_element); - } - - return req_events; -} - -std::unordered_map -Json_parser::parsePubEvents(const nlohmann::json& json_data) { - std::unordered_map - pub_events; - - for (auto it = json_data["pub_events"].begin(); - it != json_data["pub_events"].end(); ++it) { - const std::string& event_key = it.key(); - const nlohmann::json& event_data = it.value(); - - uint16_t event_id = event_data["event_id"]; - - simba::database::objects::EventElement event_element(event_id); - - for (const auto& subscriber : event_data["subscribers"]) { - uint16_t service_id = subscriber["service_id"]; - std::string name = subscriber["interface"]["name"]; // Where to save? - std::string ip = subscriber["interface"]["ip"]; - uint16_t port = subscriber["interface"]["port"]; - - simba::database::objects::ServiceElement service_element(service_id, ip, - port); - event_element.AddService(service_element); - } - - pub_events.emplace(event_key, event_element); - } - - return pub_events; -} - -std::unordered_map -Json_parser::parseDb(const nlohmann::json& data) { - std::unordered_map db; - - for (auto it = data["db"].begin(); it != data["db"].end(); ++it) { - const std::string& key = it.key(); - const nlohmann::json& method_data = it.value(); - - uint16_t method_id = method_data["method_id"]; - uint16_t service_id = method_data["service_id"]; - std::string name = method_data["interface"]["name"]; // Where to store? - std::string ip_address = method_data["interface"]["ip"]; - uint16_t port = method_data["service"]["port"]; - - simba::database::objects::ServiceElement service_element(service_id, - ip_address, port); - simba::database::objects::MethodElement method_element(method_id, - service_element); - - db.emplace(key, method_element); - } - - return db; -} - -std::unordered_map Json_parser::parseConfig( - const nlohmann::json& json_data) { - std::unordered_map conf; - - for (auto it = json_data["conf"].begin(); it != json_data["conf"].end(); - ++it) { - const std::string& key = it.key(); - const std::string& value = it.value(); - conf[key] = value; - } - - return conf; -} - -} // namespace json -} // namespace database -} // namespace simba diff --git a/communication-core/json-parser/json_parser.h b/communication-core/json-parser/json_parser.h deleted file mode 100644 index a03bfa59..00000000 --- a/communication-core/json-parser/json_parser.h +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file json_parser.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-10 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef COMMUNICATION_CORE_JSON_PARSER_JSON_PARSER_H_ -#define COMMUNICATION_CORE_JSON_PARSER_JSON_PARSER_H_ -#include -#include - -#include "communication-core/json-parser/Ijson_parser.h" - -namespace simba { -namespace database { -namespace json { -class Json_parser : public Ijson_parser { - private: - simba::database::objects::AppElement ParseJson( - const nlohmann::json& data) override; - std::unordered_map parsePubMethods( - const nlohmann::json& json_data); - std::unordered_map - Json_parser::parseReqEvents(const nlohmann::json& json_data); - std::unordered_map - Json_parser::parsePubEvents(const nlohmann::json& json_data); - std::unordered_map - parseDb(const nlohmann::json& data); - std::unordered_map parseConfig( - const nlohmann::json& json_data); - - public: - Json_parser() = default; - ~Json_parser() = default; - simba::database::objects::AppElement LoadJson( - const std::string& path) override; -}; -} // namespace json -} // namespace database -} // namespace simba -#endif // COMMUNICATION_CORE_JSON_PARSER_JSON_PARSER_H_ diff --git a/communication-core/network-data/network_data_structure.h b/communication-core/network-data/network_data_structure.h index a7b64685..83f13989 100644 --- a/communication-core/network-data/network_data_structure.h +++ b/communication-core/network-data/network_data_structure.h @@ -26,10 +26,17 @@ class NetworkDataStructure : public interface::IFrame { void AddData(interface::IFrame* field); public: - void Copy(const NetworkDataStructure& other); NetworkDataStructure(/* args */) = default; + // NetworkDataStructure(const NetworkDataStructure&) = delete; virtual ~NetworkDataStructure() = default; + +/** + * @brief Return Structure as uint8 vector + * + * @return std::vector + */ std::vector GetBuffor() const override; + simba::core::ErrorCode SetBuffor(std::vector data) override; }; } // namespace network diff --git a/communication-core/sockets/udp_multicast_socket.cc b/communication-core/sockets/udp_multicast_socket.cc index 045aadc9..58720602 100644 --- a/communication-core/sockets/udp_multicast_socket.cc +++ b/communication-core/sockets/udp_multicast_socket.cc @@ -32,16 +32,16 @@ simba::core::ErrorCode UdpMulticastSocket::Init(const SocketConfig &config) { groupSock.sin_family = AF_INET; groupSock.sin_addr.s_addr = inet_addr("231.255.42.99"); groupSock.sin_port = htons(config.GetRxPort()); - // { - // char loopch = 0; + { + char loopch = 0; - // if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, - // (char *)&loopch, // NOLINT - // sizeof(loopch)) < 0) { - // close(sd); - // return simba::core::ErrorCode::kError; - // } - // } + if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, + (char *)&loopch, // NOLINT + sizeof(loopch)) < 0) { + close(sd); + return simba::core::ErrorCode::kError; + } + } localInterface.s_addr = inet_addr(config.GetIp().c_str()); if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localInterface, // NOLINT diff --git a/communication-core/sockets/udp_socket.cc b/communication-core/sockets/udp_socket.cc index 63db3169..7f029adb 100644 --- a/communication-core/sockets/udp_socket.cc +++ b/communication-core/sockets/udp_socket.cc @@ -56,7 +56,7 @@ simba::core::ErrorCode UdpSocket::Transmit(const std::string& ip, } remote.sin_family = AF_INET; remote.sin_addr.s_addr = inet_addr(ip.c_str()); - remote.sin_port = port; + remote.sin_port = htons(port); std::uint8_t* buffor = new std::uint8_t[payload.size()]; std::copy(payload.begin(), payload.end(), buffor); rc = sendto(client_socket, buffor, payload.size(), 0, diff --git a/communication-core/someip-controller/BUILD b/communication-core/someip-controller/BUILD index cb05470a..e06f98d3 100644 --- a/communication-core/someip-controller/BUILD +++ b/communication-core/someip-controller/BUILD @@ -1,14 +1,44 @@ cc_library( - name = "someip_interface", + name = "interfaces", hdrs = [ - "Isomeip_controller.h", + "callbacks.h", + "iproxy.h", + "iskeleton.h", ], - visibility = ["//communication-core:__subpackages__"], + visibility = [], deps = [ - "//communication-core/someip:someip_header", "//communication-core/someip:someip_types", - "//communication-core/someip/factory:someip_message_factory", - "//core/common:common_types", + "//communication-core/someip-database/code:someip_database_lib", + ], +) + +cc_library( + name = "proxy", + srcs = [], + hdrs = [ + "event_proxy.h", + "method_proxy.h", + ], + visibility = ["//visibility:public"], + deps = [ + ":interfaces", + "//communication-core/someip-database/code:app_config_object", + "//core/logger:Logger", + ], +) + +cc_library( + name = "skeleton", + srcs = [], + hdrs = [ + "event_skeleton.h", + "method_skeleton.h", + ], + visibility = ["//visibility:public"], + deps = [ + ":interfaces", + "//communication-core/someip-database/code:app_config_object", + "//core/logger:Logger", ], ) @@ -22,21 +52,17 @@ cc_library( ) cc_library( - name = "someip_controller", - srcs = ["someip_controller.cc"], - hdrs = [ - "someip_controller.h", - ], - visibility = ["//communication-core:__subpackages__"], + name = "controller", + srcs = ["controller.cc"], + hdrs = ["controller.h"], + visibility = ["//visibility:public"], deps = [ - ":someip_interface", - "//communication-core/database:DatabaseLib", - # "//communication-core/json-parser:JsonParser", - "//communication-core/sockets:socket_interface", - "//communication-core/someip:someip_header", - "//communication-core/someip:someip_types", - "//communication-core/someip/factory:someip_header_factory", - "//communication-core/someip/factory:someip_message_factory", - "//communication-core/someip-controller:transfer_lib", + "//communication-core/sockets:socket_ipc", + "//communication-core/sockets:socket_udp", + "//communication-core/someip:someip_objects", + "//communication-core/someip-controller:interfaces", + "//communication-core/someip-database/code:someip_database_lib", + "//core/common:wait_queue", + "//core/logger:Logger", ], ) diff --git a/communication-core/someip-controller/Isomeip_controller.h b/communication-core/someip-controller/Isomeip_controller.h deleted file mode 100644 index 7c12afe3..00000000 --- a/communication-core/someip-controller/Isomeip_controller.h +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file Isomeip_controller.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-11-15 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_ISOMEIP_CONTROLLER_H_ -#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_ISOMEIP_CONTROLLER_H_ -#include -#include -#include -#include -#include - -#include "core/common/error_code.h" -#include "communication-core/someip/message_code.h" -namespace simba { -namespace com { -namespace someip { -using SomeIPMethod = std::function, com::core::data::MessageCode>>( - const std::vector payload)>; -class ISomeIpController { - public: - virtual std::optional> Request( - const uint16_t service_id, const uint16_t method_id, - const std::vector payload) = 0; - virtual bool RequestNoResponse(const uint16_t service_id, - const uint16_t method_id, - const std::vector payload) = 0; - virtual simba::core::ErrorCode AddMethod(const uint16_t method_id, - SomeIPMethod callback) = 0; - virtual simba::core::ErrorCode AddEventValue( - const uint16_t event_id, const std::vector payload) = 0; - virtual simba::core::ErrorCode Init() = 0; - virtual simba::core::ErrorCode LoadServiceList(const std::string& path) = 0; -}; -} // namespace someip -} // namespace com -} // namespace simba - -#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_ISOMEIP_CONTROLLER_H_ diff --git a/communication-core/someip-controller/callbacks.h b/communication-core/someip-controller/callbacks.h new file mode 100644 index 00000000..6aafd82f --- /dev/null +++ b/communication-core/someip-controller/callbacks.h @@ -0,0 +1,52 @@ +/** + * @file callbacks.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_CALLBACKS_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_CALLBACKS_H_ +#include +#include +#include +#include +#include + +#include "communication-core/someip-database/code/endpoint.h" +#include "communication-core/someip-database/code/interface.h" +#include "communication-core/someip/message_code.h" +#include "communication-core/someip/message_type.h" + +namespace simba { +namespace com { +namespace someip { + +using ResultCallback = + std::function payload, + data::MessageCode code, const uint16_t transfer_id)>; + +using SendCallback = std::function payload, const objects::Endpoint& endpoint, + const objects::Interface& interface, data::MessageType type, + ResultCallback result)>; +using MethodCallback = std::function>( + const std::vector payload)>; + +using DropTransferCallback = std::function; + +using SubscribeCallback = std::function; +using FindServiceCallbackResult = + std::function; +using FindCallback = std::function; +} // namespace someip +} // namespace com +} // namespace simba + +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_CALLBACKS_H_ diff --git a/communication-core/someip-controller/controller.cc b/communication-core/someip-controller/controller.cc new file mode 100644 index 00000000..383ae84e --- /dev/null +++ b/communication-core/someip-controller/controller.cc @@ -0,0 +1,321 @@ +/** + * @file controller.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#include "communication-core/someip-controller/controller.h" + +#include "communication-core/sockets/ipc_socket.h" +#include "communication-core/sockets/udp_socket.h" +#include "communication-core/someip/factory/someip_header_factory.h" +#include "communication-core/someip/factory/someip_message_factory.h" +#include "core/common/error_code.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace com { +namespace someip { +void Controller::DropTransferCallback(const uint16_t transfer_id) noexcept { + std::unique_lock lk{transfer_mutex}; + std::remove_if( + this->transfer_list.begin(), this->transfer_list.end(), + [&transfer_id](const std::pair& obj) { + return obj.first == transfer_id; + }); +} + +void Controller::FindServiceCallback( + const objects::Endpoint& endpoint, + FindServiceCallbackResult res_callback) noexcept { + AppLogger::Info("[ SOMEIP CONTROLLER ]: Find Service start (" + + std::to_string(endpoint.GetServiceId()) + ")"); + auto obj = db->FindService(endpoint.GetServiceId()); + if (obj.has_value()) { + res_callback(obj.value()); + } +} + +uint16_t Controller::SendFrameCallback(const std::vector payload, + const objects::Endpoint endpoint, + const objects::Interface interface, + data::MessageType type, + ResultCallback result) noexcept { + if (type == data::MessageType::kRequest) { + const uint16_t trans_id = this->GetTransferID(); + auto header = header_factory->CreateRequest(endpoint.GetServiceId(), + endpoint.GetEndpointId()); + auto msg = + msg_factory->GetBuffor(header, this->service_id, trans_id, payload); + if (Transfer(std::move(interface), std::move(msg))) { + std::unique_lock lk{transfer_mutex}; + this->transfer_list.push_back({trans_id, std::move(result)}); + return trans_id; + } + } else if (type == data::MessageType::kNotification) { + this->event_queue.push({std::move(endpoint), std::move(payload)}); + } + return 0; +} +void Controller::SendEvent(const objects::Endpoint endpoint, + const uint16_t client, std::vector data) { + auto interface = db->FindService(client); + if (interface.has_value()) { + auto header = + header_factory->CreatEvent(this->service_id, endpoint.GetEndpointId()); + auto msg = msg_factory->GetBuffor(std::move(header), client, 0, data); + this->Transfer(interface.value(), std::move(msg)); + } else { + AppLogger::Error("[ SOMEIP CONTROLLER ]: Can't find service " + + std::to_string(client)); + } +} +void Controller::SendEventLoop(const objects::Endpoint endpoint, + std::vector data) { + const auto r_list = db->FindEventClient(endpoint.GetEndpointId()); + if (r_list.has_value()) { + const auto list = r_list.value(); + for (const auto& item : list) { + this->SendEvent(endpoint, item, data); + } + } +} +void Controller::SubscribeCallback(const objects::Endpoint endpoint, + const objects::Interface interface, + ResultCallback result) noexcept { + const uint32_t id = (static_cast(endpoint.GetServiceId()) << 16) + + static_cast(endpoint.GetEndpointId()); + this->event_callback.insert({id, std::move(result)}); + AppLogger::Info("Subscribed to " + std::to_string(endpoint.GetServiceId()) + + ":" + std::to_string(endpoint.GetEndpointId())); +} + +void Controller::RXCallback(const std::string& ip, const std::uint16_t& port, + std::vector data) noexcept { + const auto header = msg_factory->GetHeader(data); + if (header->GetServiceID() == this->service_id) { + if (header->GetMessageType() == data::MessageType::kRequest) { + auto payload = msg_factory->GetPayload(data); + this->onRequest(std::move(header), std::move(payload)); + return; + } + + } else if (header->GetMessageType() == data::MessageType::kResponse && + header->GetClientID() == this->service_id) { + const auto payload = msg_factory->GetPayload(data); + this->onResult(std::move(header), std::move(payload)); + return; + } else if (header->GetMessageType() == data::MessageType::kNotification && + header->GetClientID() == this->service_id) { + const auto payload = msg_factory->GetPayload(data); + this->onEvent(std::move(header), std::move(payload)); + return; + } else if (header->GetMessageType() == data::MessageType::kRequest) { + AppLogger::Error("[ SOMEIP CONTROLLER ]: Wrong service ID"); + } +} +void Controller::onRequest(std::shared_ptr header, + const std::vector payload) { + const uint16_t s_id = + (header->GetServiceID() == service_id) ? 0 : header->GetServiceID(); + const uint32_t id = (static_cast(s_id) << 16) + + static_cast(header->GetMethodID()); + const auto func = this->callback.find(id); + if (func == this->callback.end()) { + AppLogger::Error("[ SOMEIP CONTROLLER ]: Method not found!"); + } else { + AppLogger::Info("[ SOMEIP CONTROLLER ]: Callback found!"); + auto data = func->second(std::move(payload)); + if (data.has_value()) { + auto res_header = this->header_factory->CreateResponse( + header->GetServiceID(), header->GetMethodID(), + data::MessageCode::kEOk); + auto msg = msg_factory->GetBuffor(res_header, header->GetClientID(), + header->GetSessionID(), data.value()); + auto interf = db->FindService(header->GetClientID()); + if (interf.has_value()) { + Transfer(interf.value(), msg); + } else { + AppLogger::Error("[ SOMEIP CONTROLLER ]: can't find service: " + + std::to_string(header->GetClientID())); + } + } else { + } + } +} + +void Controller::onResult(std::shared_ptr header, + const std::vector payload) { + const auto trans_id = header->GetSessionID(); + ResultCallback callback; + bool exist{false}; + { + std::unique_lock lk{transfer_mutex}; + auto cal = std::find_if( + this->transfer_list.begin(), this->transfer_list.end(), + [&trans_id](const std::pair& obj) { + return obj.first == trans_id; + }); + if (cal != this->transfer_list.end()) { + callback = (cal->second); + exist = true; + } + } + if (exist) { + callback(std::move(payload), + static_cast(header->GetReturnCode()), trans_id); + std::unique_lock lk{transfer_mutex}; + std::remove_if(this->transfer_list.begin(), this->transfer_list.end(), + [&trans_id](const std::pair& obj) { + return obj.first == trans_id; + }); + } +} + +void Controller::onEvent(std::shared_ptr header, + const std::vector payload) { + const uint32_t id = (static_cast(header->GetServiceID()) << 16) + + static_cast(header->GetMethodID()); + const auto func = this->event_callback.find(id); + if (func == this->event_callback.end()) { + AppLogger::Error("[ SOMEIP CONTROLLER ]: Event not subscribed!"); + return; + } + + func->second(std::move(payload), + static_cast(header->GetReturnCode()), 0); +} + +Controller::Controller(std::shared_ptr db_) + : db{std::move(db_)}, service_id{db->GetServiceId()} { + const auto interfaces = db->GetInterfaces(); + for (const auto& inter : interfaces) { + AppLogger::Info("[ SOMEIP CONTROLLER ]: Interface added - " + + inter.GetIp() + ":" + std::to_string(inter.GetPort())); + if (inter.GetPort() == 0) { + ipc_soc_ = std::make_unique(); + ipc_soc_->Init(soc::SocketConfig{inter.GetIp(), inter.GetPort(), 0}); + ipc_soc_->SetRXCallback( + std::bind(&Controller::RXCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + ipc_soc_->StartRXThread(); + AppLogger::Info("[ SOMEIP CONTROLLER ]: IPC soc started"); + } else { + udp_soc_ = std::make_unique(); + udp_soc_->Init(soc::SocketConfig{inter.GetIp(), inter.GetPort(), 0}); + udp_soc_->SetRXCallback( + std::bind(&Controller::RXCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + udp_soc_->StartRXThread(); + AppLogger::Info("[ SOMEIP CONTROLLER ]: UDP soc started on port: " + + std::to_string(inter.GetPort())); + } + + header_factory = std::make_unique(); + msg_factory = std::make_unique(); + } +} + +bool Controller::Transfer(const objects::Interface interface, + const std::vector& payload) { + if (interface.GetPort() == 0) { + return this->SendIpcMsg(std::move(interface), std::move(payload)); + } else { + return this->SendUdpMsg(std::move(interface), std::move(payload)); + } +} + +bool Controller::SendIpcMsg(const objects::Interface interface, + const std::vector& payload) { + if (this->ipc_soc_) { + std::unique_lock lk{ipc_soc_mutex}; + return ipc_soc_->Transmit(interface.GetIp(), 0, std::move(payload)) == + simba::core::ErrorCode::kOk; + } + return false; +} +bool Controller::SendUdpMsg(const objects::Interface interface, + const std::vector& payload) { + if (this->udp_soc_) { + std::unique_lock lk{udp_soc_mutex}; + return udp_soc_->Transmit(interface.GetIp(), interface.GetPort(), + std::move(payload)) == + simba::core::ErrorCode::kOk; + } + return false; +} +void Controller::SendAck(const uint16_t client_id, const uint16_t endpoint_id, + const uint16_t trans_id) { + auto header = + this->header_factory->CreateRequestACK(this->service_id, endpoint_id); + + auto msg = this->msg_factory->GetBuffor(header, client_id, trans_id, {}); + auto interf = db->FindService(client_id); + if (interf.has_value()) { + Transfer(interf.value(), msg); + } else { + AppLogger::Error("[ SOMEIP CONTROLLER ]: can't find service: " + + std::to_string(client_id)); + } +} +uint16_t Controller::GetTransferID() { + ++this->transfer_id; + if (transfer_id == 0) { + ++transfer_id; + } + return transfer_id; +} + +void Controller::Add(std::shared_ptr skeleton) { + auto endpoint = skeleton->GetEndPoint(); + if (endpoint.has_value()) { + if (endpoint.value().GetEndpointId() < 0x8000) { + uint32_t id = + (static_cast(endpoint.value().GetServiceId()) << 16) + + endpoint.value().GetEndpointId(); + + this->callback.insert({id, std::bind(&ISkeleton::Call, skeleton.get(), + std::placeholders::_1)}); + AppLogger::Info("[ SOMEIP CONTROLLER ]: Method skeleton added (" + + skeleton->GetName() + ")"); + } else { + if (!this->event_thread) { + this->event_thread = + std::make_unique([this]() { this->ThreadLoop(); }); + } + skeleton->SetCallback( + std::bind(&Controller::SendFrameCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3, + std::placeholders::_4, std::placeholders::_5)); + AppLogger::Info("[ SOMEIP CONTROLLER ]: Event skeleton added (" + + skeleton->GetName() + ")"); + } + } +} +void Controller::ThreadLoop() { + while (true) { + auto event = this->event_queue.Get(); + this->SendEventLoop(std::move(event.first), std::move(event.second)); + } +} +void Controller::Add(std::shared_ptr proxy) { + AppLogger::Info("[ SOMEIP CONTROLLER ]: Proxy added (" + proxy->GetName() + + ")"); + proxy->SetSendCallback( + std::bind(&Controller::SendFrameCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3, + std::placeholders::_4, std::placeholders::_5), + std::bind(&Controller::FindServiceCallback, this, std::placeholders::_1, + std::placeholders::_2), + std::bind(&Controller::DropTransferCallback, this, std::placeholders::_1), + std::bind(&Controller::SubscribeCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); +} + +} // namespace someip +} // namespace com +} // namespace simba diff --git a/communication-core/someip-controller/controller.h b/communication-core/someip-controller/controller.h new file mode 100644 index 00000000..c4589255 --- /dev/null +++ b/communication-core/someip-controller/controller.h @@ -0,0 +1,100 @@ +/** + * @file controller.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_CONTROLLER_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_CONTROLLER_H_ + +#include +#include // NOLINT +#include +#include // NOLINT +#include +#include +#include + +#include "communication-core/sockets/Isocket.h" +#include "communication-core/someip-controller/callbacks.h" +#include "communication-core/someip-controller/iproxy.h" +#include "communication-core/someip-controller/iskeleton.h" +#include "communication-core/someip-database/code/database.h" +#include "communication-core/someip/factory/Isomeip_header_factory.h" +#include "communication-core/someip/factory/Isomeip_message_factory.h" +#include "core/common/wait_queue.h" +namespace simba { +namespace com { +namespace someip { +class Controller { + protected: + std::unordered_map callback{}; + std::unordered_map event_callback{}; + std::shared_ptr db; + std::unique_ptr udp_soc_; + std::mutex udp_soc_mutex{}; + std::unique_ptr ipc_soc_; + std::mutex ipc_soc_mutex{}; + std::unique_ptr header_factory; + std::unique_ptr msg_factory; + std::mutex transfer_mutex{}; + std::vector> transfer_list{}; + simba::core::WaitQueue< + std::pair>> + event_queue{}; + std::unique_ptr event_thread; + const uint16_t service_id; + uint16_t transfer_id{0}; + void FindServiceCallback(const objects::Endpoint& endpoint, + FindServiceCallbackResult res_callback) noexcept; + + uint16_t SendFrameCallback(const std::vector payload, + const objects::Endpoint endpoint, + const objects::Interface interface, + data::MessageType type, + ResultCallback result) noexcept; + + void SubscribeCallback(const objects::Endpoint endpoint, + const objects::Interface interface, + ResultCallback result) noexcept; + void DropTransferCallback(const uint16_t transfer_id) noexcept; + + void RXCallback(const std::string& ip, const std::uint16_t& port, + std::vector data) noexcept; + bool SendIpcMsg(const objects::Interface interface, + const std::vector& payload); + bool SendUdpMsg(const objects::Interface interface, + const std::vector& payload); + bool Transfer(const objects::Interface interface, + const std::vector& payload); + uint16_t GetTransferID(); + void SendAck(const uint16_t client_id, const uint16_t endpoint_id, + const uint16_t trans_id); + void onRequest(std::shared_ptr header, + const std::vector payload); + void onResult(std::shared_ptr header, + const std::vector payload); + void onEvent(std::shared_ptr header, + const std::vector payload); + void SendEventLoop(const objects::Endpoint endpoint, + std::vector data); + void SendEvent(const objects::Endpoint endpoint, const uint16_t client, + std::vector data); + void ThreadLoop(); + + public: + void Add(std::shared_ptr proxy); + void Add(std::shared_ptr skeleton); + explicit Controller(std::shared_ptr db_); + ~Controller() = default; +}; + +} // namespace someip +} // namespace com +} // namespace simba + +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_CONTROLLER_H_ diff --git a/communication-core/someip-controller/event_proxy.h b/communication-core/someip-controller/event_proxy.h new file mode 100644 index 00000000..8ba9732e --- /dev/null +++ b/communication-core/someip-controller/event_proxy.h @@ -0,0 +1,143 @@ +/** + * @file event_proxy.h + * @author your name (you@domain.com) + * @brief + * @version 0.1 + * @date 2024-03-23 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_EVENT_PROXY_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_EVENT_PROXY_H_ + +#include // NOLINT +#include // NOLINT +#include +#include +#include +#include + +#include "communication-core/someip-controller/iproxy.h" +#include "communication-core/someip-database/code/com_config.h" +#include "communication-core/someip-database/code/endpoint.h" +#include "communication-core/someip-database/code/interface.h" +#include "communication-core/someip/message_code.h" +#include "communication-core/someip/message_type.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace com { +namespace someip { + +using EventCallback = std::function payload)>; + +class EventProxyBase : public IProxy { + private: + const std::string instance; + const std::optional object; + std::optional interface; + std::mutex msg_mutex{}; + std::condition_variable request_cv{}; + bool is_callback{false}; + bool is_response{false}; + std::vector response; + data::MessageCode response_code; + FindCallback f_callback_; + SubscribeCallback s_callback; + EventCallback callback_; + const bool is_event_callback; + void RxCallback(const std::vector payload, + simba::com::data::MessageCode code, const uint16_t) { + if (code == data::MessageCode::kEOk) { + if (is_event_callback) { + callback_(std::move(payload)); + return; + } else { + response = std::move(payload); + is_response = true; + request_cv.notify_all(); + } + } else { + AppLogger::Error("[ SOMEIP PROXY ]: Received frame with wrong data type"); + } + } + void FindServiceCallback(const objects::Interface& interface) { + AppLogger::Info("[ SOMEIP PROXY ]: Service fonded (" + instance + ") - " + + interface.GetIp() + ":" + + std::to_string(interface.GetPort())); + this->interface = std::move(interface); + this->s_callback( + object.value(), this->interface.value(), + std::bind(&EventProxyBase::RxCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + } + + public: + explicit EventProxyBase(const std::string& instance_) + : instance{instance_}, + object{std::move(com::config::ComConfig::FindObject(instance))}, + is_event_callback{false} { + if (!object.has_value()) { + AppLogger::Error("[ SOMEIP PROXY ]: Can't find object for: " + instance); + } else { + AppLogger::Info("[ SOMEIP PROXY ]: " + instance + " mapped to " + + std::to_string(object.value().GetServiceId()) + "/" + + std::to_string(object.value().GetEndpointId())); + } + } + EventProxyBase(const std::string& instance_, EventCallback callback) + : instance{instance_}, + object{std::move(com::config::ComConfig::FindObject(instance))}, + callback_{callback}, + is_event_callback{true} { + if (!object.has_value()) { + AppLogger::Error("[ SOMEIP PROXY ]: Can't find object for: " + instance); + } else { + AppLogger::Info("[ SOMEIP PROXY ]: " + instance + " mapped to " + + std::to_string(object.value().GetServiceId()) + "/" + + std::to_string(object.value().GetEndpointId())); + } + } + std::optional GetEndPoint() const noexcept override { + return this->object; + } + + std::optional> Get() noexcept { + if (is_response) { + is_response = false; + return response; + } else { + std::unique_lock lk(msg_mutex); + if (request_cv.wait_for(lk, std::chrono::seconds{1}) == + std::cv_status::timeout) { + AppLogger::Error("[ SOMEIP PROXY ](" + instance + "): Timeout !"); + return {}; + } + is_response = false; + return response; + } + } + + void SetSendCallback(SendCallback, FindCallback f_callback, + DropTransferCallback, SubscribeCallback sub_callback) { + f_callback_ = f_callback; + is_callback = true; + s_callback = sub_callback; + } + void StartFindService() { + if (is_callback && object.has_value()) { + f_callback_(object.value(), + std::bind(&EventProxyBase::FindServiceCallback, this, + std::placeholders::_1)); + } + } + std::string GetName() const { return instance; } + + ~EventProxyBase() = default; +}; +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_EVENT_PROXY_H_ diff --git a/communication-core/someip-controller/event_skeleton.h b/communication-core/someip-controller/event_skeleton.h new file mode 100644 index 00000000..24f8d2f9 --- /dev/null +++ b/communication-core/someip-controller/event_skeleton.h @@ -0,0 +1,103 @@ +/** + * @file event_skeleton.h + * @author Bartosz Snieg (snieg45@gmial.com) + * @brief + * @version 0.1 + * @date 2024-03-23 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_EVENT_SKELETON_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_EVENT_SKELETON_H_ + +#include +#include // NOLINT +#include +#include // NOLINT +#include +#include +#include // NOLINT +#include +#include + +#include "communication-core/someip-controller/callbacks.h" +#include "communication-core/someip-controller/iskeleton.h" +#include "communication-core/someip-database/code/com_config.h" +#include "communication-core/someip-database/code/endpoint.h" +#include "communication-core/someip-database/code/interface.h" +#include "communication-core/someip/message_code.h" +#include "communication-core/someip/message_type.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace com { +namespace someip { +class EventSkeleton : public ISkeleton { + private: + const std::optional object; + const std::string instance_; + SendCallback callback_; + std::vector value{}; + std::mutex value_mutex{}; + + std::mutex loop_mutex{}; + std::condition_variable loop_cv{}; + std::unique_ptr thread; + + public: + std::optional GetEndPoint() const noexcept override { + return object; + } + std::optional> Call( + std::vector payload) noexcept override { + return {}; + } + std::string GetName() const override { return instance_; } + + explicit EventSkeleton(const std::string instance) + : object{std::move(com::config::ComConfig::FindObject(instance))}, + instance_{std::move(instance)} { + if (!object.has_value()) { + AppLogger::Error("[ SOMEIP SKELETON ]: Can't find object for: " + + instance); + } else { + AppLogger::Info("[ SOMEIP SKELETON ]: " + instance_ + " mapped to " + + std::to_string(object.value().GetServiceId()) + "/" + + std::to_string(object.value().GetEndpointId())); + } + } + void Loop(std::stop_token token) { + while (!token.stop_requested()) { + std::unique_lock lk{loop_mutex}; + loop_cv.wait_for(lk, std::chrono::seconds{1}); + { + std::unique_lock lkv{value_mutex}; + if (value.size() > 0) { + callback_(this->value, object.value(), objects::Interface{"", 0}, + data::MessageType::kNotification, nullptr); + } + } + } + } + void SetValue(const std::vector& data) { + { + std::unique_lock lk{value_mutex}; + value = std::move(data); + } + loop_cv.notify_all(); + } + void SetCallback(SendCallback callback) { + callback_ = callback; + this->thread = std::make_unique( + std::bind(&EventSkeleton::Loop, this, std::placeholders::_1)); + } + ~EventSkeleton() { + thread->request_stop(); + loop_cv.notify_all(); + } +}; +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_EVENT_SKELETON_H_ diff --git a/communication-core/someip-controller/iproxy.h b/communication-core/someip-controller/iproxy.h new file mode 100644 index 00000000..e7a52fd6 --- /dev/null +++ b/communication-core/someip-controller/iproxy.h @@ -0,0 +1,38 @@ +/** + * @file iproxy.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_IPROXY_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_IPROXY_H_ + +#include +#include +#include +#include + +#include "communication-core/someip-controller/callbacks.h" +#include "communication-core/someip-database/code/endpoint.h" +#include "communication-core/someip-database/code/interface.h" + +namespace simba { +namespace com { +namespace someip { +class IProxy { + public: + virtual void SetSendCallback(SendCallback callback, FindCallback f_callback, + DropTransferCallback d_callback, + SubscribeCallback s_callback) = 0; + virtual std::string GetName() const = 0; + virtual std::optional GetEndPoint() const noexcept = 0; + virtual ~IProxy() = default; +}; +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_IPROXY_H_ diff --git a/communication-core/someip-controller/iskeleton.h b/communication-core/someip-controller/iskeleton.h new file mode 100644 index 00000000..f4dbe43e --- /dev/null +++ b/communication-core/someip-controller/iskeleton.h @@ -0,0 +1,35 @@ +/** + * @file iskeleton.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_ISKELETON_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_ISKELETON_H_ +#include +#include +#include +#include + +#include "communication-core/someip-controller/callbacks.h" +#include "communication-core/someip-database/code/endpoint.h" +namespace simba { +namespace com { +namespace someip { +class ISkeleton { + public: + virtual void SetCallback(SendCallback callback) {} + virtual std::optional GetEndPoint() const noexcept = 0; + virtual std::optional> Call( + std::vector) noexcept = 0; + virtual std::string GetName() const = 0; + virtual ~ISkeleton() = default; +}; +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_ISKELETON_H_ diff --git a/communication-core/someip-controller/method_proxy.h b/communication-core/someip-controller/method_proxy.h new file mode 100644 index 00000000..bcfe75f9 --- /dev/null +++ b/communication-core/someip-controller/method_proxy.h @@ -0,0 +1,142 @@ +/** + * @file method_proxy.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_PROXY_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_PROXY_H_ + +#include // NOLINT +#include // NOLINT +#include +#include +#include +#include + +#include "communication-core/someip-controller/iproxy.h" +#include "communication-core/someip-database/code/com_config.h" +#include "communication-core/someip-database/code/endpoint.h" +#include "communication-core/someip-database/code/interface.h" +#include "communication-core/someip/message_code.h" +#include "communication-core/someip/message_type.h" +#include "core/logger/Logger.h" +namespace simba { +namespace com { +namespace someip { +class MethodProxyBase : public IProxy { + private: + const std::string instance; + const std::optional object; + std::optional interface; + std::mutex msg_mutex{}; + std::condition_variable request_cv{}; + bool is_callback{false}; + bool is_response{false}; + std::vector response; + data::MessageCode response_code; + uint16_t transfer_id_; + SendCallback callback_; + FindCallback f_callback_; + DropTransferCallback d_callback_; + + void RxCallback(const std::vector payload, + simba::com::data::MessageCode code, + const uint16_t transfer_id) { + if (transfer_id == transfer_id_) { + is_response = true; + response_code == code; + response = payload; + request_cv.notify_all(); + } + } + + void FindServiceCallback(const objects::Interface& interface) { + AppLogger::Info("[ SOMEIP PROXY ]: Service fonded (" + instance + ") - " + + interface.GetIp() + ":" + + std::to_string(interface.GetPort())); + this->interface = interface; + } + + public: + explicit MethodProxyBase(const std::string& instance_) + : instance{instance_}, + object{std::move(com::config::ComConfig::FindObject(instance))} { + if (!object.has_value()) { + AppLogger::Error("[ SOMEIP PROXY ]: Can't find object for: " + instance); + } else { + AppLogger::Info("[ SOMEIP PROXY ]: " + instance + " mapped to " + + std::to_string(object.value().GetServiceId()) + "/" + + std::to_string(object.value().GetEndpointId())); + } + } + + std::optional GetEndPoint() const noexcept override { + return this->object; + } + + std::optional> Get(std::vector data) noexcept { + if (!is_callback) { + AppLogger::Error("[ SOMEIP PROXY ]: No send callback"); + return {}; + } + is_response = false; + if (!object.has_value()) { + AppLogger::Error("[ SOMEIP PROXY ]: No object"); + return {}; + } + if (!interface.has_value()) { + AppLogger::Error("[ SOMEIP PROXY ]: No interface"); + return {}; + } + std::unique_lock lk(msg_mutex); + transfer_id_ = callback_( + std::move(data), object.value(), interface.value(), + simba::com::data::MessageType::kRequest, + std::bind(&MethodProxyBase::RxCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + if (transfer_id_ == 0) { + AppLogger::Error("[ SOMEIP PROXY ]: Sending error"); + return {}; + } + if (request_cv.wait_for(lk, std::chrono::seconds{1}) == + std::cv_status::timeout) { + AppLogger::Error("[ SOMEIP PROXY ](" + instance + "): Timeout !"); + d_callback_(transfer_id_); + return {}; + } + if (response_code == data::MessageCode::kEOk) { + return std::move(this->response); + } else { + return {}; + } + } + + std::optional> Get() noexcept { return Get({}); } + + void SetSendCallback(SendCallback callback, FindCallback f_callback, + DropTransferCallback d_callback, SubscribeCallback) { + callback_ = callback; + f_callback_ = f_callback; + d_callback_ = d_callback; + is_callback = true; + } + void StartFindService() { + if (is_callback && object.has_value()) { + f_callback_(object.value(), + std::bind(&MethodProxyBase::FindServiceCallback, this, + std::placeholders::_1)); + } + } + std::string GetName() const { return instance; } + + ~MethodProxyBase() = default; +}; +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_PROXY_H_ diff --git a/communication-core/someip-controller/method_skeleton.h b/communication-core/someip-controller/method_skeleton.h new file mode 100644 index 00000000..d9d98bf8 --- /dev/null +++ b/communication-core/someip-controller/method_skeleton.h @@ -0,0 +1,67 @@ +/** + * @file method_skeleton.h + * @author Bartosz Snieg (snieg45@gmial.com) + * @brief + * @version 0.1 + * @date 2024-03-23 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_SKELETON_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_SKELETON_H_ + +#include // NOLINT +#include // NOLINT +#include +#include +#include +#include + +#include "communication-core/someip-controller/callbacks.h" +#include "communication-core/someip-controller/iskeleton.h" +#include "communication-core/someip-database/code/com_config.h" +#include "communication-core/someip-database/code/endpoint.h" +#include "communication-core/someip-database/code/interface.h" +#include "communication-core/someip/message_code.h" +#include "communication-core/someip/message_type.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace com { +namespace someip { +class MethodSkeleton : public ISkeleton { + private: + const std::optional object; + MethodCallback callback_; + const std::string instance_; + + public: + std::optional GetEndPoint() const noexcept override { + return object; + } + std::optional> Call( + std::vector payload) noexcept override { + return callback_(std::move(payload)); + } + std::string GetName() const override { return instance_; } + + MethodSkeleton(const std::string instance, MethodCallback callback) + : object{std::move(com::config::ComConfig::FindObject(instance))}, + callback_{callback}, + instance_{std::move(instance)} { + if (!object.has_value()) { + AppLogger::Error("[ SOMEIP SKELETON ]: Can't find object for: " + + instance); + } else { + AppLogger::Info("[ SOMEIP SKELETON ]: " + instance_ + " mapped to " + + std::to_string(object.value().GetServiceId()) + "/" + + std::to_string(object.value().GetEndpointId())); + } + } + ~MethodSkeleton() = default; +}; +} // namespace someip +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_SKELETON_H_ diff --git a/communication-core/someip-controller/someip_controller.cc b/communication-core/someip-controller/someip_controller.cc deleted file mode 100644 index 3172da9f..00000000 --- a/communication-core/someip-controller/someip_controller.cc +++ /dev/null @@ -1,222 +0,0 @@ -/** - * @file someip_controller.cc - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-11-15 - * - * @copyright Copyright (c) 2023 - * - */ -#include "communication-core/someip-controller/someip_controller.h" - -#include - -// #include "communication-core/json-parser/database_json_parser.h" -#include "communication-core/someip/message_code.h" -#include "communication-core/someip/message_type.h" -#include "communication-core/someip/someip_header.h" -namespace simba { -namespace com { -namespace someip { -std::optional> SomeIpController::Request( - const uint16_t service_id, const uint16_t method_id, - const std::vector payload) { - const auto service_data = db_.GetService(service_id); - if (!service_data.has_value()) { - AppLogger::Error("[SOMEIPCONTROLLER] Service_id: " + - std::to_string(service_id) + " not found!"); - return {}; - } else { - AppLogger::Error( - "[SOMEIPCONTROLLER] Service_id: " + std::to_string(service_id) + - " ip = " + service_data.value().GetIp()); - } - const auto transfer = GetTransferID(); - auto req = header_factory.CreateRequest(service_id, method_id); - auto req_payload = msg_factory.GetBuffor(req, service_id_, transfer, payload); - auto trans = this->AddTransfer(transfer); - AppLogger::Debug("Sending to: " + std::to_string(req->GetServiceID()) + - " From " + std::to_string(req->GetClientID())); - if (this->socket_->Transmit(service_data.value().GetIp(), - service_data.value().GetPort(), - req_payload) != simba::core::ErrorCode::kOk) { - std::remove_if( - this->transfers.begin(), transfers.end(), - [trans](std::shared_ptr tr) { - return tr->GetTransferID() == trans->GetTransferID(); - }); - AppLogger::Error( - "[SOMEIPCONTROLLER] Request to :" + std::to_string(service_id) + - " method_id: " + std::to_string(method_id) + " No connection"); - return {}; - } - const auto res = trans->GetPayloadAsc(); - auto vec = trans->GetPayload(); - std::remove_if( - this->transfers.begin(), transfers.end(), - [trans](std::shared_ptr tr) { - return tr->GetTransferID() == trans->GetTransferID(); - }); - if (res.has_value()) { - return std::optional>{vec}; - } else { - AppLogger::Error( - "[SOMEIPCONTROLLER] Request to :" + std::to_string(service_id) + " : " + - std::to_string(method_id) + " Timeout"); - return {}; - } -} - -bool SomeIpController::RequestNoResponse(const uint16_t service_id, - const uint16_t method_id, - const std::vector payload) { - const auto service_data = db_.GetService(service_id); - if (!service_data.has_value()) { - AppLogger::Error("[SOMEIPCONTROLLER] Service_id: " + - std::to_string(service_id) + " not found!"); - return false; - } - const auto transfer = GetTransferID(); - auto req = header_factory.CreateRequestNoReturn(service_id, method_id); - auto req_payload = - msg_factory.GetBuffor(req, this->service_id_, transfer, payload); - auto trans = this->AddTransfer(transfer); - - this->socket_->Transmit(service_data.value().GetIp(), - service_data.value().GetPort(), req_payload); - const auto res = trans->GetACK(); - if (res.has_value()) { - return res.value(); - } else { - AppLogger::Error( - "[SOMEIPCONTROLLER] Request to :" + std::to_string(service_id) + " : " + - std::to_string(method_id) + " Timeout"); - } -} - -simba::core::ErrorCode SomeIpController::AddMethod(const uint16_t method_id, - SomeIPMethod callback) { - this->methods.insert({method_id, callback}); - return simba::core::ErrorCode::kOk; -} - -simba::core::ErrorCode SomeIpController::AddEventValue( - const uint16_t event_id, const std::vector payload) { - return simba::core::ErrorCode::kNotDefine; -} - -simba::core::ErrorCode SomeIpController::Init() { - AppLogger::Info("[SOMEIPCONTROLLER] Socket starting"); - /// TODO: Do this better with config or config - if (this->socket_->Init(this->config_) == simba::core::ErrorCode::kOk) { - this->socket_->StartRXThread(); - AppLogger::Info("[SOMEIPCONTROLLER] Socket started RX Thhread"); - } - return simba::core::ErrorCode::kOk; -} - -void SomeIpController::RxCallback(const std::string& ip, - const std::uint16_t& port, - std::vector payload) { - const auto header = msg_factory.GetHeader(payload); - AppLogger::Debug("[SOMEIPCONTROLLER] New data for: " + - std::to_string(header->GetServiceID()) + - " from: " + std::to_string(header->GetClientID()) + - " transfer: " + std::to_string(header->GetSessionID())); - AppLogger::Info("[SOMEIPCONTROLLER] New Data"); - if (header->GetClientID() == this->service_id_) { - this->Response(header, msg_factory.GetPayload(payload)); - } else if (header->GetServiceID() == this->service_id_) { - this->MethodCalled(header, msg_factory.GetPayload(payload)); - } else { - // TODO(any) : Implementacja Error nie ten serwis - } -} - -SomeIpController::SomeIpController(const uint16_t service_id, - std::unique_ptr socket, - const soc::SocketConfig& config) - : socket_{std::move(socket)}, service_id_{service_id}, config_{config} { - socket_->SetRXCallback([this](const std::string& ip, - const std::uint16_t& port, - std::vector payload) { - this->RxCallback(ip, port, payload); - }); -} - -simba::core::ErrorCode SomeIpController::LoadServiceList( - const std::string& path) { - // database::json::DatabaseJsonParser::LoadJson(this->db_, path); - AppLogger::Info("[SOMEIPCONTROLLER] loaded config file with services"); - return simba::core::ErrorCode::kOk; -} - -void SomeIpController::MethodCalled( - const std::shared_ptr header, - std::vector data) { - AppLogger::Debug("[SOMEIPCONTROLLER] Call method"); - const auto obj = this->methods.find(header->GetMethodID()); - if (obj == this->methods.end()) { - AppLogger::Error("[SOMEIPCONTROLLER] Method Not found method_id: " + - std::to_string(header->GetMethodID())); - // TODO(any) : implemnet error method uknown - return; - } - - const auto res = obj->second(data); - - if (!res.has_value()) { - AppLogger::Info("[SOMEIPCONTROLLER] Socket Send Respons No Value"); - // TODO(any) : implemnet error kNOK - } - - if (res.value().second != com::core::data::MessageCode::kEOk) { - AppLogger::Info("[SOMEIPCONTROLLER] Socket Send Respons No OK"); - // TODO(any) : implemnet error - } else { - if (header->GetMessageType() == com::core::data::MessageType::kRequest) { - header->SetMessageType(core::data::MessageType::kResponse); - header->SetReturnCode(core::data::MessageCode::kEOk); - this->SendResponse(header, res.value().first); - AppLogger::Info("[SOMEIPCONTROLLER] Socket Send Respons"); - } - } -} -void SomeIpController::Response( - const std::shared_ptr header, - std::vector data) { - auto obj = std::find_if( - this->transfers.begin(), this->transfers.end(), - [header](std::shared_ptr tr) { - return tr->GetTransferID() == header->GetSessionID(); - }); - if (obj == this->transfers.end()) { - return; - } - AppLogger::Info("Response data size: " + std::to_string(data.size())); - obj->get()->SetResponse(data); - AppLogger::Info("Response done!"); -} -void SomeIpController::UknowReqeust( - const std::shared_ptr header, - std::vector data) {} -void SomeIpController::SendResponse( - const std::shared_ptr header, - std::vector data) { - const auto service_id = header->GetClientID(); - const auto service_data = db_.GetService(service_id); - if (!service_data.has_value()) { - AppLogger::Error("[SOMEIPCONTROLLER] (" + std::string(__func__) + - ") Service_id: " + std::to_string(service_id) + - " not found!"); - } - - this->socket_->Transmit(service_data.value().GetIp(), - service_data.value().GetPort(), - msg_factory.GetBuffor(header, header->GetClientID(), - header->GetSessionID(), data)); -} -} // namespace someip -} // namespace com -} // namespace simba diff --git a/communication-core/someip-controller/someip_controller.h b/communication-core/someip-controller/someip_controller.h deleted file mode 100644 index 9f4ee4b8..00000000 --- a/communication-core/someip-controller/someip_controller.h +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @file someip_controller.h - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2023-11-15 - * - * @copyright Copyright (c) 2023 - * - */ -#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_SOMEIP_CONTROLLER_H_ -#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_SOMEIP_CONTROLLER_H_ -#include -#include // NOLINT -#include // NOLINT -#include -#include -#include -#include // NOLINT -#include -#include -#include -#include - -#include "communication-core/database/database.h" -#include "communication-core/sockets/Isocket.h" -#include "communication-core/sockets/socket_config.h" -#include "communication-core/someip-controller/Isomeip_controller.h" -#include "communication-core/someip-controller/transfer.h" -#include "communication-core/someip/factory/someip_header_factory.h" -#include "communication-core/someip/factory/someip_message_factory.h" -#include "core/common/error_code.h" -#include "core/logger/Logger.h" -#include "memory" - -namespace simba { -namespace com { -namespace someip { -class SomeIpController : public ISomeIpController { - private: - void RxCallback(const std::string& ip, const std::uint16_t& port, - std::vector payload); - std::unique_ptr socket_; - std::shared_ptr logger_; - const std::uint16_t service_id_; - const soc::SocketConfig config_; - database::Database db_{}; - com::core::someip::factory::SomeIpHeaderFactory header_factory{}; - com::core::someip::factory::SomeIpMessageFactory msg_factory{}; - uint16_t transfer_id = 2; - - inline const uint16_t GetTransferID() { return transfer_id++; } - - std::vector> transfers{}; - std::unordered_map methods{}; - std::shared_ptr AddTransfer(const uint16_t transfer) { - auto res = std::make_shared(transfer); - this->transfers.push_back(res); - return res; - } - - void MethodCalled( - const std::shared_ptr header, - std::vector data); - void Response( - const std::shared_ptr header, - std::vector data); - void UknowReqeust( - const std::shared_ptr header, - std::vector data); - void SendResponse( - const std::shared_ptr header, - std::vector data); - - public: - std::optional> Request( - const uint16_t service_id, const uint16_t method_id, - const std::vector payload) override; - - bool RequestNoResponse(const uint16_t service_id, const uint16_t method_id, - const std::vector payload) override; - - simba::core::ErrorCode AddMethod(const uint16_t method_id, - SomeIPMethod callback) override; - - simba::core::ErrorCode AddEventValue( - const uint16_t event_id, const std::vector payload) override; - simba::core::ErrorCode Init() override; - simba::core::ErrorCode LoadServiceList(const std::string& path) override; - SomeIpController(const uint16_t service_id, - std::unique_ptr socket, - const soc::SocketConfig& config); -}; -} // namespace someip -} // namespace com -} // namespace simba - -#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_SOMEIP_CONTROLLER_H_ diff --git a/communication-core/someip-controller/transfer.h b/communication-core/someip-controller/transfer.h index caabc5e7..d7e1bb87 100644 --- a/communication-core/someip-controller/transfer.h +++ b/communication-core/someip-controller/transfer.h @@ -8,6 +8,7 @@ * @copyright Copyright (c) 2023 * */ + #ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_TRANSFER_H_ #define COMMUNICATION_CORE_SOMEIP_CONTROLLER_TRANSFER_H_ #include diff --git a/communication-core/someip-database/code/BUILD b/communication-core/someip-database/code/BUILD index 91286b43..20b6f224 100644 --- a/communication-core/someip-database/code/BUILD +++ b/communication-core/someip-database/code/BUILD @@ -51,3 +51,16 @@ cc_library( "@com_json//:json", ], ) + +cc_library( + name = "app_config_object", + hdrs = ["com_config.h"], + srcs = ["com_config.cc"], + visibility = ["//visibility:public"], + deps = [ + "//communication-core/someip-database/code:config_database_lib_p", + "//communication-core/someip-database/code:config_database_parser_lib", + "@com_json//:json", + "//core/logger:Logger", + ], +) diff --git a/communication-core/someip-database/code/com_config.cc b/communication-core/someip-database/code/com_config.cc new file mode 100644 index 00000000..cb0049b5 --- /dev/null +++ b/communication-core/someip-database/code/com_config.cc @@ -0,0 +1,45 @@ +/** + * @file com_config.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#include "communication-core/someip-database/code/com_config.h" + +#include + +#include "core/logger/Logger.h" + +namespace simba { +namespace com { +namespace config { + +std::shared_ptr ComConfig::config_db = nullptr; + +std::optional ComConfig::FindObject( + const std::string& key) { + if (config_db) { + return config_db->FindObject(key); + } + return {}; +} +void ComConfig::SetConfigDb(std::shared_ptr config) { + config_db = std::move(config); +} +void ComConfig::InitConfigDb(const std::string& path) { + std::ifstream f(path); + if (f.is_open()) { + AppLogger::Info("Config DB initialization"); + auto obj = std::make_shared(); + auto json_obj = nlohmann::json::parse(f); + someip::json::ConfigDbParser::ParseJsonObject(obj, json_obj); + ComConfig::SetConfigDb(obj); + } +} +} // namespace config +} // namespace com +} // namespace simba diff --git a/communication-core/someip-database/code/com_config.h b/communication-core/someip-database/code/com_config.h new file mode 100644 index 00000000..5485dbb2 --- /dev/null +++ b/communication-core/someip-database/code/com_config.h @@ -0,0 +1,39 @@ +/** + * @file com_config.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_COM_CONFIG_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_COM_CONFIG_H_ + +#include +#include +#include +#include + +#include "communication-core/someip-database/code/config_db.h" +#include "communication-core/someip-database/code/config_db_parser.h" + +namespace simba { +namespace com { +namespace config { +class ComConfig { + private: + static std::shared_ptr config_db; + + public: + ~ComConfig() = default; + static std::optional FindObject( + const std::string& key); + static void SetConfigDb(std::shared_ptr config); + static void InitConfigDb(const std::string& path); +}; +} // namespace config +} // namespace com +} // namespace simba +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_COM_CONFIG_H_ diff --git a/communication-core/someip-database/code/config_db.cc b/communication-core/someip-database/code/config_db.cc index 60f1fbcb..3737bb9d 100644 --- a/communication-core/someip-database/code/config_db.cc +++ b/communication-core/someip-database/code/config_db.cc @@ -13,7 +13,7 @@ namespace simba { namespace com { namespace someip { namespace objects { -core::ErrorCode ConfigDb::InsertObject(const std::string& key, +simba::core::ErrorCode ConfigDb::InsertObject(const std::string& key, const Endpoint& item) noexcept { if (this->item_list.find(key) != this->item_list.end()) { return core::ErrorCode::kError; diff --git a/communication-core/someip-database/code/config_db.h b/communication-core/someip-database/code/config_db.h index 8dc30dfd..c50b5e3b 100644 --- a/communication-core/someip-database/code/config_db.h +++ b/communication-core/someip-database/code/config_db.h @@ -30,7 +30,7 @@ class ConfigDb { public: - core::ErrorCode InsertObject(const std::string& key, + simba::core::ErrorCode InsertObject(const std::string& key, const Endpoint& item) noexcept; std::optional FindObject(const std::string& key) const noexcept; diff --git a/communication-core/someip-database/code/config_db_parser.h b/communication-core/someip-database/code/config_db_parser.h index 8834ef0d..d904059f 100644 --- a/communication-core/someip-database/code/config_db_parser.h +++ b/communication-core/someip-database/code/config_db_parser.h @@ -25,56 +25,67 @@ namespace json { class ConfigDbParser { public: - static core::ErrorCode ParseJsonObject(std::shared_ptr db, - const nlohmann::json& obj) noexcept { + static simba::core::ErrorCode ParseJsonObject( + std::shared_ptr db, + const nlohmann::json& obj) noexcept { auto res = ParseReqMethods(db, obj); - if (res == core::ErrorCode::kOk) { - res = ParseProvideMethods(db, obj); - } - if (res == core::ErrorCode::kOk) { - res = ParsePubEvent(db, obj); - } - if (res == core::ErrorCode::kOk) { - res = ParseReqEvent(db, obj); - } + res = ParseProvideMethods(db, obj); + res = ParsePubEvent(db, obj); + res = ParseReqEvent(db, obj); return res; } - static core::ErrorCode ParseProvideMethods( + private: + static simba::core::ErrorCode ParseProvideMethods( std::shared_ptr db, const nlohmann::json& obj) noexcept { + if (!obj.contains("pub_methods")) { + return simba::core::ErrorCode::kError; + } auto list = obj["pub_methods"]; for (auto& [key, val] : list.items()) { db->InsertObject(key, ParseObj(val)); } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; } - static core::ErrorCode ParseReqMethods(std::shared_ptr db, - const nlohmann::json& obj) noexcept { + static simba::core::ErrorCode ParseReqMethods( + std::shared_ptr db, + const nlohmann::json& obj) noexcept { + if (!obj.contains("req_methods")) { + return simba::core::ErrorCode::kError; + } auto list = obj["req_methods"]; for (auto& [key, val] : list.items()) { db->InsertObject(key, ParseObj(val)); } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; } - static core::ErrorCode ParseReqEvent(std::shared_ptr db, - const nlohmann::json& obj) noexcept { + static simba::core::ErrorCode ParseReqEvent( + std::shared_ptr db, + const nlohmann::json& obj) noexcept { + if (!obj.contains("req_events")) { + return simba::core::ErrorCode::kError; + } auto list = obj["req_events"]; for (auto& [key, val] : list.items()) { db->InsertObject(key, ParseObj(val)); } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; } - static core::ErrorCode ParsePubEvent(std::shared_ptr db, - const nlohmann::json& obj) noexcept { + static simba::core::ErrorCode ParsePubEvent( + std::shared_ptr db, + const nlohmann::json& obj) noexcept { + if (!obj.contains("pub_event")) { + return simba::core::ErrorCode::kError; + } auto list = obj["pub_event"]; for (auto& [key, val] : list.items()) { db->InsertObject(key, ParseObj(val)); } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; } static objects::Endpoint ParseObj(const nlohmann::json& obj) noexcept { uint16_t method_id = 0; diff --git a/communication-core/someip-database/code/database.cc b/communication-core/someip-database/code/database.cc index f5f5de2d..c2de1314 100644 --- a/communication-core/someip-database/code/database.cc +++ b/communication-core/someip-database/code/database.cc @@ -57,6 +57,20 @@ std::optional> DataBase::FindEventClient( return obj->second; } } + +core::ErrorCode DataBase::InsertInterface(const std::string& ip, + const uint16_t port) noexcept { + this->interfaces.push_back(objects::Interface{ip, port}); + return core::ErrorCode::kOk; +} +core::ErrorCode DataBase::SetServiceId(const uint16_t id) noexcept { + this->service_id = id; +} +uint16_t DataBase::GetServiceId() const noexcept { return this->service_id; } + +std::vector DataBase::GetInterfaces() const noexcept { + return this->interfaces; +} } // namespace objects } // namespace someip } // namespace com diff --git a/communication-core/someip-database/code/database.h b/communication-core/someip-database/code/database.h index f4e6260f..3cabcd4b 100644 --- a/communication-core/someip-database/code/database.h +++ b/communication-core/someip-database/code/database.h @@ -13,6 +13,8 @@ #include #include #include +#include + #include "communication-core/someip-database/code/interface.h" #include "communication-core/someip-database/code/service.h" #include "core/common/error_code.h" @@ -24,14 +26,23 @@ class DataBase { private: std::unordered_map list{}; std::unordered_map> event_map{}; + std::vector interfaces{}; + std::uint16_t service_id{0}; + public: + uint16_t GetServiceId() const noexcept; + std::vector GetInterfaces() const noexcept; core::ErrorCode InsertService(const uint16_t service_id, const Interface& inf) noexcept; std::optional FindService( const uint16_t service_id) const noexcept; - - core::ErrorCode InstertEvent(const uint16_t event_id, const uint16_t client_id) noexcept; - std::optional> FindEventClient(const uint16_t event_id) const noexcept; + core::ErrorCode InsertInterface(const std::string& ip, + const uint16_t port) noexcept; + core::ErrorCode SetServiceId(const uint16_t id) noexcept; + core::ErrorCode InstertEvent(const uint16_t event_id, + const uint16_t client_id) noexcept; + std::optional> FindEventClient( + const uint16_t event_id) const noexcept; }; } // namespace objects diff --git a/communication-core/someip-database/code/database_parser.h b/communication-core/someip-database/code/database_parser.h index 0ebda2ac..ec900a05 100644 --- a/communication-core/someip-database/code/database_parser.h +++ b/communication-core/someip-database/code/database_parser.h @@ -26,55 +26,64 @@ namespace someip { namespace json { class DataBaseParser { public: - static core::ErrorCode ParseJsonObject(std::shared_ptr db, + static simba::core::ErrorCode ParseJsonObject(std::shared_ptr db, const nlohmann::json& obj) noexcept { - core::ErrorCode flag = core::ErrorCode::kOk; - if (DataBaseParser::ValidateDb(obj) != core::ErrorCode::kOk) { - return core::ErrorCode::kError; + simba::core::ErrorCode flag = simba::core::ErrorCode::kOk; + if (DataBaseParser::ValidateDb(obj) != simba::core::ErrorCode::kOk) { + return simba::core::ErrorCode::kError; } auto list = obj.at("db"); for (auto& [key, val] : list.items()) { - if (DataBaseParser::ValidateItem(val) == core::ErrorCode::kOk) { + if (DataBaseParser::ValidateItem(val) == simba::core::ErrorCode::kOk) { std::string ip = val.at("ip"); uint16_t port = static_cast(val.at("port")); if (db->InsertService(static_cast(std::stoi(key)), objects::Interface{ip, port}) != - core::ErrorCode::kOk) { - flag = core::ErrorCode::kError; + simba::core::ErrorCode::kOk) { + flag = simba::core::ErrorCode::kError; } } else { - flag = core::ErrorCode::kError; + flag = simba::core::ErrorCode::kError; } } - if (flag == core::ErrorCode::kOk) { - flag = ParseEventClients(std::move(db), obj); + if (flag == simba::core::ErrorCode::kOk) { + flag = ParseEventClients(db, obj); + } + if (flag == simba::core::ErrorCode::kOk) { + flag = ParseConfig(std::move(db), obj); } return flag; } private: - static core::ErrorCode ValidateDb(const nlohmann::json& obj) noexcept { + static simba::core::ErrorCode ValidateDb(const nlohmann::json& obj) noexcept { + if (!obj.contains("interface")) { + return simba::core::ErrorCode::kError; + } + if (!obj.contains("service_id")) { + return simba::core::ErrorCode::kError; + } if (!obj.contains("db")) { - return core::ErrorCode::kError; + return simba::core::ErrorCode::kError; } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; } - static core::ErrorCode ValidateItem(const nlohmann::json& obj) noexcept { + static simba::core::ErrorCode ValidateItem(const nlohmann::json& obj) noexcept { if (!obj.contains("ip")) { - return core::ErrorCode::kError; + return simba::core::ErrorCode::kError; } if (!obj.contains("port")) { - return core::ErrorCode::kError; + return simba::core::ErrorCode::kError; } if (!obj.at("ip").is_string()) { - return core::ErrorCode::kError; + return simba::core::ErrorCode::kError; } if (!obj.at("port").is_number_unsigned()) { - return core::ErrorCode::kError; + return simba::core::ErrorCode::kError; } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; } - static core::ErrorCode ParseEventClients( + static simba::core::ErrorCode ParseEventClients( std::shared_ptr db, const nlohmann::json& obj) { auto list = obj["pub_event"]; for (auto& [key, val] : list.items()) { @@ -84,7 +93,19 @@ class DataBaseParser { db->InstertEvent(event_id, val); } } - return core::ErrorCode::kOk; + return simba::core::ErrorCode::kOk; + } + static simba::core::ErrorCode ParseConfig(std::shared_ptr db, + const nlohmann::json& obj) { + const uint16_t id = obj.at("service_id"); + db->SetServiceId(id); + auto list = obj.at("interface"); + for (auto& obj : list.items()) { + const std::string ip = obj.value()["ip"]; + const uint16_t port = obj.value()["port"]; + db->InsertInterface(ip, port); + } + return simba::core::ErrorCode::kOk; } }; diff --git a/communication-core/someip-database/code/interface.h b/communication-core/someip-database/code/interface.h index f80e1cb1..30c21af9 100644 --- a/communication-core/someip-database/code/interface.h +++ b/communication-core/someip-database/code/interface.h @@ -13,6 +13,7 @@ #include #include +#include namespace simba { namespace com { @@ -26,7 +27,10 @@ class Interface { public: Interface(const std::string& ip, const uint16_t port) : port_{port}, ip_{ip} {} - + Interface(const Interface& other) : port_{other.port_}, ip_{other.ip_} {} + Interface operator=(const Interface& other) { + return std::move(Interface(other)); + } uint16_t GetPort() const { return this->port_; } std::string GetIp() const { return this->ip_; } }; diff --git a/communication-core/someip-database/code/interface_parser.h b/communication-core/someip-database/code/interface_parser.h new file mode 100644 index 00000000..62a7c3d4 --- /dev/null +++ b/communication-core/someip-database/code/interface_parser.h @@ -0,0 +1,15 @@ +/** + * @file interface_parser.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_INTERFACE_PARSER_H_ +#define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_INTERFACE_PARSER_H_ + + +#endif // COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_INTERFACE_PARSER_H_ diff --git a/communication-core/someip/BUILD b/communication-core/someip/BUILD index d16d9392..d9f21377 100644 --- a/communication-core/someip/BUILD +++ b/communication-core/someip/BUILD @@ -17,6 +17,18 @@ cc_library( deps = [ "//communication-core/network-data:network_data_structure", "//communication-core/network-data:network_data_type", - "//core/common:common_converter" + "//core/common:common_converter", + ], +) + +cc_library( + name = "someip_objects", + visibility = ["//visibility:public"], + deps = [ + "//communication-core/someip:someip_header", + "//communication-core/someip:someip_types", + "//communication-core/someip/factory:someip_factory_interface", + "//communication-core/someip/factory:someip_header_factory", + "//communication-core/someip/factory:someip_message_factory", ], ) diff --git a/communication-core/someip/factory/BUILD b/communication-core/someip/factory/BUILD index f533f8e1..d2a5d542 100644 --- a/communication-core/someip/factory/BUILD +++ b/communication-core/someip/factory/BUILD @@ -37,4 +37,4 @@ cc_library( "//communication-core/someip:someip_header", "//communication-core/someip:someip_types", ], -) +) \ No newline at end of file diff --git a/communication-core/someip/factory/Isomeip_header_factory.h b/communication-core/someip/factory/Isomeip_header_factory.h index 3f2132de..b4377b75 100644 --- a/communication-core/someip/factory/Isomeip_header_factory.h +++ b/communication-core/someip/factory/Isomeip_header_factory.h @@ -20,7 +20,6 @@ #include "communication-core/someip/someip_header.h" namespace simba { namespace com { -namespace core { namespace someip { namespace factory { class ISomeIpHeaderFactory { @@ -55,14 +54,15 @@ class ISomeIpHeaderFactory { */ virtual std::shared_ptr CreateResponse( const std::uint16_t service_id, const std::uint16_t methode_id, - const simba::com::core::data::MessageCode res_flag) = 0; + const simba::com::data::MessageCode res_flag) = 0; virtual std::shared_ptr CreateRequestNoReturn( const std::uint16_t service_id, const std::uint16_t methode_id) = 0; + virtual std::shared_ptr CreateRequestACK( + const std::uint16_t service_id, const std::uint16_t methode_id) = 0; virtual ~ISomeIpHeaderFactory() = default; }; } // namespace factory } // namespace someip -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_FACTORY_ISOMEIP_HEADER_FACTORY_H_ diff --git a/communication-core/someip/factory/Isomeip_message_factory.h b/communication-core/someip/factory/Isomeip_message_factory.h index b4f3e3d8..84d79dec 100644 --- a/communication-core/someip/factory/Isomeip_message_factory.h +++ b/communication-core/someip/factory/Isomeip_message_factory.h @@ -18,7 +18,6 @@ #include "communication-core/someip/someip_header.h" namespace simba { namespace com { -namespace core { namespace someip { namespace factory { class ISomeIpMessageFactory { @@ -53,7 +52,6 @@ class ISomeIpMessageFactory { }; } // namespace factory } // namespace someip -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_FACTORY_ISOMEIP_MESSAGE_FACTORY_H_ diff --git a/communication-core/someip/factory/someip_header_factory.cc b/communication-core/someip/factory/someip_header_factory.cc index 9685b775..070ddf69 100644 --- a/communication-core/someip/factory/someip_header_factory.cc +++ b/communication-core/someip/factory/someip_header_factory.cc @@ -15,7 +15,6 @@ namespace simba { namespace com { -namespace core { namespace someip { namespace factory { std::shared_ptr SomeIpHeaderFactory::CreatEvent( @@ -38,12 +37,17 @@ std::shared_ptr SomeIpHeaderFactory::CreateRequestNoReturn( std::shared_ptr SomeIpHeaderFactory::CreateResponse( const std::uint16_t service_id, const std::uint16_t methode_id, - const simba::com::core::data::MessageCode res_flag) { + const simba::com::data::MessageCode res_flag) { return std::make_shared(service_id, methode_id, 0x00, 0x00, 0x00, 0x1, data::kResponse, res_flag); } + +std::shared_ptr SomeIpHeaderFactory::CreateRequestACK( + const std::uint16_t service_id, const std::uint16_t methode_id) { + return std::make_shared(service_id, methode_id, 0x00, 0x00, + 0x00, 0x1, data::kRequestAck, data::kEOk); +} } // namespace factory } // namespace someip -} // namespace core } // namespace com } // namespace simba diff --git a/communication-core/someip/factory/someip_header_factory.h b/communication-core/someip/factory/someip_header_factory.h index 161b49a3..62b5f6b5 100644 --- a/communication-core/someip/factory/someip_header_factory.h +++ b/communication-core/someip/factory/someip_header_factory.h @@ -21,7 +21,6 @@ #include "communication-core/someip/someip_header.h" namespace simba { namespace com { -namespace core { namespace someip { namespace factory { class SomeIpHeaderFactory : public ISomeIpHeaderFactory { @@ -56,14 +55,15 @@ class SomeIpHeaderFactory : public ISomeIpHeaderFactory { */ std::shared_ptr CreateResponse( const std::uint16_t service_id, const std::uint16_t methode_id, - const simba::com::core::data::MessageCode res_flag) override; + const simba::com::data::MessageCode res_flag) override; std::shared_ptr CreateRequestNoReturn( const std::uint16_t service_id, const std::uint16_t methode_id) override; + std::shared_ptr CreateRequestACK( + const std::uint16_t service_id, const std::uint16_t methode_id) override; ~SomeIpHeaderFactory() = default; }; } // namespace factory } // namespace someip -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_FACTORY_SOMEIP_HEADER_FACTORY_H_ diff --git a/communication-core/someip/factory/someip_message_factory.cc b/communication-core/someip/factory/someip_message_factory.cc index 96453135..a720dc4d 100644 --- a/communication-core/someip/factory/someip_message_factory.cc +++ b/communication-core/someip/factory/someip_message_factory.cc @@ -16,12 +16,11 @@ #include namespace simba { namespace com { -namespace core { namespace someip { namespace factory { std::vector SomeIpMessageFactory::GetBuffor( - std::shared_ptr header, const uint16_t client_id, + std::shared_ptr header, const uint16_t client_id, const uint16_t transfer_id, const std::vector payload) { header->SetClientID(client_id); header->SetSessionID(transfer_id); @@ -31,9 +30,9 @@ std::vector SomeIpMessageFactory::GetBuffor( return res; } -std::shared_ptr SomeIpMessageFactory::GetHeader( +std::shared_ptr SomeIpMessageFactory::GetHeader( std::vector raw) { - auto header = std::make_shared(); + auto header = std::make_shared(); header->SetBuffor(raw); return header; } @@ -46,6 +45,5 @@ std::vector SomeIpMessageFactory::GetPayload( } } // namespace factory } // namespace someip -} // namespace core } // namespace com } // namespace simba diff --git a/communication-core/someip/factory/someip_message_factory.h b/communication-core/someip/factory/someip_message_factory.h index 55acfc29..4a815f6a 100644 --- a/communication-core/someip/factory/someip_message_factory.h +++ b/communication-core/someip/factory/someip_message_factory.h @@ -21,7 +21,6 @@ #include "communication-core/someip/someip_header.h" namespace simba { namespace com { -namespace core { namespace someip { namespace factory { class SomeIpMessageFactory : public ISomeIpMessageFactory { @@ -29,13 +28,13 @@ class SomeIpMessageFactory : public ISomeIpMessageFactory { /** * @brief This function return ready bit stream to send * - * @param header pointer at someipHeader + * @param header pointer at simba::com::someip::SomeIpHeader * @param client_id client id * @param transfer_id transfer id * @param payload vector with payload * @return std::vector vector with ready data to send */ - std::vector GetBuffor(std::shared_ptr header, + std::vector GetBuffor(std::shared_ptr header, const uint16_t client_id, const uint16_t transfer_id, const std::vector payload) override; @@ -43,21 +42,20 @@ class SomeIpMessageFactory : public ISomeIpMessageFactory { * @brief Creat header object from raw data * * @param raw vector with bit stream - * @return std::shared_ptr header + * @return std::shared_ptr header */ - std::shared_ptr GetHeader(std::vector raw) override; + std::shared_ptr GetHeader(std::vector raw) override; /** * @brief Get payload from raw data * * @param raw vector with bit stream - * @return std::shared_ptr header + * @return std::shared_ptr header */ std::vector GetPayload(std::vector raw) override; ~SomeIpMessageFactory() = default; }; } // namespace factory } // namespace someip -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_FACTORY_SOMEIP_MESSAGE_FACTORY_H_ diff --git a/communication-core/someip/message_code.h b/communication-core/someip/message_code.h index 9e4a1249..46e6d29f 100644 --- a/communication-core/someip/message_code.h +++ b/communication-core/someip/message_code.h @@ -12,7 +12,6 @@ #define COMMUNICATION_CORE_SOMEIP_MESSAGE_CODE_H_ namespace simba { namespace com { -namespace core { namespace data { enum MessageCode { kEOk = 0x00, @@ -27,7 +26,6 @@ enum MessageCode { kEMalformedMessage = 0x09 }; } // namespace data -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_MESSAGE_CODE_H_ diff --git a/communication-core/someip/message_type.h b/communication-core/someip/message_type.h index 38f55bd8..ad5134ca 100644 --- a/communication-core/someip/message_type.h +++ b/communication-core/someip/message_type.h @@ -12,7 +12,6 @@ #define COMMUNICATION_CORE_SOMEIP_MESSAGE_TYPE_H_ namespace simba { namespace com { -namespace core { namespace data { enum MessageType { kRequest = 0x00, @@ -27,7 +26,6 @@ enum MessageType { kErrorAck = 0xC1 }; } // namespace data -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_MESSAGE_TYPE_H_ diff --git a/communication-core/someip/someip_header.cc b/communication-core/someip/someip_header.cc index 79ccf798..9596440e 100644 --- a/communication-core/someip/someip_header.cc +++ b/communication-core/someip/someip_header.cc @@ -12,7 +12,6 @@ namespace simba { namespace com { -namespace core { namespace someip { SomeIpHeader::SomeIpHeader(/* args */) { this->SetData(); } SomeIpHeader::SomeIpHeader(const SomeIpHeader& other) @@ -99,6 +98,5 @@ void SomeIpHeader::SetReturnCode(const uint8_t& value) { } // GCOVR_EXCL_STOP } // namespace someip -} // namespace core } // namespace com } // namespace simba diff --git a/communication-core/someip/someip_header.h b/communication-core/someip/someip_header.h index aa12d30d..0b2d0363 100644 --- a/communication-core/someip/someip_header.h +++ b/communication-core/someip/someip_header.h @@ -15,7 +15,6 @@ namespace simba { namespace com { -namespace core { namespace someip { class SomeIpHeader : public core::network::NetworkDataStructure { private: @@ -60,7 +59,6 @@ class SomeIpHeader : public core::network::NetworkDataStructure { }; } // namespace someip -} // namespace core } // namespace com } // namespace simba #endif // COMMUNICATION_CORE_SOMEIP_SOMEIP_HEADER_H_ diff --git a/core/application/BUILD b/core/application/BUILD index 6b48898e..2564c1cf 100644 --- a/core/application/BUILD +++ b/core/application/BUILD @@ -12,10 +12,13 @@ cc_library( ], visibility = ["//visibility:public"], deps = [ + "//communication-core/someip-controller:controller", + "//communication-core/someip-database/code:app_config_object", + "//communication-core/someip-database/code:someip_database_parser_lib", "//core/common:common_types", + "//core/json:simba_json", "//core/logger:Logger", "//diag/exec/controller:diag_exec_controller", - "//core/json:simba_json", "@boost//:algorithm", "@com_json//:json", ], @@ -23,7 +26,10 @@ cc_library( cc_library( name = "simba_application", - srcs = ["application_factory.cc","application_mw.cc"], + srcs = [ + "application_factory.cc", + "application_mw.cc", + ], hdrs = [ "Iapplication.h", "application_factory.h", diff --git a/core/application/application_common.cc b/core/application/application_common.cc index 5c11286b..1d128655 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -12,14 +12,17 @@ #include #include -#include #include +#include #include "boost/algorithm/string.hpp" +#include "communication-core/someip-database/code/com_config.h" +#include "communication-core/someip-database/code/database.h" +#include "communication-core/someip-database/code/database_parser.h" #include "core/application/parm.h" +#include "core/json/json_parser.h" #include "core/logger/Logger.h" #include "core/logger/logger_factory.h" -#include "core/json/json_parser.h" #include "nlohmann/json.hpp" namespace simba { namespace core { @@ -41,7 +44,7 @@ void ApplicationCommon::RunApp(int argc, char const* argv[]) { const std::string app_name = help_path.substr(help_path.find_last_of("/") + 1); parms.insert({"app_name", app_name}); - auto obj = json::JsonParser::Parser("/opt/" + parms.at("app_name") + + auto obj = json::JsonParser::Parser("/opt/" + parms.at("app_name") + "/etc/srp_app.json") .value(); auto app_id_ = obj.GetNumber("app_id"); @@ -63,6 +66,7 @@ void ApplicationCommon::onRun( if (this->CommonConfig(parms) != ErrorCode::kOk) { std::abort(); } + this->SomeIPConfig(parms); AppLogger::Info("Application initialize"); this->Initialize(parms); AppLogger::Info("Application running"); @@ -135,6 +139,24 @@ ErrorCode ApplicationCommon::CommonConfig( AppLogger::Info("App id: " + app_id + ", Desc: " + app_desc); return res; } + +ErrorCode ApplicationCommon::SomeIPConfig( + const std::unordered_map& parms) { + const std::string path{"/opt/" + parms.at("app_name") + + "/etc/app_someip.json"}; + com::config::ComConfig::InitConfigDb(path); + std::ifstream f(path); + if (f.is_open()) { + AppLogger::Info("Config DB initialization"); + auto obj = std::make_shared(); + auto json_obj = nlohmann::json::parse(f); + simba::com::someip::json::DataBaseParser::ParseJsonObject(obj, json_obj); + this->com = std::make_unique(obj); + } + + return ErrorCode::kOk; +} + ApplicationCommon::~ApplicationCommon() {} } // namespace core } // namespace simba diff --git a/core/application/application_common.h b/core/application/application_common.h index 7c2ab5f0..aa840915 100644 --- a/core/application/application_common.h +++ b/core/application/application_common.h @@ -11,21 +11,23 @@ #ifndef CORE_APPLICATION_APPLICATION_COMMON_H_ #define CORE_APPLICATION_APPLICATION_COMMON_H_ -#include // NOLINT +#include // NOLINT +#include #include // NOLINT #include #include // NOLINT #include -#include #include "core/application/Iapplication.h" #include "diag/exec/controller/exec_controller.hpp" +#include "communication-core/someip-controller/controller.h" namespace simba { namespace core { class ApplicationCommon : public IApplication { protected: std::stop_source source; diag::exec::ExecController exec_; + std::unique_ptr com; /** * @brief This is pre-run function only for creting new application * interfacess @@ -37,6 +39,8 @@ class ApplicationCommon : public IApplication { void SleepMainThread(); ErrorCode CommonConfig( const std::unordered_map& parms); + ErrorCode SomeIPConfig( + const std::unordered_map& parms); bool FileExist(const std::string& name); public: diff --git a/core/application/application_mw.cc b/core/application/application_mw.cc index b3ea2a4a..cbd75c09 100644 --- a/core/application/application_mw.cc +++ b/core/application/application_mw.cc @@ -27,6 +27,7 @@ void ApplicationMW::onRun( if (this->MwConfig(parms) != ErrorCode::kOk) { std::abort(); } + this->SomeIPConfig(parms); AppLogger::Info("Application [MW] configured"); AppLogger::Info("Application [MW] initialize"); this->Initialize(parms); diff --git a/deployment b/deployment index df3861c9..36ea2550 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit df3861c9cb1ce7ec854847ac99b1902e2d80f6a1 +Subproject commit 36ea255028b4fb0cbcb11fb07176b46bcb49081d diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp index bd91537d..5618314b 100644 --- a/mw/gpio_server/gpio_mw.cpp +++ b/mw/gpio_server/gpio_mw.cpp @@ -73,7 +73,6 @@ void GPIOMWService::InitializePins() { return; } for (const auto& gpio : data["gpio"]) { - std::cout<< gpio["id"] <<":"<< gpio["num"] <(gpio["id"]); uint16_t pin_num = static_cast(gpio["num"]); const std::string direct = gpio.at("direction"); diff --git a/mw/logger/code/BUILD b/mw/logger/code/BUILD index f05b7bb1..8d71b245 100644 --- a/mw/logger/code/BUILD +++ b/mw/logger/code/BUILD @@ -1,7 +1,7 @@ cc_binary( name = "dlt_server", srcs = ["main.cc"], - visibility = ["//deployment/mw/loger/dlt_fc:__pkg__"], + visibility = ["//deployment/mw/loger/dlt_fc:__pkg__","//deployment/mw/loger/dlt_fc/fc:__pkg__"], deps = [ "//core/application:simba_application", "//mw/logger/code/application:dlt_service_lib", From 9b239a3d116318101f11acc1f97b5ee15c952e92 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sun, 24 Mar 2024 12:54:05 +0100 Subject: [PATCH 37/71] subrepo update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 36ea2550..84532d72 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 36ea255028b4fb0cbcb11fb07176b46bcb49081d +Subproject commit 84532d7215b0b9bbe20e1a98640e46624388ad9b From 4d5f7c9536b285284bd1c724431fcceceb5527dd Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Sun, 24 Mar 2024 13:29:07 +0100 Subject: [PATCH 38/71] Makr moc create exec manager (#49) * moc_ gpio_controller * exec service --- apps/example/router.cc | 4 +- communication-core/sockets/mock/BUILD | 12 ++ communication-core/sockets/mock/mockSocket.h | 30 +++++ .../someip-controller/mock/BUILD | 12 ++ .../mock/mock_someip-controller.h | 38 ++++++ .../someip-database/code/database.h | 8 +- core/application/mock/BUILD | 12 ++ core/application/mock/mock_IApplication.hpp | 30 +++++ core/gpio/GPIO_digital_driver.cpp | 16 +-- core/gpio/GPIO_digital_driver.h | 49 +------- core/gpio/IGPIO_digital_driver.h | 2 +- core/gpio/mock/BUILD | 13 ++ core/gpio/mock/mock_gpio_driver.h | 32 +++++ core/i2c/BUILD | 5 +- core/i2c/Ii2cdriver.hpp | 36 ++++++ core/i2c/i2cdriver.h | 15 +-- core/i2c/mock/BUILD | 12 ++ core/i2c/mock/mock_i2cdriver.hpp | 32 +++++ core/test/benchmark/sample_benchmark.cc | 2 +- diag/exec/controller/BUILD | 12 +- diag/exec/controller/exec_controller.cpp | 19 +-- diag/exec/controller/exec_controller.hpp | 18 ++- diag/exec/controller/status.hpp | 34 ++++++ diag/exec/data/exec_header.cpp | 3 + diag/exec/data/exec_header.hpp | 5 +- diag/exec/factories/BUILD | 10 -- diag/exec/factories/exec_msg_factory.cpp | 33 ----- diag/exec/factories/exec_msg_factory.hpp | 47 -------- diag/exec/tests/BUILD | 12 +- diag/exec/tests/exec_data_factory.cc | 23 ---- diag/exec/tests/exec_structure.cc | 36 +++++- mw/em/code/BUILD | 1 + mw/em/code/em_application.cc | 21 +++- mw/em/code/em_application.h | 5 + mw/em/code/services/em/BUILD | 10 +- mw/em/code/services/em/app_config.h | 10 +- mw/em/code/services/em/em_service.cc | 59 +++++++-- mw/em/code/services/em/em_service.h | 9 +- mw/em/code/services/exec/BUILD | 29 +++++ mw/em/code/services/exec/README.md | 6 + mw/em/code/services/exec/exec_manager.cpp | 113 ++++++++++++++++++ mw/em/code/services/exec/exec_manager.hpp | 111 +++++++++++++++++ mw/em/code/services/exec/status.hpp | 34 ++++++ mw/gpio_server/BUILD | 3 + mw/gpio_server/controller/BUILD | 1 + mw/gpio_server/controller/gpio_controller.cpp | 21 +++- mw/gpio_server/controller/gpio_controller.hpp | 7 +- mw/gpio_server/gpio_mw.cpp | 4 +- mw/gpio_server/tests/BUILD | 13 ++ mw/gpio_server/tests/test_controller.cpp | 29 +++++ tools/ut/unittest.sh | 2 + 51 files changed, 840 insertions(+), 260 deletions(-) create mode 100644 communication-core/sockets/mock/BUILD create mode 100644 communication-core/sockets/mock/mockSocket.h create mode 100644 communication-core/someip-controller/mock/BUILD create mode 100644 communication-core/someip-controller/mock/mock_someip-controller.h create mode 100644 core/application/mock/BUILD create mode 100644 core/application/mock/mock_IApplication.hpp create mode 100644 core/gpio/mock/BUILD create mode 100644 core/gpio/mock/mock_gpio_driver.h create mode 100644 core/i2c/Ii2cdriver.hpp create mode 100644 core/i2c/mock/BUILD create mode 100644 core/i2c/mock/mock_i2cdriver.hpp create mode 100644 diag/exec/controller/status.hpp delete mode 100644 diag/exec/factories/BUILD delete mode 100644 diag/exec/factories/exec_msg_factory.cpp delete mode 100644 diag/exec/factories/exec_msg_factory.hpp delete mode 100644 diag/exec/tests/exec_data_factory.cc create mode 100644 mw/em/code/services/exec/README.md create mode 100644 mw/em/code/services/exec/exec_manager.cpp create mode 100644 mw/em/code/services/exec/exec_manager.hpp create mode 100644 mw/em/code/services/exec/status.hpp create mode 100644 mw/gpio_server/tests/test_controller.cpp create mode 100755 tools/ut/unittest.sh diff --git a/apps/example/router.cc b/apps/example/router.cc index e40495b6..842e5ab8 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -35,7 +35,6 @@ core::ErrorCode Router::Run(std::stop_token token) { while (true) { AppLogger::Debug("AppLogger::Debug"); AppLogger::Info("AppLogger::Info"); - AppLogger::Warning("AppLogger::Warning"); this->gpio_.SetPinValue(1, gpio::Value::HIGH); std::this_thread::sleep_for(std::chrono::seconds(1)); this->gpio_.SetPinValue(1, gpio::Value::LOW); @@ -46,7 +45,8 @@ core::ErrorCode Router::Run(std::stop_token token) { core::ErrorCode Router::Initialize( const std::unordered_map& parms) { - this->gpio_.Init(12); + this->gpio_ = gpio::GPIOController(new com::soc::IpcSocket()); + this->gpio_.Init(12); return core::ErrorCode::kOk; } } // namespace router diff --git a/communication-core/sockets/mock/BUILD b/communication-core/sockets/mock/BUILD new file mode 100644 index 00000000..bfb39272 --- /dev/null +++ b/communication-core/sockets/mock/BUILD @@ -0,0 +1,12 @@ +cc_library( + name = "mock_socket", + hdrs = [ + "mockSocket.h" + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//communication-core/sockets:socket_interface", + ], + testonly = True, +) \ No newline at end of file diff --git a/communication-core/sockets/mock/mockSocket.h b/communication-core/sockets/mock/mockSocket.h new file mode 100644 index 00000000..998ca5fc --- /dev/null +++ b/communication-core/sockets/mock/mockSocket.h @@ -0,0 +1,30 @@ +/** + * @file mockSocket.h + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-12 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOCKETS_MOCK_MOCKSOCKET_H_ +#define COMMUNICATION_CORE_SOCKETS_MOCK_MOCKSOCKET_H_ + +#include +#include +#include "gmock/gmock.h" + +#include "communication-core/sockets/socket_config.h" +#include "communication-core/sockets/Isocket.h" + +class MockSocket : public simba::com::soc::ISocket { + public: + MOCK_METHOD(void, SetRXCallback, (simba::com::soc::RXCallback), (override)); + MOCK_METHOD(simba::core::ErrorCode, Init, (const simba::com::soc::SocketConfig&), (override)); + MOCK_METHOD(simba::core::ErrorCode, Transmit, (const std::string&, const std::uint16_t, + std::vector), (override)); + MOCK_METHOD(void, StartRXThread, (), (override)); +}; + +#endif // COMMUNICATION_CORE_SOCKETS_MOCK_MOCKSOCKET_H_ diff --git a/communication-core/someip-controller/mock/BUILD b/communication-core/someip-controller/mock/BUILD new file mode 100644 index 00000000..48f797b3 --- /dev/null +++ b/communication-core/someip-controller/mock/BUILD @@ -0,0 +1,12 @@ +cc_library( + name = "mock_someip_controller", + srcs = [ + "mock_someip-controller.h", + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//communication-core/someip-controller:someip_interface", + ], + testonly = True, +) \ No newline at end of file diff --git a/communication-core/someip-controller/mock/mock_someip-controller.h b/communication-core/someip-controller/mock/mock_someip-controller.h new file mode 100644 index 00000000..9b2e7c13 --- /dev/null +++ b/communication-core/someip-controller/mock/mock_someip-controller.h @@ -0,0 +1,38 @@ +/** + * @file mock_someip-controller.h + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-12 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_MOCK_MOCK_SOMEIP_CONTROLLER_H_ +#define COMMUNICATION_CORE_SOMEIP_CONTROLLER_MOCK_MOCK_SOMEIP_CONTROLLER_H_ + +#include +#include +#include + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include "communication-core/someip-controller/Isomeip_controller.h" + + +class MockSomeIpController : public simba::com::someip::ISomeIpController{ + public: + MOCK_METHOD((std::optional>), Request, + (const uint16_t, const uint16_t, const std::vector), (override)); + MOCK_METHOD((bool), RequestNoResponse, (const uint16_t, const uint16_t, + const std::vector), (override)); + MOCK_METHOD((simba::core::ErrorCode), AddMethod, (const uint16_t, simba::com::someip::SomeIPMethod), (override)); + MOCK_METHOD((simba::core::ErrorCode), AddEventValue, (const uint16_t, const std::vector), (override)); + MOCK_METHOD((simba::core::ErrorCode), Init, (), (override)); + MOCK_METHOD((simba::core::ErrorCode), LoadServiceList, (const std::string&), (override)); + + virtual ~MockSomeIpController() = default; +}; + +#endif // COMMUNICATION_CORE_SOMEIP_CONTROLLER_MOCK_MOCK_SOMEIP_CONTROLLER_H_ diff --git a/communication-core/someip-database/code/database.h b/communication-core/someip-database/code/database.h index 3cabcd4b..0b7d73d3 100644 --- a/communication-core/someip-database/code/database.h +++ b/communication-core/someip-database/code/database.h @@ -32,14 +32,14 @@ class DataBase { public: uint16_t GetServiceId() const noexcept; std::vector GetInterfaces() const noexcept; - core::ErrorCode InsertService(const uint16_t service_id, + simba::core::ErrorCode InsertService(const uint16_t service_id, const Interface& inf) noexcept; std::optional FindService( const uint16_t service_id) const noexcept; - core::ErrorCode InsertInterface(const std::string& ip, + simba::core::ErrorCode InsertInterface(const std::string& ip, const uint16_t port) noexcept; - core::ErrorCode SetServiceId(const uint16_t id) noexcept; - core::ErrorCode InstertEvent(const uint16_t event_id, + simba::core::ErrorCode SetServiceId(const uint16_t id) noexcept; + simba::core::ErrorCode InstertEvent(const uint16_t event_id, const uint16_t client_id) noexcept; std::optional> FindEventClient( const uint16_t event_id) const noexcept; diff --git a/core/application/mock/BUILD b/core/application/mock/BUILD new file mode 100644 index 00000000..137bdefe --- /dev/null +++ b/core/application/mock/BUILD @@ -0,0 +1,12 @@ +cc_library( + name = "mock_application", + hdrs = [ + "mock_IApplication.hpp" + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//core/application:application", + ], + testonly = True, +) \ No newline at end of file diff --git a/core/application/mock/mock_IApplication.hpp b/core/application/mock/mock_IApplication.hpp new file mode 100644 index 00000000..152bc990 --- /dev/null +++ b/core/application/mock/mock_IApplication.hpp @@ -0,0 +1,30 @@ +/** + * @file mock_IApplication.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-12 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef CORE_APPLICATION_MOCK_MOCK_IAPPLICATION_HPP_ +#define CORE_APPLICATION_MOCK_MOCK_IAPPLICATION_HPP_ + +#include +#include +#include +#include "gmock/gmock.h" + +#include "core/application/Iapplication.h" + +class MockApplication : public simba::core::IApplication { + public: + MOCK_METHOD(simba::core::ErrorCode, Run, (std::stop_token), (override)); + MOCK_METHOD(void, onRun, ((const std::unordered_map&)), (override)); + MOCK_METHOD(void, StopApp, (), (override)); + MOCK_METHOD(void, RunApp, (int, const char*[]), (override)); + MOCK_METHOD(simba::core::ErrorCode, Initialize, ((const std::unordered_map&)), (override)); +}; + +#endif // CORE_APPLICATION_MOCK_MOCK_IAPPLICATION_HPP_ diff --git a/core/gpio/GPIO_digital_driver.cpp b/core/gpio/GPIO_digital_driver.cpp index 7879db31..3ac06f0d 100644 --- a/core/gpio/GPIO_digital_driver.cpp +++ b/core/gpio/GPIO_digital_driver.cpp @@ -20,13 +20,7 @@ namespace gpio { GpioDigitalDriver::GpioDigitalDriver() {} -GpioDigitalDriver::~GpioDigitalDriver() { - for (auto pin : this->registered_pins.getPins()) { - if (!this->unregisterPin(pin.number)) { - AppLogger::Error("Cant close gpio file"); - } - } -} +GpioDigitalDriver::~GpioDigitalDriver() {} core::ErrorCode GpioDigitalDriver::unregisterPin(uint8_t pinNumber) { std::ofstream file; @@ -52,7 +46,6 @@ core::ErrorCode GpioDigitalDriver::initializePin(uint8_t pinNumber, direction_t AppLogger::Error("cant set direction"); return core::ErrorCode::kError; } - this->registered_pins.AddPin(pinNumber, direction); return core::ErrorCode::kOk; } @@ -62,9 +55,6 @@ std::string GpioDigitalDriver::getEndpointPath(uint8_t pinNumber, std::string en } core::ErrorCode GpioDigitalDriver::setValue(uint8_t pinNumber , uint8_t value) { - if ( this->registered_pins.getPinDirection(pinNumber) != direction_t::OUT ) { - return core::ErrorCode::kInitializeError; - } std::ofstream file; file.open(this->getEndpointPath(pinNumber, "value")); if (!file.is_open()) { @@ -87,14 +77,10 @@ core::ErrorCode GpioDigitalDriver::setDirection(uint8_t pinNumber , direction_t } file << (direction == direction_t::IN ? "in" : "out"); file.close(); - this->registered_pins.SetDirection(pinNumber, direction); return ErrorCode::kOk; } uint8_t GpioDigitalDriver::getValue(uint8_t pinNumber) { - if (this->registered_pins.getPinDirection(pinNumber)!= direction_t::IN) { - return ErrorCode::kError; - } std::ifstream file; file.open(this->getEndpointPath(pinNumber, "value")); if (!file.is_open()) { diff --git a/core/gpio/GPIO_digital_driver.h b/core/gpio/GPIO_digital_driver.h index 09bf17e4..1958e67d 100644 --- a/core/gpio/GPIO_digital_driver.h +++ b/core/gpio/GPIO_digital_driver.h @@ -14,6 +14,7 @@ #include "IGPIO_digital_driver.h" #include +#include #include #include @@ -21,51 +22,7 @@ namespace simba { namespace core { namespace gpio { -struct Pin{ - uint16_t number; - direction_t direction_; -}; -class Pins{ - private: - std::vector pins; - - public: - std::vector getPins() { - return this->pins; - } - core::ErrorCode AddPin(uint16_t pinNumber, direction_t direction) { - this->pins.push_back(Pin(pinNumber, direction)); - return core::ErrorCode::kOk; - } - bool pinIsRegistered(uint16_t pinNumber) { - for (auto pin : this->pins) { - if (pin.number == pinNumber) { - return true; - } - } - return false; - } - direction_t getPinDirection(uint16_t pinNumber) { - for (auto pin : this->pins) { - if (pin.number == pinNumber) { - return pin.direction_; - } - } - return direction_t::ERROR; - } - ErrorCode SetDirection(uint16_t pinNumber, direction_t direction) { - for (auto pin : this->pins) { - if (pin.number == pinNumber) { - pin.direction_ = direction; - return ErrorCode::kOk; - } - } - return ErrorCode::kConnectionError; - } -}; - - -class GpioDigitalDriver:IgpioDigitalDriver{ +class GpioDigitalDriver: public IgpioDigitalDriver{ public: GpioDigitalDriver(); ~GpioDigitalDriver(); @@ -114,8 +71,6 @@ class GpioDigitalDriver:IgpioDigitalDriver{ std::string getEndpointPath(uint8_t pinNumber, std::string endpoint); core::ErrorCode unregisterPin(uint8_t pinNumber); const std::string path = "/sys/class/gpio"; - - Pins registered_pins; }; } // namespace gpio } // namespace core diff --git a/core/gpio/IGPIO_digital_driver.h b/core/gpio/IGPIO_digital_driver.h index 3b4ae9f3..0cd8321b 100644 --- a/core/gpio/IGPIO_digital_driver.h +++ b/core/gpio/IGPIO_digital_driver.h @@ -30,7 +30,7 @@ enum direction_t{ class IgpioDigitalDriver{ public: IgpioDigitalDriver() {} - + virtual ~IgpioDigitalDriver() {} virtual core::ErrorCode initializePin(uint8_t pinNumber, direction_t direction) = 0; diff --git a/core/gpio/mock/BUILD b/core/gpio/mock/BUILD new file mode 100644 index 00000000..d93c2dbb --- /dev/null +++ b/core/gpio/mock/BUILD @@ -0,0 +1,13 @@ +cc_library( + name = "mock_gpio", + srcs = [ + "mock_gpio_driver.h", + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//core/gpio:gpio_interface", + "//communication-core/sockets/mock:mock_socket" + ], + testonly = True, +) \ No newline at end of file diff --git a/core/gpio/mock/mock_gpio_driver.h b/core/gpio/mock/mock_gpio_driver.h new file mode 100644 index 00000000..b44cab7f --- /dev/null +++ b/core/gpio/mock/mock_gpio_driver.h @@ -0,0 +1,32 @@ +/** + * @file mock_gpio_driver.h + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-12 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef CORE_GPIO_MOCK_MOCK_GPIO_DRIVER_H_ +#define CORE_GPIO_MOCK_MOCK_GPIO_DRIVER_H_ + +#include + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include "core/gpio/IGPIO_digital_driver.h" + + +class MockGPIO : public simba::core::gpio::IgpioDigitalDriver { + public: + MOCK_METHOD((simba::core::ErrorCode), initializePin, (uint8_t, simba::core::gpio::direction_t), (override)); + MOCK_METHOD((uint8_t), getValue, (uint8_t), (override)); + MOCK_METHOD((simba::core::gpio::direction_t), getDirection, (uint8_t), (override)); + MOCK_METHOD((simba::core::ErrorCode), setValue, (uint8_t, uint8_t), (override)); + MOCK_METHOD((simba::core::ErrorCode), setDirection, (uint8_t, simba::core::gpio::direction_t), (override)); + virtual ~MockGPIO() = default; +}; + +#endif // CORE_GPIO_MOCK_MOCK_GPIO_DRIVER_H_ diff --git a/core/i2c/BUILD b/core/i2c/BUILD index b2bead0d..77f11529 100644 --- a/core/i2c/BUILD +++ b/core/i2c/BUILD @@ -1,7 +1,10 @@ cc_library( name = "i2cdriver", srcs = ["i2cdriver.cpp"], - hdrs = ["i2cdriver.h"], + hdrs = [ + "i2cdriver.h", + "Ii2cdriver.hpp", + ], deps = [ "//core/common:common_types", ], diff --git a/core/i2c/Ii2cdriver.hpp b/core/i2c/Ii2cdriver.hpp new file mode 100644 index 00000000..f9f92878 --- /dev/null +++ b/core/i2c/Ii2cdriver.hpp @@ -0,0 +1,36 @@ +/** + * @file Ii2cdriver.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-12 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef CORE_I2C_II2CDRIVER_HPP_ +#define CORE_I2C_II2CDRIVER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "core/common/error_code.h" + +namespace simba { +namespace core { +class II2C { + public: + virtual ErrorCode init(const std::string& path) = 0; + virtual std::optional> Read(const uint8_t address, const uint8_t reg); + virtual ErrorCode Write(const uint8_t address, const uint8_t reg, std::vector data); +}; +} // namespace core +} // namespace simba + +#endif // CORE_I2C_II2CDRIVER_HPP_ diff --git a/core/i2c/i2cdriver.h b/core/i2c/i2cdriver.h index 5335db16..94bd205b 100644 --- a/core/i2c/i2cdriver.h +++ b/core/i2c/i2cdriver.h @@ -11,19 +11,14 @@ #ifndef CORE_I2C_I2CDRIVER_H_ #define CORE_I2C_I2CDRIVER_H_ -#include -#include -#include -#include -#include -#include -#include #include -#include -#include "core/common/error_code.h" +#include + +#include "Ii2cdriver.hpp" + namespace simba { namespace core { -class I2C{ +class I2C : public II2C { public: ErrorCode init(const std::string& path); std::optional> Read(const uint8_t address, const uint8_t reg); diff --git a/core/i2c/mock/BUILD b/core/i2c/mock/BUILD new file mode 100644 index 00000000..affd522b --- /dev/null +++ b/core/i2c/mock/BUILD @@ -0,0 +1,12 @@ +cc_library( + name = "mock_i2c", + srcs = [ + "mock_i2cdriver.hpp", + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//core/i2c:i2cdriver", + ], + testonly = True, +) \ No newline at end of file diff --git a/core/i2c/mock/mock_i2cdriver.hpp b/core/i2c/mock/mock_i2cdriver.hpp new file mode 100644 index 00000000..1378a4d8 --- /dev/null +++ b/core/i2c/mock/mock_i2cdriver.hpp @@ -0,0 +1,32 @@ +/** + * @file mock_i2cdriver.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-12 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef CORE_I2C_MOCK_MOCK_I2CDRIVER_HPP_ +#define CORE_I2C_MOCK_MOCK_I2CDRIVER_HPP_ + +#include +#include +#include + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include "core/i2c/Ii2cdriver.h" + + +class MockI2C : public simba::core::II2C { + public: + MOCK_METHOD((simba::core::ErrorCode), init, const std::string&, (override)); + MOCK_METHOD((std::optional>), Read, (const uint8_t, const uint8_t), (override)); + MOCK_METHOD((simba::core::ErrorCode), Write, (const uint8_t, const uint8_t, + std::vector), (override)); + virtual ~MockI2C() = default; +}; +#endif // CORE_I2C_MOCK_MOCK_I2CDRIVER_HPP_ diff --git a/core/test/benchmark/sample_benchmark.cc b/core/test/benchmark/sample_benchmark.cc index 2defdded..5bc23e32 100644 --- a/core/test/benchmark/sample_benchmark.cc +++ b/core/test/benchmark/sample_benchmark.cc @@ -13,7 +13,7 @@ #include // NOLINT #include // NOLINT -#include "application/parm.h" +#include "core/application/parm.h" static void ParamConvertBenchmark(benchmark::State& state) { // NOLINT for (auto _ : state) { diff --git a/diag/exec/controller/BUILD b/diag/exec/controller/BUILD index b5492d3a..763a7afb 100644 --- a/diag/exec/controller/BUILD +++ b/diag/exec/controller/BUILD @@ -1,13 +1,19 @@ - cc_library( name = "diag_exec_controller", deps = [ - "//diag/exec/factories:diag_exec_factories", + "//diag/exec/data:diag_exec_header", "//communication-core/sockets:socket_ipc", - "//core/logger:Logger" + "//core/logger:Logger", + ":diag_status" ], srcs = ["exec_controller.cpp"], hdrs = ["exec_controller.hpp"], visibility = ["//visibility:public"], ) + +cc_library( + name = "diag_status", + hdrs = ["status.hpp"], + +) \ No newline at end of file diff --git a/diag/exec/controller/exec_controller.cpp b/diag/exec/controller/exec_controller.cpp index b4e2adb6..7dc889a3 100644 --- a/diag/exec/controller/exec_controller.cpp +++ b/diag/exec/controller/exec_controller.cpp @@ -11,31 +11,34 @@ #include "exec_controller.hpp" #include "core/logger/Logger.h" #include "communication-core/sockets/ipc_socket.h" -#include "diag/exec/factories/exec_msg_factory.hpp" - +#include "diag/exec/data/exec_header.hpp" namespace simba { namespace diag { namespace exec { void ExecController::Init(uint16_t service_id) { this->status_ = Status::Start_up; + this->flags_ = std::bitset<5>{"00000"}; this->thread_ = std::jthread([&](std::stop_token stop_token) { - auto factory_ = ExecMsgFactory(); auto sock_ = com::soc::IpcSocket(); - auto hdr = ExecHeader(service_id, 0, this->status_); + auto hdr = ExecHeader(service_id, 1, (this->flags_.to_ulong() << 3) | this->status_); while (!stop_token.stop_requested()) { - std::this_thread::sleep_for(std::chrono::seconds(1)); - auto data = factory_.GetBuffer(std::make_shared(hdr)); - sock_.Transmit("SIMBA.EXE", 0, data); - AppLogger::Info("id: "+ std::to_string(hdr.GetServiceID()) + this->mtx_status_.lock(); + hdr.SetFlags((this->flags_.to_ulong() << 3) | this->status_); + sock_.Transmit("SIMBA.EXE", 0, hdr.GetBuffor()); + AppLogger::Debug("id: "+ std::to_string(hdr.GetServiceID()) +" timestamp:"+std::to_string(hdr.GetTimestamp())); hdr.IncrementTimeStamp(); + this->mtx_status_.unlock(); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } }); } void ExecController::SetStatus(Status status) { + this->mtx_status_.lock(); this->status_ = status; + this->mtx_status_.unlock(); } ExecController::ExecController() {} diff --git a/diag/exec/controller/exec_controller.hpp b/diag/exec/controller/exec_controller.hpp index 8222e09d..37ec6a18 100644 --- a/diag/exec/controller/exec_controller.hpp +++ b/diag/exec/controller/exec_controller.hpp @@ -16,32 +16,28 @@ #include #include // NOLINT #include // NOLINT +#include // NOLINT +#include + +#include "status.hpp" namespace simba { namespace diag { namespace exec { -enum Status { - Start_up = 0x00, - Running = 0x01, - Running_with_dtc = 0x02, - Running_after_dtc = 0x03, - Error = 0x04, - Running_after_error = 0x05, - Running_ignore_DTC = 0x06, - Running_ignore_error = 0x07 -}; - class ExecController { private: uint16_t service_id; std::jthread thread_; + std::mutex mtx_status_; Status status_; + std::bitset<5> flags_; public: void Init(uint16_t service_id); ExecController(); void SetStatus(Status status); + void SetFlags(std::bitset<5> flags); ~ExecController(); }; } // namespace exec diff --git a/diag/exec/controller/status.hpp b/diag/exec/controller/status.hpp new file mode 100644 index 00000000..5d9259b7 --- /dev/null +++ b/diag/exec/controller/status.hpp @@ -0,0 +1,34 @@ +/** + * @file status.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-09 + * + * @copyright Copyright (c) 2024 + * +*/ + +#ifndef DIAG_EXEC_CONTROLLER_STATUS_HPP_ +#define DIAG_EXEC_CONTROLLER_STATUS_HPP_ + +namespace simba { +namespace diag { +namespace exec { + +enum Status { + Start_up = 0x00, + Running = 0x01, + Running_with_dtc = 0x02, + Running_after_dtc = 0x03, + Error = 0x04, + Running_after_error = 0x05, + Running_ignore_DTC = 0x06, + Running_ignore_error = 0x07 +}; + +} // namespace exec +} // namespace diag +} // namespace simba + +#endif // DIAG_EXEC_CONTROLLER_STATUS_HPP_ diff --git a/diag/exec/data/exec_header.cpp b/diag/exec/data/exec_header.cpp index 9a3d0856..9e1d890b 100644 --- a/diag/exec/data/exec_header.cpp +++ b/diag/exec/data/exec_header.cpp @@ -33,6 +33,9 @@ uint8_t ExecHeader::GetFlags() const { void ExecHeader::IncrementTimeStamp() { this->time_stamp_.Set(this->time_stamp_.Get()+1); } +void ExecHeader::SetFlags(uint8_t flags) { + this->flags_.Set(flags); +} } // namespace exec } // namespace diag diff --git a/diag/exec/data/exec_header.hpp b/diag/exec/data/exec_header.hpp index 212a93fc..b4a4e0d3 100644 --- a/diag/exec/data/exec_header.hpp +++ b/diag/exec/data/exec_header.hpp @@ -27,8 +27,8 @@ class ExecHeader : public com::core::network::NetworkDataStructure { // numer id serwisu com::core::network::uint16_t service_id_; // timestamp - com::core::network::uint32_t time_stamp_; - com::core::network::uint8_t flags_; + com::core::network::uint16_t time_stamp_; + com::core::network::uint8_t flags_{0}; public: ExecHeader(const uint16_t &service_id, const uint16_t &time_stamp, uint8_t flags); @@ -44,6 +44,7 @@ class ExecHeader : public com::core::network::NetworkDataStructure { uint16_t GetTimestamp() const; uint8_t GetFlags() const; void IncrementTimeStamp(); + void SetFlags(uint8_t flags); }; } // namespace exec diff --git a/diag/exec/factories/BUILD b/diag/exec/factories/BUILD deleted file mode 100644 index b4701f2d..00000000 --- a/diag/exec/factories/BUILD +++ /dev/null @@ -1,10 +0,0 @@ - -cc_library( - name = "diag_exec_factories", - deps = [ - "//diag/exec/data:diag_exec_header" - ], - srcs = ["exec_msg_factory.cpp"], - hdrs = ["exec_msg_factory.hpp"], - visibility = ["//visibility:public"], -) diff --git a/diag/exec/factories/exec_msg_factory.cpp b/diag/exec/factories/exec_msg_factory.cpp deleted file mode 100644 index 923e9d88..00000000 --- a/diag/exec/factories/exec_msg_factory.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @file exec_msg_factory.cpp - * @author Wiktor Kawka (asinesak353@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-28 - * - * @copyright Copyright (c) 2024 - * - */ -#include "diag/exec/factories/exec_msg_factory.hpp" - -#include -namespace simba { -namespace diag { -namespace exec { - -std::vector ExecMsgFactory::GetBuffer( - std::shared_ptr header) { - std::vector res{header->GetBuffor()}; - return res; -} - -std::shared_ptr ExecMsgFactory::GetHeader( - std::vector raw_data) { - auto header = diag::exec::ExecHeader(); - header.SetBuffor(raw_data); - return std::make_shared(header); -} - -} // namespace exec -} // namespace diag -} // namespace simba diff --git a/diag/exec/factories/exec_msg_factory.hpp b/diag/exec/factories/exec_msg_factory.hpp deleted file mode 100644 index 6397be80..00000000 --- a/diag/exec/factories/exec_msg_factory.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/** - * @file exec_header_factory.hpp - * @author Wiktor Kawka (asinesak353@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-28 - * - * @copyright Copyright (c) 2024 - * - */ - -#ifndef DIAG_EXEC_FACTORIES_EXEC_MSG_FACTORY_HPP_ -#define DIAG_EXEC_FACTORIES_EXEC_MSG_FACTORY_HPP_ - -#include "diag/exec/data/exec_header.hpp" -#include -#include - -namespace simba { -namespace diag { -namespace exec { - -class ExecMsgFactory { - public: - /** - * @brief This function return ready bit stream to send - * - * @param header - * @return std::vector - */ - std::vector GetBuffer(std::shared_ptr header); - - /** - * @brief Creat header object from raw data - * - * @param raw_data - * @return std::shared_ptr - */ - std::shared_ptr GetHeader( - std::vector raw_data); -}; - -} // namespace exec -} // namespace diag -} // namespace simba - -#endif // DIAG_EXEC_FACTORIES_EXEC_MSG_FACTORY_HPP_ diff --git a/diag/exec/tests/BUILD b/diag/exec/tests/BUILD index 4405244b..f0389935 100644 --- a/diag/exec/tests/BUILD +++ b/diag/exec/tests/BUILD @@ -6,14 +6,4 @@ cc_test( "//diag/exec/data:diag_exec_header", "@com_google_googletest//:gtest_main", ], -) - -cc_test( - name = "diag_data_factory", - srcs = ["exec_data_factory.cc"], - visibility = ["//visibility:public"], - deps = [ - "//diag/exec/factories:diag_exec_factories", - "@com_google_googletest//:gtest_main", - ], -) +) \ No newline at end of file diff --git a/diag/exec/tests/exec_data_factory.cc b/diag/exec/tests/exec_data_factory.cc deleted file mode 100644 index 2110790f..00000000 --- a/diag/exec/tests/exec_data_factory.cc +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @file test_diag_data_factory.cc - * @author Bartosz Snieg (snieg45@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-10 - * - * @copyright Copyright (c) 2024 - * - */ -#include - -#include "diag/exec/factories/exec_msg_factory.hpp" - -TEST(DIAG_DAT_FACTORY, CreateReadRequest) { - auto hdr = simba::diag::exec::ExecHeader(123, 12, 2); - auto sut = simba::diag::exec::ExecMsgFactory(); - auto buf = sut.GetBuffer(std::make_shared(hdr)); - auto hdr2 = sut.GetHeader(buf); - ASSERT_EQ(hdr.GetBuffor(), buf); - ASSERT_EQ(hdr.GetServiceID(), hdr2->GetServiceID()); - ASSERT_EQ(hdr.GetTimestamp(), hdr2->GetTimestamp()); -} diff --git a/diag/exec/tests/exec_structure.cc b/diag/exec/tests/exec_structure.cc index 867ab8d1..777db5fa 100644 --- a/diag/exec/tests/exec_structure.cc +++ b/diag/exec/tests/exec_structure.cc @@ -12,9 +12,35 @@ #include "diag/exec/data/exec_header.hpp" -TEST(DATA_STRUCTURE, CONSTRUCTOR_CHECK) { - simba::diag::exec::ExecHeader hdr(123, 12, 1); - EXPECT_EQ(hdr.GetServiceID(), 123); - EXPECT_EQ(hdr.GetTimestamp(), 12); - EXPECT_EQ(hdr.GetFlags(), 1); + + +class DataStructureTest : public testing::TestWithParam> { + protected: + void SetUp() override { + std::tie(service_id, timestamp, flags) = GetParam(); + header = simba::diag::exec::ExecHeader(service_id, timestamp, flags); + } + int service_id; + int timestamp; + int flags; + simba::diag::exec::ExecHeader header; +}; + +INSTANTIATE_TEST_SUITE_P(Default, DataStructureTest, + testing::Values( + std::make_tuple(123, 12, 0), + std::make_tuple(456, 34, 1), + std::make_tuple(789, 56, 2), + std::make_tuple(125, 22, 4), + std::make_tuple(426, 64, 8), + std::make_tuple(889, 46, 16), + std::make_tuple(323, 22, 32), + std::make_tuple(956, 84, 64), + std::make_tuple(149, 96, 133) +)); + +TEST_P(DataStructureTest, ConstructorCheck) { + EXPECT_EQ(header.GetServiceID(), service_id); + EXPECT_EQ(header.GetTimestamp(), timestamp); + EXPECT_EQ(header.GetFlags(), flags); } diff --git a/mw/em/code/BUILD b/mw/em/code/BUILD index e717a994..b31c73eb 100644 --- a/mw/em/code/BUILD +++ b/mw/em/code/BUILD @@ -9,5 +9,6 @@ cc_binary( deps = [ "//core/application:simba_application", "//mw/em/code/services/em:em_service", + "//mw/em/code/services/exec:exec_service", ], ) diff --git a/mw/em/code/em_application.cc b/mw/em/code/em_application.cc index 1122f462..fde24259 100644 --- a/mw/em/code/em_application.cc +++ b/mw/em/code/em_application.cc @@ -20,7 +20,25 @@ EmApplication::~EmApplication() {} core::ErrorCode EmApplication::Run(std::stop_token token) { this->em_service.StartApps(); - SleepMainThread(); + std::this_thread::sleep_for(std::chrono::seconds(2)); + this->exec_service.Init(); + while (true) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + AppLogger::Info("check if restart needed"); + auto res = this->exec_service.CheckAppCondition(); + while ( res.size() > 0 ) { + AppLogger::Error("Restart needed"); + auto pid = this->em_service.RestartApp(res.front()); + if ( !pid.has_value() ) { + AppLogger::Error("ERROR RESTART APP WITH ID: "+std::to_string(res.front())); + } else { + AppLogger::Error("RESTARTED APP WITH ID: "+std::to_string(res.front())); + this->exec_service.RestartedApp(res.front()); + res.pop(); + } + } + } + this->SleepMainThread(); return core::ErrorCode::kOk; } /** @@ -31,6 +49,7 @@ core::ErrorCode EmApplication::Run(std::stop_token token) { core::ErrorCode EmApplication::Initialize( const std::unordered_map& parms) { this->em_service.LoadApps(); + this->exec_service.SetApps(this->em_service.GetAppList()); return core::ErrorCode::kOk; } diff --git a/mw/em/code/em_application.h b/mw/em/code/em_application.h index c89bacac..faa1198b 100644 --- a/mw/em/code/em_application.h +++ b/mw/em/code/em_application.h @@ -13,9 +13,13 @@ #include #include +#include +#include // NOLINT +#include #include "core/application/application_mw.h" #include "mw/em/code/services/em/em_service.h" +#include "mw/em/code/services/exec/exec_manager.hpp" namespace simba { namespace em { class EmApplication final : public core::ApplicationMW { @@ -35,6 +39,7 @@ class EmApplication final : public core::ApplicationMW { const std::unordered_map& parms) final; service::EmService em_service{}; + mw::exec::ExecManager exec_service{}; public: EmApplication(/* args */); diff --git a/mw/em/code/services/em/BUILD b/mw/em/code/services/em/BUILD index 020a997c..14b7d8df 100644 --- a/mw/em/code/services/em/BUILD +++ b/mw/em/code/services/em/BUILD @@ -2,7 +2,6 @@ cc_library( name = "em_service", srcs = ["em_service.cc"], hdrs = [ - "app_config.h", "em_service.h", ], visibility = ["//mw/em/code:__subpackages__"], @@ -10,5 +9,14 @@ cc_library( "//core/json:simba_json", "//core/logger:Logger", # "@boost//:process", + ":em_config" ], ) + +cc_library( + name = "em_config", + hdrs = ["app_config.h"], + visibility = [ + "//mw/em/code/services/exec:__subpackages__", + ], +) diff --git a/mw/em/code/services/em/app_config.h b/mw/em/code/services/em/app_config.h index 6c64fffe..91ce175d 100644 --- a/mw/em/code/services/em/app_config.h +++ b/mw/em/code/services/em/app_config.h @@ -24,19 +24,25 @@ class AppConfig { const std::string parms_; const uint8_t startup_prio_; const uint8_t startup_after_delay_; + const uint16_t appID_; + pid_t pid{0}; public: AppConfig(const std::string &bin_path, const std::string &parms, - const uint8_t startup_prio, const uint8_t startup_after_delay) + const uint8_t startup_prio, const uint8_t startup_after_delay, const uint16_t appID) : bin_path_{bin_path}, parms_{parms}, startup_prio_{startup_prio}, - startup_after_delay_{startup_after_delay} {} + startup_after_delay_{startup_after_delay}, + appID_{appID} {} std::string GetBinPath() const { return bin_path_; } std::string GetParms() const { return parms_; } uint8_t GetStartUpPrio() const { return startup_prio_; } uint8_t GetStartUpAfterDelay() const { return startup_after_delay_; } + uint16_t GetAppID() const { return appID_; } + pid_t GetPid() { return pid; } + void SetPid(pid_t pid) { this->pid = pid; } }; } // namespace data } // namespace service diff --git a/mw/em/code/services/em/em_service.cc b/mw/em/code/services/em/em_service.cc index 75243faa..701169da 100644 --- a/mw/em/code/services/em/em_service.cc +++ b/mw/em/code/services/em/em_service.cc @@ -89,6 +89,7 @@ std::optional EmService::GetAppConfig( uint8_t prio{0}; uint8_t delay{0}; uint8_t error_count{0}; + uint16_t app_id{0}; { auto bin_path_r = obj.GetString("bin_path"); if (bin_path_r.has_value()) { @@ -126,11 +127,19 @@ std::optional EmService::GetAppConfig( ", don't have: startup_after_delay"); error_count++; } + auto app_id_r = obj.GetNumber("app_id"); + if (!app_id_r.has_value()) { + error_count++; + AppLogger::Error("Application from: " + path + + ", don't have: app_id"); + } else { + app_id = app_id_r.value(); + } } if (error_count != 0) { return {}; } else { - return std::optional{data::AppConfig{bin_path, parm, prio, delay}}; + return std::optional{data::AppConfig{bin_path, parm, prio, delay, app_id}}; } } void EmService::StartApps() noexcept { @@ -144,22 +153,48 @@ void EmService::StartApps() noexcept { } void EmService::StartApps(const uint8_t level) noexcept { - for (const auto& app : app_list) { + for (auto& app : app_list) { if (app.GetStartUpPrio() == level) { - pid_t pid; - char* app_args = new char[app.GetBinPath().size()]; - sprintf(app_args, "%s", app.GetBinPath().c_str()); // NOLINT - char* argv[] = {app_args, NULL}; - int status{0}; - status = - posix_spawn(&pid, app.GetBinPath().c_str(), NULL, NULL, argv, NULL); - delete[] app_args; - AppLogger::Info("Spawning app: " + app.GetBinPath() + - " pid: " + std::to_string(pid)); + pid_t pid = this->StartApp(app); + if (pid == 0) { + AppLogger::Error("Failed to start app"); + return; + } + app.SetPid(pid); /**todo Dodać sleep w gdy serwis oczekuje czekania*/ } } } + +std::optional EmService::RestartApp(const uint16_t appID) { + for ( auto &app : this->app_list ) { + if ( app.GetAppID() == appID ) { + if (kill(app.GetPid(), SIGKILL) != 0) { + return {}; + } + pid_t pid = this->StartApp(app); + if (pid == 0) { + AppLogger::Error("Failed to start app"); + return {}; + } + app.SetPid(pid); + return std::optional{pid}; + } + } +} + +pid_t EmService::StartApp(const simba::em::service::data::AppConfig &app) { + pid_t pid{0}; + char* app_args = new char[app.GetBinPath().size()]; + sprintf(app_args, "%s", app.GetBinPath().c_str()); // NOLINT + char* argv[] = {app_args, NULL}; + posix_spawn(&pid, app.GetBinPath().c_str(), NULL, NULL, argv, NULL); + delete[] app_args; + AppLogger::Info("Spawning app: " + app.GetBinPath() + + " pid: " + std::to_string(pid)); + return pid; + } + } // namespace service } // namespace em } // namespace simba diff --git a/mw/em/code/services/em/em_service.h b/mw/em/code/services/em/em_service.h index 7603d800..80f90079 100644 --- a/mw/em/code/services/em/em_service.h +++ b/mw/em/code/services/em/em_service.h @@ -14,8 +14,9 @@ #include #include #include +#include -#include "mw/em/code/services/em/app_config.h" +#include "app_config.h" namespace simba { namespace em { @@ -26,11 +27,15 @@ class EmService { std::vector app_list{}; bool IsSrpApp(const std::string& path) noexcept; std::optional GetAppConfig(const std::string& path) noexcept; - + pid_t StartApp(const simba::em::service::data::AppConfig &app); public: + std::vector GetAppList() { + return this->app_list; + } void LoadApps() noexcept; void StartApps() noexcept; void StartApps(const uint8_t level) noexcept; + std::optional RestartApp(const uint16_t appID); EmService(/* args */); ~EmService(); }; diff --git a/mw/em/code/services/exec/BUILD b/mw/em/code/services/exec/BUILD index e69de29b..f398e9f2 100644 --- a/mw/em/code/services/exec/BUILD +++ b/mw/em/code/services/exec/BUILD @@ -0,0 +1,29 @@ +cc_library( + name = "exec_service", + srcs = [ + "exec_manager.cpp", + ], + hdrs = [ + "exec_manager.hpp", + ], + deps = [ + "//core/application:simba_application", + "//communication-core/sockets:socket_ipc", + "//core/logger:Logger", + ":exec_status", + "//mw/em/code/services/em:em_config", + ], + visibility = [ + "//mw:__subpackages__", + ], +) + +cc_library( + name = "exec_status", + hdrs = [ + "status.hpp", + ], + visibility = [ + "//mw:__subpackages__", + ], +) diff --git a/mw/em/code/services/exec/README.md b/mw/em/code/services/exec/README.md new file mode 100644 index 00000000..697f25c5 --- /dev/null +++ b/mw/em/code/services/exec/README.md @@ -0,0 +1,6 @@ +# Exec Manager + + +## Założenia +warunki są sprawdzane co 100 ms +timestamp = 0 powoduje pominięcie sprawdzania działania tej aplikacji ( dozwolone wartości od 1 - 65535 ) \ No newline at end of file diff --git a/mw/em/code/services/exec/exec_manager.cpp b/mw/em/code/services/exec/exec_manager.cpp new file mode 100644 index 00000000..793d1947 --- /dev/null +++ b/mw/em/code/services/exec/exec_manager.cpp @@ -0,0 +1,113 @@ +/** + * @file exec_manager.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-06 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include +#include + +#include "exec_manager.hpp" + +namespace simba { +namespace mw { +namespace exec { + +std::pair> ExecManager::getStatusAndFlags(uint8_t data) { + simba::diag::exec::Status status_ = simba::diag::exec::Status(data & 0b00000111); + std::bitset<8> bits(data); + std::bitset<5> flags(bits.to_string().substr(0, 5)); + return {status_, flags}; +} + +void ExecManager::RxCallback(const std::string& ip, const std::uint16_t& port, + std::vector payload) { + if ( payload.size() <=0 ) { return; } + std::lock_guard lock(mtx); + diag::exec::ExecHeader hdr{}; + hdr.SetBuffor(payload); + AppLogger::Debug("Receive hb:"+std::to_string(hdr.GetServiceID())+ + ", timestamp:"+std::to_string(hdr.GetTimestamp())); + auto it = this->db_.find(hdr.GetServiceID()); + if (it == this->db_.end()) { + AppLogger::Warning("Invalid service id:"+std::to_string(hdr.GetServiceID())); + return; + } + auto pair = this->getStatusAndFlags(hdr.GetFlags()); + it->second.last_timestamp_time = std::chrono::high_resolution_clock::now(); + if (it->second.last_timestamp+1 != hdr.GetTimestamp() && it->second.last_timestamp != 0) { + AppLogger::Warning("Missing timestamp service_id: "+std::to_string(hdr.GetServiceID())); + } + if ( std::chrono::duration_cast(std::chrono::high_resolution_clock::now() + - it->second.last_timestamp_time).count() > 1250 ) { + it->second.invalid_timestamp_num++; + } + it->second.last_timestamp = hdr.GetTimestamp(); + if ( it->second.state != pair.first ) { + AppLogger::Info("change app "+std::to_string(it->first)+" status to "+std::to_string(it->second.state)); + it->second.state = pair.first; + } + if (it->second.flags != pair.second) { + it->second.flags = pair.second; + } +} + +void ExecManager::SetApps(std::vector apps) { + std::lock_guard lock(mtx); + for (auto app : apps) { + this->db_.insert({app.GetAppID(), Service(0)}); + } +} + +std::queue ExecManager::CheckAppCondition() { + std::lock_guard lock(mtx); + std::queue res; + for ( auto &app : this->db_ ) { + if ( app.second.last_timestamp == 0 || app.second.execState == ExecState::kRestartNeeded ) { + continue; + } + auto delta = std::chrono::duration_cast + (std::chrono::high_resolution_clock::now() - app.second.last_timestamp_time).count(); + if ( (delta > 5000 || app.second.invalid_timestamp_num > 5) + && app.second.execState != ExecState::kRestartNeeded && app.first != 258) { + AppLogger::Error("app need restart[][][][][][][][][][][]"); + res.push(app.first); + app.second.execState = ExecState::kRestartNeeded; + } + } + return res; +} + +void ExecManager::Init() { + if (this->sock_.Init(com::soc::SocketConfig{"SIMBA.EXE", 0, 0}) != core::ErrorCode::kOk) { + AppLogger::Error("failed to bind ipc"); + } else { + AppLogger::Debug("ipc bind succesfully"); + } + this->sock_.SetRXCallback( + std::bind(&ExecManager::RxCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + this->sock_.StartRXThread(); + AppLogger::Debug("finish startup exec"); +} + +void ExecManager::RestartedApp(uint16_t appID) { + for (auto& app : this->db_) { + if (app.first == appID) { + app.second.execState = ExecState::kRunning, + app.second.state = diag::exec::Status::Start_up; + app.second.last_timestamp = 0; + app.second.flags = 0; + app.second.invalid_timestamp_num = 0; + } + } +} + +} // namespace exec +} // namespace mw +} // namespace simba diff --git a/mw/em/code/services/exec/exec_manager.hpp b/mw/em/code/services/exec/exec_manager.hpp new file mode 100644 index 00000000..0483e00d --- /dev/null +++ b/mw/em/code/services/exec/exec_manager.hpp @@ -0,0 +1,111 @@ +/** + * @file exec_manager.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-06 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_EM_CODE_SERVICES_EXEC_EXEC_MANAGER_HPP_ +#define MW_EM_CODE_SERVICES_EXEC_EXEC_MANAGER_HPP_ + +#include +#include +#include +#include // NOLINT +#include +#include +#include +#include +#include + +#include "communication-core/sockets/ipc_socket.h" +#include "diag/exec/controller/exec_controller.hpp" +#include "mw/em/code/services/em/app_config.h" +#include "diag/exec/data/exec_header.hpp" +#include "core/logger/Logger.h" + +namespace simba { +namespace mw { +namespace exec { + +enum ExecState { + kRunning, + kRestartNeeded, +}; + + +struct Service{ + /** + * @brief numer ostatniego timestamp + */ + uint16_t last_timestamp{0}; + /** + * @brief czas otrzymania ostatniego hb + * + */ + std::chrono::_V2::system_clock::time_point last_timestamp_time{}; + /** + * @brief liczba hb otrzymanych w niepoprawnym czasie + * + */ + uint8_t invalid_timestamp_num{0}; + /** + * @brief status aplikacji + * + */ + diag::exec::Status state{diag::exec::Status::Start_up}; + /** + * @brief dodatkowe flagi + * + */ + std::bitset<5> flags{0}; + + /** + * @brief Stan aplikacji według em application + * + */ + ExecState execState{ExecState::kRunning}; + + + Service() {} + explicit Service(uint16_t timestamp) { + this->last_timestamp = timestamp; + this->last_timestamp_time = std::chrono::high_resolution_clock::now(); + } + Service(uint16_t timestamp, diag::exec::Status status) { + this->last_timestamp = timestamp; + this->last_timestamp_time = std::chrono::high_resolution_clock::now(); + this->state = status; + } + Service(uint16_t timestamp, diag::exec::Status status, std::bitset<5> flags) { + this->last_timestamp = timestamp; + this->last_timestamp_time = std::chrono::high_resolution_clock::now(); + this->state = status; + this->flags = flags; + } +}; + +class ExecManager{ + private: + com::soc::IpcSocket sock_; + std::mutex mtx; + std::unordered_map db_; + void RxCallback(const std::string& ip, const std::uint16_t& port, + std::vector payload); + std::pair> getStatusAndFlags(uint8_t data); + public: + std::queue CheckAppCondition(); + void SetApps(std::vector apps); + void Init(); + void RestartedApp(uint16_t appID); +}; + +} // namespace exec +} // namespace mw +} // namespace simba + +#endif // MW_EM_CODE_SERVICES_EXEC_EXEC_MANAGER_HPP_ diff --git a/mw/em/code/services/exec/status.hpp b/mw/em/code/services/exec/status.hpp new file mode 100644 index 00000000..346e0ceb --- /dev/null +++ b/mw/em/code/services/exec/status.hpp @@ -0,0 +1,34 @@ +/** + * @file status.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-09 + * + * @copyright Copyright (c) 2024 + * +*/ + +#ifndef MW_EM_CODE_SERVICES_EXEC_STATUS_HPP_ +#define MW_EM_CODE_SERVICES_EXEC_STATUS_HPP_ + +namespace simba { +namespace diag { +namespace exec { + +enum Status { + Start_up = 0x00, + Running = 0x01, + Running_with_dtc = 0x02, + Running_after_dtc = 0x03, + Error = 0x04, + Running_after_error = 0x05, + Running_ignore_DTC = 0x06, + Running_ignore_error = 0x07 +}; + +} // namespace exec +} // namespace diag +} // namespace simba + +#endif // MW_EM_CODE_SERVICES_EXEC_STATUS_HPP_ diff --git a/mw/gpio_server/BUILD b/mw/gpio_server/BUILD index 3de22557..ade4adfe 100644 --- a/mw/gpio_server/BUILD +++ b/mw/gpio_server/BUILD @@ -12,6 +12,9 @@ cc_library( "//core/application:simba_application", "//core/json:simba_json", ], + visibility = [ + "//mw/gpio_server/tests:__subpackages__", + ], ) cc_binary( diff --git a/mw/gpio_server/controller/BUILD b/mw/gpio_server/controller/BUILD index be70fef6..8c951992 100644 --- a/mw/gpio_server/controller/BUILD +++ b/mw/gpio_server/controller/BUILD @@ -10,5 +10,6 @@ cc_library( hdrs = ["gpio_controller.hpp"], visibility = [ "//apps:__subpackages__", + "//mw:__subpackages__", ], ) \ No newline at end of file diff --git a/mw/gpio_server/controller/gpio_controller.cpp b/mw/gpio_server/controller/gpio_controller.cpp index 159e82c6..c9297ac1 100644 --- a/mw/gpio_server/controller/gpio_controller.cpp +++ b/mw/gpio_server/controller/gpio_controller.cpp @@ -19,16 +19,31 @@ namespace simba { namespace gpio { -void GPIOController::Init(uint16_t service_id) { + +GPIOController::GPIOController(com::soc::ISocket* socket) { + this->sock_ = socket; +} +GPIOController::GPIOController() { + this->sock_ = new com::soc::IpcSocket(); +} + +core::ErrorCode GPIOController::Init(uint16_t service_id) { this->service_id = service_id; + return core::ErrorCode::kOk; } core::ErrorCode GPIOController::SetPinValue(uint16_t pinID, Value value) { + if (value == Value::ERROR) { + return core::ErrorCode::kError; + } + if (this->sock_== nullptr) { + return core::ErrorCode::kInitializeError; + } gpio::Header hdr(this->service_id, pinID, value); - return this->sock_.Transmit("SIMBA.GPIO.SET", 0, hdr.GetBuffor()); + return this->sock_->Transmit("SIMBA.GPIO.SET", 0, hdr.GetBuffor()); } -Value GPIOController::GetPinValue(uint16_t pinID) { +Value GPIOController::GetPinValue(uint16_t actuatorID) { return Value::HIGH; } diff --git a/mw/gpio_server/controller/gpio_controller.hpp b/mw/gpio_server/controller/gpio_controller.hpp index 5a9e01cd..0bd92994 100644 --- a/mw/gpio_server/controller/gpio_controller.hpp +++ b/mw/gpio_server/controller/gpio_controller.hpp @@ -26,18 +26,21 @@ namespace simba { namespace gpio { enum Value{ + ERROR = -1, LOW = 0, HIGH = 1, }; class GPIOController { private: - com::soc::IpcSocket sock_; + com::soc::ISocket* sock_; uint16_t service_id; public: + explicit GPIOController(com::soc::ISocket* socket); + GPIOController(); core::ErrorCode SetPinValue(uint16_t pinID, Value value); Value GetPinValue(uint16_t pinID); - void Init(uint16_t service_id); + core::ErrorCode Init(uint16_t service_id); }; } // namespace gpio diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp index 5618314b..6c626b96 100644 --- a/mw/gpio_server/gpio_mw.cpp +++ b/mw/gpio_server/gpio_mw.cpp @@ -26,9 +26,6 @@ namespace mw { void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, const std::vector data) { - if (data.size() <= 0) { - return; - } gpio::Header hdr(0, 0, 0); hdr.SetBuffor(data); auto it = this->config.find(hdr.GetPinID()); @@ -38,6 +35,7 @@ void GPIOMWService::RxCallback(const std::string& ip, const std::uint16_t& port, } if (it->second.direction != core::gpio::direction_t::OUT) { AppLogger::Warning("Try to set IN pin value, ID: "+std::to_string(hdr.GetPinID())); + return; } if (this->gpio_driver_.getValue(it->second.pinNum) != hdr.GetValue()) { AppLogger::Debug("set pin to position:"+std::to_string(hdr.GetValue())); diff --git a/mw/gpio_server/tests/BUILD b/mw/gpio_server/tests/BUILD index 65954555..843c9711 100644 --- a/mw/gpio_server/tests/BUILD +++ b/mw/gpio_server/tests/BUILD @@ -9,3 +9,16 @@ cc_test( "//mw/gpio_server/data:gpio_hdr" ] ) + +cc_test( + name = "gpio_controller", + srcs = [ + "test_controller.cpp", + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//mw/gpio_server/controller:gpio_controller", + "//communication-core/sockets/mock:mock_socket", + ] +) diff --git a/mw/gpio_server/tests/test_controller.cpp b/mw/gpio_server/tests/test_controller.cpp new file mode 100644 index 00000000..656d6d64 --- /dev/null +++ b/mw/gpio_server/tests/test_controller.cpp @@ -0,0 +1,29 @@ +/** + * @file test_controller.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ +#include "gtest/gtest.h" + +#include "mw/gpio_server/controller/gpio_controller.hpp" +#include "communication-core/sockets/mock/mockSocket.h" +#include "core/common/error_code.h" + +using ::testing::_; +using ::testing::Return; + +TEST(GPIO_CONTROLLER, TESTS) { + MockSocket sock_; + ON_CALL(sock_, Transmit(_, _, _)) + .WillByDefault(Return(simba::core::ErrorCode::kOk)); + simba::gpio::GPIOController gpio_(&sock_); + EXPECT_EQ(gpio_.SetPinValue(12, simba::gpio::Value::HIGH), simba::core::ErrorCode::kOk); + EXPECT_EQ(gpio_.SetPinValue(14, simba::gpio::Value::ERROR), simba::core::ErrorCode::kError); + EXPECT_EQ(gpio_.GetPinValue(21), simba::gpio::Value::HIGH); + EXPECT_EQ(gpio_.Init(12), simba::core::ErrorCode::kOk); +} diff --git a/tools/ut/unittest.sh b/tools/ut/unittest.sh new file mode 100755 index 00000000..64270633 --- /dev/null +++ b/tools/ut/unittest.sh @@ -0,0 +1,2 @@ +#!/bin/bash +bazel test `bazel query 'kind(cc_.*, tests(//...))'` \ No newline at end of file From adcc44cdb876286be2bdab5454a3a54b3b2c32bc Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sat, 6 Apr 2024 21:25:06 +0200 Subject: [PATCH 39/71] submodule update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 84532d72..99a1f00b 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 84532d7215b0b9bbe20e1a98640e46624388ad9b +Subproject commit 99a1f00b7710c1662b702da88405162c4e4a5a26 From bd4fa2449b578f508cac8c5a130c83734aa4c2b2 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sat, 6 Apr 2024 22:22:25 +0200 Subject: [PATCH 40/71] added fake dtc --- apps/example/BUILD | 1 + apps/example/router.cc | 9 +++- .../someip-database/code/database.cc | 1 + core/application/BUILD | 1 + core/application/application_common.cc | 26 +++++++++ core/application/application_common.h | 6 ++- deployment | 2 +- diag/controller/BUILD | 9 ++++ diag/controller/diag_controller.h | 36 +++++++++++++ diag/dtc/controller/BUILD | 31 ++++++++--- ..._dtc_controller.hpp => I_dtc_controller.h} | 27 +++++----- diag/dtc/controller/dtc.h | 39 ++++++++++++++ diag/dtc/controller/dtc_controller.cpp | 34 +++++++----- diag/dtc/controller/dtc_controller.h | 42 +++++++++++++++ diag/dtc/controller/dtc_controller.hpp | 53 ------------------- diag/dtc/controller/i_dtc.h | 34 ++++++++++++ 16 files changed, 257 insertions(+), 94 deletions(-) create mode 100644 diag/controller/BUILD create mode 100644 diag/controller/diag_controller.h rename diag/dtc/controller/{I_dtc_controller.hpp => I_dtc_controller.h} (50%) create mode 100644 diag/dtc/controller/dtc.h create mode 100644 diag/dtc/controller/dtc_controller.h delete mode 100644 diag/dtc/controller/dtc_controller.hpp create mode 100644 diag/dtc/controller/i_dtc.h diff --git a/apps/example/BUILD b/apps/example/BUILD index 40b8d477..0ce459b3 100644 --- a/apps/example/BUILD +++ b/apps/example/BUILD @@ -10,6 +10,7 @@ cc_binary( "//communication-core/someip-controller:proxy", "//communication-core/someip-controller:skeleton", "//core/application:simba_application", + "//diag/dtc/controller:diag_dtc_", "//mw/gpio_server/controller:gpio_controller", "@untar", ], diff --git a/apps/example/router.cc b/apps/example/router.cc index 842e5ab8..072c5a9d 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -16,6 +16,7 @@ #include "communication-core/someip-controller/event_proxy.h" #include "communication-core/someip-controller/method_skeleton.h" #include "core/logger/Logger.h" +#include "diag/dtc/controller/dtc.h" namespace simba { namespace router { @@ -32,12 +33,16 @@ core::ErrorCode Router::Run(std::stop_token token) { com->Add(example); com->Add(proxy_event); proxy_event->StartFindService(); + auto dtc = std::make_shared(20); + diag_controller.RegisterDTC(dtc); while (true) { AppLogger::Debug("AppLogger::Debug"); AppLogger::Info("AppLogger::Info"); + dtc->Pass(); this->gpio_.SetPinValue(1, gpio::Value::HIGH); std::this_thread::sleep_for(std::chrono::seconds(1)); this->gpio_.SetPinValue(1, gpio::Value::LOW); + dtc->Failed(); std::this_thread::sleep_for(std::chrono::seconds(1)); } return core::ErrorCode::kOk; @@ -45,8 +50,8 @@ core::ErrorCode Router::Run(std::stop_token token) { core::ErrorCode Router::Initialize( const std::unordered_map& parms) { - this->gpio_ = gpio::GPIOController(new com::soc::IpcSocket()); - this->gpio_.Init(12); + this->gpio_ = gpio::GPIOController(new com::soc::IpcSocket()); + this->gpio_.Init(12); return core::ErrorCode::kOk; } } // namespace router diff --git a/communication-core/someip-database/code/database.cc b/communication-core/someip-database/code/database.cc index c2de1314..bb69c2b5 100644 --- a/communication-core/someip-database/code/database.cc +++ b/communication-core/someip-database/code/database.cc @@ -65,6 +65,7 @@ core::ErrorCode DataBase::InsertInterface(const std::string& ip, } core::ErrorCode DataBase::SetServiceId(const uint16_t id) noexcept { this->service_id = id; + return core::ErrorCode::kOk; } uint16_t DataBase::GetServiceId() const noexcept { return this->service_id; } diff --git a/core/application/BUILD b/core/application/BUILD index 2564c1cf..f4c3e9d4 100644 --- a/core/application/BUILD +++ b/core/application/BUILD @@ -18,6 +18,7 @@ cc_library( "//core/common:common_types", "//core/json:simba_json", "//core/logger:Logger", + "//diag/controller:diag_controller", "//diag/exec/controller:diag_exec_controller", "@boost//:algorithm", "@com_json//:json", diff --git a/core/application/application_common.cc b/core/application/application_common.cc index 1d128655..a8883a92 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -67,6 +67,7 @@ void ApplicationCommon::onRun( std::abort(); } this->SomeIPConfig(parms); + this->DiagConfig(parms); AppLogger::Info("Application initialize"); this->Initialize(parms); AppLogger::Info("Application running"); @@ -92,6 +93,7 @@ ErrorCode ApplicationCommon::CommonConfig( if (data.contains("app_id")) { if (data.at("app_id").is_string()) { app_id = data.at("app_id"); + } else { res = ErrorCode::kError; } @@ -157,6 +159,30 @@ ErrorCode ApplicationCommon::SomeIPConfig( return ErrorCode::kOk; } +ErrorCode ApplicationCommon::DiagConfig( + const std::unordered_map& parms) { + std::ifstream file{"/opt/" + parms.at("app_name") + "/etc/srp_app.json"}; + if (!file.is_open()) { + std::cerr << "App config file not exist! -> " + << "/opt/" + parms.at("app_name") + "/etc/srp_app.json" + << std::endl; + return ErrorCode::kError; + } + nlohmann::json data = nlohmann::json::parse(file); + uint16_t app_id_{}; + if (data.contains("app_id")) { + if (data.at("app_id").is_string()) { + app_id_ = data.at("app_id"); + diag_controller.Init(app_id_); + return ErrorCode::kOk; + } else { + return ErrorCode::kError; + } + } else { + return ErrorCode::kError; + } +} + ApplicationCommon::~ApplicationCommon() {} } // namespace core } // namespace simba diff --git a/core/application/application_common.h b/core/application/application_common.h index aa840915..7233ef6a 100644 --- a/core/application/application_common.h +++ b/core/application/application_common.h @@ -18,13 +18,15 @@ #include // NOLINT #include +#include "communication-core/someip-controller/controller.h" #include "core/application/Iapplication.h" +#include "diag/controller/diag_controller.h" #include "diag/exec/controller/exec_controller.hpp" -#include "communication-core/someip-controller/controller.h" namespace simba { namespace core { class ApplicationCommon : public IApplication { protected: + diag::CommonDiagController diag_controller{}; std::stop_source source; diag::exec::ExecController exec_; std::unique_ptr com; @@ -41,6 +43,8 @@ class ApplicationCommon : public IApplication { const std::unordered_map& parms); ErrorCode SomeIPConfig( const std::unordered_map& parms); + ErrorCode DiagConfig( + const std::unordered_map& parms); bool FileExist(const std::string& name); public: diff --git a/deployment b/deployment index 99a1f00b..02f7cee1 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 99a1f00b7710c1662b702da88405162c4e4a5a26 +Subproject commit 02f7cee1cb53ac724ed58a3050e9e44ef06890cc diff --git a/diag/controller/BUILD b/diag/controller/BUILD new file mode 100644 index 00000000..6509a2bb --- /dev/null +++ b/diag/controller/BUILD @@ -0,0 +1,9 @@ +cc_library( + name = "diag_controller", + hdrs = ["diag_controller.h"], + visibility = ["//visibility:public"], + deps = [ + "//diag/dtc/controller:diag_dtc_I_controller", + "//diag/dtc/controller:diag_dtc_controller", + ], +) diff --git a/diag/controller/diag_controller.h b/diag/controller/diag_controller.h new file mode 100644 index 00000000..45e969e9 --- /dev/null +++ b/diag/controller/diag_controller.h @@ -0,0 +1,36 @@ +/** + * @file diag_controller.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-06 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef DIAG_CONTROLLER_DIAG_CONTROLLER_H_ +#define DIAG_CONTROLLER_DIAG_CONTROLLER_H_ + +#include + +#include "diag/dtc/controller/dtc_controller.h" +#include "diag/dtc/controller/i_dtc.h" + +namespace simba { +namespace diag { + +class CommonDiagController { + public: + core::ErrorCode RegisterDTC(std::weak_ptr dtc_object) { + this->dtc_controller.RegisterDTC(dtc_object); + return core::ErrorCode::kOk; + } + void Init(uint16_t service_id) { dtc_controller.Init(service_id); } + + private: + dtc::DtcController dtc_controller{}; +}; +} // namespace diag +} // namespace simba + +#endif // DIAG_CONTROLLER_DIAG_CONTROLLER_H_ diff --git a/diag/dtc/controller/BUILD b/diag/dtc/controller/BUILD index 30e882bd..dc162d7c 100644 --- a/diag/dtc/controller/BUILD +++ b/diag/dtc/controller/BUILD @@ -1,21 +1,36 @@ cc_library( name = "diag_dtc_controller", srcs = ["dtc_controller.cpp"], - hdrs = ["dtc_controller.hpp"], - deps=[ + hdrs = ["dtc_controller.h"], + visibility = ["//visibility:public"], + deps = [ ":diag_dtc_I_controller", + "//core/logger:Logger", + "//diag/dtc/data:diag_dtc_data_structure", "//diag/dtc/factories:diag_dtc_msg_factory", - "//diag/dtc/data:diag_dtc_data_structure" ], - visibility = ["//visibility:public"], ) cc_library( name = "diag_dtc_I_controller", - hdrs = ["I_dtc_controller.hpp"], - deps=[ + hdrs = [ + "I_dtc_controller.h", + "i_dtc.h", + ], + visibility = ["//visibility:public"], + deps = [ "//communication-core/sockets:socket_interface", - "//communication-core/sockets:socket_ipc" + "//communication-core/sockets:socket_ipc", + ], +) + +cc_library( + name = "diag_dtc_", + hdrs = [ + "dtc.h", ], visibility = ["//visibility:public"], -) \ No newline at end of file + deps = [ + "//diag/dtc/controller:diag_dtc_I_controller", + ], +) diff --git a/diag/dtc/controller/I_dtc_controller.hpp b/diag/dtc/controller/I_dtc_controller.h similarity index 50% rename from diag/dtc/controller/I_dtc_controller.hpp rename to diag/dtc/controller/I_dtc_controller.h index ff991566..9b17a3ce 100644 --- a/diag/dtc/controller/I_dtc_controller.hpp +++ b/diag/dtc/controller/I_dtc_controller.h @@ -1,39 +1,36 @@ /** * @file I_dtc_controller.hpp * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-01-03 - * + * * @copyright Copyright (c) 2024 - * + * */ +#ifndef DIAG_DTC_CONTROLLER_I_DTC_CONTROLLER_H_ +#define DIAG_DTC_CONTROLLER_I_DTC_CONTROLLER_H_ -#ifndef DIAG_DTC_CONTROLLER_I_DTC_CONTROLLER_HPP_ -#define DIAG_DTC_CONTROLLER_I_DTC_CONTROLLER_HPP_ - -#include #include +#include -#include "core/common/error_code.h" #include "communication-core/sockets/socket_config.h" +#include "core/common/error_code.h" +#include "diag/dtc/controller/i_dtc.h" namespace simba { namespace diag { namespace dtc { -class IDtcController{ +class IDtcController { public: - virtual void Init(std::shared_ptr config) = 0; - - virtual core::ErrorCode RegisterError(const uint16_t &dtc_error_id, - const std::vector &payload, const uint8_t &dtc_status) = 0; + virtual void Init(uint16_t service_id) = 0; + virtual core::ErrorCode RegisterDTC(std::weak_ptr dtc_object) = 0; }; } // namespace dtc } // namespace diag } // namespace simba - -#endif // DIAG_DTC_CONTROLLER_I_DTC_CONTROLLER_HPP_ +#endif // DIAG_DTC_CONTROLLER_I_DTC_CONTROLLER_H_ diff --git a/diag/dtc/controller/dtc.h b/diag/dtc/controller/dtc.h new file mode 100644 index 00000000..61ca7b6f --- /dev/null +++ b/diag/dtc/controller/dtc.h @@ -0,0 +1,39 @@ +/** + * @file dtc.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-06 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef DIAG_DTC_CONTROLLER_DTC_H_ +#define DIAG_DTC_CONTROLLER_DTC_H_ + +#include "diag/dtc/controller/i_dtc.h" + +namespace simba { +namespace diag { +namespace dtc { +class DTCObject : public IDTC { + protected: + const uint8_t id; + DTCSendCallback callback; + + public: + void Pass() const noexcept { callback(id, 2U); } + void Failed() const noexcept { callback(id, 1U); } + explicit DTCObject(const uint16_t id_) : id{id_} {} + void SetCallback(DTCSendCallback callback_) noexcept override { + callback = callback_; + callback(id, 0U); + } + uint16_t GetId() const override { return id; } +}; + +} // namespace dtc +} // namespace diag +} // namespace simba + +#endif // DIAG_DTC_CONTROLLER_DTC_H_ diff --git a/diag/dtc/controller/dtc_controller.cpp b/diag/dtc/controller/dtc_controller.cpp index 4b8462c6..c5a2693b 100644 --- a/diag/dtc/controller/dtc_controller.cpp +++ b/diag/dtc/controller/dtc_controller.cpp @@ -1,35 +1,41 @@ /** * @file dtc_controller.cpp * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-01-03 - * + * * @copyright Copyright (c) 2024 - * + * */ -#include "diag/dtc/controller/dtc_controller.hpp" -#include "diag/dtc/data/dtc_header.hpp" +#include "diag/dtc/controller/dtc_controller.h" #include +#include "core/logger/Logger.h" +#include "diag/dtc/data/dtc_header.hpp" namespace simba { namespace diag { namespace dtc { -void DtcController::Init( - std::shared_ptr config) { - this->sock_.Init(*config.get()); +void DtcController::Init(uint16_t service_id) { + // this->sock_.Init(*config.get()); + this->service_id = service_id; } -core::ErrorCode DtcController::RegisterError(const uint16_t &dtc_error_id, - const std::vector &payload, const uint8_t &dtc_status) { - DtcHeader hdr{dtc_error_id, dtc_status}; - std::vector data = this->factory_.GetBuffer( - std::make_shared(hdr), payload); - return this->sock_.Transmit("SIMBA.DIAG.DTC", 0, data); +core::ErrorCode DtcController::RegisterDTC(std::weak_ptr dtc_object) { + dtc_object.lock()->SetCallback(std::bind(&DtcController::RXCallback, this, + std::placeholders::_1, + std::placeholders::_2)); + AppLogger::Info("[DTC]: New DTC added: " + + std::to_string(dtc_object.lock()->GetId())); + return core::ErrorCode::kOk; } +void DtcController::RXCallback(const uint8_t& dtc_id, const uint8_t& flag) { + AppLogger::Info("[DTC]: State changed for " + std::to_string(dtc_id) + + " new status " + std::to_string(flag)); +} } // namespace dtc } // namespace diag diff --git a/diag/dtc/controller/dtc_controller.h b/diag/dtc/controller/dtc_controller.h new file mode 100644 index 00000000..7435e8f9 --- /dev/null +++ b/diag/dtc/controller/dtc_controller.h @@ -0,0 +1,42 @@ +/** + * @file dtc_controller.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-01-03 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef DIAG_DTC_CONTROLLER_DTC_CONTROLLER_H_ +#define DIAG_DTC_CONTROLLER_DTC_CONTROLLER_H_ + +#include +#include + +#include "communication-core/sockets/ipc_socket.h" +#include "diag/dtc/controller/I_dtc_controller.h" +#include "diag/dtc/factories/dtc_msg_factory.hpp" + +namespace simba { +namespace diag { +namespace dtc { + +class DtcController : public IDtcController { + public: + core::ErrorCode RegisterDTC(std::weak_ptr dtc_object) override; + void Init(uint16_t service_id) override; + + private: + void RXCallback(const uint8_t& dtc_id, const uint8_t& flag); + com::soc::IpcSocket sock_; + static DtcMsgFactory factory_; + uint16_t service_id; +}; + +} // namespace dtc +} // namespace diag +} // namespace simba + +#endif // DIAG_DTC_CONTROLLER_DTC_CONTROLLER_H_ diff --git a/diag/dtc/controller/dtc_controller.hpp b/diag/dtc/controller/dtc_controller.hpp deleted file mode 100644 index 1bd15875..00000000 --- a/diag/dtc/controller/dtc_controller.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file dtc_controller.hpp - * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief - * @version 0.1 - * @date 2024-01-03 - * - * @copyright Copyright (c) 2024 - * - */ - -#ifndef DIAG_DTC_CONTROLLER_DTC_CONTROLLER_HPP_ -#define DIAG_DTC_CONTROLLER_DTC_CONTROLLER_HPP_ - -#include -#include - -#include "diag/dtc/controller/I_dtc_controller.hpp" -#include "communication-core/sockets/ipc_socket.h" -#include "diag/dtc/factories/dtc_msg_factory.hpp" - -namespace simba { -namespace diag { -namespace dtc { - -class DtcController:public IDtcController{ - public: - /** - * @brief zgłaszanie błędów do DTC service - * - * @param dtc_error_id kod błędu - * @param dtc_status flagi błędu - * @param payload dodatkowe dane - * @return core::ErrorCode - */ - core::ErrorCode RegisterError(const uint16_t &dtc_error_id, - const std::vector &payload, const uint8_t &dtc_status) override; - void Init(std::shared_ptr config) override; - - private: - com::soc::IpcSocket sock_; - static DtcMsgFactory factory_; - static const uint16_t service_id = 0x0101; -}; - - -} // namespace dtc -} // namespace diag -} // namespace simba - - - -#endif // DIAG_DTC_CONTROLLER_DTC_CONTROLLER_HPP_ diff --git a/diag/dtc/controller/i_dtc.h b/diag/dtc/controller/i_dtc.h new file mode 100644 index 00000000..484b3377 --- /dev/null +++ b/diag/dtc/controller/i_dtc.h @@ -0,0 +1,34 @@ +/** + * @file i_dtc.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-06 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef DIAG_DTC_CONTROLLER_I_DTC_H_ +#define DIAG_DTC_CONTROLLER_I_DTC_H_ + +#include +#include + +#include "core/common/error_code.h" + +namespace simba { +namespace diag { +namespace dtc { +using DTCSendCallback = + std::function; + +class IDTC { + public: + virtual void SetCallback(DTCSendCallback callback) noexcept = 0; + virtual uint16_t GetId() const = 0; +}; + +} // namespace dtc +} // namespace diag +} // namespace simba +#endif // DIAG_DTC_CONTROLLER_I_DTC_H_ From 90ba1b9c09d43ef34495c0b6771fbff58ad2f529 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Mon, 25 Mar 2024 16:11:44 +0100 Subject: [PATCH 41/71] Check --- .github/workflows/build_cpu.yaml | 36 ++++++++++++++++++++++++++ .github/workflows/build_cpu_linux.yaml | 15 ++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 3002c588..05613f69 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -22,6 +22,26 @@ jobs: with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} + + - name: RM 1 + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + uses: thollander/actions-comment-pull-request@v2 + with: + message: | + Successfully built software for BeagleBone (EC) + comment_tag: to_delete + mode: delete + + - name: RM 2 + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + uses: thollander/actions-comment-pull-request@v2 + with: + message: | + Successfully built software for BeagleBone (FC) + comment_tag: to_delete + mode: delete + + - name: Install bazel if: contains(steps.pr-labels.outputs.labels, 'check-bbb') run: | @@ -38,6 +58,22 @@ jobs: if: contains(steps.pr-labels.outputs.labels, 'check-bbb') run: | bazel build --config=bbb //deployment/cpu/ec:pkg + - name: Add msg + if: contains(steps.pr-labels.outputs.labels, 'check') + uses: thollander/actions-comment-pull-request@v2 + with: + message: | + Successfully built software for BeagleBone (EC) + - name: Run build flight computer + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + run: | + bazel build --config=bbb //deployment/cpu/fc:pkg + - name: Add msg_2 + if: contains(steps.pr-labels.outputs.labels, 'check') + uses: thollander/actions-comment-pull-request@v2 + with: + message: | + Successfully built software for BeagleBone (FC) \ No newline at end of file diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index 42eba72f..f1b8c925 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -21,7 +21,14 @@ jobs: with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} - + - name: RM 1 + if: contains(steps.pr-labels.outputs.labels, 'check-bbb') + uses: thollander/actions-comment-pull-request@v2 + with: + message: | + Successfully built software for linux + comment_tag: to_delete + mode: delete - name: Install bazel if: contains(steps.pr-labels.outputs.labels, 'check') run: | @@ -38,5 +45,11 @@ jobs: if: contains(steps.pr-labels.outputs.labels, 'check') run: | bazel build //deployment/cpu/ec:pkg + - name: Add msg + if: contains(steps.pr-labels.outputs.labels, 'check') + uses: thollander/actions-comment-pull-request@v2 + with: + message: | + Successfully built software for linux \ No newline at end of file From e16df1dfe7aeff554fca16545e0b5b9427a2db4d Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Wed, 10 Apr 2024 21:51:07 +0200 Subject: [PATCH 42/71] submodule update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 02f7cee1..efca4c0d 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 02f7cee1cb53ac724ed58a3050e9e44ef06890cc +Subproject commit efca4c0d374b485c2edd65feeed8f1770334ba54 From 470d6dc84f30ecb7e99f28aa7b24564a8f0affe0 Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Fri, 12 Apr 2024 16:09:19 +0200 Subject: [PATCH 43/71] temp_service_made_by_mmatuszewsky (#59) * configSensors * temp_controller + add temp to env Service * add dtc --- apps/env_service/BUILD | 19 +++ apps/env_service/env_service.cpp | 91 ++++++++++ apps/env_service/env_service.hpp | 62 +++++++ apps/env_service/main.cpp | 18 ++ apps/example/router.cc | 2 +- deployment | 2 +- diag/exec/controller/exec_controller.cpp | 4 + diag/exec/controller/exec_controller.hpp | 1 + mw/em/code/em_application.cc | 1 + mw/temp/controller/BUILD | 25 +++ mw/temp/controller/temp_controller.cpp | 72 ++++++++ mw/temp/controller/temp_controller.h | 56 +++++++ mw/temp/service/BUILD | 25 +++ mw/temp/service/main.cc | 18 ++ mw/temp/service/temp_service.cpp | 158 ++++++++++++++++++ mw/temp/service/temp_service.h | 87 ++++++++++ mw/temp/subscribe_msg/BUILD | 24 +++ mw/temp/subscribe_msg/subscribe_header.cpp | 47 ++++++ mw/temp/subscribe_msg/subscribe_header.h | 43 +++++ .../subscribe_msg/subscribe_msg_factory.cpp | 48 ++++++ mw/temp/subscribe_msg/subscribe_msg_factory.h | 57 +++++++ mw/temp/temp_reading_msg/BUILD | 9 + .../temp_reading_msg_factory.cpp | 62 +++++++ .../temp_reading_msg_factory.h | 50 ++++++ mw/temp/tests/BUILD | 30 ++++ mw/temp/tests/test_subscribe_msg.cpp | 21 +++ mw/temp/tests/test_subscribe_msg_factory.cpp | 26 +++ .../tests/test_temp_reading_msg_factory.cpp | 29 ++++ 28 files changed, 1085 insertions(+), 2 deletions(-) create mode 100644 apps/env_service/BUILD create mode 100644 apps/env_service/env_service.cpp create mode 100644 apps/env_service/env_service.hpp create mode 100644 apps/env_service/main.cpp create mode 100644 mw/temp/controller/BUILD create mode 100644 mw/temp/controller/temp_controller.cpp create mode 100644 mw/temp/controller/temp_controller.h create mode 100644 mw/temp/service/BUILD create mode 100644 mw/temp/service/main.cc create mode 100644 mw/temp/service/temp_service.cpp create mode 100644 mw/temp/service/temp_service.h create mode 100644 mw/temp/subscribe_msg/BUILD create mode 100644 mw/temp/subscribe_msg/subscribe_header.cpp create mode 100644 mw/temp/subscribe_msg/subscribe_header.h create mode 100644 mw/temp/subscribe_msg/subscribe_msg_factory.cpp create mode 100644 mw/temp/subscribe_msg/subscribe_msg_factory.h create mode 100644 mw/temp/temp_reading_msg/BUILD create mode 100644 mw/temp/temp_reading_msg/temp_reading_msg_factory.cpp create mode 100644 mw/temp/temp_reading_msg/temp_reading_msg_factory.h create mode 100644 mw/temp/tests/BUILD create mode 100644 mw/temp/tests/test_subscribe_msg.cpp create mode 100644 mw/temp/tests/test_subscribe_msg_factory.cpp create mode 100644 mw/temp/tests/test_temp_reading_msg_factory.cpp diff --git a/apps/env_service/BUILD b/apps/env_service/BUILD new file mode 100644 index 00000000..9e6d2760 --- /dev/null +++ b/apps/env_service/BUILD @@ -0,0 +1,19 @@ +cc_binary( + name = "env_service", + srcs = [ + "main.cpp", + "env_service.cpp", + "env_service.hpp" + ], + visibility = [ + "//deployment/apps:__subpackages__" + ], + deps = [ + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", + "//core/application:simba_application", + "//mw/temp/controller:temp_controller_mw", + "//diag/dtc/controller:diag_dtc_", + "@untar", + ], +) \ No newline at end of file diff --git a/apps/env_service/env_service.cpp b/apps/env_service/env_service.cpp new file mode 100644 index 00000000..3ed707c3 --- /dev/null +++ b/apps/env_service/env_service.cpp @@ -0,0 +1,91 @@ +/** + * @file env_service.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-04 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include "apps/env_service/env_service.hpp" +#include "mw/temp/temp_reading_msg/temp_reading_msg_factory.h" + +namespace simba { +namespace envService { + + +std::vector convertPayload(const double &value) { + std::vector bytes; + bytes.resize(sizeof(int16_t)); + const int16_t floatValue = static_cast(value * 10); + std::memcpy(bytes.data(), &floatValue, sizeof(int16_t)); + return bytes; +} + +core::ErrorCode EnvService::Run(std::stop_token token) { + this->SleepMainThread(); + return core::ErrorCode::kOk; +} + +core::ErrorCode EnvService::Initialize( + const std::unordered_map& parms) { + core::ErrorCode res; + this->temp1_event = std::make_shared("EnvApp/newTempEvent_1"); + this->temp2_event = std::make_shared("EnvApp/newTempEvent_2"); + this->temp3_event = std::make_shared("EnvApp/newTempEvent_3"); + this->dtc_temp_error = std::make_shared(0x20); + this->dtc_temp_connection_error_0xB0 = std::make_shared(0xB0); + diag_controller.RegisterDTC(dtc_temp_connection_error_0xB0); + diag_controller.RegisterDTC(dtc_temp_error); + uint8_t i = 0; + do { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + res = this->temp_.Init(514, std::bind(&EnvService::TempRxCallback, + this, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)); + } while (res != core::ErrorCode::kOk && i < 6); + if (res != core::ErrorCode::kOk) { + this->dtc_temp_connection_error_0xB0->Failed(); + return res; + } + return core::ErrorCode::kOk; +} +bool EnvService::CheckTempError(const double &value) { + if (value > 120 || value <-30) { + dtc_temp_error->Failed(); + return false; + } else { + dtc_temp_error->Pass(); + return true; + } +} + +void EnvService::TempRxCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data) { + mw::temp::TempReadingMsgFactory factory_; + auto hdrs = factory_.GetPayload(data); + for (auto &hdr : hdrs) { + this->CheckTempError(hdr.second); + AppLogger::Info("Receive temp id: "+std::to_string(hdr.first)+",temp:"+std::to_string(hdr.second)); + switch (hdr.first) { + case 0: + this->temp1_event->SetValue(convertPayload(hdr.second)); + break; + case 1: + this->temp2_event->SetValue(convertPayload(hdr.second)); + break; + case 2: + this->temp3_event->SetValue(convertPayload(hdr.second)); + break; + default: + AppLogger::Warning("ID spoza zakresu:"+std::to_string(hdr.first)); + break; + } + } +} + + +} // namespace envService +} // namespace simba diff --git a/apps/env_service/env_service.hpp b/apps/env_service/env_service.hpp new file mode 100644 index 00000000..f0ce954b --- /dev/null +++ b/apps/env_service/env_service.hpp @@ -0,0 +1,62 @@ +/** + * @file env_service.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-04 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef APPS_ENV_SERVICE_ENV_SERVICE_HPP_ +#define APPS_ENV_SERVICE_ENV_SERVICE_HPP_ + +#include +#include +#include +#include + +#include "mw/temp/controller/temp_controller.h" +#include "core/application/application_no_ipc.h" +#include "communication-core/someip-controller/event_skeleton.h" +#include "diag/dtc/controller/dtc.h" + +namespace simba { +namespace envService { + +class EnvService : public core::ApplicationNoIPC{ + private: + std::shared_ptr dtc_temp_error; + std::shared_ptr dtc_temp_connection_error_0xB0; + mw::temp::TempController temp_{}; + std::shared_ptr temp1_event; + std::shared_ptr temp2_event; + std::shared_ptr temp3_event; + + protected: + /** + * @brief This function is called to launch the application + * + * @param token stop token + */ + core::ErrorCode Run(std::stop_token token) final; + /** + * @brief This function is called to initialiaze the application + * + * @param parms map with parms + */ + core::ErrorCode Initialize( + const std::unordered_map& parms) final; + void TempRxCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data); + bool CheckTempError(const double &value); + + public: + ~EnvService() = default; +}; + +} // namespace envService +} // namespace simba + + +#endif // APPS_ENV_SERVICE_ENV_SERVICE_HPP_ diff --git a/apps/env_service/main.cpp b/apps/env_service/main.cpp new file mode 100644 index 00000000..2c23f8f2 --- /dev/null +++ b/apps/env_service/main.cpp @@ -0,0 +1,18 @@ +/** + * @file main.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-04 + * + * @copyright Copyright (c) 2024 + * + */ +#include "apps/env_service/env_service.hpp" +#include "core/application/application_factory.h" +#include "untar/untar.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/apps/example/router.cc b/apps/example/router.cc index 072c5a9d..2a2bcd45 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -33,7 +33,7 @@ core::ErrorCode Router::Run(std::stop_token token) { com->Add(example); com->Add(proxy_event); proxy_event->StartFindService(); - auto dtc = std::make_shared(20); + auto dtc = std::make_shared(0x20); diag_controller.RegisterDTC(dtc); while (true) { AppLogger::Debug("AppLogger::Debug"); diff --git a/deployment b/deployment index efca4c0d..860f4376 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit efca4c0d374b485c2edd65feeed8f1770334ba54 +Subproject commit 860f43768d9658502af3d702893dc8a65fe833d2 diff --git a/diag/exec/controller/exec_controller.cpp b/diag/exec/controller/exec_controller.cpp index 7dc889a3..a8bc958a 100644 --- a/diag/exec/controller/exec_controller.cpp +++ b/diag/exec/controller/exec_controller.cpp @@ -46,6 +46,10 @@ ExecController::ExecController() {} ExecController::~ExecController() { } +void ExecController::ForceStop() { + this->thread_.request_stop(); +} + } // namespace exec } // namespace diag diff --git a/diag/exec/controller/exec_controller.hpp b/diag/exec/controller/exec_controller.hpp index 37ec6a18..6578dc05 100644 --- a/diag/exec/controller/exec_controller.hpp +++ b/diag/exec/controller/exec_controller.hpp @@ -39,6 +39,7 @@ class ExecController { void SetStatus(Status status); void SetFlags(std::bitset<5> flags); ~ExecController(); + void ForceStop(); }; } // namespace exec } // namespace diag diff --git a/mw/em/code/em_application.cc b/mw/em/code/em_application.cc index fde24259..537bb579 100644 --- a/mw/em/code/em_application.cc +++ b/mw/em/code/em_application.cc @@ -48,6 +48,7 @@ core::ErrorCode EmApplication::Run(std::stop_token token) { */ core::ErrorCode EmApplication::Initialize( const std::unordered_map& parms) { + this->exec_.ForceStop(); this->em_service.LoadApps(); this->exec_service.SetApps(this->em_service.GetAppList()); return core::ErrorCode::kOk; diff --git a/mw/temp/controller/BUILD b/mw/temp/controller/BUILD new file mode 100644 index 00000000..ea112084 --- /dev/null +++ b/mw/temp/controller/BUILD @@ -0,0 +1,25 @@ +cc_library( + name = "temp_controller_mw", + srcs = [ + "temp_controller.h", + "temp_controller.cpp", + ], + visibility = [ + "//deployment:__subpackages__", + "//apps/env_service:__subpackages__", + ], + + deps = [ + "//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type", + "//communication-core/sockets:socket_interface", + "//communication-core/sockets:socket_ipc", + "//mw/temp/subscribe_msg:subscribe_header", + "//mw/temp/subscribe_msg:subscribe_msg_factory", + "//mw/temp/temp_reading_msg:temp_reading_msg_factory", + "//mw/temp/service:temp_service_mw", + "@com_json//:json" + + ], + data = [] +) \ No newline at end of file diff --git a/mw/temp/controller/temp_controller.cpp b/mw/temp/controller/temp_controller.cpp new file mode 100644 index 00000000..706b6745 --- /dev/null +++ b/mw/temp/controller/temp_controller.cpp @@ -0,0 +1,72 @@ +/** + * @file temp_controller.cpp + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#include "temp_controller.h" +#include +#include // NOLINT +#include // NOLINT +#include // NOLINT +#include + +namespace simba { +namespace mw { +namespace temp { + +namespace { + static constexpr char const* + kTempServiceName = "SIMBA.TEMP.SERVICE"; + static constexpr char const* + kSubscriberPrefix = "SIMBA.TEMP."; +} + +simba::core::ErrorCode TempController::Init( + uint16_t service_id, simba::com::soc::RXCallback callback) { + auto res = core::ErrorCode::kOk; + this->service_id = service_id; + if (res = this->sub_sock_.Init( + com::soc::SocketConfig( + kSubscriberPrefix + std::to_string(this->service_id), 0, 0))) { + AppLogger::Error("Couldn't initialize socket!"); + return res; + } + this->callback_ = callback; + SetTempRXCallback(); + res = this->Subscribe(); + if (res != core::ErrorCode::kOk) { + return res; + } + this->sub_sock_.StartRXThread(); + return res; +} + +simba::core::ErrorCode TempController::Subscribe() { + static simba::mw::temp::SubMsgFactory factory; + SubscribeHeader hdr{this->service_id}; + std::vector data = + factory.GetBuffer(std::make_shared(hdr), {}); + if (auto res = sub_sock_.Transmit(kTempServiceName, 0, data)) { + AppLogger::Error("Failed to subscribe to " + std::string(kTempServiceName)+":::"+std::to_string(res)); + return res; + } + return simba::core::ErrorCode::kOk; +} + +void TempController::SetTempRXCallback() { + simba::com::soc::RXCallback lambdaCallback = [this]( + const std::string& ip, const std::uint16_t& port, + const std::vector data) { + this->callback_(ip, port, data); + }; + this->sub_sock_.SetRXCallback(lambdaCallback); +} + +} // namespace temp +} // namespace mw +} // namespace simba diff --git a/mw/temp/controller/temp_controller.h b/mw/temp/controller/temp_controller.h new file mode 100644 index 00000000..a38f4205 --- /dev/null +++ b/mw/temp/controller/temp_controller.h @@ -0,0 +1,56 @@ +/** + * @file temp_controller.h + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef MW_TEMP_CONTROLLER_TEMP_CONTROLLER_H_ +#define MW_TEMP_CONTROLLER_TEMP_CONTROLLER_H_ + +#include +#include +#include +#include + +#include +#include +#include + +#include "communication-core/sockets/ipc_socket.h" +#include "communication-core/sockets/socket_config.h" +#include "core/logger/Logger.h" + +#include "mw/temp/subscribe_msg/subscribe_header.h" +#include "mw/temp/subscribe_msg/subscribe_msg_factory.h" + +#include "mw/temp/temp_reading_msg/temp_reading_msg_factory.h" + +#include "mw/temp/service/temp_service.h" + +namespace simba { +namespace mw { +namespace temp { + +class TempController { + protected: + uint16_t service_id; + com::soc::IpcSocket sub_sock_{}; + static simba::mw::temp::TempReadingMsgFactory factory; + simba::com::soc::RXCallback callback_; + + private: + virtual void SetTempRXCallback(); + virtual simba::core::ErrorCode Subscribe(); + public: + virtual simba::core::ErrorCode Init(uint16_t service_id, simba::com::soc::RXCallback callback); +}; + +} // namespace temp +} // namespace mw +} // namespace simba + +#endif // MW_TEMP_CONTROLLER_TEMP_CONTROLLER_H_ diff --git a/mw/temp/service/BUILD b/mw/temp/service/BUILD new file mode 100644 index 00000000..d68996b6 --- /dev/null +++ b/mw/temp/service/BUILD @@ -0,0 +1,25 @@ +cc_binary( + name = "temp_service_mw", + srcs = [ + "main.cc", + "temp_service.h", + "temp_service.cpp", + ], + visibility = [ + "//deployment:__subpackages__", + "//mw/temp:__subpackages__" + ], + + deps = [ + "//core/application:simba_application", + "//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type", + "//communication-core/sockets:socket_interface", + "//communication-core/sockets:socket_ipc", + "//mw/temp/subscribe_msg:subscribe_header", + "//mw/temp/subscribe_msg:subscribe_msg_factory", + "//mw/temp/temp_reading_msg:temp_reading_msg_factory", + "@com_json//:json" + + ], +) \ No newline at end of file diff --git a/mw/temp/service/main.cc b/mw/temp/service/main.cc new file mode 100644 index 00000000..3fc8e0f2 --- /dev/null +++ b/mw/temp/service/main.cc @@ -0,0 +1,18 @@ +/** + * @file main.cc + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "temp_service.h" +#include "core/application/application_factory.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/mw/temp/service/temp_service.cpp b/mw/temp/service/temp_service.cpp new file mode 100644 index 00000000..4877b233 --- /dev/null +++ b/mw/temp/service/temp_service.cpp @@ -0,0 +1,158 @@ +/** + * @file TempService.cpp + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#include "temp_service.h" +#include +#include // NOLINT +#include // NOLINT + +namespace simba { +namespace mw { +namespace temp { + +namespace { + static constexpr char const* + kTempServiceName = "SIMBA.TEMP.SERVICE"; + static constexpr char const* + kSubscriberPrefix = "SIMBA.TEMP."; + constexpr uint8_t sensor_resolution = 10; + constexpr const char* sensor_path = "/sys/bus/w1/devices/"; +} + +simba::core::ErrorCode TempService::Run(std::stop_token token) { + ConfigSensors(); + this->StartTempThread(); + AppLogger::Info("Temp Service started!"); + this->SleepMainThread(); + return core::ErrorCode::kError; +} + +simba::core::ErrorCode TempService::Initialize( + const std::unordered_map& parms) { + LoadConfig(parms); + if (auto ret = this->sub_sock_.Init( + com::soc::SocketConfig(kTempServiceName, 0, 0))) { + AppLogger::Error("Couldn't initialize " + + std::string(kTempServiceName) + "socket!"); + return ret; + } + + this->sub_sock_.SetRXCallback( + std::bind(&simba::mw::temp::TempService::SubCallback, this, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + this->sub_sock_.StartRXThread(); + return simba::core::ErrorCode::kOk; +} + +simba::core::ErrorCode TempService::ConfigSensors() { + for (auto sensor : this->sensorPathsToIds) { + std::fstream file(sensor.first + "/resolution"); + if (!file) { + AppLogger::Warning("Sensor " + sensor.first + " not available!"); + break; + } + AppLogger::Debug("set resolution for sensor"+sensor.first); + file << static_cast(sensor_resolution); + file.close(); + } + return simba::core::ErrorCode::kOk; +} + +void TempService::StartTempThread() { + if (temp_thread != nullptr) { + AppLogger::Error("Error starting temperature thread!"); + return; + } + this->temp_thread = std::make_unique( + [&](std::stop_token stoken) { this->Loop(stoken); }); +} + +void TempService::SubCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data) { + auto hdr = factory.GetHeader(data); + + std::uint16_t service_id = hdr->GetServiceID(); + + if (!this->subscribers.contains(service_id)) { + this->subscribers.insert(service_id); + AppLogger::Info("Registered new client with id: " + + std::to_string(service_id)); + } +} + +simba::core::ErrorCode TempService::LoadConfig( + const std::unordered_map& parms) { + std::ifstream file{"/opt/" + parms.at("app_name") + "/etc/config.json"}; + if (!file) { + AppLogger::Error("Couldn't load temperature sensors config!"); + return simba::core::ErrorCode::kError; + } + + json jsonData; + file >> jsonData; + file.close(); + + for (auto sensor : jsonData["sensors-temp"].items()) { + sensorPathsToIds[sensor_path+sensor.key()] = sensor.value(); + } + return simba::core::ErrorCode::kOk; +} + +std::vector TempService::RetrieveTempReadings() { + std::vector readings; + for (const auto& path : sensorPathsToIds) { + std::ifstream file(path.first + "/temperature"); + + if (!file) { + AppLogger::Warning("Sensor " + path.first + " not available!"); + break; + } + + std::string line; + std::getline(file, line); + const double sensorValueRaw = std::stoi(line)/ 1000.0; + file.close(); + + AppLogger::Debug("Sensor " + path.first + + ": " + std::to_string(sensorValueRaw)); + + readings.push_back(TempReading{path.second, sensorValueRaw}); + } + return readings; +} + +void TempService::SendTempReadings( + const std::vector& readings) { + for (const auto& client_id : this->subscribers) { + simba::mw::temp::TempReadingMsgFactory factory; + std::string ip = kSubscriberPrefix + std::to_string(client_id); + + std::vector data = factory.GetBuffer(readings); + + if (this->sub_sock_.Transmit(ip, 0, data)) { + AppLogger::Error("Can't send message to: " + ip); + break; + } + } +} + +simba::core::ErrorCode TempService::Loop(std::stop_token stoken) { + std::vector readings; + while (true) { + readings = RetrieveTempReadings(); + SendTempReadings(readings); + readings.clear(); + std::this_thread::sleep_for(this->temp_timeout); + } +} + +} // namespace temp +} // namespace mw +} // namespace simba diff --git a/mw/temp/service/temp_service.h b/mw/temp/service/temp_service.h new file mode 100644 index 00000000..d908329e --- /dev/null +++ b/mw/temp/service/temp_service.h @@ -0,0 +1,87 @@ +/** + * @file TempService.h + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_TEMP_SERVICE_TEMP_SERVICE_H_ +#define MW_TEMP_SERVICE_TEMP_SERVICE_H_ + +#include +#include + +#include +#include +#include +#include +#include "core/json/json_parser.h" +#include "nlohmann/json.hpp" + +#include "core/application/application_mw.h" +#include "communication-core/sockets/ipc_socket.h" +#include "communication-core/sockets/socket_config.h" +#include "core/logger/Logger.h" + +#include "mw/temp/subscribe_msg/subscribe_header.h" +#include "mw/temp/subscribe_msg/subscribe_msg_factory.h" + +#include "mw/temp/temp_reading_msg/temp_reading_msg_factory.h" + +using json = nlohmann::json; + +namespace simba { +namespace mw { +namespace temp { + +class TempService final : public simba::core::ApplicationMW { + protected: + com::soc::IpcSocket sub_sock_{}; + const std::chrono::milliseconds temp_timeout{500}; + + private: + std::unique_ptr temp_thread; + std::set subscribers{}; + std::unordered_map sensorPathsToIds{}; + simba::mw::temp::SubMsgFactory factory; + + void StartTempThread(); + + simba::core::ErrorCode LoadConfig( + const std::unordered_map& parms); + simba::core::ErrorCode ConfigSensors(); + + /** + * @brief This function is called to launch the application + * + * @param token stop token + */ + simba::core::ErrorCode Run(std::stop_token token) final; + /** + * @brief This function is called to initialize the application + * + * @param parms map with params + */ + simba::core::ErrorCode Initialize( + const std::unordered_map& parms) final; + + std::vector RetrieveTempReadings(); + + void SendTempReadings(const std::vector& readings); + + public: + simba::core::ErrorCode Loop(std::stop_token stoken); + + void SubCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data); +}; + +} // namespace temp +} // namespace mw +} // namespace simba + +#endif // MW_TEMP_SERVICE_TEMP_SERVICE_H_ diff --git a/mw/temp/subscribe_msg/BUILD b/mw/temp/subscribe_msg/BUILD new file mode 100644 index 00000000..96822f10 --- /dev/null +++ b/mw/temp/subscribe_msg/BUILD @@ -0,0 +1,24 @@ +cc_library( + name = "subscribe_header", + srcs = ["subscribe_header.cpp"], + hdrs = ["subscribe_header.h"], + visibility = [ + "//mw/temp:__subpackages__", + ], + + deps = ["//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type" + ] +) + +cc_library( + name = "subscribe_msg_factory", + srcs = ["subscribe_msg_factory.cpp"], + hdrs = ["subscribe_msg_factory.h"], + + visibility = [ + "//mw/temp:__subpackages__", + ], + + deps = [":subscribe_header"], +) \ No newline at end of file diff --git a/mw/temp/subscribe_msg/subscribe_header.cpp b/mw/temp/subscribe_msg/subscribe_header.cpp new file mode 100644 index 00000000..4aeef340 --- /dev/null +++ b/mw/temp/subscribe_msg/subscribe_header.cpp @@ -0,0 +1,47 @@ +/** + * @file + * @author + * @brief + * @version 0.1 + * @date + * + * @copyright Copyright (c) 2024 + * + */ + +#include "subscribe_header.h" + +namespace simba { +namespace mw { +namespace temp { + +SubscribeHeader::SubscribeHeader(const uint16_t &service_id) + : service_id_(service_id), length_(sizeof(uint16_t)) { + SetData(); +} + +SubscribeHeader::SubscribeHeader() + : service_id_(0U), length_(sizeof(uint16_t)) { + SetData(); +} + +uint16_t SubscribeHeader::GetServiceID() const { + return this->service_id_.Get(); +} + +uint8_t SubscribeHeader::GetLength() const { + return this->length_.Get(); +} + +void SubscribeHeader::SetLength(const uint8_t& value) { + this->length_ = value + sizeof(uint16_t); +} + +void SubscribeHeader::SetData() { + this->AddData(&service_id_); + this->AddData(&length_); +} + +} // namespace temp +} // namespace mw +} // namespace simba diff --git a/mw/temp/subscribe_msg/subscribe_header.h b/mw/temp/subscribe_msg/subscribe_header.h new file mode 100644 index 00000000..a998ad11 --- /dev/null +++ b/mw/temp/subscribe_msg/subscribe_header.h @@ -0,0 +1,43 @@ +/** + * @file subscribe_header.h + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_TEMP_SUBSCRIBE_MSG_SUBSCRIBE_HEADER_H_ +#define MW_TEMP_SUBSCRIBE_MSG_SUBSCRIBE_HEADER_H_ + +#include // NOLINT +#include + +#include "communication-core/network-data/network_data_structure.h" +#include "communication-core/network-data/network_data_type.h" + +namespace simba { +namespace mw { +namespace temp { + +class SubscribeHeader : public com::core::network::NetworkDataStructure { + private: + com::core::network::uint16_t service_id_; + com::core::network::uint8_t length_; + + public: + explicit SubscribeHeader(const uint16_t &service_id); + SubscribeHeader(); + uint16_t GetServiceID() const; + uint8_t GetLength() const; + void SetLength(const uint8_t& value); + void SetData(); +}; + +} // namespace temp +} // namespace mw +} // namespace simba + +#endif // MW_TEMP_SUBSCRIBE_MSG_SUBSCRIBE_HEADER_H_ diff --git a/mw/temp/subscribe_msg/subscribe_msg_factory.cpp b/mw/temp/subscribe_msg/subscribe_msg_factory.cpp new file mode 100644 index 00000000..84280b5e --- /dev/null +++ b/mw/temp/subscribe_msg/subscribe_msg_factory.cpp @@ -0,0 +1,48 @@ +/** + * @file dtc_msg_factory.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2023-12-23 + * + * @copyright Copyright (c) 2023 + * + */ +#include "mw/temp/subscribe_msg/subscribe_header.h" +#include "subscribe_msg_factory.h" + + +#include +namespace simba { +namespace mw { +namespace temp { + +std::vector SubMsgFactory::GetBuffer( + std::shared_ptr header, + std::vector&& payload) { + std::vector res{header->GetBuffor()}; + std::copy(payload.begin(), payload.end(), std::back_inserter(res)); + return res; +} + +std::shared_ptr SubMsgFactory::GetHeader( + std::vector raw_data) { + + auto header = std::make_shared(); + header->SetBuffor(raw_data); + return header; +} + +std::vector SubMsgFactory::GetPayload(std::vector raw_data) { + std::vector payload{}; + if (raw_data.size() > 4) { + std::copy(raw_data.begin() + 0x4, + raw_data.end(), std::back_inserter(payload)); + return payload; + } + return {}; +} + +} // namespace temp +} // namespace mw +} // namespace simba diff --git a/mw/temp/subscribe_msg/subscribe_msg_factory.h b/mw/temp/subscribe_msg/subscribe_msg_factory.h new file mode 100644 index 00000000..a593977e --- /dev/null +++ b/mw/temp/subscribe_msg/subscribe_msg_factory.h @@ -0,0 +1,57 @@ +/** + * @file subscribe_msg_factory.h + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_TEMP_SUBSCRIBE_MSG_SUBSCRIBE_MSG_FACTORY_H_ +#define MW_TEMP_SUBSCRIBE_MSG_SUBSCRIBE_MSG_FACTORY_H_ + +#include "subscribe_header.h" +#include +#include + +namespace simba { +namespace mw { +namespace temp { + +class SubMsgFactory { + public: + /** + * @brief This function return ready bit stream to send + * + * @param header + * @param payload + * @return std::vector + */ + std::vector GetBuffer(std::shared_ptr header, + std::vector&& payload); + + /** + * @brief Creat header object from raw data + * + * @param raw_data + * @return std::shared_ptr + */ + std::shared_ptr GetHeader( + std::vector raw_data); + + /** + * @brief Get payload from raw data + * + * @param raw_data + * @return std::vector + */ + std::vector GetPayload(std::vector raw_data); +}; + +} // namespace temp +} // namespace mw +} // namespace simba + +#endif // MW_TEMP_SUBSCRIBE_MSG_SUBSCRIBE_MSG_FACTORY_H_ diff --git a/mw/temp/temp_reading_msg/BUILD b/mw/temp/temp_reading_msg/BUILD new file mode 100644 index 00000000..668342ac --- /dev/null +++ b/mw/temp/temp_reading_msg/BUILD @@ -0,0 +1,9 @@ +cc_library( + name = "temp_reading_msg_factory", + srcs = ["temp_reading_msg_factory.cpp"], + hdrs = ["temp_reading_msg_factory.h"], + + visibility = [ + "//mw/temp:__subpackages__", + ], +) \ No newline at end of file diff --git a/mw/temp/temp_reading_msg/temp_reading_msg_factory.cpp b/mw/temp/temp_reading_msg/temp_reading_msg_factory.cpp new file mode 100644 index 00000000..cdca0501 --- /dev/null +++ b/mw/temp/temp_reading_msg/temp_reading_msg_factory.cpp @@ -0,0 +1,62 @@ +/** + * @file dtc_msg_factory.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2023-12-23 + * + * @copyright Copyright (c) 2023 + * + */ + +#include "temp_reading_msg_factory.h" + +#include +#include +#include +#include +namespace simba { +namespace mw { +namespace temp { + +std::vector TempReadingMsgFactory::GetBuffer( + std::vector> payload) { + std::vector res; + + for (const auto& pair : payload) { + uint8_t first = pair.first; + double second = pair.second; + std::array firstBytes; + std::array secondBytes; + + memcpy(firstBytes.data(), &first, sizeof(uint8_t)); + memcpy(secondBytes.data(), &second, sizeof(double)); + + res.insert(res.end(), firstBytes.begin(), firstBytes.end()); + res.insert(res.end(), secondBytes.begin(), secondBytes.end()); + } + + return res; +} + +std::vector> + TempReadingMsgFactory::GetPayload(std::vector raw_data) { + std::vector> payload{}; + if (raw_data.size() > 4) { + for (size_t i = 0; i < raw_data.size(); i += (sizeof(uint8_t) + sizeof(double))) { + uint8_t first; + std::memcpy(&first, &raw_data[i], sizeof(uint8_t)); + + double second; + std::memcpy(&second, &raw_data[i+sizeof(uint8_t)], sizeof(double)); + + payload.push_back(std::make_pair(first, second)); + } + return payload; + } + return {}; +} + +} // namespace temp +} // namespace mw +} // namespace simba diff --git a/mw/temp/temp_reading_msg/temp_reading_msg_factory.h b/mw/temp/temp_reading_msg/temp_reading_msg_factory.h new file mode 100644 index 00000000..9b7c0726 --- /dev/null +++ b/mw/temp/temp_reading_msg/temp_reading_msg_factory.h @@ -0,0 +1,50 @@ +/** + * @file temp_reading_msg_factory.h + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_TEMP_TEMP_READING_MSG_TEMP_READING_MSG_FACTORY_H_ +#define MW_TEMP_TEMP_READING_MSG_TEMP_READING_MSG_FACTORY_H_ + +#include +#include +#include + +namespace simba { +namespace mw { +namespace temp { + +// first - sensor_id, second - value +using TempReading = std::pair; + +class TempReadingMsgFactory { + public: + /** + * @brief This function return ready bit stream to send + * + * @param header + * @param payload + * @return std::vector + */ + std::vector GetBuffer(std::vector payload); + + /** + * @brief Get payload from raw data + * + * @param raw_data + * @return std::vector + */ + std::vector GetPayload(std::vector raw_data); +}; + +} // namespace temp +} // namespace mw +} // namespace simba + +#endif // MW_TEMP_TEMP_READING_MSG_TEMP_READING_MSG_FACTORY_H_ diff --git a/mw/temp/tests/BUILD b/mw/temp/tests/BUILD new file mode 100644 index 00000000..f0717283 --- /dev/null +++ b/mw/temp/tests/BUILD @@ -0,0 +1,30 @@ +cc_test( + name = "subscribe_msg", + srcs = ["test_subscribe_msg.cpp"], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//mw/temp/subscribe_msg:subscribe_header", + ] +) + +cc_test( + name = "subscribe_msg_factory", + srcs = ["test_subscribe_msg_factory.cpp"], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//mw/temp/subscribe_msg:subscribe_header", + "//mw/temp/subscribe_msg:subscribe_msg_factory", + ] +) + +cc_test( + name = "temp_reading_msg_factory", + srcs = ["test_temp_reading_msg_factory.cpp"], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//mw/temp/temp_reading_msg:temp_reading_msg_factory", + ] +) \ No newline at end of file diff --git a/mw/temp/tests/test_subscribe_msg.cpp b/mw/temp/tests/test_subscribe_msg.cpp new file mode 100644 index 00000000..7929d3e3 --- /dev/null +++ b/mw/temp/tests/test_subscribe_msg.cpp @@ -0,0 +1,21 @@ +/** + * @file test_subscribe_msg.cpp + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#include + +#include "mw/temp/subscribe_msg/subscribe_header.h" + +TEST(SUBSCRIBE_HEADER, CONSTRUCTOR_CHECK) { + const uint16_t id = 0x0010; + simba::mw::temp::SubscribeHeader hdr{id}; + const std::vector payload{0x01, 0x02, 0x03}; + EXPECT_EQ(id, hdr.GetServiceID()); + EXPECT_EQ(02, hdr.GetLength()); +} diff --git a/mw/temp/tests/test_subscribe_msg_factory.cpp b/mw/temp/tests/test_subscribe_msg_factory.cpp new file mode 100644 index 00000000..4d0938b8 --- /dev/null +++ b/mw/temp/tests/test_subscribe_msg_factory.cpp @@ -0,0 +1,26 @@ +/** + * @file test_subscribe_msg_factory.cpp + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#include + +#include "mw/temp/subscribe_msg/subscribe_header.h" +#include "mw/temp/subscribe_msg/subscribe_msg_factory.h" + +TEST(SUBSCRIBE_MSG_FACTORIES, SUBSCRIBE_MSG_FACTORIES_TEST) { + simba::mw::temp::SubMsgFactory factory; + std::vector payload = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5}; + const uint16_t id = 0x0001; + simba::mw::temp::SubscribeHeader hdr{id}; + const std::vector data = factory.GetBuffer( + std::make_shared(hdr), std::move(payload)); + const auto hdr2 = factory.GetHeader(data); + EXPECT_EQ(hdr2->GetServiceID(), hdr.GetServiceID()); + EXPECT_EQ(hdr2->GetLength(), hdr.GetLength()); +} diff --git a/mw/temp/tests/test_temp_reading_msg_factory.cpp b/mw/temp/tests/test_temp_reading_msg_factory.cpp new file mode 100644 index 00000000..a18879a5 --- /dev/null +++ b/mw/temp/tests/test_temp_reading_msg_factory.cpp @@ -0,0 +1,29 @@ +/** + * @file test_temp_reading_msg_factory.cpp + * @author Maciek Matuszewski (maciej.matuszewsky@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#include + +#include "mw/temp/temp_reading_msg/temp_reading_msg_factory.h" + +TEST(TEMP_READING_MSG_FACTORY, TEMP_READING_MSG_FACTORY_TEST) { + simba::mw::temp::TempReadingMsgFactory factory; + std::vector payload = { + {0, 0.0}, + {1, -1.1}, + {2, 123.654} + }; + + std::vector raw_data = factory.GetBuffer(payload); + const auto payload2 = factory.GetPayload(raw_data); + + EXPECT_EQ(payload[0], payload2[0]); + EXPECT_EQ(payload[1], payload2[1]); + EXPECT_EQ(payload[2], payload2[2]); +} From addf7179d82ae042a4dc5ea25b9d2bd3734bfe08 Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Fri, 12 Apr 2024 16:25:27 +0200 Subject: [PATCH 44/71] Create Devcontainer (#62) * devcontainer init * DevContainer --- .devcontainer/Dockerfile | 9 +++++++ .devcontainer/devcontainer.json | 46 +++++++++++++++++++++++++++++++++ .devcontainer/start.sh | 5 ++++ .github/dependabot.yml | 12 +++++++++ deployment | 2 +- 5 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/start.sh create mode 100644 .github/dependabot.yml diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 00000000..2a1da44b --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,9 @@ +FROM mcr.microsoft.com/devcontainers/base:jammy + +RUN apt-get install -y \ + git \ + gcc \ + g++ \ + build-essential + +WORKDIR /workspace diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000..eb153a41 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,46 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/ubuntu +{ + "name": "Simba-Devcontainer", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + // "dockerFile": "Dockerfile", + "image": "matiko42/simba_dev_container", + // Features to add to the dev container. More info: https://containers.dev/features. + "features": { + "ghcr.io/balazs23/devcontainers-features/bazel":1 + }, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "sh /workspaces/srp/.devcontainer/start.sh", + + // Configure tool-specific properties. + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cpptools", + "BazelBuild.vscode-bazel", + "StackBuild.bazel-stack-vscode", + "ms-vscode.cpptools-extension-pack", + "mine.cpplint", + "cschlosser.doxdocgen", + "MS-CEINTL.vscode-language-pack-pl", + "ms-azuretools.vscode-docker" + ], + "settings": { + "C_Cpp.default.cppStandard": "c++23", + "C_Cpp.default.cStandard": "c17", + "cpplint.lineLength": 120, + "cpplint.cpplintPath": "/usr/bin/cpplint" + } + } + }, + "mounts": [ + "source=${localEnv:HOME}${localEnv:USERPROFILE}/.ssh,target=/root/.ssh,readonly,type=bind" + ], + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + "remoteUser": "root" +} diff --git a/.devcontainer/start.sh b/.devcontainer/start.sh new file mode 100644 index 00000000..d336cbeb --- /dev/null +++ b/.devcontainer/start.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +bazel --version +apt update +apt install cpplint \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..f33a02cd --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for more information: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://containers.dev/guide/dependabot + +version: 2 +updates: + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly diff --git a/deployment b/deployment index 860f4376..9f641dd3 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 860f43768d9658502af3d702893dc8a65fe833d2 +Subproject commit 9f641dd360466c9037e775c1014be2f1e2b35ec6 From bbdcbcd9a60b7f59260b1b3ee2f03794da54cdcf Mon Sep 17 00:00:00 2001 From: Mateusz Date: Fri, 12 Apr 2024 23:27:41 +0200 Subject: [PATCH 45/71] fix --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 9f641dd3..32a5b2f4 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 9f641dd360466c9037e775c1014be2f1e2b35ec6 +Subproject commit 32a5b2f4813c41bed811fc439c6662990e8df614 From 86adf18f529e33b0244383efeb572837cec84b9a Mon Sep 17 00:00:00 2001 From: Mateusz Date: Wed, 17 Apr 2024 08:18:13 +0200 Subject: [PATCH 46/71] force fix --- apps/env_service/env_service.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/env_service/env_service.cpp b/apps/env_service/env_service.cpp index 3ed707c3..74714628 100644 --- a/apps/env_service/env_service.cpp +++ b/apps/env_service/env_service.cpp @@ -35,6 +35,9 @@ core::ErrorCode EnvService::Initialize( this->temp1_event = std::make_shared("EnvApp/newTempEvent_1"); this->temp2_event = std::make_shared("EnvApp/newTempEvent_2"); this->temp3_event = std::make_shared("EnvApp/newTempEvent_3"); + com->Add(temp1_event); + com->Add(temp2_event); + com->Add(temp3_event); this->dtc_temp_error = std::make_shared(0x20); this->dtc_temp_connection_error_0xB0 = std::make_shared(0xB0); diag_controller.RegisterDTC(dtc_temp_connection_error_0xB0); From 382a2ff7cdd1a1f28255f45734e9d61857e30972 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sat, 27 Apr 2024 12:10:07 +0200 Subject: [PATCH 47/71] V1.5 --- apps/example/router.cc | 14 +-- apps/example/router2.cc | 10 +- .../someip-controller/callbacks.h | 13 ++- .../someip-controller/controller.cc | 92 +++++++++++++++---- .../someip-controller/controller.h | 9 +- .../someip-controller/event_skeleton.h | 5 +- .../someip-controller/iskeleton.h | 5 +- .../someip-controller/method_proxy.h | 15 ++- .../someip-controller/method_skeleton.h | 28 ++++-- .../someip-database/code/config_db_parser.h | 13 ++- .../someip-database/code/endpoint.h | 20 +++- .../test/config_db_parser_test.cc | 2 + .../test/resource/app_someip2.json | 6 +- .../someip/factory/Isomeip_header_factory.h | 3 + .../someip/factory/someip_header_factory.cc | 7 ++ .../someip/factory/someip_header_factory.h | 3 + communication-core/someip/message_code.h | 2 +- communication-core/someip/message_type.h | 2 +- deployment | 2 +- 19 files changed, 192 insertions(+), 59 deletions(-) diff --git a/apps/example/router.cc b/apps/example/router.cc index 2a2bcd45..b3f9c1a9 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -21,19 +21,21 @@ namespace simba { namespace router { core::ErrorCode Router::Run(std::stop_token token) { - auto proxy_event = std::make_shared( - "ExampleApp/someevent", - [this](const std::vector) { AppLogger::Info("EVENT !!!!!!!"); }); auto example = std::make_shared( "ExampleApp/exampleMethod", [this](const std::vector payload) -> std::optional> { return std::vector{0, 1, 2}; }); + auto example2 = std::make_shared( + "ExampleApp/exampleMethod2", + [this](const std::vector payload) + -> std::optional> { + return std::vector{0, 1, 2}; + }); com->Add(example); - com->Add(proxy_event); - proxy_event->StartFindService(); - auto dtc = std::make_shared(0x20); + com->Add(example2); + auto dtc = std::make_shared(20); diag_controller.RegisterDTC(dtc); while (true) { AppLogger::Debug("AppLogger::Debug"); diff --git a/apps/example/router2.cc b/apps/example/router2.cc index 6d44131e..89a3080c 100644 --- a/apps/example/router2.cc +++ b/apps/example/router2.cc @@ -20,15 +20,17 @@ namespace router { core::ErrorCode Router::Run(std::stop_token token) { auto example = std::make_shared("ExampleApp2/someproxy"); - auto event_example = - std::make_shared("ExampleApp2/exampleEvent"); + auto example2 = + std::make_shared("ExampleApp2/someproxy2"); + com->Add(example); - com->Add(event_example); + com->Add(example2); example->StartFindService(); - event_example->SetValue({10, 11, 12, 13, 14, 15}); + example2->StartFindService(); while (true) { // this->gpio_.SetPinValue(5,gpio::Value::HIGH); std::ignore = example->Get(); + std::ignore = example2->Get(); // this->gpio_.SetPinValue(5,gpio::Value::LOW); std::this_thread::sleep_for(std::chrono::seconds(1)); } diff --git a/communication-core/someip-controller/callbacks.h b/communication-core/someip-controller/callbacks.h index 6aafd82f..2e002a61 100644 --- a/communication-core/someip-controller/callbacks.h +++ b/communication-core/someip-controller/callbacks.h @@ -1,12 +1,12 @@ /** * @file callbacks.h * @author Bartosz Snieg (snieg45@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-03-24 - * + * * @copyright Copyright (c) 2024 - * + * */ #ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_CALLBACKS_H_ #define COMMUNICATION_CORE_SOMEIP_CONTROLLER_CALLBACKS_H_ @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "communication-core/someip-database/code/endpoint.h" @@ -33,7 +34,11 @@ using SendCallback = std::function payload, const objects::Endpoint& endpoint, const objects::Interface& interface, data::MessageType type, ResultCallback result)>; -using MethodCallback = std::function>( +using MethodCallback = std::function< + std::pair>>( + const std::vector payload, const objects::Endpoint endpoint)>; + +using LocalMethodCallback = std::function>( const std::vector payload)>; using DropTransferCallback = std::function; diff --git a/communication-core/someip-controller/controller.cc b/communication-core/someip-controller/controller.cc index 383ae84e..d943e217 100644 --- a/communication-core/someip-controller/controller.cc +++ b/communication-core/someip-controller/controller.cc @@ -1,12 +1,12 @@ /** * @file controller.cc * @author Bartosz Snieg (snieg45@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-03-24 - * + * * @copyright Copyright (c) 2024 - * + * */ #include "communication-core/someip-controller/controller.h" @@ -114,8 +114,40 @@ void Controller::RXCallback(const std::string& ip, const std::uint16_t& port, const auto payload = msg_factory->GetPayload(data); this->onEvent(std::move(header), std::move(payload)); return; + } else if (header->GetMessageType() == data::MessageType::kError && + header->GetClientID() == this->service_id) { + this->onError(std::move(header)); + return; } else if (header->GetMessageType() == data::MessageType::kRequest) { AppLogger::Error("[ SOMEIP CONTROLLER ]: Wrong service ID"); + SendError(header, data::MessageCode::kEUnknownService); + } +} + +void Controller::onError(std::shared_ptr header) { + const auto trans_id = header->GetSessionID(); + ResultCallback callback; + bool exist{false}; + { + std::unique_lock lk{transfer_mutex}; + auto cal = std::find_if( + this->transfer_list.begin(), this->transfer_list.end(), + [&trans_id](const std::pair& obj) { + return obj.first == trans_id; + }); + if (cal != this->transfer_list.end()) { + callback = (cal->second); + exist = true; + } + } + if (exist) { + callback({}, static_cast(header->GetReturnCode()), + trans_id); + std::unique_lock lk{transfer_mutex}; + std::remove_if(this->transfer_list.begin(), this->transfer_list.end(), + [&trans_id](const std::pair& obj) { + return obj.first == trans_id; + }); } } void Controller::onRequest(std::shared_ptr header, @@ -127,27 +159,47 @@ void Controller::onRequest(std::shared_ptr header, const auto func = this->callback.find(id); if (func == this->callback.end()) { AppLogger::Error("[ SOMEIP CONTROLLER ]: Method not found!"); + SendError(header, data::MessageCode::kEUnknownMethod); + return; } else { AppLogger::Info("[ SOMEIP CONTROLLER ]: Callback found!"); - auto data = func->second(std::move(payload)); - if (data.has_value()) { - auto res_header = this->header_factory->CreateResponse( - header->GetServiceID(), header->GetMethodID(), - data::MessageCode::kEOk); - auto msg = msg_factory->GetBuffor(res_header, header->GetClientID(), - header->GetSessionID(), data.value()); - auto interf = db->FindService(header->GetClientID()); - if (interf.has_value()) { - Transfer(interf.value(), msg); - } else { - AppLogger::Error("[ SOMEIP CONTROLLER ]: can't find service: " + - std::to_string(header->GetClientID())); + auto data = func->second(std::move(payload), + objects::Endpoint{header->GetClientID(), 0}); + if (data.first == data::MessageCode::kEOk) { + if (data.second.has_value()) { + auto res_header = this->header_factory->CreateResponse( + header->GetServiceID(), header->GetMethodID(), + data::MessageCode::kEOk); + auto msg = + msg_factory->GetBuffor(res_header, header->GetClientID(), + header->GetSessionID(), data.second.value()); + auto interf = db->FindService(header->GetClientID()); + if (interf.has_value()) { + Transfer(interf.value(), msg); + } else { + AppLogger::Error("[ SOMEIP CONTROLLER ]: can't find service: " + + std::to_string(header->GetClientID())); + } } } else { + SendError(header, data.first); } } } - +void Controller::SendError(std::shared_ptr rx_header, + data::MessageCode error_code) { + auto res_header = this->header_factory->CreateErrorResponse( + rx_header->GetServiceID(), rx_header->GetMethodID(), error_code); + auto msg = msg_factory->GetBuffor(res_header, rx_header->GetClientID(), + rx_header->GetSessionID(), {}); + auto interf = db->FindService(rx_header->GetClientID()); + if (interf.has_value()) { + Transfer(interf.value(), msg); + } else { + AppLogger::Error("[ SOMEIP CONTROLLER ]: can't find service: " + + std::to_string(rx_header->GetClientID())); + } +} void Controller::onResult(std::shared_ptr header, const std::vector payload) { const auto trans_id = header->GetSessionID(); @@ -277,9 +329,9 @@ void Controller::Add(std::shared_ptr skeleton) { uint32_t id = (static_cast(endpoint.value().GetServiceId()) << 16) + endpoint.value().GetEndpointId(); - - this->callback.insert({id, std::bind(&ISkeleton::Call, skeleton.get(), - std::placeholders::_1)}); + this->callback.insert( + {id, std::bind(&ISkeleton::Call, skeleton.get(), + std::placeholders::_1, std::placeholders::_2)}); AppLogger::Info("[ SOMEIP CONTROLLER ]: Method skeleton added (" + skeleton->GetName() + ")"); } else { diff --git a/communication-core/someip-controller/controller.h b/communication-core/someip-controller/controller.h index c4589255..50f30257 100644 --- a/communication-core/someip-controller/controller.h +++ b/communication-core/someip-controller/controller.h @@ -1,12 +1,12 @@ /** * @file controller.h * @author Bartosz Snieg (snieg45@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-03-24 - * + * * @copyright Copyright (c) 2024 - * + * */ #ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_CONTROLLER_H_ #define COMMUNICATION_CORE_SOMEIP_CONTROLLER_CONTROLLER_H_ @@ -74,6 +74,8 @@ class Controller { uint16_t GetTransferID(); void SendAck(const uint16_t client_id, const uint16_t endpoint_id, const uint16_t trans_id); + void SendError(std::shared_ptr rx_header, + data::MessageCode error_code); void onRequest(std::shared_ptr header, const std::vector payload); void onResult(std::shared_ptr header, @@ -85,6 +87,7 @@ class Controller { void SendEvent(const objects::Endpoint endpoint, const uint16_t client, std::vector data); void ThreadLoop(); + void onError(std::shared_ptr header); public: void Add(std::shared_ptr proxy); diff --git a/communication-core/someip-controller/event_skeleton.h b/communication-core/someip-controller/event_skeleton.h index 24f8d2f9..e609dc61 100644 --- a/communication-core/someip-controller/event_skeleton.h +++ b/communication-core/someip-controller/event_skeleton.h @@ -49,8 +49,9 @@ class EventSkeleton : public ISkeleton { std::optional GetEndPoint() const noexcept override { return object; } - std::optional> Call( - std::vector payload) noexcept override { + std::pair>> Call( + std::vector payload, + const objects::Endpoint endpoint) noexcept override { return {}; } std::string GetName() const override { return instance_; } diff --git a/communication-core/someip-controller/iskeleton.h b/communication-core/someip-controller/iskeleton.h index f4dbe43e..b30323ea 100644 --- a/communication-core/someip-controller/iskeleton.h +++ b/communication-core/someip-controller/iskeleton.h @@ -14,6 +14,7 @@ #include #include #include +#include #include "communication-core/someip-controller/callbacks.h" #include "communication-core/someip-database/code/endpoint.h" @@ -24,8 +25,8 @@ class ISkeleton { public: virtual void SetCallback(SendCallback callback) {} virtual std::optional GetEndPoint() const noexcept = 0; - virtual std::optional> Call( - std::vector) noexcept = 0; + virtual std::pair>> Call( + std::vector, const objects::Endpoint) noexcept = 0; virtual std::string GetName() const = 0; virtual ~ISkeleton() = default; }; diff --git a/communication-core/someip-controller/method_proxy.h b/communication-core/someip-controller/method_proxy.h index bcfe75f9..b5651af3 100644 --- a/communication-core/someip-controller/method_proxy.h +++ b/communication-core/someip-controller/method_proxy.h @@ -1,12 +1,12 @@ /** * @file method_proxy.h * @author Bartosz Snieg (snieg45@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-03-24 - * + * * @copyright Copyright (c) 2024 - * + * */ #ifndef COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_PROXY_H_ #define COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_PROXY_H_ @@ -49,7 +49,7 @@ class MethodProxyBase : public IProxy { const uint16_t transfer_id) { if (transfer_id == transfer_id_) { is_response = true; - response_code == code; + response_code = code; response = payload; request_cv.notify_all(); } @@ -112,6 +112,13 @@ class MethodProxyBase : public IProxy { if (response_code == data::MessageCode::kEOk) { return std::move(this->response); } else { + if (response_code == data::MessageCode::kENotReachable) { + AppLogger::Error("[ SOMEIP PROXY ](" + instance + "): Access denied !"); + } else { + AppLogger::Error( + "[ SOMEIP PROXY ](" + instance + + "): Response with error: " + std::to_string(response_code)); + } return {}; } } diff --git a/communication-core/someip-controller/method_skeleton.h b/communication-core/someip-controller/method_skeleton.h index d9d98bf8..ff6f8f53 100644 --- a/communication-core/someip-controller/method_skeleton.h +++ b/communication-core/someip-controller/method_skeleton.h @@ -12,7 +12,7 @@ #define COMMUNICATION_CORE_SOMEIP_CONTROLLER_METHOD_SKELETON_H_ #include // NOLINT -#include // NOLINT +#include // NOLINT #include #include #include @@ -33,20 +33,36 @@ namespace someip { class MethodSkeleton : public ISkeleton { private: const std::optional object; - MethodCallback callback_; + LocalMethodCallback callback_; const std::string instance_; public: std::optional GetEndPoint() const noexcept override { return object; } - std::optional> Call( - std::vector payload) noexcept override { - return callback_(std::move(payload)); + std::pair>> Call( + std::vector payload, + const objects::Endpoint endpoint) noexcept override { + if (this->object.value().CanPass(endpoint.GetServiceId())) { + AppLogger::Info("[ SOMEIP SKELETON ]: " + instance_ + + " Access granted for service id: " + + std::to_string(endpoint.GetServiceId())); + const auto res = callback_(std::move(payload)); + if (res.has_value()) { + return {data::MessageCode::kEOk, std::move(res)}; + } else { + return {data::MessageCode::kENotOk, {}}; + } + } else { + AppLogger::Error("[ SOMEIP SKELETON ]: " + instance_ + + " Access denied for service id: " + + std::to_string(endpoint.GetServiceId())); + return {data::MessageCode::kENotReachable, {}}; + } } std::string GetName() const override { return instance_; } - MethodSkeleton(const std::string instance, MethodCallback callback) + MethodSkeleton(const std::string instance, LocalMethodCallback callback) : object{std::move(com::config::ComConfig::FindObject(instance))}, callback_{callback}, instance_{std::move(instance)} { diff --git a/communication-core/someip-database/code/config_db_parser.h b/communication-core/someip-database/code/config_db_parser.h index d904059f..2c96a4b8 100644 --- a/communication-core/someip-database/code/config_db_parser.h +++ b/communication-core/someip-database/code/config_db_parser.h @@ -13,6 +13,7 @@ #include #include +#include #include "communication-core/someip-database/code/config_db.h" #include "communication-core/someip-database/code/endpoint.h" @@ -99,7 +100,17 @@ class ConfigDbParser { if (obj.contains("service_id")) { service_id = obj["service_id"]; } - return objects::Endpoint{service_id, method_id}; + if (obj.contains("access_list")) { + auto list = obj["access_list"]; + std::vector access_list{}; + for (auto& [key, val] : list.items()) { + const uint16_t id = val; + access_list.push_back(id); + } + return objects::Endpoint{service_id, method_id, access_list}; + } else { + return objects::Endpoint{service_id, method_id}; + } } }; diff --git a/communication-core/someip-database/code/endpoint.h b/communication-core/someip-database/code/endpoint.h index a72311f0..d77c8e11 100644 --- a/communication-core/someip-database/code/endpoint.h +++ b/communication-core/someip-database/code/endpoint.h @@ -10,8 +10,10 @@ */ #ifndef COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_ENDPOINT_H_ #define COMMUNICATION_CORE_SOMEIP_DATABASE_CODE_ENDPOINT_H_ +#include #include - +#include +#include namespace simba { namespace com { namespace someip { @@ -20,12 +22,26 @@ class Endpoint { protected: const uint16_t service_id_; const uint16_t endpoint_id_; + const std::vector access_list_; public: Endpoint(const uint16_t service_id, const uint16_t endpoint_id) - : service_id_{service_id}, endpoint_id_{endpoint_id} {} + : service_id_{service_id}, endpoint_id_{endpoint_id}, access_list_{} {} + Endpoint(const uint16_t service_id, const uint16_t endpoint_id, + const std::vector access_list) + : service_id_{service_id}, + endpoint_id_{endpoint_id}, + access_list_{std::move(access_list)} {} uint16_t GetServiceId() const { return service_id_; } uint16_t GetEndpointId() const { return endpoint_id_; } + bool CanPass(const std::uint16_t& service_id) const { + if (access_list_.size() == 0) { + return true; + } + const auto res = + std::find(access_list_.begin(), access_list_.end(), service_id); + return res != access_list_.end(); + } }; } // namespace objects } // namespace someip diff --git a/communication-core/someip-database/test/config_db_parser_test.cc b/communication-core/someip-database/test/config_db_parser_test.cc index 75096e71..742cd88f 100644 --- a/communication-core/someip-database/test/config_db_parser_test.cc +++ b/communication-core/someip-database/test/config_db_parser_test.cc @@ -54,6 +54,8 @@ TEST(DataBaseParser, ParsingAndFindPubMethod) { const auto r = db->FindObject("ExampleApp/exampleMethod"); EXPECT_EQ(10, r.value().GetEndpointId()); EXPECT_EQ(0, r.value().GetServiceId()); + EXPECT_TRUE(r.value().CanPass(15)); + EXPECT_FALSE(r.value().CanPass(150)); } TEST(DataBaseParser, ParsingAndFindReqEvent) { diff --git a/communication-core/someip-database/test/resource/app_someip2.json b/communication-core/someip-database/test/resource/app_someip2.json index 9953dff6..feb73e44 100755 --- a/communication-core/someip-database/test/resource/app_someip2.json +++ b/communication-core/someip-database/test/resource/app_someip2.json @@ -12,10 +12,12 @@ ], "pub_methods": { "ExampleApp/exampleMethod": { - "method_id": 10 + "method_id": 10, + "access_list": [15] }, "ExampleApp/exampleMethod2": { - "method_id": 100 + "method_id": 100, + "access_list": [1000] } }, "pub_event": { diff --git a/communication-core/someip/factory/Isomeip_header_factory.h b/communication-core/someip/factory/Isomeip_header_factory.h index b4377b75..f4885253 100644 --- a/communication-core/someip/factory/Isomeip_header_factory.h +++ b/communication-core/someip/factory/Isomeip_header_factory.h @@ -59,6 +59,9 @@ class ISomeIpHeaderFactory { const std::uint16_t service_id, const std::uint16_t methode_id) = 0; virtual std::shared_ptr CreateRequestACK( const std::uint16_t service_id, const std::uint16_t methode_id) = 0; + virtual std::shared_ptr CreateErrorResponse( + const std::uint16_t service_id, const std::uint16_t methode_id, + const simba::com::data::MessageCode res_flag) = 0; virtual ~ISomeIpHeaderFactory() = default; }; } // namespace factory diff --git a/communication-core/someip/factory/someip_header_factory.cc b/communication-core/someip/factory/someip_header_factory.cc index 070ddf69..56173921 100644 --- a/communication-core/someip/factory/someip_header_factory.cc +++ b/communication-core/someip/factory/someip_header_factory.cc @@ -41,6 +41,13 @@ std::shared_ptr SomeIpHeaderFactory::CreateResponse( return std::make_shared(service_id, methode_id, 0x00, 0x00, 0x00, 0x1, data::kResponse, res_flag); } +std::shared_ptr SomeIpHeaderFactory::CreateErrorResponse( + const std::uint16_t service_id, const std::uint16_t methode_id, + const simba::com::data::MessageCode res_flag) { + return std::make_shared(service_id, methode_id, 0x00, 0x00, + 0x00, 0x1, data::kError, res_flag); +} + std::shared_ptr SomeIpHeaderFactory::CreateRequestACK( const std::uint16_t service_id, const std::uint16_t methode_id) { diff --git a/communication-core/someip/factory/someip_header_factory.h b/communication-core/someip/factory/someip_header_factory.h index 62b5f6b5..854bdf1d 100644 --- a/communication-core/someip/factory/someip_header_factory.h +++ b/communication-core/someip/factory/someip_header_factory.h @@ -60,6 +60,9 @@ class SomeIpHeaderFactory : public ISomeIpHeaderFactory { const std::uint16_t service_id, const std::uint16_t methode_id) override; std::shared_ptr CreateRequestACK( const std::uint16_t service_id, const std::uint16_t methode_id) override; + std::shared_ptr CreateErrorResponse( + const std::uint16_t service_id, const std::uint16_t methode_id, + const simba::com::data::MessageCode res_flag) override; ~SomeIpHeaderFactory() = default; }; } // namespace factory diff --git a/communication-core/someip/message_code.h b/communication-core/someip/message_code.h index 46e6d29f..4444957e 100644 --- a/communication-core/someip/message_code.h +++ b/communication-core/someip/message_code.h @@ -13,7 +13,7 @@ namespace simba { namespace com { namespace data { -enum MessageCode { +enum MessageCode: uint8_t { kEOk = 0x00, kENotOk = 0x01, kEUnknownService = 0x02, diff --git a/communication-core/someip/message_type.h b/communication-core/someip/message_type.h index ad5134ca..d2f54d68 100644 --- a/communication-core/someip/message_type.h +++ b/communication-core/someip/message_type.h @@ -13,7 +13,7 @@ namespace simba { namespace com { namespace data { -enum MessageType { +enum MessageType: uint8_t { kRequest = 0x00, kRequestNoReturn = 0x01, kNotification = 0x02, diff --git a/deployment b/deployment index 32a5b2f4..51e959de 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 32a5b2f4813c41bed811fc439c6662990e8df614 +Subproject commit 51e959de63445ca50ee4d00a0eb3aa38d0f2c9fd From b9d1412da633c0a6452ba3eec82657807eee9bfe Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sat, 27 Apr 2024 14:11:09 +0200 Subject: [PATCH 48/71] sub repo update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 51e959de..2bfbfdd5 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 51e959de63445ca50ee4d00a0eb3aa38d0f2c9fd +Subproject commit 2bfbfdd56d9ed173196b4a581b0764b42f4767d7 From a78a67db0287ecd336cac27a0d1a5553b5fdd7d8 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Wed, 10 Apr 2024 21:44:57 +0200 Subject: [PATCH 49/71] Base version --- .github/workflows/build_cpu.yaml | 13 +- .github/workflows/build_cpu_linux.yaml | 3 +- apps/diag_ota/BUILD | 0 apps/diag_ota/code/BUILD | 13 ++ apps/diag_ota/code/application/BUILD | 13 ++ apps/diag_ota/code/application/diag-ota.cc | 164 ++++++++++++++++++ apps/diag_ota/code/application/diag-ota.h | 65 +++++++ apps/diag_ota/code/main.cc | 18 ++ apps/example/router.cc | 29 +--- .../someip-controller/controller.h | 1 + .../someip-controller/event_proxy.h | 4 +- .../someip-controller/event_skeleton.h | 4 +- .../someip-controller/method_proxy.h | 6 +- .../someip-controller/method_skeleton.h | 8 +- core/application/application_common.cc | 2 +- deployment | 2 +- diag/base/controller/BUILD | 1 + diag/base/controller/diag_controller.cc | 1 + diag/controller/BUILD | 1 + diag/controller/diag_controller.h | 34 +++- sock.py | 10 ++ 21 files changed, 340 insertions(+), 52 deletions(-) create mode 100644 apps/diag_ota/BUILD create mode 100644 apps/diag_ota/code/BUILD create mode 100644 apps/diag_ota/code/application/BUILD create mode 100644 apps/diag_ota/code/application/diag-ota.cc create mode 100644 apps/diag_ota/code/application/diag-ota.h create mode 100644 apps/diag_ota/code/main.cc create mode 100644 sock.py diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 05613f69..61139426 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -28,19 +28,8 @@ jobs: uses: thollander/actions-comment-pull-request@v2 with: message: | - Successfully built software for BeagleBone (EC) + Starting built software for BeagleBone (EC) comment_tag: to_delete - mode: delete - - - name: RM 2 - if: contains(steps.pr-labels.outputs.labels, 'check-bbb') - uses: thollander/actions-comment-pull-request@v2 - with: - message: | - Successfully built software for BeagleBone (FC) - comment_tag: to_delete - mode: delete - - name: Install bazel if: contains(steps.pr-labels.outputs.labels, 'check-bbb') diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index f1b8c925..e160244c 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -26,9 +26,8 @@ jobs: uses: thollander/actions-comment-pull-request@v2 with: message: | - Successfully built software for linux + Starting built software for linux comment_tag: to_delete - mode: delete - name: Install bazel if: contains(steps.pr-labels.outputs.labels, 'check') run: | diff --git a/apps/diag_ota/BUILD b/apps/diag_ota/BUILD new file mode 100644 index 00000000..e69de29b diff --git a/apps/diag_ota/code/BUILD b/apps/diag_ota/code/BUILD new file mode 100644 index 00000000..f1c5bf52 --- /dev/null +++ b/apps/diag_ota/code/BUILD @@ -0,0 +1,13 @@ +cc_binary( + name = "diag_ota", + srcs = [ + "main.cc", + ], + visibility = ["//deployment/apps/diag_ota:__subpackages__"], + deps = [ + "//apps/diag_ota/code/application:diag-app", + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", + "//core/application:simba_application", + ], +) \ No newline at end of file diff --git a/apps/diag_ota/code/application/BUILD b/apps/diag_ota/code/application/BUILD new file mode 100644 index 00000000..8f02dc90 --- /dev/null +++ b/apps/diag_ota/code/application/BUILD @@ -0,0 +1,13 @@ +cc_library( + name = "diag-app", + srcs = ["diag-ota.cc"], + hdrs = ["diag-ota.h"], + visibility = ["//apps/diag_ota:__subpackages__"], + deps = [ + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", + "//core/application:simba_application", + "//core/json:simba_json", + "//diag/base/controller:diag_controller", + ], +) diff --git a/apps/diag_ota/code/application/diag-ota.cc b/apps/diag_ota/code/application/diag-ota.cc new file mode 100644 index 00000000..b9f5bd56 --- /dev/null +++ b/apps/diag_ota/code/application/diag-ota.cc @@ -0,0 +1,164 @@ +/** + * @file diag-ota.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ +#include "apps/diag_ota/code/application/diag-ota.h" + +#include +#include +#include + +#include "core/json/json_parser.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace diag_ota { + +/** + * @brief This function is called to launch the application + * + * @param token stop token + */ +core::ErrorCode DiagOta::Run(std::stop_token token) { + AppLogger::Info("Ecu id: " + std::to_string(ecu_id)); + AppLogger::Info("Eng token: " + std::to_string(eng_token)); + AppLogger::Info("Plant token: " + std::to_string(plant_token)); + AppLogger::Info("ECU MODE token: " + std::to_string(mode)); + if (eng_token == mode) { + AppLogger::Info("ECU MODE: Eng mode"); + mode_event->SetValue({0x01}); + } else { + AppLogger::Info("ECU MODE: Plant mode"); + mode_event->SetValue({0x00}); + } + diag_controller.Read(1000, 10); + this->SleepMainThread(); +} +/** + * @brief This function is called to initialiaze the application + * + * @param parms map with parms + */ +core::ErrorCode DiagOta::Initialize( + const std::unordered_map& parms) { + auto obj_r = core::json::JsonParser::Parser("/opt/" + parms.at("app_name") + + "/etc/config.json"); + if (!obj_r.has_value()) { + AppLogger::Error("File not found: /opt/" + parms.at("app_name") + + "/etc/config.json"); + return core::kError; + } + auto json_obj = obj_r.value(); + { + auto ip_t = json_obj.GetNumber("ecu_id"); + if (!ip_t.has_value()) { + AppLogger::Error("ecu_id not found in config file"); + return core::kError; + } + ecu_id = ip_t.value(); + } + { + auto ip_t = json_obj.GetNumber("eng_token"); + if (!ip_t.has_value()) { + AppLogger::Error("eng_token not found in config file"); + return core::kError; + } + eng_token = ip_t.value(); + } + { + auto ip_t = json_obj.GetNumber("plant-token"); + if (!ip_t.has_value()) { + AppLogger::Error("plant-token not found in config file"); + return core::kError; + } + plant_token = ip_t.value(); + } + { + auto ip_t = json_obj.GetNumber("current_mode"); + if (!ip_t.has_value()) { + AppLogger::Error("current_mode not found in config file"); + return core::kError; + } + mode = ip_t.value(); + } + if (this->com->GetServiceId() == 512) { + mode_event = std::make_shared( + "FC_DiagOtaApp/currentMode"); + write_someip = std::make_shared( + "FC_DiagOtaApp/diagMethodRequestWrite", + std::bind(&DiagOta::WriteSomeip, this, std::placeholders::_1)); + read_someip = std::make_shared( + "FC_DiagOtaApp/diagMethodRequestRead", + std::bind(&DiagOta::ReadSomeip, this, std::placeholders::_1)); + job_someip = std::make_shared( + "FC_DiagOtaApp/diagMethodRequestJob", + std::bind(&DiagOta::JobSomeip, this, std::placeholders::_1)); + this->com->Add(mode_event); + this->com->Add(write_someip); + this->com->Add(read_someip); + this->com->Add(job_someip); + } else { + mode_event = std::make_shared( + "EC_DiagOtaApp/currentMode"); + write_someip = std::make_shared( + "EC_DiagOtaApp/diagMethodRequestWrite", + std::bind(&DiagOta::WriteSomeip, this, std::placeholders::_1)); + read_someip = std::make_shared( + "EC_DiagOtaApp/diagMethodRequestRead", + std::bind(&DiagOta::ReadSomeip, this, std::placeholders::_1)); + job_someip = std::make_shared( + "EC_DiagOtaApp/diagMethodRequestJob", + std::bind(&DiagOta::JobSomeip, this, std::placeholders::_1)); + this->com->Add(mode_event); + this->com->Add(write_someip); + this->com->Add(read_someip); + this->com->Add(job_someip); + } + + this->someip_diag_controller = std::make_unique( + 0x00, std::make_unique()); + this->someip_diag_controller->Init(); +} + +std::optional> DiagOta::ReadSomeip( + const std::vector payload) { + if (payload.size() != 3U) { + return {}; + } + uint16_t s_id{payload[0] << 1 + payload[2]}; + return someip_diag_controller->Read(s_id, payload[3]); +} +std::optional> DiagOta::JobSomeip( + const std::vector payload) { + if (payload.size() < 3U) { + return {}; + } + std::vector pp{}; + uint16_t s_id{payload[0] << 1 + payload[2]}; + std::copy(payload.begin() + 3, payload.end(), std::back_inserter(pp)); + return someip_diag_controller->Job(s_id, payload[3], std::move(pp)); +} +std::optional> DiagOta::WriteSomeip( + const std::vector payload) { + if (payload.size() < 3U) { + return {}; + } + std::vector pp{}; + uint16_t s_id{payload[0] << 1 + payload[2]}; + std::copy(payload.begin() + 3, payload.end(), std::back_inserter(pp)); + if (someip_diag_controller->Write(s_id, payload[3], std::move(pp)) == + core::ErrorCode::kOk) { + return std::vector{}; + } else { + return {}; + } +} + +} // namespace diag_ota +} // namespace simba diff --git a/apps/diag_ota/code/application/diag-ota.h b/apps/diag_ota/code/application/diag-ota.h new file mode 100644 index 00000000..335bbfd7 --- /dev/null +++ b/apps/diag_ota/code/application/diag-ota.h @@ -0,0 +1,65 @@ +/** + * @file diag-ota.h + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef APPS_DIAG_OTA_CODE_APPLICATION_DIAG_OTA_H_ +#define APPS_DIAG_OTA_CODE_APPLICATION_DIAG_OTA_H_ + +#include +#include +#include +#include +#include + +#include "communication-core/someip-controller/event_skeleton.h" +#include "communication-core/someip-controller/method_skeleton.h" +#include "core/application/application_no_ipc.h" +#include "diag/base/controller/idiag_controller.h" +namespace simba { +namespace diag_ota { + +class DiagOta : public core::ApplicationNoIPC { + protected: + std::unique_ptr someip_diag_controller; + uint32_t ecu_id{0}; + uint32_t eng_token{0}; + uint32_t plant_token{0}; + uint32_t mode{0}; + std::shared_ptr mode_event; + std::shared_ptr read_someip; + std::shared_ptr write_someip; + std::shared_ptr job_someip; + /** + * @brief This function is called to launch the application + * + * @param token stop token + */ + core::ErrorCode Run(std::stop_token token) final; + /** + * @brief This function is called to initialiaze the application + * + * @param parms map with parms + */ + core::ErrorCode Initialize( + const std::unordered_map& parms) final; + std::optional> ReadSomeip( + const std::vector payload); + std::optional> JobSomeip( + const std::vector payload); + std::optional> WriteSomeip( + const std::vector payload); + + public: + ~DiagOta() = default; +}; + +} // namespace diag_ota +} // namespace simba +#endif // APPS_DIAG_OTA_CODE_APPLICATION_DIAG_OTA_H_ diff --git a/apps/diag_ota/code/main.cc b/apps/diag_ota/code/main.cc new file mode 100644 index 00000000..1d90551d --- /dev/null +++ b/apps/diag_ota/code/main.cc @@ -0,0 +1,18 @@ +/** + * @file main.cc + * @author Bartosz Snieg (snieg45@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-24 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "apps/diag_ota/code/application/diag-ota.h" +#include "core/application/application_factory.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/apps/example/router.cc b/apps/example/router.cc index b3f9c1a9..df98a379 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -21,31 +21,14 @@ namespace simba { namespace router { core::ErrorCode Router::Run(std::stop_token token) { - auto example = std::make_shared( - "ExampleApp/exampleMethod", - [this](const std::vector payload) - -> std::optional> { - return std::vector{0, 1, 2}; + auto current_mode_proxy = std::make_shared( + "ExampleApp/currentMode", [](const std::vector payload) { + AppLogger::Info("Current cpu mode: " + std::to_string(payload[0])); }); - auto example2 = std::make_shared( - "ExampleApp/exampleMethod2", - [this](const std::vector payload) - -> std::optional> { - return std::vector{0, 1, 2}; - }); - com->Add(example); - com->Add(example2); - auto dtc = std::make_shared(20); - diag_controller.RegisterDTC(dtc); +com->Add(current_mode_proxy); +current_mode_proxy->StartFindService(); while (true) { - AppLogger::Debug("AppLogger::Debug"); - AppLogger::Info("AppLogger::Info"); - dtc->Pass(); - this->gpio_.SetPinValue(1, gpio::Value::HIGH); - std::this_thread::sleep_for(std::chrono::seconds(1)); - this->gpio_.SetPinValue(1, gpio::Value::LOW); - dtc->Failed(); - std::this_thread::sleep_for(std::chrono::seconds(1)); + this->SleepMainThread(); } return core::ErrorCode::kOk; } diff --git a/communication-core/someip-controller/controller.h b/communication-core/someip-controller/controller.h index 50f30257..155ee492 100644 --- a/communication-core/someip-controller/controller.h +++ b/communication-core/someip-controller/controller.h @@ -92,6 +92,7 @@ class Controller { public: void Add(std::shared_ptr proxy); void Add(std::shared_ptr skeleton); + uint16_t GetServiceId() const { return service_id; } explicit Controller(std::shared_ptr db_); ~Controller() = default; }; diff --git a/communication-core/someip-controller/event_proxy.h b/communication-core/someip-controller/event_proxy.h index 8ba9732e..c68759da 100644 --- a/communication-core/someip-controller/event_proxy.h +++ b/communication-core/someip-controller/event_proxy.h @@ -43,14 +43,14 @@ class EventProxyBase : public IProxy { bool is_callback{false}; bool is_response{false}; std::vector response; - data::MessageCode response_code; + com::data::MessageCode response_code; FindCallback f_callback_; SubscribeCallback s_callback; EventCallback callback_; const bool is_event_callback; void RxCallback(const std::vector payload, simba::com::data::MessageCode code, const uint16_t) { - if (code == data::MessageCode::kEOk) { + if (code == com::data::MessageCode::kEOk) { if (is_event_callback) { callback_(std::move(payload)); return; diff --git a/communication-core/someip-controller/event_skeleton.h b/communication-core/someip-controller/event_skeleton.h index e609dc61..d8ff3d29 100644 --- a/communication-core/someip-controller/event_skeleton.h +++ b/communication-core/someip-controller/event_skeleton.h @@ -49,7 +49,7 @@ class EventSkeleton : public ISkeleton { std::optional GetEndPoint() const noexcept override { return object; } - std::pair>> Call( + std::pair>> Call( std::vector payload, const objects::Endpoint endpoint) noexcept override { return {}; @@ -76,7 +76,7 @@ class EventSkeleton : public ISkeleton { std::unique_lock lkv{value_mutex}; if (value.size() > 0) { callback_(this->value, object.value(), objects::Interface{"", 0}, - data::MessageType::kNotification, nullptr); + com::data::MessageType::kNotification, nullptr); } } } diff --git a/communication-core/someip-controller/method_proxy.h b/communication-core/someip-controller/method_proxy.h index b5651af3..320456dd 100644 --- a/communication-core/someip-controller/method_proxy.h +++ b/communication-core/someip-controller/method_proxy.h @@ -38,7 +38,7 @@ class MethodProxyBase : public IProxy { bool is_callback{false}; bool is_response{false}; std::vector response; - data::MessageCode response_code; + com::data::MessageCode response_code; uint16_t transfer_id_; SendCallback callback_; FindCallback f_callback_; @@ -109,10 +109,10 @@ class MethodProxyBase : public IProxy { d_callback_(transfer_id_); return {}; } - if (response_code == data::MessageCode::kEOk) { + if (response_code == com::data::MessageCode::kEOk) { return std::move(this->response); } else { - if (response_code == data::MessageCode::kENotReachable) { + if (response_code == com::data::MessageCode::kENotReachable) { AppLogger::Error("[ SOMEIP PROXY ](" + instance + "): Access denied !"); } else { AppLogger::Error( diff --git a/communication-core/someip-controller/method_skeleton.h b/communication-core/someip-controller/method_skeleton.h index ff6f8f53..9f1fa74a 100644 --- a/communication-core/someip-controller/method_skeleton.h +++ b/communication-core/someip-controller/method_skeleton.h @@ -40,7 +40,7 @@ class MethodSkeleton : public ISkeleton { std::optional GetEndPoint() const noexcept override { return object; } - std::pair>> Call( + std::pair>> Call( std::vector payload, const objects::Endpoint endpoint) noexcept override { if (this->object.value().CanPass(endpoint.GetServiceId())) { @@ -49,15 +49,15 @@ class MethodSkeleton : public ISkeleton { std::to_string(endpoint.GetServiceId())); const auto res = callback_(std::move(payload)); if (res.has_value()) { - return {data::MessageCode::kEOk, std::move(res)}; + return {com::data::MessageCode::kEOk, std::move(res)}; } else { - return {data::MessageCode::kENotOk, {}}; + return {com::data::MessageCode::kENotOk, {}}; } } else { AppLogger::Error("[ SOMEIP SKELETON ]: " + instance_ + " Access denied for service id: " + std::to_string(endpoint.GetServiceId())); - return {data::MessageCode::kENotReachable, {}}; + return {com::data::MessageCode::kENotReachable, {}}; } } std::string GetName() const override { return instance_; } diff --git a/core/application/application_common.cc b/core/application/application_common.cc index a8883a92..d1c5f06d 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -171,7 +171,7 @@ ErrorCode ApplicationCommon::DiagConfig( nlohmann::json data = nlohmann::json::parse(file); uint16_t app_id_{}; if (data.contains("app_id")) { - if (data.at("app_id").is_string()) { + if (data.at("app_id").is_number()) { app_id_ = data.at("app_id"); diag_controller.Init(app_id_); return ErrorCode::kOk; diff --git a/deployment b/deployment index 2bfbfdd5..46057f26 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 2bfbfdd56d9ed173196b4a581b0764b42f4767d7 +Subproject commit 46057f26968b9f28bcee78ff226d27e18dfab9d7 diff --git a/diag/base/controller/BUILD b/diag/base/controller/BUILD index f1e28581..78bca190 100644 --- a/diag/base/controller/BUILD +++ b/diag/base/controller/BUILD @@ -23,6 +23,7 @@ cc_library( visibility = [ "//apps:__subpackages__", "//core:__subpackages__", + "//diag/controller:__subpackages__", "//mw:__subpackages__", ], deps = [ diff --git a/diag/base/controller/diag_controller.cc b/diag/base/controller/diag_controller.cc index b13272ae..4af00da5 100644 --- a/diag/base/controller/diag_controller.cc +++ b/diag/base/controller/diag_controller.cc @@ -49,6 +49,7 @@ simba::core::ErrorCode DiagController::AddMethod( simba::core::ErrorCode DiagController::Init() { if (this->socket_driver == nullptr) { + AppLogger::Error("[DIAG_CONTROLLER] No socket!!"); return core::ErrorCode::kError; } diff --git a/diag/controller/BUILD b/diag/controller/BUILD index 6509a2bb..2c7c0bf5 100644 --- a/diag/controller/BUILD +++ b/diag/controller/BUILD @@ -3,6 +3,7 @@ cc_library( hdrs = ["diag_controller.h"], visibility = ["//visibility:public"], deps = [ + "//diag/base/controller:diag_controller", "//diag/dtc/controller:diag_dtc_I_controller", "//diag/dtc/controller:diag_dtc_controller", ], diff --git a/diag/controller/diag_controller.h b/diag/controller/diag_controller.h index 45e969e9..94dfd138 100644 --- a/diag/controller/diag_controller.h +++ b/diag/controller/diag_controller.h @@ -12,10 +12,14 @@ #define DIAG_CONTROLLER_DIAG_CONTROLLER_H_ #include +#include +#include +#include "communication-core/sockets/ipc_socket.h" +#include "diag/base/controller/diag_controller.h" +#include "diag/base/controller/idiag_controller.h" #include "diag/dtc/controller/dtc_controller.h" #include "diag/dtc/controller/i_dtc.h" - namespace simba { namespace diag { @@ -25,10 +29,36 @@ class CommonDiagController { this->dtc_controller.RegisterDTC(dtc_object); return core::ErrorCode::kOk; } - void Init(uint16_t service_id) { dtc_controller.Init(service_id); } + void Init(uint16_t service_id) { + dtc_controller.Init(service_id); + diag_controller = std::make_unique( + service_id, std::make_unique()); + diag_controller->Init(); + } + simba::core::ErrorCode AddMethod(const uint8_t diag_id, DiagMethod callback, + const DiagMethodType method_type) { + return diag_controller->AddMethod(std::move(diag_id), std::move(callback), + std::move(method_type)); + } + std::optional> Read(const uint16_t service_id, + const uint8_t diag_id) { + return diag_controller->Read(std::move(service_id), std::move(diag_id)); + } + simba::core::ErrorCode Write(const uint16_t service_id, const uint8_t diag_id, + const std::vector payload) { + return diag_controller->Write(std::move(service_id), std::move(diag_id), + std::move(payload)); + } + std::optional> Job(const uint16_t service_id, + const uint8_t diag_id, + const std::vector payload) { + return diag_controller->Job(std::move(service_id), std::move(diag_id), + std::move(payload)); + } private: dtc::DtcController dtc_controller{}; + std::unique_ptr diag_controller; }; } // namespace diag } // namespace simba diff --git a/sock.py b/sock.py new file mode 100644 index 00000000..16cb6614 --- /dev/null +++ b/sock.py @@ -0,0 +1,10 @@ +import socket +UDP_IP = "192.168.10.4" +UDP_PORT = 1001 +sock = socket.socket(socket.AF_INET, # Internet + socket.SOCK_DGRAM) # UDP +sock.bind((UDP_IP, UDP_PORT)) + +while True: + data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes + print("received message: %s" % data) \ No newline at end of file From 47e9fb8837761fb8b15ed151551df51a7d166828 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sat, 27 Apr 2024 17:42:25 +0200 Subject: [PATCH 50/71] sub repo update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 46057f26..1a3d29a1 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 46057f26968b9f28bcee78ff226d27e18dfab9d7 +Subproject commit 1a3d29a1a690d723412639da6a659be00c388ba8 From 150d5faa2d81ffb4a53816418cc58cbda536548d Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 09:13:49 +0200 Subject: [PATCH 51/71] add caching fix caching 3 --- .github/workflows/build_cpu.yaml | 7 ++++++- .github/workflows/build_cpu_linux.yaml | 7 ++++++- .github/workflows/run_ut.yaml | 6 ++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 61139426..57cc2351 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -22,7 +22,12 @@ jobs: with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} - + - name: Cache bazel directories + uses: actions/cache@v2 + with: + path: | + /home/runner/.cache/bazel/_bazel_runner/* + key: ${{ runner.os }}-bazel-bbb-${{ hashFiles('**/lockfiles') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') uses: thollander/actions-comment-pull-request@v2 diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index e160244c..e5ac70f6 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -14,13 +14,18 @@ jobs: - name: check lable id: pr-labels uses: joerick/pr-labels-action@v1.0.8 - - name: Checkout Repository if: contains(steps.pr-labels.outputs.labels, 'check') uses: actions/checkout@v2 with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} + - name: Cache bazel directories + uses: actions/cache@v2 + with: + path: | + /home/runner/.cache/bazel/_bazel_runner/* + key: ${{ runner.os }}-bazel-pc-${{ hashFiles('**/lockfiles') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') uses: thollander/actions-comment-pull-request@v2 diff --git a/.github/workflows/run_ut.yaml b/.github/workflows/run_ut.yaml index 0ea3bac5..9205bccb 100644 --- a/.github/workflows/run_ut.yaml +++ b/.github/workflows/run_ut.yaml @@ -13,6 +13,12 @@ jobs: steps: - name: Checkout Repository uses: actions/checkout@v2 + - name: Cache bazel directories + uses: actions/cache@v2 + with: + path: | + /home/runner/.cache/bazel/_bazel_runner/* + key: ${{ runner.os }}-bazel-ut-${{ hashFiles('**/lockfiles') }} - name: Install bazel run: | From 492b3d7621f64631b00d45491a2f22fe0db32b69 Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Sun, 28 Apr 2024 10:11:10 +0200 Subject: [PATCH 52/71] Makr i2c +pca (#69) --- apps/example/router.cc | 30 +++- core/application/application_common.cc | 1 + core/application/application_common.h | 1 + core/application/application_mw.cc | 1 + core/i2c/BUILD | 12 +- core/i2c/Ii2cdriver.hpp | 36 ----- core/i2c/i2cdriver.cpp | 74 +++++----- core/i2c/i2cdriver.h | 34 ----- core/i2c/i2cdriver.hpp | 50 +++++++ core/i2c/mock/BUILD | 24 ++-- core/i2c/mock/mock_i2cdriver.hpp | 32 ----- deployment | 2 +- diag/dtc/controller/dtc.h | 2 +- mw/em/code/em_application.cc | 2 - mw/i2c_service/BUILD | 20 +++ mw/i2c_service/controller/BUILD | 16 +++ mw/i2c_service/controller/i2c_controller.cpp | 37 +++++ mw/i2c_service/controller/i2c_controller.h | 58 ++++++++ mw/i2c_service/controller/pca9685/BUILD | 18 +++ .../controller/pca9685/controller.cpp | 135 ++++++++++++++++++ .../controller/pca9685/controller.hpp | 55 +++++++ mw/i2c_service/data/BUILD | 23 +++ mw/i2c_service/data/header.cpp | 31 ++++ mw/i2c_service/data/header.h | 51 +++++++ mw/i2c_service/data/i2c_factory.cpp | 42 ++++++ mw/i2c_service/data/i2c_factory.h | 29 ++++ mw/i2c_service/i2c_service.cpp | 71 +++++++++ mw/i2c_service/i2c_service.h | 38 +++++ mw/i2c_service/main.cpp | 17 +++ mw/i2c_service/tests/BUILD | 11 ++ mw/i2c_service/tests/test_header.cpp | 42 ++++++ services/ServoService/BUILD | 18 +++ services/ServoService/main.cc | 18 +++ services/ServoService/servoService.cpp | 100 +++++++++++++ services/ServoService/servoService.hpp | 44 ++++++ 35 files changed, 1006 insertions(+), 169 deletions(-) delete mode 100644 core/i2c/Ii2cdriver.hpp delete mode 100644 core/i2c/i2cdriver.h create mode 100644 core/i2c/i2cdriver.hpp delete mode 100644 core/i2c/mock/mock_i2cdriver.hpp create mode 100644 mw/i2c_service/BUILD create mode 100644 mw/i2c_service/controller/BUILD create mode 100644 mw/i2c_service/controller/i2c_controller.cpp create mode 100644 mw/i2c_service/controller/i2c_controller.h create mode 100644 mw/i2c_service/controller/pca9685/BUILD create mode 100644 mw/i2c_service/controller/pca9685/controller.cpp create mode 100644 mw/i2c_service/controller/pca9685/controller.hpp create mode 100644 mw/i2c_service/data/BUILD create mode 100644 mw/i2c_service/data/header.cpp create mode 100644 mw/i2c_service/data/header.h create mode 100644 mw/i2c_service/data/i2c_factory.cpp create mode 100644 mw/i2c_service/data/i2c_factory.h create mode 100644 mw/i2c_service/i2c_service.cpp create mode 100644 mw/i2c_service/i2c_service.h create mode 100644 mw/i2c_service/main.cpp create mode 100644 mw/i2c_service/tests/BUILD create mode 100644 mw/i2c_service/tests/test_header.cpp create mode 100644 services/ServoService/BUILD create mode 100644 services/ServoService/main.cc create mode 100644 services/ServoService/servoService.cpp create mode 100644 services/ServoService/servoService.hpp diff --git a/apps/example/router.cc b/apps/example/router.cc index df98a379..c097a005 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -14,21 +14,45 @@ #include #include "communication-core/someip-controller/event_proxy.h" +#include "communication-core/someip-controller/method_proxy.h" #include "communication-core/someip-controller/method_skeleton.h" #include "core/logger/Logger.h" #include "diag/dtc/controller/dtc.h" namespace simba { namespace router { +#define EEPROM_DEVICE "/dev/i2c-2" // Ścieżka do urządzenia I2C +#define EEPROM_ADDRESS 0x50 // Adres EEPROM +#define DATA_SIZE 128 + core::ErrorCode Router::Run(std::stop_token token) { auto current_mode_proxy = std::make_shared( "ExampleApp/currentMode", [](const std::vector payload) { AppLogger::Info("Current cpu mode: " + std::to_string(payload[0])); }); -com->Add(current_mode_proxy); -current_mode_proxy->StartFindService(); + auto example2 = std::make_shared( + "ExampleApp/exampleMethod2", + [this](const std::vector payload) + -> std::optional> { + return std::vector{0, 1, 2}; + }); + auto servo = std::make_shared("ExampleApp/setServoValue"); + com->Add(servo); + com->Add(example2); + servo->StartFindService(); + auto dtc = std::make_shared(20); + diag_controller.RegisterDTC(dtc); while (true) { - this->SleepMainThread(); + AppLogger::Debug("AppLogger::Debug"); + AppLogger::Info("AppLogger::Info"); + dtc->Pass(); + this->gpio_.SetPinValue(1, gpio::Value::HIGH); + servo->Get({1}); + std::this_thread::sleep_for(std::chrono::seconds(1)); + this->gpio_.SetPinValue(1, gpio::Value::LOW); + servo->Get({0}); + dtc->Failed(); + std::this_thread::sleep_for(std::chrono::seconds(1)); } return core::ErrorCode::kOk; } diff --git a/core/application/application_common.cc b/core/application/application_common.cc index d1c5f06d..7dfdf779 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -173,6 +173,7 @@ ErrorCode ApplicationCommon::DiagConfig( if (data.contains("app_id")) { if (data.at("app_id").is_number()) { app_id_ = data.at("app_id"); + this->app_id_ = app_id_; diag_controller.Init(app_id_); return ErrorCode::kOk; } else { diff --git a/core/application/application_common.h b/core/application/application_common.h index 7233ef6a..c2d647da 100644 --- a/core/application/application_common.h +++ b/core/application/application_common.h @@ -27,6 +27,7 @@ namespace core { class ApplicationCommon : public IApplication { protected: diag::CommonDiagController diag_controller{}; + uint16_t app_id_; std::stop_source source; diag::exec::ExecController exec_; std::unique_ptr com; diff --git a/core/application/application_mw.cc b/core/application/application_mw.cc index cbd75c09..cf828cbe 100644 --- a/core/application/application_mw.cc +++ b/core/application/application_mw.cc @@ -54,6 +54,7 @@ ErrorCode ApplicationMW::MwConfig( } auto app_ = obj.GetNumber("app_id"); if (app_.has_value()) { + this->app_id_ = app_.value(); this->exec_.Init(app_.value()); } else { return ErrorCode::kError; diff --git a/core/i2c/BUILD b/core/i2c/BUILD index 77f11529..1c5fac66 100644 --- a/core/i2c/BUILD +++ b/core/i2c/BUILD @@ -1,12 +1,12 @@ cc_library( name = "i2cdriver", srcs = ["i2cdriver.cpp"], - hdrs = [ - "i2cdriver.h", - "Ii2cdriver.hpp", - ], + hdrs = ["i2cdriver.hpp",], deps = [ "//core/common:common_types", ], - visibility = ["//core:__subpackages__"], -) + visibility = ["//core:__subpackages__", + "//mw:__subpackages__", + "//apps:__subpackages__", + ], +) \ No newline at end of file diff --git a/core/i2c/Ii2cdriver.hpp b/core/i2c/Ii2cdriver.hpp deleted file mode 100644 index f9f92878..00000000 --- a/core/i2c/Ii2cdriver.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @file Ii2cdriver.hpp - * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief - * @version 0.1 - * @date 2024-03-12 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef CORE_I2C_II2CDRIVER_HPP_ -#define CORE_I2C_II2CDRIVER_HPP_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "core/common/error_code.h" - -namespace simba { -namespace core { -class II2C { - public: - virtual ErrorCode init(const std::string& path) = 0; - virtual std::optional> Read(const uint8_t address, const uint8_t reg); - virtual ErrorCode Write(const uint8_t address, const uint8_t reg, std::vector data); -}; -} // namespace core -} // namespace simba - -#endif // CORE_I2C_II2CDRIVER_HPP_ diff --git a/core/i2c/i2cdriver.cpp b/core/i2c/i2cdriver.cpp index f5509d84..bc24b183 100644 --- a/core/i2c/i2cdriver.cpp +++ b/core/i2c/i2cdriver.cpp @@ -1,62 +1,52 @@ /** * @file i2cdriver.cpp - * @author Michal Mankowski (m.mankowski2004@gmail.com) - * @brief This file defines I2C driver + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief * @version 0.1 - * @date 2024-01-14 + * @date 2024-04-03 * * @copyright Copyright (c) 2024 * */ -#include "i2cdriver.h" + +#include "core/i2c/i2cdriver.hpp" + +#define path "/dev/i2c-2" namespace simba { namespace core { -int32_t I2C::i2c_smbus_access(char read_write, uint8_t command, int size, union i2c_smbus_data *data) { - i2c_smbus_ioctl_data args; - args.read_write = read_write; - args.command = command; - args.size = size; - args.data = data; - return ioctl(this->file, I2C_SMBUS, &args); -} -std::optional I2C::i2c_smbus_read_byte_data(const uint8_t command) { - union i2c_smbus_data data; - if (i2c_smbus_access(I2C_SMBUS_READ, command, I2C_SMBUS_BYTE_DATA, &data) != 0) { - return{}; +namespace i2c { + +core::ErrorCode I2CDriver::Init() { + if ((this->i2cFile = open(path, O_RDWR)) < 0) { + return core::ErrorCode::kInitializeError; } - return std::optional(0xFF & data.byte); + return core::ErrorCode::kOk; } -ErrorCode I2C::init(const std::string& path) { - this->file = open(path.c_str(), O_RDWR); - if (this->file < 0) { - return ErrorCode::kError; + +core::ErrorCode I2CDriver::Ioctl(const uint8_t address, const uint16_t type) { + if (ioctl(this->i2cFile, type, address) < 0) { + return core::ErrorCode::kInitializeError; } - return ErrorCode::kOk; + return core::ErrorCode::kOk; } -std::optional> I2C::Read(const uint8_t address, const uint8_t reg) { - std::vector result; - if (ioctl(this->file, I2C_SLAVE, address) < 0) { - return {}; - } - std::optional data = i2c_smbus_read_byte_data(reg); - if (!data.has_value()) { - return {}; - } - while (data.value() >= 0) { - result.push_back(data.value()); - data = i2c_smbus_read_byte_data(reg); + +core::ErrorCode I2CDriver::Write(const std::vector RegData) { + for (int i = 0; i < RegData.size(); i+=2) { + uint8_t buf[2] = {RegData[i], RegData[i+1]}; + if (write(i2cFile, buf, 2) != 2) { + return core::ErrorCode::kInitializeError; + } } - return std::optional>{result}; + return core::ErrorCode::kOk; } -ErrorCode I2C::Write(const uint8_t address, const uint8_t reg, std::vector data) { - if (ioctl(this->file, I2C_SLAVE, address) < 0) { - return ErrorCode::kInitializeError; - } - if (write(file, data.data(), data.size()) != data.size()) { - return ErrorCode::kError; +core::ErrorCode I2CDriver::PageWrite(std::vector data) { + data.insert(data.begin(), 0x00); + if (write(i2cFile, data.data(), data.size()) != data.size()) { + return core::ErrorCode::kInitializeError; } - return ErrorCode::kOk; + return core::ErrorCode::kOk; } +} // namespace i2c } // namespace core } // namespace simba diff --git a/core/i2c/i2cdriver.h b/core/i2c/i2cdriver.h deleted file mode 100644 index 94bd205b..00000000 --- a/core/i2c/i2cdriver.h +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @file i2cdriver.h - * @author Michal Mankowski (m.mankowski2004@gmail.com) - * @brief This file defines I2C driver - * @version 0.1 - * @date 2024-01-14 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef CORE_I2C_I2CDRIVER_H_ -#define CORE_I2C_I2CDRIVER_H_ - -#include -#include - -#include "Ii2cdriver.hpp" - -namespace simba { -namespace core { -class I2C : public II2C { - public: - ErrorCode init(const std::string& path); - std::optional> Read(const uint8_t address, const uint8_t reg); - ErrorCode Write(const uint8_t address, const uint8_t reg, std::vector data); - private: - int file = -1; - int32_t i2c_smbus_access(char read_write, - uint8_t command, int size, union i2c_smbus_data *data); - std::optional i2c_smbus_read_byte_data(const uint8_t command); -}; -} // namespace core -} // namespace simba -#endif // CORE_I2C_I2CDRIVER_H_ diff --git a/core/i2c/i2cdriver.hpp b/core/i2c/i2cdriver.hpp new file mode 100644 index 00000000..244d7ba7 --- /dev/null +++ b/core/i2c/i2cdriver.hpp @@ -0,0 +1,50 @@ +/** + * @file i2cdriver.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-03 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef CORE_I2C_I2CDRIVER_HPP_ +#define CORE_I2C_I2CDRIVER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "core/common/error_code.h" + +namespace simba { +namespace core { +namespace i2c { + +class I2CDriver{ + private: + int i2cFile; + public: + core::ErrorCode Init(); + core::ErrorCode Ioctl(const uint8_t address, const uint16_t type = I2C_SLAVE); + /** + * @brief Function to write data to device on i2c bus + * + * @param data pair ( req, data) + * @return core::ErrorCode + */ + core::ErrorCode Write(const std::vector RegData); + core::ErrorCode PageWrite(std::vector data); +}; +} // namespace i2c +} // namespace core +} // namespace simba + +#endif // CORE_I2C_I2CDRIVER_HPP_ diff --git a/core/i2c/mock/BUILD b/core/i2c/mock/BUILD index affd522b..0a22b3c7 100644 --- a/core/i2c/mock/BUILD +++ b/core/i2c/mock/BUILD @@ -1,12 +1,12 @@ -cc_library( - name = "mock_i2c", - srcs = [ - "mock_i2cdriver.hpp", - ], - visibility = ["//visibility:public"], - deps=[ - "@com_google_googletest//:gtest_main", - "//core/i2c:i2cdriver", - ], - testonly = True, -) \ No newline at end of file +# cc_library( +# name = "mock_i2c", +# srcs = [ +# "mock_i2cdriver.hpp", +# ], +# visibility = ["//visibility:public"], +# deps=[ +# "@com_google_googletest//:gtest_main", +# "//core/i2c:i2cdriver", +# ], +# testonly = True, +# ) \ No newline at end of file diff --git a/core/i2c/mock/mock_i2cdriver.hpp b/core/i2c/mock/mock_i2cdriver.hpp deleted file mode 100644 index 1378a4d8..00000000 --- a/core/i2c/mock/mock_i2cdriver.hpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file mock_i2cdriver.hpp - * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief - * @version 0.1 - * @date 2024-03-12 - * - * @copyright Copyright (c) 2024 - * - */ -#ifndef CORE_I2C_MOCK_MOCK_I2CDRIVER_HPP_ -#define CORE_I2C_MOCK_MOCK_I2CDRIVER_HPP_ - -#include -#include -#include - -#include "gmock/gmock.h" -#include "gtest/gtest.h" - -#include "core/i2c/Ii2cdriver.h" - - -class MockI2C : public simba::core::II2C { - public: - MOCK_METHOD((simba::core::ErrorCode), init, const std::string&, (override)); - MOCK_METHOD((std::optional>), Read, (const uint8_t, const uint8_t), (override)); - MOCK_METHOD((simba::core::ErrorCode), Write, (const uint8_t, const uint8_t, - std::vector), (override)); - virtual ~MockI2C() = default; -}; -#endif // CORE_I2C_MOCK_MOCK_I2CDRIVER_HPP_ diff --git a/deployment b/deployment index 1a3d29a1..cd681d80 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 1a3d29a1a690d723412639da6a659be00c388ba8 +Subproject commit cd681d80062ea036c6a9b58215338585a83f9f46 diff --git a/diag/dtc/controller/dtc.h b/diag/dtc/controller/dtc.h index 61ca7b6f..57faf9af 100644 --- a/diag/dtc/controller/dtc.h +++ b/diag/dtc/controller/dtc.h @@ -18,7 +18,7 @@ namespace diag { namespace dtc { class DTCObject : public IDTC { protected: - const uint8_t id; + const uint16_t id; DTCSendCallback callback; public: diff --git a/mw/em/code/em_application.cc b/mw/em/code/em_application.cc index 537bb579..bb383afc 100644 --- a/mw/em/code/em_application.cc +++ b/mw/em/code/em_application.cc @@ -24,10 +24,8 @@ core::ErrorCode EmApplication::Run(std::stop_token token) { this->exec_service.Init(); while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); - AppLogger::Info("check if restart needed"); auto res = this->exec_service.CheckAppCondition(); while ( res.size() > 0 ) { - AppLogger::Error("Restart needed"); auto pid = this->em_service.RestartApp(res.front()); if ( !pid.has_value() ) { AppLogger::Error("ERROR RESTART APP WITH ID: "+std::to_string(res.front())); diff --git a/mw/i2c_service/BUILD b/mw/i2c_service/BUILD new file mode 100644 index 00000000..91cafe82 --- /dev/null +++ b/mw/i2c_service/BUILD @@ -0,0 +1,20 @@ +cc_library( + name = "i2c_lib", + srcs = ["i2c_service.cpp"], + hdrs = ["i2c_service.h"], + visibility = ["//mw/i2c_service:__subpackages__"], + deps = [ + "//communication-core/sockets:socket_ipc", + "//core/application:simba_application", + "//core/i2c:i2cdriver", + "//mw/i2c_service/data:i2c_factory", + ], +) +cc_binary( + name = "i2c_service", + deps = [":i2c_lib"], + srcs = ["main.cpp"], + visibility = [ + "//deployment:__subpackages__", + ], +) diff --git a/mw/i2c_service/controller/BUILD b/mw/i2c_service/controller/BUILD new file mode 100644 index 00000000..8ffeaa12 --- /dev/null +++ b/mw/i2c_service/controller/BUILD @@ -0,0 +1,16 @@ +cc_library( + name = "i2c_controller", + deps = [ + "//core/i2c:i2cdriver", + "//communication-core/sockets:socket_ipc", + "//mw/i2c_service/data:i2c_hdr", + "//mw/i2c_service/data:i2c_factory", + "//core/logger:Logger", + ], + srcs = ["i2c_controller.cpp"], + hdrs = ["i2c_controller.h"], + visibility = [ + "//apps:__subpackages__", + "//mw/i2c_service/controller:__subpackages__", + ], +) \ No newline at end of file diff --git a/mw/i2c_service/controller/i2c_controller.cpp b/mw/i2c_service/controller/i2c_controller.cpp new file mode 100644 index 00000000..6c993941 --- /dev/null +++ b/mw/i2c_service/controller/i2c_controller.cpp @@ -0,0 +1,37 @@ +/** + * @file i2c_controller.cpp + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ +#include "mw/i2c_service/controller/i2c_controller.h" +#include "core/logger/Logger.h" + +namespace simba { +namespace i2c { + +I2CController::I2CController() { + // this->sock_.Init({"SIMBA.I2C.RESPONSE." + std::to_string(this->service_id), 0, 0}); + // this->sock_.SetRXCallback(std::bind(&I2CController::ReceiveCallback, this, std::placeholders::_1, + // std::placeholders::_2, std::placeholders::_3)); + // this->sock_.StartRXThread(); +} +core::ErrorCode I2CController::Write(const uint8_t address, const std::vector data) { + AppLogger::Debug("Sent i2c msg"); + auto hdr = Header(ACTION::Write, address, this->service_id); + auto buf = factory_.GetBuffer(std::make_shared
(hdr), data); + return this->sock_.Transmit("SIMBA.I2C", 0, buf); +} +core::ErrorCode I2CController::PageWrite(const uint8_t address, const std::vector data) { + AppLogger::Debug("Sent i2c msg"); + auto hdr = Header(ACTION::PageWrite, address, this->service_id); + auto buf = factory_.GetBuffer(std::make_shared
(hdr), data); + return this->sock_.Transmit("SIMBA.I2C", 0, buf); +} + +} // namespace i2c +} // namespace simba diff --git a/mw/i2c_service/controller/i2c_controller.h b/mw/i2c_service/controller/i2c_controller.h new file mode 100644 index 00000000..b0bb4e0b --- /dev/null +++ b/mw/i2c_service/controller/i2c_controller.h @@ -0,0 +1,58 @@ +/** + * @file i2c_controller.h + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef MW_I2C_SERVICE_CONTROLLER_I2C_CONTROLLER_H_ +#define MW_I2C_SERVICE_CONTROLLER_I2C_CONTROLLER_H_ +#include +#include +#include +#include +#include // NOLINT +#include "core/i2c/i2cdriver.hpp" +#include "communication-core/sockets/ipc_socket.h" +#include "mw/i2c_service/data/header.h" +#include "mw/i2c_service/data/i2c_factory.h" + + +namespace simba { +namespace i2c { +class I2CController{ + private: + com::soc::IpcSocket sock_; + std::mutex mtx; + I2CFactory factory_; + uint16_t service_id; + + public: + I2CController(); + void Init(uint16_t service_id) { + this->service_id = service_id; + } + /** + * @brief + * + * @param address (reg,data) + * @param data + * @return core::ErrorCode + */ + core::ErrorCode Write(const uint8_t address, const std::vector data); + /** + * @brief + * + * @param address + * @param data + * @return core::ErrorCode + */ + core::ErrorCode PageWrite(const uint8_t address, const std::vector data); +}; +} // namespace i2c +} // namespace simba + +#endif // MW_I2C_SERVICE_CONTROLLER_I2C_CONTROLLER_H_ diff --git a/mw/i2c_service/controller/pca9685/BUILD b/mw/i2c_service/controller/pca9685/BUILD new file mode 100644 index 00000000..e3ae3fd4 --- /dev/null +++ b/mw/i2c_service/controller/pca9685/BUILD @@ -0,0 +1,18 @@ +cc_library( + name = "pca9685_controller", + deps = [ + "//communication-core/sockets:socket_ipc", + "//mw/i2c_service/data:i2c_hdr", + "//mw/i2c_service/data:i2c_factory", + "//core/logger:Logger", + "//mw/i2c_service/controller:i2c_controller", + "//mw/gpio_server/controller:gpio_controller", + "//core/json:simba_json", + ], + srcs = ["controller.cpp"], + hdrs = ["controller.hpp"], + visibility = [ + "//apps:__subpackages__", + "//services/ServoService:__subpackages__", + ], +) \ No newline at end of file diff --git a/mw/i2c_service/controller/pca9685/controller.cpp b/mw/i2c_service/controller/pca9685/controller.cpp new file mode 100644 index 00000000..9af56961 --- /dev/null +++ b/mw/i2c_service/controller/pca9685/controller.cpp @@ -0,0 +1,135 @@ +/** + * @file controller.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-09 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include +#include // NOLINT + +#include "mw/i2c_service/controller/pca9685/controller.hpp" +#include "core/json/json_parser.h" +#include "core/common/error_code.h" +#include "core/logger/Logger.h" +namespace simba { +namespace i2c { + +namespace { + constexpr uint8_t PCA9685_ADDRESS = 0x70; + constexpr uint8_t MODE1_REG = 0x00; + constexpr uint8_t PRESCALE_REG = 0xFE; + constexpr uint8_t LED0_ON_L = 0x06; + constexpr uint8_t LED0_ON_H = 0x07; + constexpr uint8_t LED0_OFF_L = 0x08; + constexpr uint8_t LED0_OFF_H = 0x09; +} + +PCA9685::PCA9685() { +} +void PCA9685::Init(uint16_t service_id, const std::unordered_map& parms) { + this->app_name = parms.at("app_name"); + this->i2c_.Init(service_id); + this->gpio_.Init(service_id); + if (this->ReadConfig() != core::ErrorCode::kOk) { + AppLogger::Error("Servo config does not exist"); + } + for (auto chan : this->db_) { + this->SetServo(chan.second.channel, chan.second.off_pos); + } +} +core::ErrorCode PCA9685::AutoSetServoPosition(uint8_t actuator_id, uint8_t state) { + auto it = this->db_.find(actuator_id); + if (it == this->db_.end()) { + AppLogger::Warning("Not find service"); + return core::ErrorCode::kNotDefine; + } + if (it->second.position != state) { + if (it->second.need_mosfet) { + this->gpio_.SetPinValue(it->second.mosfet_id, gpio::Value::HIGH); + std::this_thread::sleep_for(std::chrono::milliseconds(it->second.servo_delay)); + } + this->SetServo(it->second.channel, it->second.position == 1 ? it->second.on_pos : it->second.off_pos); + if (it->second.need_loosening) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + this->SetServo(it->second.channel, + it->second.position == 1 ? it->second.on_loosening : it->second.off_loosening); + } + if (it->second.need_mosfet) { + std::this_thread::sleep_for(std::chrono::milliseconds(it->second.mosfet_delay)); + this->gpio_.SetPinValue(it->second.mosfet_id, gpio::Value::LOW); + } + it->second.position = state; + } + return core::ErrorCode::kOk; +} + +core::ErrorCode PCA9685::SetServo(uint8_t channel, uint16_t pos) { + std::vector data = { + MODE1_REG, 0x01, // setup reset mode + PRESCALE_REG, 121, // przeskalowanie dla 50 Hz + static_cast(LED0_ON_L+4*channel), 0x0 & 0xFF, // ON LOW REG Val + static_cast(LED0_ON_H+4*channel), 0x0 >> 8, // ON HIGH REG Val + static_cast(LED0_OFF_L+4*channel), static_cast(pos & 0xFF), // OFF LOW REG Val + static_cast(LED0_OFF_H+4*channel), static_cast(pos >> 8)}; // OFF HIGH REG Val; + return this->i2c_.Write(PCA9685_ADDRESS, data); +} + +std::optional PCA9685::ReadServoPosition(uint8_t actuator_id) { + auto servo = this->db_.find(actuator_id); + if (servo != this->db_.end()) { + return servo->second.position; + } + return {}; +} + +core::ErrorCode PCA9685::ReadConfig() { + std::ifstream file("/opt/"+this->app_name+"/etc/config.json"); + if (!file.is_open()) { + AppLogger::Warning("Cant find file on path /opt/"+this->app_name+"/etc/config.json"); + return core::ErrorCode::kInitializeError; + } + nlohmann::json data = nlohmann::json::parse(file); + if (!data.contains("servos")) { + return core::ErrorCode::kNotDefine; + } + for (const auto& servo : data["servos"]) { + if (!servo.contains("actuator_id") || !servo.contains("channel") + || !servo.contains("on_pos") || !servo.contains("off_pos")) { + AppLogger::Warning("Invalid servo config"); + continue; + } + Servo ser; + uint8_t actuator_id = static_cast(servo["actuator_id"]); + ser.channel = static_cast(servo["channel"]); + ser.on_pos = static_cast(servo["on_pos"]); + ser.off_pos = static_cast(servo["off_pos"]); + + if (servo.contains("mosfet_id")) { + ser.need_mosfet = true; + ser.mosfet_id = static_cast(servo["mosfet_id"]); + } + if (servo.contains("on_losening_pos") && servo.contains("off_losening_pos")) { + ser.need_loosening = true; + ser.on_loosening = static_cast(servo["on_losening_pos"]); + ser.off_loosening = static_cast(servo["off_losening_pos"]); + } + if (servo.contains("servo_delay")) { + ser.servo_delay = static_cast(servo["servo_delay"]); + } + if (servo.contains("mosfet_delay")) { + ser.mosfet_delay = static_cast(servo["mosfet_delay"]); + } + this->db_.insert({actuator_id, ser}); + AppLogger::Debug("Register servo id:"+std::to_string(static_cast(actuator_id))); + } + return core::ErrorCode::kOk; +} + +} // namespace i2c +} // namespace simba + diff --git a/mw/i2c_service/controller/pca9685/controller.hpp b/mw/i2c_service/controller/pca9685/controller.hpp new file mode 100644 index 00000000..5fe5c4ec --- /dev/null +++ b/mw/i2c_service/controller/pca9685/controller.hpp @@ -0,0 +1,55 @@ +/** + * @file controller.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-09 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_I2C_SERVICE_CONTROLLER_PCA9685_CONTROLLER_HPP_ +#define MW_I2C_SERVICE_CONTROLLER_PCA9685_CONTROLLER_HPP_ + +#include +#include + +#include "mw/i2c_service/controller/i2c_controller.h" +#include "mw/gpio_server/controller/gpio_controller.hpp" +namespace simba { +namespace i2c { + +struct Servo { + uint16_t on_pos; + uint16_t off_pos; + uint8_t channel; + uint8_t position{0}; + bool need_mosfet{false}; + uint8_t mosfet_id; + bool need_loosening{false}; + uint16_t on_loosening; + uint16_t off_loosening; + uint8_t servo_delay{50}; + uint8_t mosfet_delay{50}; +}; + +class PCA9685 { + private: + I2CController i2c_; + gpio::GPIOController gpio_{}; + std::unordered_map db_; + std::string app_name; + core::ErrorCode ReadConfig(); + core::ErrorCode SetServo(uint8_t channel, uint16_t pos); + public: + PCA9685(); + void Init(uint16_t service_id, const std::unordered_map& parms); + core::ErrorCode AutoSetServoPosition(uint8_t actuator_id, uint8_t state); + std::optional ReadServoPosition(uint8_t actuator_id); +}; + +} // namespace i2c +} // namespace simba + +#endif // MW_I2C_SERVICE_CONTROLLER_PCA9685_CONTROLLER_HPP_ diff --git a/mw/i2c_service/data/BUILD b/mw/i2c_service/data/BUILD new file mode 100644 index 00000000..4a554711 --- /dev/null +++ b/mw/i2c_service/data/BUILD @@ -0,0 +1,23 @@ +cc_library( + name = "i2c_hdr", + srcs = [ + "header.cpp", + ], + hdrs = [ + "header.h", + ], + deps = [ + "//communication-core/network-data:network_data_structure", + "//communication-core/network-data:network_data_type", + ], + visibility = ["//visibility:public"], +) +cc_library( + name = "i2c_factory", + srcs = ["i2c_factory.cpp"], + hdrs = ["i2c_factory.h"], + visibility = ["//visibility:public"], + deps = [ + ":i2c_hdr" + ], +) \ No newline at end of file diff --git a/mw/i2c_service/data/header.cpp b/mw/i2c_service/data/header.cpp new file mode 100644 index 00000000..7ae3dec3 --- /dev/null +++ b/mw/i2c_service/data/header.cpp @@ -0,0 +1,31 @@ +/** + * @file header.cpp + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "header.h" + +namespace simba { +namespace i2c { + +Header::Header(ACTION action, uint8_t address, uint16_t service_id) { + this->action = action; + this->address = address; + this->service_id = service_id; + this->SetData(); +} + +void Header::SetData() { + this->AddData(&action); + this->AddData(&address); + this->AddData(&service_id); +} + +} // namespace i2c +} // namespace simba diff --git a/mw/i2c_service/data/header.h b/mw/i2c_service/data/header.h new file mode 100644 index 00000000..a829fbe0 --- /dev/null +++ b/mw/i2c_service/data/header.h @@ -0,0 +1,51 @@ +/** + * @file header.h + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_I2C_SERVICE_DATA_HEADER_H_ +#define MW_I2C_SERVICE_DATA_HEADER_H_ + +#include + +#include "communication-core/network-data/network_data_structure.h" +#include "communication-core/network-data/network_data_type.h" + + +namespace simba { +namespace i2c { +enum ACTION { + Read = 0x01, + Write = 0x02, + ReadWrite = 0x03, + RES = 0x04, + PageWrite = 0x05, + PageRead = 0x06, +}; + +class Header : public com::core::network::NetworkDataStructure { + private: + com::core::network::uint8_t action; + com::core::network::uint8_t address; + com::core::network::uint16_t service_id; + void SetData(); + public: + ACTION GetAction() { return static_cast(this->action.Get()); } + uint8_t GetAddress() { return this->address.Get(); } + uint16_t GetServiceId() { return this->service_id.Get(); } + Header(ACTION action, uint8_t address, uint16_t service_id); +}; + +} // namespace i2c +} // namespace simba + + + + +#endif // MW_I2C_SERVICE_DATA_HEADER_H_ diff --git a/mw/i2c_service/data/i2c_factory.cpp b/mw/i2c_service/data/i2c_factory.cpp new file mode 100644 index 00000000..c50c375a --- /dev/null +++ b/mw/i2c_service/data/i2c_factory.cpp @@ -0,0 +1,42 @@ +/** + * @file i2c_factory.cpp + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ + +#include "mw/i2c_service/data/i2c_factory.h" + +namespace simba { +namespace i2c { + +namespace { + const constexpr uint8_t HDR_SIZE = 0x04; +} + +std::vector I2CFactory::GetBuffer(std::shared_ptr
header, const std::vector& payload) { + std::vector buffer = header->GetBuffor(); + buffer.insert(buffer.end(), payload.begin(), payload.end()); + return buffer; + } + +std::shared_ptr
I2CFactory::GetHeader(const std::vector& raw_data) { + if (raw_data.size() < 4) { + return nullptr; + } + Header hdr(i2c::ACTION::Read, 0x00, 0x00); + hdr.SetBuffor(raw_data); + return std::make_shared
(hdr); + } +std::vector I2CFactory::GetPayload(const std::vector& raw_data) { + if (raw_data.size() <= HDR_SIZE) { + return {}; + } + return std::vector(raw_data.begin() + HDR_SIZE, raw_data.end()); + } +} // namespace i2c +} // namespace simba diff --git a/mw/i2c_service/data/i2c_factory.h b/mw/i2c_service/data/i2c_factory.h new file mode 100644 index 00000000..8642607a --- /dev/null +++ b/mw/i2c_service/data/i2c_factory.h @@ -0,0 +1,29 @@ +/** + * @file i2c_factory.h + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-14 + * + * @copyright Copyright (c) 2024 + * + */ + +#ifndef MW_I2C_SERVICE_DATA_I2C_FACTORY_H_ +#define MW_I2C_SERVICE_DATA_I2C_FACTORY_H_ + +#include +#include +#include +#include "header.h" +namespace simba { +namespace i2c { +class I2CFactory { + public: + static std::vector GetBuffer(std::shared_ptr
header, const std::vector& payload); + static std::shared_ptr
GetHeader(const std::vector& raw_data); + static std::vector GetPayload(const std::vector& raw_data); +}; +} // namespace i2c +} // namespace simba +#endif // MW_I2C_SERVICE_DATA_I2C_FACTORY_H_ diff --git a/mw/i2c_service/i2c_service.cpp b/mw/i2c_service/i2c_service.cpp new file mode 100644 index 00000000..b441142a --- /dev/null +++ b/mw/i2c_service/i2c_service.cpp @@ -0,0 +1,71 @@ +/** + * @file i2c_service.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-03 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include "mw/i2c_service/i2c_service.h" +#include "mw/i2c_service/data/i2c_factory.h" +#include "core/logger/Logger.h" +namespace simba { +namespace mw { + +namespace { + constexpr uint8_t PCA9685_ADDRESS = 0x70; + constexpr uint8_t MODE1_REG = 0x00; + constexpr uint8_t PRESCALE_REG = 0xFE; + constexpr uint8_t LED0_ON_L = 0x06; + constexpr uint8_t LED0_ON_H = 0x07; + constexpr uint8_t LED0_OFF_L = 0x08; + constexpr uint8_t LED0_OFF_H = 0x09; +} + +void I2CService::RxCallback(const std::string& ip, + const std::uint16_t& port, const std::vector data) { + std::unique_lock lock(this->i2c_mtx); + std::shared_ptr headerPtr = i2c::I2CFactory::GetHeader(data); + this->i2c_.Ioctl(headerPtr->GetAddress()); + std::vector payload; + AppLogger::Debug("Receive i2c msg"); + switch (headerPtr->GetAction()) { + case i2c::ACTION::Write: + payload = i2c::I2CFactory::GetPayload(data); + i2c_.Write(payload); + break; + case i2c::ACTION::PageWrite: + payload = i2c::I2CFactory::GetPayload(data); + i2c_.PageWrite(payload); + break; + case i2c::ACTION::Read: + break; + case i2c::ACTION::ReadWrite: + break; + case i2c::ACTION::PageRead: + break; + default: + AppLogger::Warning("Invalid type"); + break; + } +} + +core::ErrorCode I2CService::Run(std::stop_token token) { + this->SleepMainThread(); + return core::ErrorCode::kOk; +} +core::ErrorCode I2CService::Initialize( + const std::unordered_map& parms) { + this->i2c_.Init(); + this->sock_.Init(com::soc::SocketConfig("SIMBA.I2C", 0, 0)); + this->sock_.SetRXCallback(std::bind(&I2CService::RxCallback, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); + this->sock_.StartRXThread(); + return core::ErrorCode::kOk; +} + +} // namespace mw +} // namespace simba diff --git a/mw/i2c_service/i2c_service.h b/mw/i2c_service/i2c_service.h new file mode 100644 index 00000000..d1e3fb1d --- /dev/null +++ b/mw/i2c_service/i2c_service.h @@ -0,0 +1,38 @@ +/** + * @file i2c_service.h + * @author Michal Mankowski (m.mankowski2004@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-02 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef MW_I2C_SERVICE_I2C_SERVICE_H_ +#define MW_I2C_SERVICE_I2C_SERVICE_H_ +#include +#include +#include +#include +#include "core/application/application_mw.h" +#include "communication-core/sockets/ipc_socket.h" +#include "core/i2c/i2cdriver.hpp" +namespace simba { +namespace mw { +class I2CService : public core::ApplicationMW { + private: + std::mutex i2c_mtx; + core::i2c::I2CDriver i2c_; + com::soc::IpcSocket sock_; + void RxCallback(const std::string& ip, const std::uint16_t& port, + const std::vector data); + + public: + core::ErrorCode Run(std::stop_token token) final; + core::ErrorCode Initialize( + const std::unordered_map& parms) final; +}; +} // namespace mw +} // namespace simba + +#endif // MW_I2C_SERVICE_I2C_SERVICE_H_ diff --git a/mw/i2c_service/main.cpp b/mw/i2c_service/main.cpp new file mode 100644 index 00000000..d365d082 --- /dev/null +++ b/mw/i2c_service/main.cpp @@ -0,0 +1,17 @@ +/** + * @file main.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-03 + * + * @copyright Copyright (c) 2024 + * + */ +#include "mw/i2c_service/i2c_service.h" +#include "core/application/application_factory.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/mw/i2c_service/tests/BUILD b/mw/i2c_service/tests/BUILD new file mode 100644 index 00000000..e9944f2f --- /dev/null +++ b/mw/i2c_service/tests/BUILD @@ -0,0 +1,11 @@ +cc_test( + name = "data_structure", + srcs = [ + "test_header.cpp", + ], + visibility = ["//visibility:public"], + deps=[ + "@com_google_googletest//:gtest_main", + "//mw/i2c_service/data:i2c_factory" + ] +) diff --git a/mw/i2c_service/tests/test_header.cpp b/mw/i2c_service/tests/test_header.cpp new file mode 100644 index 00000000..d2928147 --- /dev/null +++ b/mw/i2c_service/tests/test_header.cpp @@ -0,0 +1,42 @@ +/** + * @file test_header.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-08 + * + * @copyright Copyright (c) 2024 + * + */ + +#include + +#include "mw/i2c_service/data/header.h" +#include "mw/i2c_service/data/i2c_factory.h" + +TEST(HEADER, CONSTRUCTOR_CHECK) { + const uint16_t service_id = 0x11; + const auto action = simba::i2c::ACTION::Write; + const uint16_t address = 0x22; +simba::i2c::Header hdr{action, address, service_id}; +EXPECT_EQ(hdr.GetAction(), action); +EXPECT_EQ(hdr.GetServiceId(), service_id); +EXPECT_EQ(hdr.GetAddress(), address); +} + + +TEST(FACTORY, FACTORY_CHECK) { + const uint16_t service_id = 0x22; + const auto action = simba::i2c::ACTION::Write; + const uint16_t address = 0x11; + simba::i2c::I2CFactory factory; + simba::i2c::Header hdr{action, address, service_id}; + std::vector payload = {0, 1, 2, 3, 4}; + auto buf = factory.GetBuffer(std::make_shared(hdr), payload); + auto hdr2 = factory.GetHeader(buf); + auto payload2 = factory.GetPayload(buf); + EXPECT_EQ(hdr.GetAction(), hdr2->GetAction()); + EXPECT_EQ(hdr.GetServiceId(), hdr2->GetServiceId()); + EXPECT_EQ(hdr.GetAddress(), hdr2->GetAddress()); + EXPECT_EQ(payload, payload2); +} diff --git a/services/ServoService/BUILD b/services/ServoService/BUILD new file mode 100644 index 00000000..dd3ad631 --- /dev/null +++ b/services/ServoService/BUILD @@ -0,0 +1,18 @@ +cc_binary( + name = "ServoService", + srcs = [ + "main.cc", + "servoService.cpp", + "servoService.hpp", + ], + visibility = [ + "//deployment/apps/servo_service:__subpackages__" + ], + deps = [ + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", + "//core/application:simba_application", + "//mw/i2c_service/controller/pca9685:pca9685_controller", + "@untar", + ], +) diff --git a/services/ServoService/main.cc b/services/ServoService/main.cc new file mode 100644 index 00000000..4fc84c8e --- /dev/null +++ b/services/ServoService/main.cc @@ -0,0 +1,18 @@ +/** + * @file main.cc + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-26 + * + * @copyright Copyright (c) 2024 + * + */ +#include "servoService.hpp" +#include "core/application/application_factory.h" +#include "untar/untar.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/services/ServoService/servoService.cpp b/services/ServoService/servoService.cpp new file mode 100644 index 00000000..92ca9739 --- /dev/null +++ b/services/ServoService/servoService.cpp @@ -0,0 +1,100 @@ +/** + * @file servoService.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-26 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include +#include + +#include "servoService.hpp" + +#include "core/logger/Logger.h" + +namespace simba { +namespace service { + +core::ErrorCode ServoService::Run(std::stop_token token) { + while (true) { + // update servo positions; + auto val = this->servo_controller.ReadServoPosition(60); + if (val.has_value()) { + main_servo_status_event->SetValue({val.value()}); + } + auto val2 = this->servo_controller.ReadServoPosition(61); + if (val2.has_value()) { + vent_servo_status_event->SetValue({val2.value()}); + } else { + AppLogger::Warning("FUASHUD"); + } + AppLogger::Info("Send servo status event"); + std::this_thread::sleep_for(std::chrono::milliseconds(975)); + } +} + +core::ErrorCode ServoService::Initialize( + const std::unordered_map& parms) { + this->servo_controller.Init(this->app_id_, parms); +// Dodanie publikowanych eventów + main_servo_status_event = + std::make_shared("ServoApp/servoStatusEvent"); + vent_servo_status_event = + std::make_shared("ServoApp/servoVentStatusEvent"); +// Rejestracja method + this->set_servo_val = std::make_shared( + "ServoApp/setServoValue", + [this](const std::vector payload) + -> std::optional> { + if (payload.size() == 1) { + AppLogger::Debug("move servo id: 60 to pos"+std::to_string(static_cast(payload[0]))); + this->servo_controller.AutoSetServoPosition(60, payload[0]); + return std::vector{1}; + } + return std::vector{0}; +}); +this->set_vent_val = std::make_shared( + "ServoApp/setServoVentValue", + [this](const std::vector payload) + -> std::optional> { + if (payload.size() == 1) { + AppLogger::Debug("move servo id: 61 to pos"+std::to_string(static_cast(payload[0]))); + this->servo_controller.AutoSetServoPosition(61, payload[0]); + return std::vector{1}; + } + return std::vector{0}; +}); + +// NOW unsupported +// auto read_servo_val = std::make_shared( +// "ServoApp/readServoValue", +// [this](const std::vector payload) +// -> std::optional> { +// return std::vector{this->servo_controller.ReadServoPosition(60).value()}; +// }); +// auto read_vent_val = std::make_shared( +// "ServoApp/readServoVentValue", +// [this](const std::vector payload) +// -> std::optional> { +// return std::vector{this->servo_controller.ReadServoPosition(61).value()}; +// }); + + +// Rejestracja Metod i eventow +com->Add(main_servo_status_event); +com->Add(vent_servo_status_event); +com->Add(set_servo_val); +com->Add(set_vent_val); +// UNSUPPORTED +// com->Add(read_servo_val); +// com->Add(read_vent_val); + +return core::ErrorCode::kOk; +} + +} // namespace service +} // namespace simba diff --git a/services/ServoService/servoService.hpp b/services/ServoService/servoService.hpp new file mode 100644 index 00000000..e2ef161b --- /dev/null +++ b/services/ServoService/servoService.hpp @@ -0,0 +1,44 @@ +/** + * @file servoService.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-03-26 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef SERVICES_SERVOSERVICE_SERVOSERVICE_HPP_ +#define SERVICES_SERVOSERVICE_SERVOSERVICE_HPP_ +#include +#include +#include + +#include "communication-core/someip-controller/event_proxy.h" +#include "communication-core/someip-controller/method_skeleton.h" +#include "communication-core/someip-controller/event_skeleton.h" +#include "communication-core/someip-controller/method_proxy.h" +#include "mw/i2c_service/controller/pca9685/controller.hpp" +#include "core/application/application_no_ipc.h" +namespace simba { +namespace service { +class ServoService : public core::ApplicationNoIPC{ + private: + std::shared_ptr main_servo_status_event; + std::shared_ptr vent_servo_status_event; + std::shared_ptr set_servo_val; + std::shared_ptr set_vent_val; + i2c::PCA9685 servo_controller; + protected: + core::ErrorCode Run(std::stop_token token) final; + + core::ErrorCode Initialize( + const std::unordered_map& parms) final; + + public: + ~ServoService() = default; +}; + +} // namespace service +} // namespace simba +#endif // SERVICES_SERVOSERVICE_SERVOSERVICE_HPP_ From 754fd60f08d630bfc0a8f31d2c850f2413b23f0e Mon Sep 17 00:00:00 2001 From: Mateusz Krajewski Date: Sun, 28 Apr 2024 10:52:26 +0200 Subject: [PATCH 53/71] MaKr SOME/IP Primer Service (#64) --- .github/workflows/build_cpu.yaml | 2 +- apps/example/router.cc | 34 +++--- apps/primer_service/BUILD | 16 +++ apps/primer_service/main.cc | 17 +++ apps/primer_service/primer_service.cpp | 161 +++++++++++++++++++++++++ apps/primer_service/primer_service.hpp | 58 +++++++++ core/application/application_common.cc | 6 +- deployment | 2 +- diag/dtc/controller/dtc.h | 4 +- mw/gpio_server/gpio_mw.cpp | 5 +- 10 files changed, 279 insertions(+), 26 deletions(-) create mode 100644 apps/primer_service/BUILD create mode 100644 apps/primer_service/main.cc create mode 100644 apps/primer_service/primer_service.cpp create mode 100644 apps/primer_service/primer_service.hpp diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 57cc2351..e2326c2c 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -26,7 +26,7 @@ jobs: uses: actions/cache@v2 with: path: | - /home/runner/.cache/bazel/_bazel_runner/* + /home/runner/.cache/bazel/* key: ${{ runner.os }}-bazel-bbb-${{ hashFiles('**/lockfiles') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') diff --git a/apps/example/router.cc b/apps/example/router.cc index c097a005..059fc94c 100644 --- a/apps/example/router.cc +++ b/apps/example/router.cc @@ -26,31 +26,37 @@ namespace router { #define DATA_SIZE 128 core::ErrorCode Router::Run(std::stop_token token) { - auto current_mode_proxy = std::make_shared( - "ExampleApp/currentMode", [](const std::vector payload) { - AppLogger::Info("Current cpu mode: " + std::to_string(payload[0])); - }); - auto example2 = std::make_shared( - "ExampleApp/exampleMethod2", + uint8_t servo_pos; + auto proxy_event = std::make_shared( + "ExampleApp/someevent", + [this](const std::vector) { AppLogger::Info("EVENT !!!!!!!"); }); + auto example = std::make_shared( + "ExampleApp/exampleMethod", [this](const std::vector payload) -> std::optional> { return std::vector{0, 1, 2}; }); + auto off_prime = std::make_shared("ExampleApp/offPrime"); + auto on_prime = std::make_shared("ExampleApp/onPrime"); auto servo = std::make_shared("ExampleApp/setServoValue"); + com->Add(example); + com->Add(on_prime); com->Add(servo); - com->Add(example2); + com->Add(off_prime); + com->Add(proxy_event); + on_prime->StartFindService(); servo->StartFindService(); - auto dtc = std::make_shared(20); + off_prime->StartFindService(); + proxy_event->StartFindService(); + auto dtc = std::make_shared(0x20); diag_controller.RegisterDTC(dtc); while (true) { - AppLogger::Debug("AppLogger::Debug"); - AppLogger::Info("AppLogger::Info"); dtc->Pass(); - this->gpio_.SetPinValue(1, gpio::Value::HIGH); - servo->Get({1}); + std::ignore = on_prime->Get(); + std::ignore = servo->Get({1}); std::this_thread::sleep_for(std::chrono::seconds(1)); - this->gpio_.SetPinValue(1, gpio::Value::LOW); - servo->Get({0}); + std::ignore = off_prime->Get(); + std::ignore = servo->Get({0}); dtc->Failed(); std::this_thread::sleep_for(std::chrono::seconds(1)); } diff --git a/apps/primer_service/BUILD b/apps/primer_service/BUILD new file mode 100644 index 00000000..0dbd17c7 --- /dev/null +++ b/apps/primer_service/BUILD @@ -0,0 +1,16 @@ +cc_binary( + name = "primer", + srcs = [ + "primer_service.cpp", + "primer_service.hpp", + "main.cc", + ], + visibility = ["//deployment:__subpackages__"], + deps = [ + "//core/application:simba_application", + "//communication-core/someip-controller:proxy", + "//communication-core/someip-controller:skeleton", + "//diag/dtc/controller:diag_dtc_", + "//mw/gpio_server/controller:gpio_controller", + ], +) diff --git a/apps/primer_service/main.cc b/apps/primer_service/main.cc new file mode 100644 index 00000000..38959582 --- /dev/null +++ b/apps/primer_service/main.cc @@ -0,0 +1,17 @@ +/** + * @file main.cc + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-16 + * + * @copyright Copyright (c) 2024 + * + */ +#include "apps/primer_service/primer_service.hpp" +#include "core/application/application_factory.h" + +int main(int argc, char const *argv[]) { + simba::core::ApplicationFactory::Start(argc, argv); + return 0; +} diff --git a/apps/primer_service/primer_service.cpp b/apps/primer_service/primer_service.cpp new file mode 100644 index 00000000..35209e94 --- /dev/null +++ b/apps/primer_service/primer_service.cpp @@ -0,0 +1,161 @@ +/** + * @file primer_service.cpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-16 + * + * @copyright Copyright (c) 2024 + * + */ +#include +#include +#include +#include // NOLINT + +#include "apps/primer_service/primer_service.hpp" +#include "communication-core/someip-controller/event_proxy.h" +#include "communication-core/someip-controller/method_skeleton.h" +#include "nlohmann/json.hpp" +#include "core/json/json_parser.h" + +namespace simba { +namespace primer { + +namespace { + /** + * @brief domyślne wartości + * + */ + const constexpr uint8_t IGNITER_PIN_ID = 5; + const constexpr uint16_t IGNITER_ACTIVE_TIME = 250; +} + + +core::ErrorCode PrimerService::ChangePrimerState(gpio::Value state) { + if (this->primerState != state) { + core::ErrorCode error; + uint8_t i = 0; + do { + error = this->gpio_.SetPinValue(this->primer_pin_, state); + i++; + } while ( error != core::ErrorCode::kOk || i > 5); + if (i > 5) { + this->dtc_31->Failed(); + return core::ErrorCode::kError; + } + this->primerState = state; + this->primer_event->SetValue({static_cast(state)}); + return core::ErrorCode::kOk; + } + return core::ErrorCode::kNotDefine; +} + + +core::ErrorCode PrimerService::Run(std::stop_token token) { + auto primerOnMethod = std::make_shared( + "PrimerApp/onPrime", + [this](const std::vector payload) + -> std::optional> { + AppLogger::Debug("Receive onPrime method"); + if (this->ChangePrimerState(gpio::Value::HIGH) == core::ErrorCode::kOk) { + return std::vector{1}; + } + return std::vector{0}; + }); + auto primerOffMethod = std::make_shared( + "PrimerApp/offPrime", + [this](const std::vector payload) + -> std::optional> { + AppLogger::Debug("Receive offPrime method"); + if (this->ChangePrimerState(gpio::Value::LOW) == core::ErrorCode::kOk) { + return std::vector{1}; + } + return std::vector{0}; + }); + auto startPrimeMethod = std::make_shared( + "PrimerApp/startPrime", + [this](const std::vector payload) + -> std::optional> { + auto future = std::async(std::launch::async, [this](){ + if (this->ChangePrimerState(gpio::Value::HIGH) != core::ErrorCode::kOk) { + return std::vector{0}; + } + std::this_thread::sleep_for(std::chrono::milliseconds(this->active_time)); + if (this->ChangePrimerState(gpio::Value::HIGH) == core::ErrorCode::kOk) { + return std::vector{1}; + } + return std::vector{0}; + }); + }); + com->Add(primerOffMethod); + com->Add(primerOnMethod); + com->Add(startPrimeMethod); + this->primer_event->SetValue({static_cast(this->primerState)}); + while (true) { + this->SleepMainThread(); + } + return core::ErrorCode::kOk; +} + +core::ErrorCode PrimerService::ReadConfig(const std::unordered_map& parms) { + std::ifstream file{"/opt/" + parms.at("app_name") + "/etc/config.json"}; + if (!file.is_open()) { + AppLogger::Warning("cant find config file, use DEFAULT IGNITER ID"); + this->active_time = IGNITER_ACTIVE_TIME; + this->primer_pin_ = IGNITER_PIN_ID; + return core::ErrorCode::kInitializeError; + } + nlohmann::json data = nlohmann::json::parse(file); + file.close(); + if (!data.contains("primer")) { + AppLogger::Warning("invalid config format, use DEFAULT IGNITER ID"); + this->active_time = IGNITER_ACTIVE_TIME; + this->primer_pin_ = IGNITER_PIN_ID; + return core::ErrorCode::kInitializeError; + } + if (!data.at("primer").contains("active_time")) { + AppLogger::Warning("Cant find active_time in config, use default value"); + this->active_time = IGNITER_ACTIVE_TIME; + } else { + this->active_time = static_cast(data.at("primer").at("active_time")); + } + if (!data.at("primer").contains("id")) { + this->primer_pin_ = IGNITER_PIN_ID; + } else { + this->primer_pin_ = static_cast(data.at("primer").at("id")); + } + return core::ErrorCode::kOk; +} + +core::ErrorCode PrimerService::Initialize( + const std::unordered_map& parms) { + /** + * @brief define and register errors + * + */ + this->dtc_30 = std::make_shared(0x30); + this->dtc_31 = std::make_shared(0x31); + this->diag_controller.RegisterDTC(dtc_30); + this->diag_controller.RegisterDTC(dtc_31); + + this->gpio_ = gpio::GPIOController(new com::soc::IpcSocket()); + this->gpio_.Init(this->app_id_); + ReadConfig(parms); + + /** + * @brief register events + * + */ + this->primer_event = + std::make_shared("PrimerApp/primeStatusEvent"); + /** + * @brief register SOME/IP events in network + * + */ + com->Add(primer_event); + return core::ErrorCode::kOk; +} + +} // namespace primer +} // namespace simba diff --git a/apps/primer_service/primer_service.hpp b/apps/primer_service/primer_service.hpp new file mode 100644 index 00000000..54c55b1e --- /dev/null +++ b/apps/primer_service/primer_service.hpp @@ -0,0 +1,58 @@ +/** + * @file primer_service.hpp + * @author Mateusz Krajewski (matikrajek42@gmail.com) + * @brief + * @version 0.1 + * @date 2024-04-21 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef APPS_PRIMER_SERVICE_PRIMER_SERVICE_HPP_ +#define APPS_PRIMER_SERVICE_PRIMER_SERVICE_HPP_ + +#include +#include +#include +#include + +#include "core/application/application_no_ipc.h" +#include "mw/gpio_server/controller/gpio_controller.hpp" +#include "communication-core/someip-controller/event_skeleton.h" +#include "diag/dtc/controller/dtc.h" +namespace simba { +namespace primer { + +class PrimerService final : public core::ApplicationNoIPC { + private: + core::ErrorCode ChangePrimerState(gpio::Value state); + core::ErrorCode ReadConfig(const std::unordered_map& parms); + + /** + * @brief This function is called to launch the application + * + * @param token stop token + */ + core::ErrorCode Run(std::stop_token token) final; + /** + * @brief This function is called to initialize the application + * + * @param parms map with parms + */ + core::ErrorCode Initialize( + const std::unordered_map& parms) final; + + gpio::GPIOController gpio_; + gpio::Value primerState {gpio::Value::LOW}; + uint8_t primer_pin_; + std::uint16_t active_time; + + std::shared_ptr primer_event; + + std::shared_ptr dtc_30; + std::shared_ptr dtc_31; +}; + +} // namespace primer +} // namespace simba +#endif // APPS_PRIMER_SERVICE_PRIMER_SERVICE_HPP_ diff --git a/core/application/application_common.cc b/core/application/application_common.cc index 7dfdf779..6c458ae6 100644 --- a/core/application/application_common.cc +++ b/core/application/application_common.cc @@ -169,11 +169,9 @@ ErrorCode ApplicationCommon::DiagConfig( return ErrorCode::kError; } nlohmann::json data = nlohmann::json::parse(file); - uint16_t app_id_{}; if (data.contains("app_id")) { - if (data.at("app_id").is_number()) { - app_id_ = data.at("app_id"); - this->app_id_ = app_id_; + if (data.at("app_id").is_string()) { + this->app_id_ = data.at("app_id"); diag_controller.Init(app_id_); return ErrorCode::kOk; } else { diff --git a/deployment b/deployment index cd681d80..bbfe6a1f 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit cd681d80062ea036c6a9b58215338585a83f9f46 +Subproject commit bbfe6a1ffd00e425d56a8fa4431cec573158ef5f diff --git a/diag/dtc/controller/dtc.h b/diag/dtc/controller/dtc.h index 57faf9af..2d5d6029 100644 --- a/diag/dtc/controller/dtc.h +++ b/diag/dtc/controller/dtc.h @@ -18,13 +18,13 @@ namespace diag { namespace dtc { class DTCObject : public IDTC { protected: - const uint16_t id; + const uint8_t id; DTCSendCallback callback; public: void Pass() const noexcept { callback(id, 2U); } void Failed() const noexcept { callback(id, 1U); } - explicit DTCObject(const uint16_t id_) : id{id_} {} + explicit DTCObject(const uint8_t id_) : id{id_} {} void SetCallback(DTCSendCallback callback_) noexcept override { callback = callback_; callback(id, 0U); diff --git a/mw/gpio_server/gpio_mw.cpp b/mw/gpio_server/gpio_mw.cpp index 6c626b96..d49ab82b 100644 --- a/mw/gpio_server/gpio_mw.cpp +++ b/mw/gpio_server/gpio_mw.cpp @@ -76,10 +76,7 @@ void GPIOMWService::InitializePins() { const std::string direct = gpio.at("direction"); core::gpio::direction_t direction = direct == "out" ? core::gpio::direction_t::OUT : core::gpio::direction_t::IN; - this->config.insert({ - pin_id, { - pin_num, direction} - }); + this->config.insert({pin_id, {pin_num, direction}}); } for (auto pin : this->config) { this->gpio_driver_.initializePin(pin.second.pinNum, pin.second.direction); From 17af0bf7313530f45480413446fe93568634586b Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 10:53:15 +0200 Subject: [PATCH 54/71] force fix cache --- .github/workflows/build_cpu_linux.yaml | 2 +- .github/workflows/run_ut.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index e5ac70f6..5fbf5992 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -24,7 +24,7 @@ jobs: uses: actions/cache@v2 with: path: | - /home/runner/.cache/bazel/_bazel_runner/* + /home/runner/.cache/bazel/* key: ${{ runner.os }}-bazel-pc-${{ hashFiles('**/lockfiles') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') diff --git a/.github/workflows/run_ut.yaml b/.github/workflows/run_ut.yaml index 9205bccb..16b8dac3 100644 --- a/.github/workflows/run_ut.yaml +++ b/.github/workflows/run_ut.yaml @@ -17,7 +17,7 @@ jobs: uses: actions/cache@v2 with: path: | - /home/runner/.cache/bazel/_bazel_runner/* + /home/runner/.cache/bazel/* key: ${{ runner.os }}-bazel-ut-${{ hashFiles('**/lockfiles') }} - name: Install bazel From dac3b3fbf250ec213bc2a45156175b514a287f2c Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 10:57:46 +0200 Subject: [PATCH 55/71] 1 --- .github/workflows/build_cpu.yaml | 2 +- .github/workflows/build_cpu_linux.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index e2326c2c..729baf1c 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -26,7 +26,7 @@ jobs: uses: actions/cache@v2 with: path: | - /home/runner/.cache/bazel/* + /home/runner/.cache/* key: ${{ runner.os }}-bazel-bbb-${{ hashFiles('**/lockfiles') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index 5fbf5992..6de115a2 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -24,7 +24,7 @@ jobs: uses: actions/cache@v2 with: path: | - /home/runner/.cache/bazel/* + /home/runner/.cache/* key: ${{ runner.os }}-bazel-pc-${{ hashFiles('**/lockfiles') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') From ae65b5aa8d2da041c45be3da42f529b00397580f Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Sun, 28 Apr 2024 13:22:20 +0200 Subject: [PATCH 56/71] sub repo update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index bbfe6a1f..38d35c15 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit bbfe6a1ffd00e425d56a8fa4431cec573158ef5f +Subproject commit 38d35c15292b7c0274ff45bdc188861efcb23d34 From a80d802c84b4706b8f597fa32aacede722b79666 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 13:33:51 +0200 Subject: [PATCH 57/71] force fix depl --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index 38d35c15..043455d5 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 38d35c15292b7c0274ff45bdc188861efcb23d34 +Subproject commit 043455d5d151db4db4f69e94f81f14f5c16312a0 From a00f0416a62d7148bae66a83673f9fed57edce5c Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 12:56:10 +0200 Subject: [PATCH 58/71] init --- .github/workflows/build_cpu.yaml | 23 +++++------------------ .github/workflows/build_cpu_linux.yaml | 25 +++++++++---------------- .github/workflows/run_ut.yaml | 23 ++++++----------------- 3 files changed, 20 insertions(+), 51 deletions(-) diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 729baf1c..08f01dba 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -9,8 +9,9 @@ on: jobs: build: - runs-on: ubuntu-latest + container: + image: matiko42/simba_github_action:latest steps: - name: check lable id: pr-labels @@ -22,12 +23,11 @@ jobs: with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} - - name: Cache bazel directories + - name: Cache Bazel data uses: actions/cache@v2 with: - path: | - /home/runner/.cache/* - key: ${{ runner.os }}-bazel-bbb-${{ hashFiles('**/lockfiles') }} + path: ~/.cache/bazel + key: bazel-cache-cpu-${{ runner.os }}-${{ hashFiles('**/BUILD.bazel') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') uses: thollander/actions-comment-pull-request@v2 @@ -35,19 +35,6 @@ jobs: message: | Starting built software for BeagleBone (EC) comment_tag: to_delete - - - name: Install bazel - if: contains(steps.pr-labels.outputs.labels, 'check-bbb') - run: | - sudo apt install apt-transport-https curl gnupg - sudo add-apt-repository ppa:ubuntu-toolchain-r/ppa -y - sudo apt update - sudo apt install g++-13 gcc-13 - curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg - sudo mv bazel.gpg /etc/apt/trusted.gpg.d/ - echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list - sudo apt update && sudo apt install bazel-5.4.1 - - name: Run build engine computer if: contains(steps.pr-labels.outputs.labels, 'check-bbb') run: | diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index 6de115a2..196d1af6 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -10,6 +10,8 @@ on: jobs: build: runs-on: ubuntu-latest + container: + image: matiko42/simba_github_action:latest steps: - name: check lable id: pr-labels @@ -20,12 +22,11 @@ jobs: with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} - - name: Cache bazel directories + - name: Cache Bazel data uses: actions/cache@v2 with: - path: | - /home/runner/.cache/* - key: ${{ runner.os }}-bazel-pc-${{ hashFiles('**/lockfiles') }} + path: ~/.cache/bazel + key: bazel-cache-bbb-${{ runner.os }}-${{ hashFiles('**/BUILD.bazel') }} - name: RM 1 if: contains(steps.pr-labels.outputs.labels, 'check-bbb') uses: thollander/actions-comment-pull-request@v2 @@ -33,22 +34,14 @@ jobs: message: | Starting built software for linux comment_tag: to_delete - - name: Install bazel - if: contains(steps.pr-labels.outputs.labels, 'check') - run: | - sudo apt install apt-transport-https curl gnupg - sudo add-apt-repository ppa:ubuntu-toolchain-r/ppa -y - sudo apt update - sudo apt install g++-13 gcc-13 - curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg - sudo mv bazel.gpg /etc/apt/trusted.gpg.d/ - echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list - sudo apt update && sudo apt install bazel-5.4.1 - - name: Run build engine computer if: contains(steps.pr-labels.outputs.labels, 'check') run: | bazel build //deployment/cpu/ec:pkg + - name: Run build flight computer + if: contains(steps.pr-labels.outputs.labels, 'check') + run: | + bazel build --config=bbb //deployment/cpu/fc:pkg - name: Add msg if: contains(steps.pr-labels.outputs.labels, 'check') uses: thollander/actions-comment-pull-request@v2 diff --git a/.github/workflows/run_ut.yaml b/.github/workflows/run_ut.yaml index 16b8dac3..150f7d93 100644 --- a/.github/workflows/run_ut.yaml +++ b/.github/workflows/run_ut.yaml @@ -7,29 +7,18 @@ on: - master jobs: - build-and-test: + build: runs-on: ubuntu-latest - + container: + image: matiko42/simba_github_action:latest steps: - name: Checkout Repository uses: actions/checkout@v2 - - name: Cache bazel directories + - name: Cache Bazel data uses: actions/cache@v2 with: - path: | - /home/runner/.cache/bazel/* - key: ${{ runner.os }}-bazel-ut-${{ hashFiles('**/lockfiles') }} - - - name: Install bazel - run: | - sudo apt install apt-transport-https curl gnupg - sudo add-apt-repository ppa:ubuntu-toolchain-r/ppa -y - sudo apt update - sudo apt install g++-13 gcc-13 - curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg - sudo mv bazel.gpg /etc/apt/trusted.gpg.d/ - echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list - sudo apt update && sudo apt install bazel-5.4.1 + path: ~/.cache/bazel + key: bazel-cache-ut-${{ runner.os }}-${{ hashFiles('**/BUILD.bazel') }} - name: Run ut run: | gcc --version From 52d8b9f0619d6936871548fd7588323529da6752 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 13:03:15 +0200 Subject: [PATCH 59/71] fix --- .github/workflows/Check syntax.yaml | 2 +- .github/workflows/build_cpu.yaml | 2 +- .github/workflows/build_cpu_linux.yaml | 2 +- .github/workflows/run_ut.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/Check syntax.yaml b/.github/workflows/Check syntax.yaml index 3554008f..ae84faab 100644 --- a/.github/workflows/Check syntax.yaml +++ b/.github/workflows/Check syntax.yaml @@ -12,7 +12,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Install cpplint run: | diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 08f01dba..11fbfb8d 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -19,7 +19,7 @@ jobs: - name: Checkout Repository if: contains(steps.pr-labels.outputs.labels, 'check-bbb') - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index 196d1af6..b674c1da 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -18,7 +18,7 @@ jobs: uses: joerick/pr-labels-action@v1.0.8 - name: Checkout Repository if: contains(steps.pr-labels.outputs.labels, 'check') - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: submodules: 'true' ssh-key: ${{ secrets.PRIVATE_KEY_FOR_DEPLOY_KEY_IN_SUBMODULE }} diff --git a/.github/workflows/run_ut.yaml b/.github/workflows/run_ut.yaml index 150f7d93..27d23b24 100644 --- a/.github/workflows/run_ut.yaml +++ b/.github/workflows/run_ut.yaml @@ -13,7 +13,7 @@ jobs: image: matiko42/simba_github_action:latest steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Cache Bazel data uses: actions/cache@v2 with: From 52a53bf79e5b04881d34f5c6933e856e6844eb9d Mon Sep 17 00:00:00 2001 From: Mateusz Date: Sun, 28 Apr 2024 13:08:26 +0200 Subject: [PATCH 60/71] fix --- .github/workflows/Check syntax.yaml | 8 ++------ .github/workflows/run_ut.yaml | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/.github/workflows/Check syntax.yaml b/.github/workflows/Check syntax.yaml index ae84faab..0fa332d6 100644 --- a/.github/workflows/Check syntax.yaml +++ b/.github/workflows/Check syntax.yaml @@ -9,15 +9,11 @@ on: jobs: build: runs-on: ubuntu-latest - + container: + image: matiko42/simba_github_action:latest steps: - name: Checkout Repository uses: actions/checkout@v4 - - - name: Install cpplint - run: | - sudo apt install cpplint - - name: Check C++ Syntax run: | cpp_files=$(find . -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp") diff --git a/.github/workflows/run_ut.yaml b/.github/workflows/run_ut.yaml index 27d23b24..8e8d14b5 100644 --- a/.github/workflows/run_ut.yaml +++ b/.github/workflows/run_ut.yaml @@ -7,7 +7,7 @@ on: - master jobs: - build: + build-and-test: runs-on: ubuntu-latest container: image: matiko42/simba_github_action:latest From 54366ce9bca7b07d42838ac2b084d25f11cab3c5 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Tue, 30 Apr 2024 22:59:12 +0200 Subject: [PATCH 61/71] Bazel update from 5.4.1 to 7.1.1 --- .bazelversion | 2 +- .gitignore | 3 ++- core/i2c/i2cdriver.cpp | 46 ++++++++++++++++++++++-------------------- core/i2c/i2cdriver.hpp | 24 +++++++++++++--------- deployment | 2 +- 5 files changed, 42 insertions(+), 35 deletions(-) diff --git a/.bazelversion b/.bazelversion index ade65226..ef09838c 100644 --- a/.bazelversion +++ b/.bazelversion @@ -1 +1 @@ -5.4.1 +7.1.1 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3b78ae97..a4b9948e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ bazel-* .vscode .pyc __pycache__ -.coverage \ No newline at end of file +.coverage +MODULE.bazel.lock diff --git a/core/i2c/i2cdriver.cpp b/core/i2c/i2cdriver.cpp index bc24b183..fa1dd6bd 100644 --- a/core/i2c/i2cdriver.cpp +++ b/core/i2c/i2cdriver.cpp @@ -1,16 +1,18 @@ /** * @file i2cdriver.cpp * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-04-03 - * + * * @copyright Copyright (c) 2024 - * + * */ #include "core/i2c/i2cdriver.hpp" +#include + #define path "/dev/i2c-2" namespace simba { @@ -18,34 +20,34 @@ namespace core { namespace i2c { core::ErrorCode I2CDriver::Init() { - if ((this->i2cFile = open(path, O_RDWR)) < 0) { - return core::ErrorCode::kInitializeError; - } - return core::ErrorCode::kOk; + if ((this->i2cFile = open(path, O_RDWR)) < 0) { + return core::ErrorCode::kInitializeError; + } + return core::ErrorCode::kOk; } core::ErrorCode I2CDriver::Ioctl(const uint8_t address, const uint16_t type) { - if (ioctl(this->i2cFile, type, address) < 0) { - return core::ErrorCode::kInitializeError; - } - return core::ErrorCode::kOk; + if (ioctl(this->i2cFile, type, address) < 0) { + return core::ErrorCode::kInitializeError; + } + return core::ErrorCode::kOk; } core::ErrorCode I2CDriver::Write(const std::vector RegData) { - for (int i = 0; i < RegData.size(); i+=2) { - uint8_t buf[2] = {RegData[i], RegData[i+1]}; - if (write(i2cFile, buf, 2) != 2) { - return core::ErrorCode::kInitializeError; - } + for (int i = 0; i < RegData.size(); i += 2) { + uint8_t buf[2] = {RegData[i], RegData[i + 1]}; + if (write(i2cFile, buf, 2) != 2) { + return core::ErrorCode::kInitializeError; } - return core::ErrorCode::kOk; + } + return core::ErrorCode::kOk; } core::ErrorCode I2CDriver::PageWrite(std::vector data) { - data.insert(data.begin(), 0x00); - if (write(i2cFile, data.data(), data.size()) != data.size()) { - return core::ErrorCode::kInitializeError; - } - return core::ErrorCode::kOk; + data.insert(data.begin(), 0x00); + if (write(i2cFile, data.data(), data.size()) != data.size()) { + return core::ErrorCode::kInitializeError; + } + return core::ErrorCode::kOk; } } // namespace i2c } // namespace core diff --git a/core/i2c/i2cdriver.hpp b/core/i2c/i2cdriver.hpp index 244d7ba7..9ef6d24c 100644 --- a/core/i2c/i2cdriver.hpp +++ b/core/i2c/i2cdriver.hpp @@ -1,44 +1,48 @@ /** * @file i2cdriver.hpp * @author Mateusz Krajewski (matikrajek42@gmail.com) - * @brief + * @brief * @version 0.1 * @date 2024-04-03 - * + * * @copyright Copyright (c) 2024 - * + * */ #ifndef CORE_I2C_I2CDRIVER_HPP_ #define CORE_I2C_I2CDRIVER_HPP_ -#include #include #include -#include #include +#include +#include #include + +#include +#include #include -#include #include -#include +#include + #include "core/common/error_code.h" namespace simba { namespace core { namespace i2c { -class I2CDriver{ +class I2CDriver { private: int i2cFile; + public: core::ErrorCode Init(); core::ErrorCode Ioctl(const uint8_t address, const uint16_t type = I2C_SLAVE); /** * @brief Function to write data to device on i2c bus - * + * * @param data pair ( req, data) - * @return core::ErrorCode + * @return core::ErrorCode */ core::ErrorCode Write(const std::vector RegData); core::ErrorCode PageWrite(std::vector data); diff --git a/deployment b/deployment index 043455d5..c831a118 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit 043455d5d151db4db4f69e94f81f14f5c16312a0 +Subproject commit c831a11847b1c2138bedbc53342ec58464b132ae From f265feb8a2f2caec13fa96710247feb062bf17f6 Mon Sep 17 00:00:00 2001 From: Bartosz Snieg Date: Mon, 6 May 2024 20:16:15 +0200 Subject: [PATCH 62/71] submodule update --- deployment | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment b/deployment index c831a118..baf6b1f3 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit c831a11847b1c2138bedbc53342ec58464b132ae +Subproject commit baf6b1f3b39a41f7f855a962b2293ce56114d920 From 1beb8bcdb5692c0384826e9252d9b332010caa8a Mon Sep 17 00:00:00 2001 From: Mateusz Date: Mon, 6 May 2024 21:21:16 +0200 Subject: [PATCH 63/71] makr_fix_actions_for_bazel_7.4.1 --- .github/workflows/build_cpu.yaml | 4 ++-- .github/workflows/build_cpu_linux.yaml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build_cpu.yaml b/.github/workflows/build_cpu.yaml index 11fbfb8d..ac70cd36 100644 --- a/.github/workflows/build_cpu.yaml +++ b/.github/workflows/build_cpu.yaml @@ -38,7 +38,7 @@ jobs: - name: Run build engine computer if: contains(steps.pr-labels.outputs.labels, 'check-bbb') run: | - bazel build --config=bbb //deployment/cpu/ec:pkg + bazel build --platforms=//bazel/platforms:bbb //deployment/cpu/ec:pkg - name: Add msg if: contains(steps.pr-labels.outputs.labels, 'check') uses: thollander/actions-comment-pull-request@v2 @@ -48,7 +48,7 @@ jobs: - name: Run build flight computer if: contains(steps.pr-labels.outputs.labels, 'check-bbb') run: | - bazel build --config=bbb //deployment/cpu/fc:pkg + bazel build --platforms=//bazel/platforms:bbb //deployment/cpu/fc:pkg - name: Add msg_2 if: contains(steps.pr-labels.outputs.labels, 'check') uses: thollander/actions-comment-pull-request@v2 diff --git a/.github/workflows/build_cpu_linux.yaml b/.github/workflows/build_cpu_linux.yaml index b674c1da..67b29e66 100644 --- a/.github/workflows/build_cpu_linux.yaml +++ b/.github/workflows/build_cpu_linux.yaml @@ -41,7 +41,7 @@ jobs: - name: Run build flight computer if: contains(steps.pr-labels.outputs.labels, 'check') run: | - bazel build --config=bbb //deployment/cpu/fc:pkg + bazel build //deployment/cpu/fc:pkg - name: Add msg if: contains(steps.pr-labels.outputs.labels, 'check') uses: thollander/actions-comment-pull-request@v2 From 2a0a58bcca65e73b76074d567d6552c9d7dc190d Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 7 May 2024 09:32:35 +0200 Subject: [PATCH 64/71] fix devcontainer --- .devcontainer/Dockerfile | 9 --------- .devcontainer/devcontainer.json | 3 +-- .devcontainer/start.sh | 5 ----- 3 files changed, 1 insertion(+), 16 deletions(-) delete mode 100644 .devcontainer/Dockerfile delete mode 100644 .devcontainer/start.sh diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index 2a1da44b..00000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM mcr.microsoft.com/devcontainers/base:jammy - -RUN apt-get install -y \ - git \ - gcc \ - g++ \ - build-essential - -WORKDIR /workspace diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index eb153a41..6c1eb1c9 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -7,14 +7,13 @@ "image": "matiko42/simba_dev_container", // Features to add to the dev container. More info: https://containers.dev/features. "features": { - "ghcr.io/balazs23/devcontainers-features/bazel":1 }, // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. - "postCreateCommand": "sh /workspaces/srp/.devcontainer/start.sh", + // "postCreateCommand": "sh /workspaces/srp/.devcontainer/start.sh", // Configure tool-specific properties. "customizations": { diff --git a/.devcontainer/start.sh b/.devcontainer/start.sh deleted file mode 100644 index d336cbeb..00000000 --- a/.devcontainer/start.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -bazel --version -apt update -apt install cpplint \ No newline at end of file From 8afb29edaa6f8fae2aa427db3e329af522a73920 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 7 May 2024 10:13:50 +0200 Subject: [PATCH 65/71] add pylint check --- .github/workflows/python_syntax.yaml | 78 ++++++++----------- .github/workflows/python_unittest.yaml | 33 ++++++++ deployment | 2 +- tools/pylint/pylint.sh | 18 +++++ .../tests/{test_gui.py => __gui.py} | 0 .../tests/data_10_35_22.csv | 1 + .../tests/data_10_35_4.csv | 1 + .../tests/data_10_38_50.csv | 1 + 8 files changed, 88 insertions(+), 46 deletions(-) create mode 100644 .github/workflows/python_unittest.yaml create mode 100755 tools/pylint/pylint.sh rename tools/sensors_data_display_api/tests/{test_gui.py => __gui.py} (100%) create mode 100644 tools/sensors_data_display_api/tests/data_10_35_22.csv create mode 100644 tools/sensors_data_display_api/tests/data_10_35_4.csv create mode 100644 tools/sensors_data_display_api/tests/data_10_38_50.csv diff --git a/.github/workflows/python_syntax.yaml b/.github/workflows/python_syntax.yaml index 829b1397..aa5775f4 100644 --- a/.github/workflows/python_syntax.yaml +++ b/.github/workflows/python_syntax.yaml @@ -1,56 +1,44 @@ -name: Python Pylint Analysis +name: Pylint Check on: push: branches: - - main + - master pull_request: branches: - - main + - master jobs: - pylint-analysis: + pylint_check: runs-on: ubuntu-latest - + steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install pylint - - - name: Run pylint and count errors - id: pylint - run: | - # Lista folderów, w których przeprowadzana jest analiza Pylint - folders=("tools") - - total_errors=0 - - for folder in "${folders[@]}"; do - find "$folder" -type f -name "*.py" | while read -r file; do - errors=$(pylint --output-format=text "$file" | grep -c '^\*\*\*') - total_errors=$((total_errors + errors)) - done - done - - echo "::set-output name=total_errors::$total_errors" - - - name: Display total errors - run: | - echo "Total errors: ${{ steps.pylint.outputs.total_errors }}" - - - name: Check for errors and return error if any - run: | - total_errors=${{ steps.pylint.outputs.total_errors }} - if [ "$total_errors" -gt 0 ]; then - echo "Errors found. Exiting with status code 1." - exit 1 + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.11' + + - name: Install dependencies + run: pip install pylint + + - name: Run pylint + run: | + py_files=$(find tools -name "*.py") + total_errors=0 + + for file in $py_files; do + errors=$(pylint --max-line-length=120 $file | wc -l) + if [[ $errors -gt 1 ]]; then + total_errors=$((total_errors + errors - 1)) fi + done + + if [[ $total_errors -gt 0 ]]; then + echo "Too many errors ($total_errors), failing the build." + exit 1 + else + echo "Acceptable number of errors ($total_errors)." + fi diff --git a/.github/workflows/python_unittest.yaml b/.github/workflows/python_unittest.yaml new file mode 100644 index 00000000..9b30e999 --- /dev/null +++ b/.github/workflows/python_unittest.yaml @@ -0,0 +1,33 @@ +name: Python Unit Test + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + pip install -r tools/sensors_data_display_api/requirements.txt + python3 -m pip install coverage + + - name: Run unit tests + run: | + cd tools/sensors_data_display_api/tests/ + coverage run -m unittest discover -s . -v + coverage report -m diff --git a/deployment b/deployment index baf6b1f3..569bbd3e 160000 --- a/deployment +++ b/deployment @@ -1 +1 @@ -Subproject commit baf6b1f3b39a41f7f855a962b2293ce56114d920 +Subproject commit 569bbd3e8130b51b4e018c14453528a11f3cbee7 diff --git a/tools/pylint/pylint.sh b/tools/pylint/pylint.sh new file mode 100755 index 00000000..6606becf --- /dev/null +++ b/tools/pylint/pylint.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +py_files=$(find tools -name "*.py") +total_errors=0 + +for file in $py_files; do + errors=$(pylint --max-line-length=120 $file | wc -l) + if [[ $errors -gt 1 ]]; then + total_errors=$((total_errors + errors - 1)) + fi +done + +if [[ $total_errors -gt 0 ]]; then + echo "Too many errors ($total_errors), failing the build." + exit 1 +else + echo "Acceptable number of errors ($total_errors)." +fi diff --git a/tools/sensors_data_display_api/tests/test_gui.py b/tools/sensors_data_display_api/tests/__gui.py similarity index 100% rename from tools/sensors_data_display_api/tests/test_gui.py rename to tools/sensors_data_display_api/tests/__gui.py diff --git a/tools/sensors_data_display_api/tests/data_10_35_22.csv b/tools/sensors_data_display_api/tests/data_10_35_22.csv new file mode 100644 index 00000000..a617ff26 --- /dev/null +++ b/tools/sensors_data_display_api/tests/data_10_35_22.csv @@ -0,0 +1 @@ +TIMESTAMP,TEMPERATURE_UP,TEMPERATURE_DOWN,TEMPERATURE_MIDDLE,TANK_PRESSURE,JET_PRESSURE,PRESSURE_DIFFERENCE,MAIN_VALVE,VENT diff --git a/tools/sensors_data_display_api/tests/data_10_35_4.csv b/tools/sensors_data_display_api/tests/data_10_35_4.csv new file mode 100644 index 00000000..a617ff26 --- /dev/null +++ b/tools/sensors_data_display_api/tests/data_10_35_4.csv @@ -0,0 +1 @@ +TIMESTAMP,TEMPERATURE_UP,TEMPERATURE_DOWN,TEMPERATURE_MIDDLE,TANK_PRESSURE,JET_PRESSURE,PRESSURE_DIFFERENCE,MAIN_VALVE,VENT diff --git a/tools/sensors_data_display_api/tests/data_10_38_50.csv b/tools/sensors_data_display_api/tests/data_10_38_50.csv new file mode 100644 index 00000000..a617ff26 --- /dev/null +++ b/tools/sensors_data_display_api/tests/data_10_38_50.csv @@ -0,0 +1 @@ +TIMESTAMP,TEMPERATURE_UP,TEMPERATURE_DOWN,TEMPERATURE_MIDDLE,TANK_PRESSURE,JET_PRESSURE,PRESSURE_DIFFERENCE,MAIN_VALVE,VENT From 2c49d5354def5e445d2a26b81c3b1236eeb74342 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 7 May 2024 11:31:48 +0200 Subject: [PATCH 66/71] add coverage actions --- .github/workflows/python_unittest.yaml | 10 +++++++++- tools/sensors_data_display_api/tests/data_10_35_22.csv | 1 - tools/sensors_data_display_api/tests/data_10_35_4.csv | 1 - tools/sensors_data_display_api/tests/data_10_38_50.csv | 1 - tools/sensors_data_display_api/tests/totalCoverage.sh | 9 +++++++++ 5 files changed, 18 insertions(+), 4 deletions(-) delete mode 100644 tools/sensors_data_display_api/tests/data_10_35_22.csv delete mode 100644 tools/sensors_data_display_api/tests/data_10_35_4.csv delete mode 100644 tools/sensors_data_display_api/tests/data_10_38_50.csv create mode 100755 tools/sensors_data_display_api/tests/totalCoverage.sh diff --git a/.github/workflows/python_unittest.yaml b/.github/workflows/python_unittest.yaml index 9b30e999..a2a436fd 100644 --- a/.github/workflows/python_unittest.yaml +++ b/.github/workflows/python_unittest.yaml @@ -30,4 +30,12 @@ jobs: run: | cd tools/sensors_data_display_api/tests/ coverage run -m unittest discover -s . -v - coverage report -m + - name: Check Code coverange + run: | + cd tools/sensors_data_display_api/tests/ + coverage_report=$(coverage report -m) + total_coverage=$(echo "$coverage_report" | grep "TOTAL" | awk '{print $NF}') + echo "Całkowita procentowa pokrywalność kodu: $total_coverage" + if (( $(echo "$total_coverage < 90" | bc -l) )); then + exit 1 + fi diff --git a/tools/sensors_data_display_api/tests/data_10_35_22.csv b/tools/sensors_data_display_api/tests/data_10_35_22.csv deleted file mode 100644 index a617ff26..00000000 --- a/tools/sensors_data_display_api/tests/data_10_35_22.csv +++ /dev/null @@ -1 +0,0 @@ -TIMESTAMP,TEMPERATURE_UP,TEMPERATURE_DOWN,TEMPERATURE_MIDDLE,TANK_PRESSURE,JET_PRESSURE,PRESSURE_DIFFERENCE,MAIN_VALVE,VENT diff --git a/tools/sensors_data_display_api/tests/data_10_35_4.csv b/tools/sensors_data_display_api/tests/data_10_35_4.csv deleted file mode 100644 index a617ff26..00000000 --- a/tools/sensors_data_display_api/tests/data_10_35_4.csv +++ /dev/null @@ -1 +0,0 @@ -TIMESTAMP,TEMPERATURE_UP,TEMPERATURE_DOWN,TEMPERATURE_MIDDLE,TANK_PRESSURE,JET_PRESSURE,PRESSURE_DIFFERENCE,MAIN_VALVE,VENT diff --git a/tools/sensors_data_display_api/tests/data_10_38_50.csv b/tools/sensors_data_display_api/tests/data_10_38_50.csv deleted file mode 100644 index a617ff26..00000000 --- a/tools/sensors_data_display_api/tests/data_10_38_50.csv +++ /dev/null @@ -1 +0,0 @@ -TIMESTAMP,TEMPERATURE_UP,TEMPERATURE_DOWN,TEMPERATURE_MIDDLE,TANK_PRESSURE,JET_PRESSURE,PRESSURE_DIFFERENCE,MAIN_VALVE,VENT diff --git a/tools/sensors_data_display_api/tests/totalCoverage.sh b/tools/sensors_data_display_api/tests/totalCoverage.sh new file mode 100755 index 00000000..a983018b --- /dev/null +++ b/tools/sensors_data_display_api/tests/totalCoverage.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# Wykonanie polecenia coverage report -m i przechwycenie wyniku +coverage_report=$(python3-coverage report -m) + +# Przechwycenie procentowego pokrycia z wyniku +total_coverage=$(echo "$coverage_report" | grep "TOTAL" | awk '{print $NF}') + +echo "Całkowita procentowa pokrywalność kodu: $total_coverage" \ No newline at end of file From 6df2b2c3129e75ad5430db4a557a38a0c738762c Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 7 May 2024 11:34:36 +0200 Subject: [PATCH 67/71] fix --- .github/workflows/python_unittest.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/python_unittest.yaml b/.github/workflows/python_unittest.yaml index a2a436fd..53b5f599 100644 --- a/.github/workflows/python_unittest.yaml +++ b/.github/workflows/python_unittest.yaml @@ -36,6 +36,7 @@ jobs: coverage_report=$(coverage report -m) total_coverage=$(echo "$coverage_report" | grep "TOTAL" | awk '{print $NF}') echo "Całkowita procentowa pokrywalność kodu: $total_coverage" - if (( $(echo "$total_coverage < 90" | bc -l) )); then + if [[ $total_coverage -lt 90 ]]; then + echo "Zbyt małe pokrycie kodu" exit 1 fi From 7f7578ecc0af182e0954e50d627f9a4c3e450ceb Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 7 May 2024 11:36:25 +0200 Subject: [PATCH 68/71] . --- .github/workflows/python_unittest.yaml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/python_unittest.yaml b/.github/workflows/python_unittest.yaml index 53b5f599..3f1f2939 100644 --- a/.github/workflows/python_unittest.yaml +++ b/.github/workflows/python_unittest.yaml @@ -30,13 +30,14 @@ jobs: run: | cd tools/sensors_data_display_api/tests/ coverage run -m unittest discover -s . -v - - name: Check Code coverange + - name: Check Code Coverage run: | cd tools/sensors_data_display_api/tests/ coverage_report=$(coverage report -m) - total_coverage=$(echo "$coverage_report" | grep "TOTAL" | awk '{print $NF}') - echo "Całkowita procentowa pokrywalność kodu: $total_coverage" - if [[ $total_coverage -lt 90 ]]; then + total_coverage=$(echo "$coverage_report" | grep "TOTAL" | awk '{print $NF}' | tr -d '%') # Usuwanie procentu + echo "Całkowita procentowa pokrywalność kodu: $total_coverage%" + if [ $total_coverage -lt 90 ]; then echo "Zbyt małe pokrycie kodu" exit 1 fi + shell: bash From 5ce30ca802c6799ae033e46f390d757c35f0b813 Mon Sep 17 00:00:00 2001 From: Mateusz Date: Tue, 7 May 2024 11:40:09 +0200 Subject: [PATCH 69/71] . --- .github/workflows/python_unittest.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/python_unittest.yaml b/.github/workflows/python_unittest.yaml index 3f1f2939..3fe24dfd 100644 --- a/.github/workflows/python_unittest.yaml +++ b/.github/workflows/python_unittest.yaml @@ -36,7 +36,7 @@ jobs: coverage_report=$(coverage report -m) total_coverage=$(echo "$coverage_report" | grep "TOTAL" | awk '{print $NF}' | tr -d '%') # Usuwanie procentu echo "Całkowita procentowa pokrywalność kodu: $total_coverage%" - if [ $total_coverage -lt 90 ]; then + if [ $total_coverage -lt 75 ]; then echo "Zbyt małe pokrycie kodu" exit 1 fi From c325929213b56190a1aa9e31efc62012bb96796d Mon Sep 17 00:00:00 2001 From: sandra Date: Fri, 17 May 2024 16:39:09 +0200 Subject: [PATCH 70/71] add search by req_method --- tools/sensors_data_display_api/app.py | 15 ++++++++++----- tools/sensors_data_display_api/data_reader.py | 12 ++++++++++++ tools/sensors_data_display_api/data_sender.py | 8 ++++---- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/tools/sensors_data_display_api/app.py b/tools/sensors_data_display_api/app.py index 79842e52..0d000b68 100644 --- a/tools/sensors_data_display_api/app.py +++ b/tools/sensors_data_display_api/app.py @@ -38,7 +38,6 @@ def __init__(self): self.saving_thread = None self.data_to_save = Data() self.collection_time = 10 - self.data_sender = DataSender() # measurements temperature_up_frame = tk.Frame(self) @@ -157,6 +156,9 @@ def __init__(self): self.data_reader = DataReader(gui=self) self.read_data() + # initiate variable sender + self.data_sender = DataSender(self.data_reader.ip, self.data_reader.port) + def read_data(self): self.data_reader_thread = threading.Thread(target=self.data_reader.read_data, daemon=True) self.data_reader_thread.start() @@ -206,18 +208,21 @@ def _save_to_file(self): logging.info("NOT SAVED") def launch_rocket(self, value): + req_method="PC_APP/EngineStart" if value == 1: result = messagebox.askyesno('Launch rocket', 'Are you sure you want to launch rocket?') if result: - self.data_sender.send_data(value=value, service_id=518, method_id=1) + self.data_sender.send_data(value=value, method_id=self.get_method_id(req_method), service_id=self.get_service_id(req_method)) else: - self.data_sender.send_data(value=value, service_id=518, method_id=1) + self.data_sender.send_data(value=value, method_id=self.get_method_id(req_method), service_id=self.get_service_id(req_method)) def set_main_valve(self, value): - self.data_sender.send_data(value=value, service_id=515, method_id=1) + req_method="PC_APP/setServoValue" + self.data_sender.send_data(value=value, method_id=self.get_method_id(req_method), service_id=self.get_service_id(req_method)) def set_vent(self, value): - self.data_sender.send_data(value=value, service_id=515, method_id=3) + req_method="PC_APP/setVentValue" + self.data_sender.send_data(value=value, method_id=self.get_method_id(req_method), service_id=self.get_service_id(req_method)) def exit(self): self.stop_reading = True diff --git a/tools/sensors_data_display_api/data_reader.py b/tools/sensors_data_display_api/data_reader.py index c469b3bd..8c026013 100644 --- a/tools/sensors_data_display_api/data_reader.py +++ b/tools/sensors_data_display_api/data_reader.py @@ -24,6 +24,18 @@ def _prepare_lookup_table(self): method_id = value.get('event_id') lookup_table[(service_id, method_id)] = key return lookup_table + + def get_service_id(self, request_name): + req_methods = self.config.get('req_methods', {}) + if request_name in req_methods: + return req_methods[request_name]['service_id'] + return None, None + + def get_method_id(self, request_name): + req_methods = self.config.get('req_methods', {}) + if request_name in req_methods: + return req_methods[request_name]['method_id'] + return None, None def read_data(self): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: diff --git a/tools/sensors_data_display_api/data_sender.py b/tools/sensors_data_display_api/data_sender.py index fe19e735..ad69587b 100644 --- a/tools/sensors_data_display_api/data_sender.py +++ b/tools/sensors_data_display_api/data_sender.py @@ -1,3 +1,4 @@ +import json import socket import struct @@ -5,11 +6,10 @@ class DataSender: - def __init__(self): - self.receiver_host = '127.0.0.1' - self.receiver_port = 10101 + def __init__(self, receiver_host, receiver_port): + self.receiver_host = receiver_host + self.receiver_port = receiver_port self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.socket.connect((self.receiver_host, self.receiver_port)) def send_data(self, value: int, service_id: int, method_id: int): hdr = SomeIPHeader(service_id, method_id) From 8eff523ad2331a9c21bff857251a9468f6fb8120 Mon Sep 17 00:00:00 2001 From: sandra Date: Sat, 25 May 2024 18:29:58 +0200 Subject: [PATCH 71/71] fix set_valve --- tools/sensors_data_display_api/app.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/sensors_data_display_api/app.py b/tools/sensors_data_display_api/app.py index 0d000b68..af3f1b33 100644 --- a/tools/sensors_data_display_api/app.py +++ b/tools/sensors_data_display_api/app.py @@ -90,8 +90,8 @@ def __init__(self): main_valve_set_0_button = tk.Button(main_valve_button_frame, text="Main valve: set 0", command=lambda: self.set_main_valve(value=0)) vent_button_frame = tk.Frame(self) - vent_set_1_button = tk.Button(vent_button_frame, text="Vent: set 1", command=lambda: self.set_vent(value=1)) - vent_set_0_button = tk.Button(vent_button_frame, text="Vent: set 0", command=lambda: self.set_vent(value=0)) + vent_set_1_button = tk.Button(vent_button_frame, text="Vent: set 1", command=lambda: self.set_vent(self, value=1)) + vent_set_0_button = tk.Button(vent_button_frame, text="Vent: set 0", command=lambda: self.set_vent(self, value=0)) launch_rocket_button_frame = tk.Frame(self) launch_rocket_button = tk.Button(launch_rocket_button_frame, text="Launch rocket", command=lambda: self.launch_rocket(value=1))