b35f9e37423ca894dcfd735c8bbb8fbd33d22f29
[src/low-level-can-generator.git] / src / main.cpp
1 /*\r
2  * Copyright (C) 2015, 2016 "IoT.bzh"\r
3  * Author "Loïc Collignon" <loic.collignon@iot.bzh>\r
4  * Author "Romain Forlot" <romain.forlot@iot.bzh>\r
5  *\r
6  * Licensed under the Apache License, Version 2.0 (the "License");\r
7  * you may not use this file except in compliance with the License.\r
8  * You may obtain a copy of the License at\r
9  *\r
10  *       http://www.apache.org/licenses/LICENSE-2.0\r
11  *\r
12  * Unless required by applicable law or agreed to in writing, software\r
13  * distributed under the License is distributed on an "AS IS" BASIS,\r
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
15  * See the License for the specific language governing permissions and\r
16  * limitations under the License.\r
17  */\r
18 \r
19 #include <unistd.h>\r
20 #include <stdlib.h>\r
21 #include <libgen.h>\r
22 #include <exception>\r
23 #include <fstream>\r
24 #include <iostream>\r
25 #include <string>\r
26 #include <numeric>\r
27 #include <iterator>\r
28 #include <json.hpp>\r
29 #include "openxc/message_set.hpp"\r
30 \r
31 #define EXIT_SUCCESS                            0\r
32 #define EXIT_UNKNOWN_ERROR                      1\r
33 #define EXIT_COMMAND_LINE_ERROR         2\r
34 #define EXIT_PROGRAM_ERROR                      3\r
35 \r
36 \r
37 /**\r
38  * FLAGS\r
39  */\r
40 \r
41 #define INVALID_FLAG 0x0001\r
42 #define STANDARD_ID 0x0002\r
43 #define EXTENDED_ID 0x0004\r
44 #define BCM_PROTOCOL 0x0008\r
45 #define J1939_PROTOCOL 0x0010\r
46 #define J1939_ADDR_CLAIM_PROTOCOL 0x0020\r
47 #define ISOTP_PROTOCOL 0x0040\r
48 #define FD_FRAME 0x0800\r
49 \r
50 template <typename T>\r
51 struct generator\r
52 {\r
53         T v_;\r
54         std::string line_prefix_;\r
55         generator(T v, std::string line_prefix = "") : v_{v}, line_prefix_{line_prefix} {}\r
56 };\r
57 \r
58 template <>\r
59 struct generator<openxc::signal>\r
60 {\r
61         const openxc::signal& v_;\r
62         std::uint32_t index_;\r
63         std::string line_prefix_;\r
64         generator(const openxc::signal& v, std::uint32_t index, std::string line_prefix = "")\r
65                 : v_{v}, index_{index}, line_prefix_{line_prefix}\r
66         {\r
67         }\r
68 };\r
69 \r
70 template <typename T>\r
71 generator<T> gen(const T& v, std::string line_prefix = "") { return generator<T>(v, line_prefix); }\r
72 \r
73 generator<openxc::signal> gen(const openxc::signal& v, std::uint32_t index, std::string line_prefix = "")\r
74 {\r
75         return generator<openxc::signal>(v, index, line_prefix);\r
76 }\r
77 \r
78 template <typename T>\r
79 std::ostream& operator<<(std::ostream& o, const generator<T>& v)\r
80 {\r
81         o << v.line_prefix_ << v.v_;\r
82         return o;\r
83 }\r
84 \r
85 template <>\r
86 std::ostream& operator<<(std::ostream& o, const generator<bool>& v)\r
87 {\r
88         o << v.line_prefix_ << (v.v_ ? "true" : "false");\r
89         return o;\r
90 }\r
91 \r
92 template <>\r
93 std::ostream& operator<<(std::ostream& o, const generator<float>& v)\r
94 {\r
95         o << v.line_prefix_ << std::showpoint << v.v_ << "f";\r
96         return o;\r
97 }\r
98 \r
99 template <>\r
100 std::ostream& operator<<(std::ostream& o, const generator<std::string>& v)\r
101 {\r
102         o << v.line_prefix_ << '\"' << v.v_ << '\"';\r
103         return o;\r
104 }\r
105 \r
106 template <typename T>\r
107 std::ostream& operator<<(std::ostream& o, const generator<std::vector<T>>& v)\r
108 {\r
109 //      o << v.line_prefix_;\r
110         auto sz = v.v_.size();\r
111         for(const T& i : v.v_)\r
112         {\r
113                 o << gen(i, v.line_prefix_ + '\t');\r
114                 if (sz > 1) o << ",";\r
115                 --sz;\r
116 //              o << '\n';\r
117         }\r
118 //      o << v.line_prefix_;\r
119         return o;\r
120 }\r
121 \r
122 template <>\r
123 std::ostream& operator<<(std::ostream& o, const generator<openxc::message_set>& v)\r
124 {\r
125         o       << v.line_prefix_\r
126                 << "{std::make_shared<message_set_t>(message_set_t{"\r
127                 << "0,"\r
128                 << gen(v.v_.name()) << ",\n"\r
129                 << "\t\t\t{ // beginning message_definition_ vector\n"\r
130                 << gen(v.v_.messages(), "\t\t\t")\r
131                 << "\n\t\t}, // end message_definition vector\n"\r
132                 << "\t\t\t{ // beginning diagnostic_messages_ vector\n"\r
133                 << gen(v.v_.diagnostic_messages(),"\t\t\t") << "\n"\r
134                 << "\t\t\t} // end diagnostic_messages_ vector\n"\r
135                 << "\t\t})} // end message_set entry\n";\r
136         return o;\r
137 }\r
138 \r
139 template <>\r
140 std::ostream& operator<<(std::ostream& o, const generator<std::map<std::string, std::vector<std::uint32_t>>>& v)\r
141 {\r
142         o << v.line_prefix_ << "{\n";\r
143         std::uint32_t c1 = (uint32_t)v.v_.size();\r
144         for(const auto& state : v.v_)\r
145         {\r
146                 std::uint32_t c2 = (uint32_t)state.second.size();\r
147                 for(const auto& i : state.second)\r
148                 {\r
149                         o << v.line_prefix_ << "\t" << "{" << i << "," << gen(state.first) << "}";\r
150                         if (c1 > 1 || c2 > 1) o << ',';\r
151                         o << '\n';\r
152                         --c2;\r
153                 }\r
154                 --c1;\r
155         }\r
156         o << v.line_prefix_ << "}";\r
157         return o;\r
158 }\r
159 \r
160 template <>\r
161 std::ostream& operator<<(std::ostream& o, const generator<openxc::signal>& v)\r
162 {\r
163         o       << v.line_prefix_ << "{std::make_shared<signal_t> (signal_t{\n"\r
164                 << v.line_prefix_ << "\t" << gen(v.v_.generic_name()) << ",// generic_name\n"\r
165                 << v.line_prefix_ << "\t" << v.v_.bit_position() << ",// bit_position\n"\r
166                 << v.line_prefix_ << "\t" << v.v_.bit_size() << ",// bit_size\n"\r
167                 << v.line_prefix_ << "\t" << gen(v.v_.factor()) << ",// factor\n"\r
168                 << v.line_prefix_ << "\t" << gen(v.v_.offset()) << ",// offset\n"\r
169                 << v.line_prefix_ << "\t" << "0,// min_value\n"\r
170                 << v.line_prefix_ << "\t" << "0,// max_value\n"\r
171                 << v.line_prefix_ << "\tfrequency_clock_t(" << gen(v.v_.max_frequency()) << "),// frequency\n"\r
172                 << v.line_prefix_ << "\t" << gen(v.v_.send_same()) << ",// send_same\n"\r
173                 << v.line_prefix_ << "\t" << gen(v.v_.force_send_changed()) << ",// force_send_changed\n"\r
174                 << gen(v.v_.states(), v.line_prefix_ + '\t') << ",// states\n"\r
175                 << v.line_prefix_ << '\t' << gen(v.v_.writable()) << ",// writable\n"\r
176                 << v.line_prefix_ << '\t' << (v.v_.decoder().size() ? v.v_.decoder() : v.v_.states().size() ? "decoder_t::decode_state" : "nullptr") << ",// decoder\n"\r
177                 << v.line_prefix_ << '\t' << (v.v_.encoder().size() ? v.v_.encoder() : "nullptr") << ",// encoder\n"\r
178                 << v.line_prefix_ << '\t' << "false,// received\n";\r
179                 std::string multi_first = "";\r
180                 if(v.v_.multiplex().first){\r
181                         multi_first = "true";\r
182                 }else{\r
183                         multi_first = "false";\r
184                 }\r
185                 std::string multi = "std::make_pair<bool, int>(" + multi_first + ", " + std::to_string(v.v_.multiplex().second) + ")";\r
186         o       << v.line_prefix_ << '\t' << multi << ",// multiplex\n"\r
187                 << v.line_prefix_ << '\t' << gen(v.v_.is_big_endian()) << ",// is_big_endian\n"\r
188                 << v.line_prefix_ << '\t' << gen(v.v_.is_signed()) << ",// is_signed\n"\r
189                 << v.line_prefix_ << "\t" << gen(v.v_.unit()) << "// unit\n"\r
190                 << v.line_prefix_ << "})}";\r
191         return o;\r
192 }\r
193 \r
194 template <>\r
195 std::ostream& operator<<(std::ostream& o, const generator<openxc::can_message>& v)\r
196 {\r
197         o       << v.line_prefix_\r
198                 << "{std::make_shared<message_definition_t>(message_definition_t{"\r
199                 << gen(v.v_.bus()) << ","\r
200                 << v.v_.id() << ","\r
201                 << "\"" << v.v_.name() << "\","\r
202                 << v.v_.length() << ",";\r
203                 uint32_t flags = 0;\r
204                 if(v.v_.is_fd())\r
205                 {\r
206                         flags = flags|FD_FRAME;\r
207                 }\r
208 \r
209                 if(v.v_.is_j1939())\r
210                 {\r
211                         flags = flags|J1939_PROTOCOL;\r
212                 }\r
213 \r
214                 if(v.v_.is_isotp())\r
215                 {\r
216                         flags = flags|ISOTP_PROTOCOL;\r
217                 }\r
218 \r
219                 if(v.v_.is_extended())\r
220                 {\r
221                         flags = flags|EXTENDED_ID;\r
222                 }\r
223                 else\r
224                 {\r
225                         flags = flags|STANDARD_ID;\r
226                 }\r
227 \r
228 \r
229                 if(v.v_.is_fd())\r
230                 {\r
231                         flags = flags|FD_FRAME;\r
232                 }\r
233 \r
234                 o << gen(flags) << ",";\r
235 \r
236         o       << "frequency_clock_t(" << gen(v.v_.max_frequency()) << "),"\r
237                 << gen(v.v_.force_send_changed()) << ",";\r
238                 std::uint32_t index = 0;\r
239         o       << "\n\t\t\t\t\t{ // beginning signals vector\n";\r
240                         std::uint32_t signal_count = (uint32_t)v.v_.signals().size();\r
241                         for(const openxc::signal& s : v.v_.signals())\r
242                         {\r
243         o                       << gen(s, index,"\t\t\t\t\t\t");\r
244                                 if (signal_count > 1) o << ',';\r
245                                 --signal_count;\r
246         o                       << '\n';\r
247                         }\r
248         o       << "\t\t\t\t\t} // end signals vector\n"\r
249                 << "\t\t\t\t})} // end message_definition entry\n";\r
250         return o;\r
251 }\r
252 \r
253 template <>\r
254 std::ostream& operator<<(std::ostream& o, const generator<openxc::diagnostic_message>& v)\r
255 {\r
256         o       << v.line_prefix_ << "{std::make_shared<diagnostic_message_t>(diagnostic_message_t{\n"\r
257                 << v.line_prefix_ << "\t" << v.v_.pid() << ",\n"\r
258                 << v.line_prefix_ << "\t" << gen(v.v_.name()) << ",\n"\r
259                 << v.line_prefix_ << "\t" << 0 << ",\n"\r
260                 << v.line_prefix_ << "\t" << 0 << ",\n"\r
261                 << v.line_prefix_ << "\t" << "UNIT::INVALID" << ",\n"\r
262                 << v.line_prefix_ << "\t" << gen(v.v_.frequency()) << ",\n"\r
263                 << v.line_prefix_ << "\t" << (v.v_.decoder().size() ? v.v_.decoder() : "nullptr") << ",\n"\r
264                 << v.line_prefix_ << "\t" << (v.v_.callback().size() ? v.v_.callback() : "nullptr") << ",\n"\r
265                 << v.line_prefix_ << "\t" << "true" << ",\n"\r
266                 << v.line_prefix_ << "\t" << "false" << "\n"\r
267                 << v.line_prefix_ << "})}\n";\r
268         return o;\r
269 }\r
270 \r
271 /// @brief Generate the application code.\r
272 /// @param[in] header Content to be inserted as a header.\r
273 /// @param[in] footer Content to be inserted as a footer.\r
274 /// @param[in] message_set application read from the json file.\r
275 /// @param[in] out Stream to write on.\r
276 void generate(const std::string& header, const std::string& footer, const openxc::message_set& message_set, std::ostream& out)\r
277 {\r
278         out << "#include \"application.hpp\"\n"\r
279                 << "#include \"../can/can-decoder.hpp\"\n"\r
280                 << "#include \"../can/can-encoder.hpp\"\n\n";\r
281 \r
282         if (header.size()) out << header << "\n";\r
283 \r
284         out     << "application_t::application_t()\n"\r
285                 << "    : can_bus_manager_{utils::config_parser_t{\"/etc/dev-mapping.conf\"}}\n"\r
286                 << "    , message_set_{\n"\r
287                 << gen(message_set, "\t\t")\r
288                 << "\t} // end message_set vector\n"\r
289                 << "{\n"\r
290                 << "    for(std::shared_ptr<message_set_t> cms: message_set_)\n"\r
291                 << "    {\n"\r
292                 << "            std::vector<std::shared_ptr<message_definition_t>> messages_definition = cms->get_messages_definition();\n"\r
293                 << "            for(std::shared_ptr<message_definition_t> cmd : messages_definition)\n"\r
294                 << "            {\n"\r
295                 << "                    cmd->set_parent(cms);\n"\r
296                 << "                    std::vector<std::shared_ptr<signal_t>> signals = cmd->get_signals();\n"\r
297                 << "                    for(std::shared_ptr<signal_t> sig: signals)\n"\r
298                 << "                    {\n"\r
299                 << "                            sig->set_parent(cmd);\n"\r
300                 << "                    }\n"\r
301                 << "            }\n\n"\r
302                 << "            std::vector<std::shared_ptr<diagnostic_message_t>> diagnostic_messages = cms->get_diagnostic_messages();\n"\r
303                 << "            for(std::shared_ptr<diagnostic_message_t> dm : diagnostic_messages)\n"\r
304                 << "            {\n"\r
305                 << "                    dm->set_parent(cms);\n"\r
306                 << "            }\n"\r
307                 << "    }\n"\r
308                 << "            }\n\n"\r
309                 << "const std::string application_t::get_diagnostic_bus() const\n"\r
310                 << "{\n";\r
311 \r
312                 std::string active_bus = "";\r
313                 for (const auto& d : message_set.diagnostic_messages())\r
314                 {\r
315                         if (d.bus().size() == 0) std::cerr << "ERROR: The bus name should be set for each diagnostic message." << std::endl;\r
316                         if (active_bus.size() == 0) active_bus = d.bus();\r
317                         if (active_bus != d.bus()) std::cerr << "ERROR: The bus name should be the same for each diagnostic message." << std::endl;\r
318                 }\r
319 \r
320         out     << "\treturn " << gen(active_bus) << ";\n"\r
321                 << "}\n\n";\r
322         out     << footer << std::endl;\r
323 }\r
324 \r
325 /// @brief Read whole file content to a string.\r
326 /// @param[in] file Path to the file.\r
327 /// @return A std::string which contains the file content. If @c file is an empty string, the return value is also empty.\r
328 /// @exception std::runtime_error Throw this exception if the specified file is not found or cannot be opened.\r
329 std::string read_file(const std::string& file)\r
330 {\r
331         if(file.size() == 0) return std::string();\r
332 \r
333         std::string content;\r
334         std::ifstream stream(file);\r
335         if (stream)\r
336         {\r
337                 stream.seekg(0, std::ios::end);\r
338                 content.reserve(stream.tellg());\r
339                 stream.seekg(0, std::ios::beg);\r
340                 content.assign((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());\r
341                 return content;\r
342         }\r
343         std::stringstream ss;\r
344         ss << "The specified file (" << file << ") is not found!";\r
345         throw std::runtime_error(ss.str());\r
346 }\r
347 \r
348 /// @brief Read whole file content as a json document.\r
349 /// @param[in] file Path to the file.\r
350 /// @return A @c nlohmann::json object.\r
351 /// @exception std::runtime_error Throw this exception if the specified file is not found or cannot be opened.\r
352 nlohmann::json read_json(const std::string& file)\r
353 {\r
354         std::ifstream stream(file);\r
355         if (stream)\r
356         {\r
357                 nlohmann::json result;\r
358                 stream >> result;\r
359                 return result;\r
360         }\r
361         std::stringstream ss;\r
362         ss << "The specified file (" << file << ") is not found!";\r
363         throw std::runtime_error(ss.str());\r
364 }\r
365 \r
366 // function that show the help information\r
367 void showhelpinfo(char *s)\r
368 {\r
369 std::cout<<"Usage:   "<<s<<" <-m inpout.json> [-o application-generated.cpp]"<< std::endl;\r
370 std::cout<<"option:  "<<"-m  input.json : JSON file describing CAN messages and signals"<< std::endl;\r
371 std::cout<<"         "<<"-h header.cpp : header source file insert at the beginning of generated file"<< std::endl;\r
372 std::cout<<"         "<<"-f footer.cpp : footer source file append to generated file."<< std::endl;\r
373 std::cout<<"         "<<"-o application-generated.cpp : output source file. Name has to be application-generated.cpp"<< std::endl;\r
374 }\r
375 \r
376 /// @brief Entry point.\r
377 /// @param[in] argc Argument's count.\r
378 /// @param[in] argv Argument's array.\r
379 /// @return Exit code, zero if success.\r
380 int main(int argc, char *argv[])\r
381 {\r
382         try\r
383         {\r
384                 std::string appName = argv[0];\r
385                 std::string message_set_file;\r
386                 std::string output_file;\r
387                 std::string header_file;\r
388                 std::string footer_file;\r
389 \r
390                 char tmp;\r
391                 /*if the program is ran witout options ,it will show the usgage and exit*/\r
392                 if(argc == 1)\r
393                 {\r
394                         showhelpinfo(argv[0]);\r
395                         exit(1);\r
396                 }\r
397                 /*use function getopt to get the arguments with option."hu:p:s:v" indicate\r
398                 that option h,v are the options without arguments while u,p,s are the\r
399                 options with arguments*/\r
400                 while((tmp=(char)getopt(argc,argv,"m:h:f:o:"))!=-1)\r
401                 {\r
402                         switch(tmp)\r
403                         {\r
404                         case 'h':\r
405                                 header_file = optarg;\r
406                                 break;\r
407                         case 'f':\r
408                                 footer_file = optarg;\r
409                                 break;\r
410                         case 'm':\r
411                                 message_set_file = optarg;\r
412                                 break;\r
413                         case 'o':\r
414                                 output_file = optarg;\r
415                                 break;\r
416                         default:\r
417                                 showhelpinfo(argv[0]);\r
418                         break;\r
419                         }\r
420                 }\r
421 \r
422                 std::stringstream header;\r
423                 header << read_file(header_file);\r
424 \r
425                 std::string footer = read_file(footer_file);\r
426                 openxc::message_set message_set;\r
427                 message_set.from_json(read_json(message_set_file));\r
428 \r
429                 std::string message_set_path = dirname(strdup(message_set_file.c_str()));\r
430                 for(const auto& s : message_set.extra_sources())\r
431                 {\r
432                         std::string extra_source = s;\r
433                         extra_source = message_set_path + "/" + extra_source;\r
434                         header << "\n// >>>>> " << s << " >>>>>\n" << read_file(extra_source) << "\n// <<<<< " << s << " <<<<<\n";\r
435                 }\r
436 \r
437                 std::ofstream out;\r
438                 if (output_file.size())\r
439                 {\r
440                         out.open(output_file);\r
441                         if(!out)\r
442                         {\r
443                                 std::stringstream ss;\r
444                                 ss << "Can't open the ouput file (" << output_file << ") for writing!";\r
445                                 throw std::runtime_error(ss.str());\r
446                         }\r
447                 }\r
448                 generate(header.str(), footer, message_set, output_file.size() ? out : std::cout);\r
449         }\r
450         catch (std::exception& e)\r
451         {\r
452                 std::cerr << "ERROR: Unhandled exception - " << e.what() << std::endl;\r
453                 return EXIT_UNKNOWN_ERROR;\r
454         }\r
455         return EXIT_SUCCESS;\r
456 }\r