├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── _old ├── Framework │ ├── config.h │ ├── dbg_console │ │ ├── dbg_console.c │ │ └── dbg_console.h │ ├── ecu │ │ ├── ecu.c │ │ └── ecu.h │ ├── framework.h │ ├── gateway │ │ ├── gateway.c │ │ └── gateway.h │ ├── interfaces │ │ ├── can │ │ │ ├── can.c │ │ │ └── can.h │ │ ├── ethernet │ │ │ ├── ethernet.c │ │ │ └── ethernet.h │ │ ├── lin │ │ │ ├── lin.c │ │ │ └── lin.h │ │ └── sdhc │ │ │ ├── sdhc.c │ │ │ └── sdhc.h │ ├── pdu_router │ │ ├── pdu_router.c │ │ └── pdu_router.h │ └── security │ │ ├── hsm_she.c │ │ └── hsm_she.h ├── Sources │ ├── main.c │ └── tables │ │ ├── can_filter.c │ │ ├── ecu_table.c │ │ └── pdu_table.c └── gateway.h ├── examples └── linux │ ├── main.c │ └── routing_table.c ├── modules ├── xcan_dev_socketcan.c └── xcan_dev_socketcan.h └── stack ├── include ├── xcan_config.h ├── xcan_device.h ├── xcan_frame.h ├── xcan_queue.h ├── xcan_router.h └── xcan_stack.h ├── xcan_device.c ├── xcan_frame.c ├── xcan_router.c └── xcan_stack.c /.gitignore: -------------------------------------------------------------------------------- 1 | build/ -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | 3 | project(XCAN 4 | VERSION 1.0 5 | DESCRIPTION "XCAN Routing Stack" 6 | LANGUAGES C 7 | ) 8 | 9 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -DDEBUG") 10 | 11 | add_executable(XCAN_EXE 12 | modules/xcan_dev_socketcan.c 13 | stack/xcan_device.c 14 | stack/xcan_frame.c 15 | stack/xcan_stack.c 16 | stack/xcan_router.c 17 | examples/linux/main.c 18 | examples/linux/routing_table.c 19 | ) 20 | 21 | target_include_directories(XCAN_EXE PUBLIC 22 | "stack" 23 | "stack/include" 24 | "modules" 25 | "examples/linux" 26 | ) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # XCAN Routing Stack 2 | 3 | ## Background 4 | 5 | CAN is a robust message-based multi-master bus protocol which is particularly dominant in the automotive industry. In large control systems with different domains, there are often several independent CAN buses with each bus connecting together the nodes of a particular domain in the system. 6 | It is the role of a central **gateway/router** device to pass certain messages between each these buses to enable the sharing of information across domains. 7 | 8 | This is where the XCAN Routing Stack fits in. 9 | 10 | The intention of this project is to provide an open-source CAN routing stack. 11 | 12 | ## Features 13 | 14 | This initial version will support the basic functionality: 15 | - Frame-based routing. 16 | - Static routing table creation tool. 17 | - Per interface frame filtering. 18 | - SocketCAN interface for testing. 19 | 20 | ## Building 21 | Project uses the `cmake` build system. 22 | 23 | ``` shell 24 | $ cmake . 25 | $ make 26 | ``` 27 | 28 | ## Example 29 | An example is provided which can be run on Linux using virtual SocketCAN interfaces. 30 | 31 | ### Setup 32 | Enable the virtual CAN kernel module and create 2 virtual CAN interfaces: 33 | ``` shell 34 | $ sudo modprobe vcan 35 | $ sudo ip link add dev vcan0 type vcan 36 | $ sudo ip link add dev vcan1 type vcan 37 | ``` 38 | 39 | Bring up the two virtual CAN interfaces: 40 | ``` shell 41 | $ sudo ip link set up vcan0 42 | $ sudo ip link set up vcan1 43 | ``` 44 | sudo ifconfig vcan0 up 45 | 46 | ### Running 47 | Send data to the CAN bus, use the `cansend` utility: 48 | ``` 49 | $ cansend can0 123#1122334455667788 50 | ``` 51 | -------------------------------------------------------------------------------- /_old/Framework/config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * config.h 3 | * 4 | * Created on: 27 Mar 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef CONFIG_H_ 9 | #define CONFIG_H_ 10 | 11 | #include "ecu.h" 12 | #include "pdu_router.h" 13 | #include "task.h" 14 | 15 | /* Number of ECUs connected to the GW */ 16 | #define NUM_OF_ECUS 4U 17 | /* Number of PDU descriptor entries in the PDU routing table */ 18 | #define NUM_OF_PDU_TYPES 5U 19 | /* Number of CAN MSG ID filter entries in the filter table */ 20 | #define NUM_OF_CANID_FILTERS 10U 21 | /* Number of PDU elements held in PDU router queue */ 22 | #define PDU_QUEUE_SIZE 5U 23 | /* Number of PDU elements held in GW queue */ 24 | #define GW_QUEUE_SIZE 10U 25 | /* Number of PDU elements held in FW update queue */ 26 | #define FW_QUEUE_SIZE 10U 27 | /* Enable debug functionality via Serial terminal. PDUs printed, ECUs printed. */ 28 | #define DEBUG_ENABLE 29 | 30 | /* HSM/SHE Configuration */ 31 | /* Boot MAC key used in Secure Boot */ 32 | #define BOOT_MAC_KEY_VALUE {0x6B, 0x65, 0x79, 0x30, 0x6B, 0x65, 0x79, 0x31, 0x6B, 0x65, 0x79, 0x32, 0x6B, 0x65, 0x79, 0x33} 33 | /* Key 1 - Used for encrypting FW frames before sending to ECU */ 34 | #define KEY_1_VALUE {0x6B, 0x65, 0x79, 0x30, 0x6B, 0x65, 0x79, 0x31, 0x6B, 0x65, 0x79, 0x32, 0x6B, 0x65, 0x79, 0x33} 35 | 36 | /* Priority of PDU Router task */ 37 | #define TASK_PRIORITY_PDU (tskIDLE_PRIORITY + 2) 38 | /* Priority of Gateway task */ 39 | #define TASK_PRIORITY_GW (tskIDLE_PRIORITY + 2) 40 | /* Priority of LWIP task */ 41 | #define TASK_PRIORITY_LWIP (tskIDLE_PRIORITY + 1) 42 | /* Priority of Heartbeat task */ 43 | #define TASK_PRIORITY_HEART (tskIDLE_PRIORITY + 2) 44 | /* Priority of Heartbeat task */ 45 | #define TASK_PRIORITY_CONSOLE (tskIDLE_PRIORITY + 1) 46 | 47 | 48 | /* Master list of information for each ECU. It is held in RAM and periodically backed up to SD card */ 49 | ECU ecu_list[NUM_OF_ECUS]; 50 | 51 | /* PDU Routing table */ 52 | PDU_Desc PDU_Descriptors[NUM_OF_PDU_TYPES]; 53 | 54 | /* SW filter for CAN IDs */ 55 | uint32_t CAN_ID_FilterTable[NUM_OF_CANID_FILTERS]; 56 | 57 | 58 | #endif /* CONFIG_H_ */ 59 | -------------------------------------------------------------------------------- /_old/Framework/dbg_console/dbg_console.c: -------------------------------------------------------------------------------- 1 | /* 2 | * debug.c 3 | * 4 | * Created on: 27 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #include 9 | #include 10 | #include "config.h" 11 | #include "ecu.h" 12 | #include "pdu_router.h" 13 | 14 | const char *cmds[] = {"ecus", "test"}; 15 | 16 | const uart_instance_t *uart_instance; /* Instance of UART */ 17 | 18 | void CONSOLE_initialise(const uart_instance_t *instance, const uart_user_config_t *config) 19 | { 20 | uart_instance = instance; 21 | 22 | /* Initialize UART PAL over LINFlexD */ 23 | UART_Init(instance, config); 24 | 25 | /* Create a FreeRTOS task which is responsible for running the debug console interface */ 26 | xTaskCreate(CONSOLE_Task, "Serial Console", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY_CONSOLE, NULL); 27 | } 28 | 29 | void CONSOLE_Task(void *pvParameters) 30 | { 31 | /* Buffer to store the received message */ 32 | //char rxBuff[5]; 33 | //status_t stat; 34 | 35 | CONSOLE_printString("\e[32m\e[1m"); 36 | 37 | CONSOLE_printString("\n\r============== GW REFERENCE PLATFORM ==============="); 38 | CONSOLE_printString("\n\r============ Created by: Sean Farrelly ============="); 39 | CONSOLE_printString("\n\r====================== V0.1 ========================\n\r"); 40 | CONSOLE_printString("\e[0m"); 41 | 42 | print_ECUs(); 43 | 44 | while(1) 45 | { 46 | // UART_SendDataBlocking(uart, welcome, strlen(welcome), 1000U); 47 | // 48 | // /* Get the message sent by user from the console, using blocking method, wait forever */ 49 | // stat = UART_ReceiveDataBlocking(uart, (uint8_t*) rxBuff, 1, portMAX_DELAY); 50 | // 51 | // if(stat == STATUS_SUCCESS) 52 | // { 53 | // if(rxBuff[0] == '1') 54 | // { 55 | // CMD_ecus(); 56 | // } 57 | // else if(rxBuff[0] == '2') 58 | // { 59 | // CMD_test(); 60 | // } 61 | // else if(rxBuff[0] == '3') 62 | // { 63 | // CMD_test(); 64 | // } 65 | // } 66 | 67 | vTaskDelay(portMAX_DELAY); 68 | } 69 | } 70 | 71 | 72 | //void Debug_Task(void *pvParameters) 73 | //{ 74 | // /* Buffer to store the received message */ 75 | // char rxBuff[50]; 76 | // status_t stat; 77 | // uint32_t i = 0; 78 | // 79 | // while(1) 80 | // { 81 | // /* Get the message sent by user from the console, using blocking method, wait forever */ 82 | // stat = UART_ReceiveDataBlocking(uart, (uint8_t*) &rxBuff[i], 1, portMAX_DELAY); 83 | // 84 | // if(stat == STATUS_SUCCESS) 85 | // { 86 | // if(rxBuff[i] == '\r') /* Execute command */ 87 | // { 88 | // rxBuff[i] = '\0'; /* Insert null character for strcmp function */ 89 | // 90 | // if(strncmp(cmds[0], &rxBuff[0], i) == 0) 91 | // { 92 | // CMD_ecus(); 93 | // } 94 | // else if(!strncmp(cmds[1], &rxBuff[0], i) == 0) 95 | // { 96 | // CMD_test(); 97 | // } 98 | // } 99 | // i++; 100 | // 101 | // if(i == sizeof(rxBuff)) 102 | // { 103 | // UART_SendDataBlocking(uart, error_length, strlen(error_length), 1000U); 104 | // i = 0; 105 | // } 106 | // } 107 | // } 108 | //} 109 | 110 | void CONSOLE_printString(char *string) 111 | { 112 | status_t stat; 113 | 114 | stat = UART_SendDataBlocking(uart_instance, (uint8_t*) string, strlen(string), 10000U); 115 | 116 | if(stat != STATUS_SUCCESS) 117 | { 118 | /* Useful debugger trap for checking if UART is being overloaded */ 119 | stat = STATUS_ERROR; 120 | } 121 | } 122 | 123 | void CONSOLE_printData(char *data, uint32_t len) 124 | { 125 | status_t stat; 126 | 127 | stat = UART_SendDataBlocking(uart_instance, (uint8_t*) data, len, 10000U); 128 | 129 | if(stat != STATUS_SUCCESS) 130 | { 131 | /* Useful debugger trap for checking if UART is being overloaded */ 132 | stat = STATUS_ERROR; 133 | } 134 | } 135 | 136 | /* Appends and colour tags to message to ensure it is easily visable as an error message */ 137 | void CONSOLE_printError(char *string) 138 | { 139 | char buff[strlen(string) + 20]; 140 | 141 | sprintf(buff, "\e[31m\e[1m%s\e[0m", string); 142 | 143 | CONSOLE_printString(buff); 144 | } 145 | 146 | void print_ECUs() 147 | { 148 | uint16_t i; 149 | char *status; 150 | char *protocol; 151 | char *endian; 152 | char buff[100]; 153 | 154 | ECU *ecu; 155 | 156 | CONSOLE_printString("\n\r+-------+---------------+---------------+---------------+---------------+---------------+---------------+"); 157 | CONSOLE_printString("\n\r| ID\t| Status\t| FW Ver\t| Protocol\t| Interface\t| Security\t| Endian\t|"); 158 | CONSOLE_printString("\n\r+-------+---------------+---------------+---------------+---------------+---------------+---------------+"); 159 | 160 | for(i = 0 ; i < NUM_OF_ECUS ; i++) 161 | { 162 | ecu = &ecu_list[i]; 163 | 164 | /* Convert enums to their string equivalent */ 165 | switch(ecu->status) 166 | { 167 | case ECU_STAT_NORMAL: status = "NORMAL "; break; 168 | case ECU_STAT_SLEEPING: status = "SLEEP "; break; 169 | case ECU_STAT_UPDATING: status = "UPDATING"; break; 170 | case ECU_STAT_CORRUPTED: status = "CORRUPTED"; break; 171 | case ECU_STAT_UNRESPONSIVE: status = "NO RESP "; break; 172 | case ECU_STAT_FAULT: status = "FAULTY "; break; 173 | default: status = "N/A "; break; 174 | } 175 | switch(ecu->protocol) 176 | { 177 | case PROTOCOL_CAN: protocol = "CAN "; break; 178 | case PROTOCOL_CANFD: protocol = "CAN-FD"; break; 179 | case PROTOCOL_LIN: protocol = "LIN "; break; 180 | case PROTOCOL_ETH: protocol = "ETH "; break; 181 | default: protocol = "N/A "; break; 182 | } 183 | switch(ecu->endianness) 184 | { 185 | case 0: endian = "LITTLE"; break; 186 | case 1: endian = "BIG "; break; 187 | default: endian = "N/A "; break; 188 | } 189 | /*********************************************/ 190 | 191 | sprintf(buff, "\n\r| %d\t| %s \t| %d\t\t| %s \t| %d\t\t| %d\t\t| %s\t|", 192 | i, status, ecu->fw_version, protocol, ecu->instance, ecu->security, endian); 193 | 194 | CONSOLE_printString(buff); 195 | } 196 | 197 | CONSOLE_printString("\n\r+-------+---------------+---------------+---------------+---------------+---------------+---------------+\n\r"); 198 | } 199 | -------------------------------------------------------------------------------- /_old/Framework/dbg_console/dbg_console.h: -------------------------------------------------------------------------------- 1 | /* 2 | * console.h 3 | * 4 | * Created on: 27 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef DBG_CONSOLE_H_ 9 | #define DBG_CONSOLE_H_ 10 | 11 | #include "Cpu.h" 12 | 13 | 14 | 15 | void CONSOLE_Task(void *pvParameters); 16 | /* Initialise debug console */ 17 | void CONSOLE_initialise(const uart_instance_t *instance, const uart_user_config_t *config); 18 | /* Print string to debug console */ 19 | void CONSOLE_printString(char *string); 20 | /* Print data to debug console */ 21 | void CONSOLE_printData(char *data, uint32_t len); 22 | /* Print string as error in debug console (red foreground) */ 23 | void CONSOLE_printError(char *string); 24 | /* Print CAN frame to debug console */ 25 | //void CONSOLE_printFrame(uint8_t instance, can_message_t *msg, bool tx) 26 | /* Print PDU frame to debug console */ 27 | //void CONSOLE_printPDU(PDU *pdu, bool tx) 28 | /* Print generic data packet to debug console */ 29 | //void CONSOLE_printDebug(char *interface, uint32_t id, uint8_t len, uint8_t *data, bool tx) 30 | /* Converts byte array to hex string equivalent and prints to debug console */ 31 | //void print_hex(uint8_t *data, uint32_t len); 32 | 33 | #endif /* DBG_COSNOLE_H_ */ 34 | -------------------------------------------------------------------------------- /_old/Framework/ecu/ecu.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ecu.c 3 | * 4 | * Created on: 24 Nov 2017 5 | * Author: B49855 6 | */ 7 | 8 | #include "ecu.h" 9 | #include "can.h" 10 | #include "lin.h" 11 | #include "ethernet.h" 12 | #include "config.h" 13 | 14 | /* 15 | * @brief: Interface for updating an ECU's firmware 16 | * @param ecu : Pointer to ECU struct 17 | * @param fw : Pointer to FW File to use 18 | * @param secureUpdate : Secure update (yes/no) 19 | * @return : STATUS_SUCCESS, STATUS_ERROR 20 | */ 21 | status_t ECU_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate) 22 | { 23 | switch(ecu_list[ecu_id].protocol) { 24 | case PROTOCOL_CAN: return CAN_updateFirmware(ecu_id, fw, secureUpdate); break; 25 | case PROTOCOL_LIN: return LIN_updateFirmware(ecu_id, fw, secureUpdate); break; 26 | case PROTOCOL_ETH: return ETH_updateFirmware(ecu_id, fw, secureUpdate); break; 27 | default: return STATUS_ERROR; break; 28 | } 29 | } 30 | 31 | /* 32 | * @brief: Interface for sending a command to ECU through correct peripheral 33 | * @param ecu : Pointer to ECU struct 34 | * @param req : Type of request 35 | * @return : none 36 | */ 37 | void ECU_sendCommand(uint8_t ecu_id, ecu_cmd cmd) 38 | { 39 | uint32_t msgId = CAN_ID_MASK_TYPE_CMD | ecu_id; /* ECU ID + Request Type */ 40 | uint8_t data = cmd; 41 | 42 | switch(ecu_list[ecu_id].protocol) { 43 | case PROTOCOL_CAN: CAN_sendFrame(ecu_list[ecu_id].instance, msgId , &data, sizeof(data)); break; 44 | case PROTOCOL_LIN: LIN_sendFrame(ecu_list[ecu_id].instance, msgId , &data, sizeof(data)); break; 45 | //case PROTOCOL_ETH: ETH_sendFrame(); break; 46 | default: break; 47 | } 48 | } 49 | 50 | /* 51 | * @brief: Interface for sending a PDU to ECU through correct peripheral 52 | * @param ecu : Pointer to ECU struct 53 | * @param req : Type of request 54 | * @return : none 55 | */ 56 | void ECU_sendPDU(uint8_t ecu_id, PDU *pdu) 57 | { 58 | switch(ecu_list[ecu_id].protocol) { 59 | case PROTOCOL_CAN: CAN_sendFrame(ecu_list[ecu_id].instance, pdu->id, pdu->data, pdu->length); break; 60 | case PROTOCOL_LIN: LIN_sendFrame(ecu_list[ecu_id].instance, pdu->id, pdu->data, pdu->length); break; 61 | //case PROTOCOL_ETH: ETH_SendPDU(ecu_id, pdu); break; 62 | default: break; 63 | } 64 | } 65 | 66 | /* 67 | * @brief: Returns a pointer to ECU struct for given ECU ID 68 | * @param ecu_id : ID of ECU 69 | * @return : Pointer to ECU within ecu_list 70 | */ 71 | ECU* ECU_getECU(uint8_t ecu_id) 72 | { 73 | return &ecu_list[ecu_id]; 74 | } 75 | -------------------------------------------------------------------------------- /_old/Framework/ecu/ecu.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ecu.h 3 | * 4 | * Created on: 22 Nov 2017 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef ECU_H_ 9 | #define ECU_H_ 10 | 11 | #include 12 | #include 13 | 14 | #include "pdu_router.h" 15 | #include "status.h" 16 | #include "ff.h" 17 | 18 | /* Each ECU within the network is defined by this structure 19 | * NOTE: The ID of the ECU is implicitly defined by its index within the ecu_list array */ 20 | typedef struct 21 | { 22 | uint32_t status: 4; /* Normal, Sleeping, Updating, Corrupted, Unresponsive, Faulty */ 23 | uint32_t endianness: 1; /* 1 = big endian, 0 = little endian */ 24 | uint32_t security: 1; /* Supports HW security? */ 25 | uint32_t protocol: 4; /* Communication protocol (CAN, LIN, ETH, ..) */ 26 | uint32_t instance: 4; /* Peripheral instance (CAN0, CAN1, ..) */ 27 | uint32_t fw_version: 8; /* Current FW version (max 256) */ 28 | uint32_t reserved: 10; /* Reserved */ 29 | } ECU; 30 | 31 | /* ECU Communication Protocol types 32 | * These are used by communication interface to determine which protocol to use */ 33 | typedef enum { 34 | PROTOCOL_CANFD = 0x01, 35 | PROTOCOL_CAN = 0x02, 36 | PROTOCOL_LIN = 0x03, 37 | PROTOCOL_ETH = 0x04, 38 | // ... 39 | } protocols; 40 | 41 | /* Set of requests for information that can be made to ECUs */ 42 | typedef enum { 43 | ECU_CMD_REQ_ALL = 0x01, /* All ECU information */ 44 | ECU_CMD_REQ_ID, /* ECU ID */ 45 | ECU_CMD_REQ_FWVER, /* FW version */ 46 | ECU_CMD_REQ_STATUS, /* Status */ 47 | ECU_CMD_RESET, /* Reset */ 48 | ECU_CMD_SLEEP /* Sleep*/ 49 | // ... 50 | } ecu_cmd; 51 | 52 | typedef enum { 53 | ECU_STAT_NORMAL = 0x01, /* Normal/Operational */ 54 | ECU_STAT_SLEEPING, /* Sleeping state */ 55 | ECU_STAT_UPDATING, /* Updating FW */ 56 | ECU_STAT_CORRUPTED, /* FW Update corrupted */ 57 | ECU_STAT_UNRESPONSIVE, /* Not responding */ 58 | ECU_STAT_FAULT /* Faulty */ 59 | // ... 60 | } ecu_status; 61 | 62 | /* Set of flags used for firmware update protocol */ 63 | typedef enum { 64 | RESET_CMD = 0xFF, 65 | RESET_ACK = 0xC4, 66 | BEGIN_SEC = 0xFC, 67 | BEGIN_NONSEC = 0xFA, 68 | FRAME_ACK = 0xC3, 69 | END_CMD = 0xFD, 70 | END_ACK = 0xC1, 71 | } fw_protocol_flag; 72 | 73 | //#define FW_HEADER_SIZE 28u /* 28 bytes */ 74 | //#define FW_HEADER 0x5757 75 | 76 | /* Each FW file stored on SD begins with a FW header containing important info about FW */ 77 | typedef struct { 78 | uint32_t opcode; /* Header/Packet opcode? */ 79 | uint32_t fw_ver; /* FW version no */ 80 | uint32_t length; /* Length of FW (bytes) */ 81 | uint32_t ecu_id; /* ECU ID the FW belongs to */ 82 | uint8_t cmac[16]; /* CMAC of FW */ 83 | } ecu_fw_header; 84 | 85 | /* Interface for updating the firmware of ECU connected to the gateway */ 86 | status_t ECU_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate); 87 | /* Interface for sending a reques to an ECU connected to the gateway */ 88 | void ECU_sendCommand(uint8_t ecu_id, ecu_cmd cmd); 89 | /* Returns a pointer to the ECU structure for the equivalent ECU ID */ 90 | ECU* ECU_getECU(uint8_t ecu_id); 91 | 92 | void ECU_sendPDU(uint8_t ecu_id, PDU *pdu); 93 | 94 | 95 | #endif /* ECU_H_ */ 96 | -------------------------------------------------------------------------------- /_old/Framework/framework.h: -------------------------------------------------------------------------------- 1 | /* 2 | * framework.h 3 | * 4 | * Created on: 29 Mar 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef FRAMEWORK_H_ 9 | #define FRAMEWORK_H_ 10 | 11 | /*Include all modules from the gateway framework, which are used for the whole project */ 12 | #include "config.h" 13 | #include "ecu.h" 14 | #include "hsm_she.h" 15 | #include "sdhc.h" 16 | #include "can.h" 17 | #include "lin.h" 18 | #include "pdu_router.h" 19 | #include "gateway.h" 20 | #include "dbg_console.h" 21 | 22 | #endif /* FRAMEWORK_H_ */ 23 | -------------------------------------------------------------------------------- /_old/Framework/gateway/gateway.c: -------------------------------------------------------------------------------- 1 | /* 2 | * gateway.c 3 | * 4 | * Created on: 26 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #include 9 | #include "gateway.h" 10 | #include "config.h" 11 | #include "task.h" 12 | #include "can.h" /* Including CAN for #defines of MASK. Perhaps need to decouple? */ 13 | 14 | 15 | void GW_initialise() 16 | { 17 | /* Create a queue to hold 10 PDUs which are for GW */ 18 | gateway_queue = xQueueCreate(GW_QUEUE_SIZE, sizeof(PDU)); 19 | 20 | /* Add Gateway Task to the FreeRTOS scheduler */ 21 | xTaskCreate(Gateway_Task, "Gateway", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY_GW, NULL); 22 | } 23 | 24 | void Gateway_Task(void *pvParameters) 25 | { 26 | uint16_t i; 27 | PDU pdu; 28 | 29 | /*********************** GATEWAY THREAD ********************/ 30 | /***********************************************************/ 31 | while(1) 32 | { 33 | /* GW Task: Receive any PDUs which are destined for GW, or require signal routing */ 34 | if(xQueueReceive(gateway_queue, &pdu, portMAX_DELAY)) 35 | { 36 | if(pdu.id & PDU_ID_MASK_TYPE_CMD) 37 | { 38 | /* Extract information from PDU and save to ECU struct */ 39 | GW_parsePDU(&pdu); 40 | /* Discard PDU and free memory */ 41 | PDU_discardPDU(&pdu); 42 | } 43 | } 44 | 45 | /* GW Task: Act upon any critical ECU statuses */ 46 | for(i = 0 ; i < NUM_OF_ECUS ; i++) 47 | { 48 | switch(ecu_list[i].status) 49 | { 50 | case ECU_STAT_NORMAL: { break; } 51 | case ECU_STAT_SLEEPING: { break; } 52 | case ECU_STAT_UPDATING: { break; } 53 | case ECU_STAT_CORRUPTED: { break; } 54 | case ECU_STAT_UNRESPONSIVE: { break; } 55 | case ECU_STAT_FAULT: { break; } 56 | } 57 | } 58 | } 59 | } 60 | 61 | 62 | /* 63 | * @brief: Task responsible for 'Heartbeat' functionality of GW. 64 | * e.g. periodically ping all ECUs for status update. 65 | * @param *pvParameters : void parameter 66 | * @return : none 67 | */ 68 | void Heartbeat_Task(void *pvParameters) 69 | { 70 | uint16_t i; 71 | 72 | TickType_t xLastWakeTime; 73 | const TickType_t xFrequency = portTICK_PERIOD_MS * 3000; /* Frequency = 1sec */ 74 | 75 | // Initialise the xLastWakeTime variable with the current time. 76 | xLastWakeTime = xTaskGetTickCount(); 77 | 78 | /******************** GW HEARTBEAT THREAD ******************/ 79 | /***********************************************************/ 80 | while(1) 81 | { 82 | // 1. Wait for the next cycle. 83 | vTaskDelayUntil( &xLastWakeTime, xFrequency ); 84 | 85 | // 2. Request status update from all ECUs 86 | for(i = 0 ; i < NUM_OF_ECUS ; i++) 87 | { 88 | if(ecu_list[i].status != ECU_STAT_UPDATING) 89 | { 90 | ECU_sendCommand(i, ECU_CMD_REQ_STATUS); 91 | vTaskDelay(100); 92 | } 93 | } 94 | } 95 | } 96 | 97 | /* 98 | * @brief: Parse ECU response to extract ID, FW VER, Health, etc.. 99 | * @param response : Pointer to response to be parsed 100 | * @return : none 101 | */ 102 | void GW_parsePDU(PDU *pdu) 103 | { 104 | uint8_t ecu_id = pdu->id & PDU_ID_MASK_ECU_ID; /* Extract ECU ID from MSG ID field */ 105 | uint8_t cmd = pdu->data[0]; /* Extract CMD type from payload */ 106 | uint8_t *data = pdu->data; 107 | 108 | ECU *ecu = ECU_getECU(ecu_id); 109 | 110 | switch(cmd) 111 | { 112 | case ECU_CMD_REQ_ALL: memcpy(ecu, data, sizeof(ECU)); break; 113 | case ECU_CMD_REQ_ID: /* Process data */ break; 114 | case ECU_CMD_REQ_FWVER: ecu->fw_version = data[1]; break; 115 | case ECU_CMD_REQ_STATUS: ecu->status = data[1]; break; 116 | case ECU_CMD_RESET: /* Process data */ break; 117 | case ECU_CMD_SLEEP: /* Process data */ break; 118 | // ... 119 | 120 | default: /* Request type not found */ break; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /_old/Framework/gateway/gateway.h: -------------------------------------------------------------------------------- 1 | /* 2 | * gateway.h 3 | * 4 | * Created on: 26 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef GATEWAY_H_ 9 | #define GATEWAY_H_ 10 | 11 | #include "pdu_router.h" 12 | #include "FreeRTOS.h" 13 | #include "queue.h" 14 | 15 | 16 | void Gateway_Task(void *pvParameters); 17 | void Heartbeat_Task(void *pvParameters); 18 | 19 | void GW_initialise(void); 20 | void GW_parsePDU(PDU *pdu); 21 | 22 | QueueHandle_t gateway_queue; 23 | 24 | #endif /* GATEWAY_H_ */ 25 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/can/can.c: -------------------------------------------------------------------------------- 1 | /* 2 | * can.c 3 | * 4 | * Created on: 25 Jan 2018 5 | * Author: B49855 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | #include "can.h" 12 | #include "config.h" 13 | #include "ff.h" 14 | #include "queue.h" 15 | #include "dbg_console.h" 16 | 17 | #define TIMEOUT 1000 /* 1 second */ 18 | 19 | can_instance_t can_ip_type; 20 | 21 | /* 22 | * @brief: Initialise CAN peripheral 23 | * @param instance : Instance of CAN to initialise 24 | * @param *config : Pointer to user configuration struct 25 | * @return : none 26 | */ 27 | void CAN_initialise(const can_instance_t *instance, const can_user_config_t *config) 28 | { 29 | /* Initialize CAN PAL */ 30 | CAN_Init(instance, config); 31 | 32 | /* Set the global CAN IP type */ 33 | can_ip_type.instType = instance->instType; 34 | 35 | /* Install Callback/ISR for when CAN interface Tx/Rx */ 36 | CAN_InstallEventCallback(instance, (can_callback_t) &CAN_eventHandler, NULL); 37 | 38 | /* Set buffer configuration 39 | * - Flexible data rate enabled 40 | * - Bit rate switch enabled to use a different bitrate for the data segment 41 | * - Use zeros for FD padding 42 | * - Standard message ID 43 | * - Not remote frame 44 | */ 45 | can_buff_config_t buffConfig = 46 | { 47 | .enableFD = true, 48 | .enableBRS = true, 49 | .fdPadding = 0U, 50 | .idType = CAN_MSG_ID_EXT, 51 | .isRemote = false 52 | }; 53 | 54 | /* Configure Rx MBs */ 55 | CAN_ConfigRxBuff(instance, RX_MB_DATA, &buffConfig, CAN_ID_MASK_TYPE_DATA); 56 | CAN_ConfigRxBuff(instance, RX_MB_CMD, &buffConfig, CAN_ID_MASK_TYPE_CMD); 57 | CAN_ConfigRxBuff(instance, RX_MB_FW, &buffConfig, CAN_ID_MASK_TYPE_FW); 58 | 59 | /* Configure Rx MB filters */ 60 | CAN_SetRxFilter(instance, CAN_MSG_ID_EXT, RX_MB_DATA, CAN_ID_MASK_TYPE_DATA); 61 | CAN_SetRxFilter(instance, CAN_MSG_ID_EXT, RX_MB_CMD, CAN_ID_MASK_TYPE_CMD); 62 | CAN_SetRxFilter(instance, CAN_MSG_ID_EXT, RX_MB_FW, CAN_ID_MASK_TYPE_FW); 63 | 64 | /* Enable Rx interrupts for MBs */ 65 | CAN_Receive(instance, RX_MB_DATA, &user_rxBuff); 66 | CAN_Receive(instance, RX_MB_CMD, &user_rxBuff); 67 | CAN_Receive(instance, RX_MB_FW, &user_rxBuff); 68 | } 69 | 70 | /* 71 | * @brief: CAN Event Handler (ISR). This is invoked on any CAN Tx/Rx activity. 72 | * : It is of type can_event_t. 73 | * @param instance : CAN peripheral instance 74 | * @param eventType : CAN event 75 | * @param objIdx : Message Buffer ID 76 | * @param *flexcanState : Pointer to CAN state 77 | * @return : none 78 | */ 79 | void CAN_eventHandler(uint32_t instance, can_event_t eventType, uint32_t objIdx, void *flexcanState) 80 | { 81 | switch(eventType) { 82 | 83 | case CAN_EVENT_RX_COMPLETE: 84 | { 85 | /* Filter the incoming CAN frame using CAN ID Filter implementing in software */ 86 | if(CAN_filterFrame(&user_rxBuff)) 87 | { 88 | CAN_buildPDU(&user_rxBuff); 89 | } 90 | 91 | /* SDK BETA 0.9.0 BUG */ 92 | can_instance_t can_instance = { instance, CAN_INST_TYPE_FLEXCAN }; 93 | 94 | /* Re-enable Rx interrupt for CAN Interface */ 95 | CAN_Receive(&can_instance, objIdx, &user_rxBuff); 96 | break; 97 | } 98 | 99 | case CAN_EVENT_TX_COMPLETE: break; 100 | default: break; 101 | } 102 | } 103 | 104 | /* 105 | * @brief: CAN Frame ID filtering implemented in software 106 | * @param *frame : CAN peripheral instance 107 | * @return : True (if frame accepted) 108 | * : False (if frame rejected) 109 | */ 110 | bool CAN_filterFrame(can_message_t *frame) 111 | { 112 | uint32_t i, tempId; 113 | 114 | tempId = frame->id & ~CAN_ID_MASK_TYPE_DATA; 115 | 116 | /*! Replace with effecient binary search !*/ 117 | /* Any CAN frames found within the filter table are rejected */ 118 | for(i = 0 ; i < (sizeof(CAN_ID_FilterTable) / sizeof(CAN_ID_FilterTable[0])) ; i++) 119 | { 120 | if(tempId == CAN_ID_FilterTable[i]) return true; 121 | } 122 | return true; /* WARNING: Just return true regardless right now. */ 123 | } 124 | 125 | 126 | /* 127 | * @brief: Build PDU from CAN frame and pass to PDU router 128 | * @param *frame : Pointer to CAN frame 129 | * @return : none 130 | */ 131 | void CAN_buildPDU(can_message_t *frame) 132 | { 133 | if(!xQueueIsQueueFullFromISR(PDU_queue)) 134 | { 135 | PDU pdu; 136 | 137 | memset(&pdu, 0, sizeof(pdu)); /* Clear PDU */ 138 | 139 | /* **** CAN Frame **** | *** PDU *** 140 | * uint32_t cs; | 141 | * uint32_t id; --|--> uint32_t id; 142 | * uint8_t length; --|--> uint8_t length; 143 | * uint8_t data[64]; --|--> uint8_t *data; 144 | */ 145 | 146 | pdu.id = frame->id; 147 | pdu.length = frame->length; 148 | pdu.data = malloc(frame->length); 149 | //pdu.data = pvPortMalloc(frame->length); 150 | 151 | /* Memory is allocated for incoming frames using malloc() 152 | * Copy the CAN frame payload to this memory pointer below. 153 | */ 154 | memcpy(pdu.data, &(frame->data), frame->length); 155 | 156 | if(errQUEUE_FULL == xQueueSendToBackFromISR(PDU_queue, (void*) &pdu, NULL)) 157 | { 158 | /* Error: PDU queue is full. CAN frame is dropped at the interface. 159 | * In this case, immediately free() the memory which was allocated. 160 | */ 161 | free(pdu.data); 162 | } else { 163 | /* Success: The CAN frame has been added to the PDU queue for processing. 164 | * WARNING: Upper layers must free() the buffer space once PDU has been processed. 165 | */ 166 | } 167 | } 168 | else { 169 | /* Error: PDU queue is full. CAN frame is dropped at the interface. */ 170 | } 171 | } 172 | 173 | /* 174 | * @brief: Implementation for updating ECU firmware over CAN with CAN bootloader 175 | * @param ecu : Pointer to ECU struct 176 | * @param fw : Pointer to FW File to use 177 | * @param secureUpdate : Secure update (yes/no) 178 | * @return : STATUS_SUCCESS, STATUS_ERROR 179 | */ 180 | status_t CAN_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate) 181 | { 182 | ECU *ecu = &ecu_list[ecu_id]; 183 | 184 | uint8_t buffer[MSG_SIZE]; /* Buffer for CAN frame */ 185 | PDU pdu; 186 | 187 | uint32_t msgId = CAN_ID_MASK_TYPE_FW | ecu_id; /* ECU ID + FW Update Type */ 188 | 189 | BaseType_t stat; 190 | UINT i, br; /* loop counter */ 191 | 192 | uint8_t rnd[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* Random number generated */ 193 | uint8_t iv[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* Initialisation vector */ 194 | 195 | uint32_t interface = ecu->instance; 196 | 197 | /*********************** FLEXCAN UPDATE FLOW **************************/ 198 | /**********************************************************************/ 199 | /*********************** 1. Send ECU reset ****************************/ 200 | buffer[0] = RESET_CMD; 201 | CAN_sendFrame(interface, msgId, buffer, 1); 202 | 203 | /*********************** 2. Wait for UP_RESET ACK *********************/ 204 | stat = xQueueReceive(fw_update_queue, &pdu, TIMEOUT); 205 | if(stat != pdTRUE || pdu.data[0] != RESET_ACK) 206 | return stat; 207 | free(pdu.data); 208 | /*********************** 3. Begin FW Update ***************************/ 209 | if(secureUpdate) buffer[0] = BEGIN_SEC; 210 | else buffer[0] = BEGIN_NONSEC; 211 | 212 | CAN_sendFrame(interface, msgId, buffer, 1); 213 | 214 | /*********************** 4. Wait for Random Number ********************/ 215 | stat = xQueueReceive(fw_update_queue, &pdu, TIMEOUT); 216 | if(stat != pdTRUE) 217 | return stat; 218 | 219 | if(secureUpdate) 220 | { 221 | memcpy(rnd, pdu.data, sizeof(rnd)); 222 | } 223 | else 224 | { 225 | if(pdu.data[0] != 0xFF) /* ERROR */ 226 | return stat; 227 | } 228 | free(pdu.data); 229 | 230 | /*********************** 5. Send Firmware ****************************/ 231 | f_read(fw, buffer, FW_DATA_SIZE, &br); /* Read 48 bytes from file */ 232 | 233 | while(br != 0) /* Exit loop when sent last remaining packet */ 234 | { 235 | for(i = (uint32_t) br ; i < FW_DATA_SIZE ; i++) { /* Pad packet with 0s if end of file */ 236 | buffer[i] = 0; 237 | } 238 | 239 | for(i = 0 ; i < FW_CMAC_SIZE ; i++) /* Insert random number */ 240 | { 241 | buffer[FW_DATA_SIZE + i] = rnd[i]; 242 | } 243 | 244 | /* Encrypt CAN Frame */ 245 | SECURITY_EncryptCbcBlocking(SECURITY_INSTANCE0, SECURITY_KEY_1, buffer, sizeof(buffer), iv, buffer, TIMEOUT); 246 | //HSM_DRV_EncryptCBC(HSM_KEY_1, buffer, sizeof(buffer), iv, buffer, TIMEOUT); 247 | 248 | /* Send 1 CAN Frame containing FW */ 249 | CAN_sendFrame(interface, msgId, buffer, MSG_SIZE); 250 | 251 | /* Wait for ACK */ 252 | stat = xQueueReceive(fw_update_queue, &pdu, TIMEOUT); 253 | if(stat != pdTRUE || pdu.data[0] != FRAME_ACK) /* ERROR */ 254 | return stat; 255 | free(pdu.data); 256 | f_read(fw, &buffer[0], FW_DATA_SIZE, &br); /* Read 48 bytes (or less) from file */ 257 | }; 258 | 259 | /*********************** 6. Send FW End Flag **************************/ 260 | buffer[0] = END_CMD; 261 | CAN_sendFrame(interface, msgId, buffer, 1); 262 | 263 | stat = xQueueReceive(fw_update_queue, &pdu, TIMEOUT); 264 | if(stat != pdTRUE || pdu.data[0] != END_ACK) /* ERROR */ 265 | return stat; 266 | free(pdu.data); 267 | /******************** FLEXCAN UPDATE FLOW FINISHED *******************/ 268 | /*********************************************************************/ 269 | return STATUS_SUCCESS; 270 | } 271 | 272 | /* 273 | * @brief: Send data via CAN to the specified mailbox with the specified message id 274 | * @param mailbox : Destination mailbox number 275 | * @param messageId : Message ID 276 | * @param data : Pointer to the TX data 277 | * @param len : Length of the TX data 278 | * @return : None 279 | */ 280 | void CAN_sendFrame(uint32_t instance, uint32_t messageId, uint8_t * data, uint32_t len) 281 | { 282 | status_t stat; 283 | 284 | can_buff_config_t buffConfig2 = 285 | { 286 | .enableFD = true, 287 | .enableBRS = true, 288 | .fdPadding = 0U, 289 | .idType = CAN_MSG_ID_EXT, 290 | .isRemote = false 291 | }; 292 | 293 | can_instance_t can_instance = { 294 | .instIdx = instance, 295 | .instType = can_ip_type.instType 296 | }; 297 | 298 | can_message_t sendMsg = { 299 | .id = messageId, 300 | .length = len 301 | }; 302 | 303 | /* Copy data into can_message_t data buffer */ 304 | memcpy(sendMsg.data, data, len); 305 | 306 | /* Configure Rx MBs */ 307 | CAN_ConfigTxBuff(&can_instance, TX_MB, &buffConfig2); 308 | 309 | /* Send data using buffer configured for transmission */ 310 | stat = CAN_SendBlocking(&can_instance, TX_MB, &sendMsg, 1U); /* Timeout 100ms */ 311 | 312 | #ifdef DEBUG_ENABLE 313 | switch(stat) 314 | { 315 | case STATUS_SUCCESS: CAN_printFrame(&can_instance, &sendMsg, true); break; 316 | default: CAN_errorHandler(&can_instance, TX_MB, &sendMsg, stat); break; 317 | } 318 | #endif 319 | } 320 | 321 | /* 322 | * @brief: CAN Error Handler. Called anytime CAN send frame API call returns non-SUCCESS 323 | * @param instance : CAN Instance 324 | * @param mailbox : MB ID 325 | * @param *msg : can_message_t pointer 326 | * @param stat : status 327 | * @return : None 328 | */ 329 | void CAN_errorHandler(const can_instance_t *instance, uint32_t mailbox, can_message_t *msg, status_t stat) 330 | { 331 | /* In this error handler you may want to: 332 | * 1. Count the number of errors. 333 | * 2. Time the occurancy of errors 334 | * 3. Act on these errors, reset/cooldown/escalate? 335 | */ 336 | 337 | /* Just print an error message for now */ 338 | CAN_printError(instance, msg, stat); 339 | } 340 | 341 | /* 342 | * @brief: Constructs error message to print on debug console. 343 | * @param instance : CAN Instance 344 | * @param *msg : can_message_t pointer 345 | * @param stat : status 346 | * @return : None 347 | */ 348 | void CAN_printError(const can_instance_t *instance, can_message_t *msg, status_t stat) 349 | { 350 | char buff[100]; 351 | char *status; 352 | uint8_t i; 353 | 354 | switch(stat) 355 | { 356 | case STATUS_BUSY: status = "BUSY "; break; 357 | case STATUS_TIMEOUT: status = "TIMEOUT "; break; 358 | case STATUS_ERROR: status = "ERROR "; break; 359 | case STATUS_CAN_BUFF_OUT_OF_RANGE: status = "MB OUT OF RANGE"; break; 360 | default: status = "N/A"; break; 361 | } 362 | 363 | sprintf(buff, "\n\r[CAN%d][Tx] %s\t0x%08X\t0x%02X\t", instance->instIdx, status, msg->id, msg->length); 364 | CONSOLE_printError(buff); 365 | 366 | for (i = 0; i < msg->length; i++) 367 | { 368 | sprintf(&buff[i*3], "%02X ", msg->data[i]); 369 | } 370 | CONSOLE_printError(buff); 371 | } 372 | 373 | /* 374 | * @brief: CAN frame toString() and print to debug console. 375 | * @param instance : CAN Instance 376 | * @param *msg : can_message_t pointer 377 | * @param tx : true = Transmit, false = Receive 378 | * @return : None 379 | */ 380 | void CAN_printFrame(const can_instance_t *instance, can_message_t *msg, bool tx) 381 | { 382 | char buff[50 + (msg->length)*3]; 383 | char *dir; 384 | char *colour; 385 | char *label; 386 | uint8_t i; 387 | 388 | switch(tx) /* Set direction of message */ 389 | { 390 | case true: dir = "Tx"; colour = "\e[33m"; break; /* Yellow foreground */ 391 | case false: dir = "Rx"; colour = "\e[0m"; break; /* White foreground */ 392 | } 393 | 394 | uint32_t ecuId = msg->id & PDU_ID_MASK_ECU_ID; 395 | 396 | if(msg->id & CAN_ID_MASK_TYPE_DATA) { 397 | label = PDU_Descriptors[ecuId].label; 398 | } 399 | else if(msg->id & CAN_ID_MASK_TYPE_CMD) { 400 | label = "COMMAND "; 401 | } 402 | else if(msg->id & CAN_ID_MASK_TYPE_FW) { 403 | label = "FIRMWARE "; 404 | } 405 | else { 406 | label = "N/A"; 407 | } 408 | 409 | sprintf(buff, "\n\r%s[CAN%d][%s] %s\t0x%08X\t0x%02X\t", colour, instance->instIdx, dir, label, msg->id, msg->length); 410 | CONSOLE_printString(buff); 411 | 412 | for (i = 0; i < msg->length; i++) 413 | { 414 | sprintf(&buff[i*3], "%02X ", msg->data[i]); 415 | } 416 | CONSOLE_printString(buff); 417 | } 418 | 419 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/can/can.h: -------------------------------------------------------------------------------- 1 | /* 2 | * can.h 3 | * 4 | * Created on: 25 Jan 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef CAN_H_ 9 | #define CAN_H_ 10 | 11 | #include 12 | #include "Cpu.h" 13 | #include "pdu_router.h" 14 | #include "ecu.h" 15 | 16 | /* CAN Frame Sizes */ 17 | #define FW_DATA_SIZE 48U 18 | #define FW_CMAC_SIZE 16U 19 | #define MSG_SIZE (FW_DATA_SIZE + FW_CMAC_SIZE) 20 | 21 | /* Mail boxes */ 22 | #define TX_MB 0U 23 | #define RX_MB_DATA 1U 24 | #define RX_MB_CMD 2U 25 | #define RX_MB_FW 3U 26 | 27 | /* CAN MSG ID Masks */ 28 | #define CAN_ID_MASK_TYPE_DATA 0x10000000U 29 | #define CAN_ID_MASK_TYPE_CMD 0x08000000U 30 | #define CAN_ID_MASK_TYPE_FW 0x04000000U 31 | #define CAN_ID_MASK_ECU_ID 0x000000FFU 32 | 33 | /* 34 | * @brief: Initialise CAN peripheral 35 | * @param instance : Instance of CAN to initialise 36 | * @param *config : Pointer to user configuration struct 37 | * 38 | * @return : none 39 | */ 40 | void CAN_initialise(const can_instance_t *instance, const can_user_config_t *config); 41 | 42 | /* 43 | * @brief: CAN Event Handler (ISR). This is invoked on any CAN Tx/Rx activity. 44 | * : It is of type can_event_t. 45 | * @param instance : CAN peripheral instance 46 | * @param eventType : CAN event 47 | * @param objIdx : Message Buffer ID 48 | * @param *flexcanState : Pointer to CAN state 49 | * @return : none 50 | */ 51 | void CAN_eventHandler(uint32_t instance, can_event_t eventType, uint32_t objIdx, void *flexcanState); 52 | 53 | /* 54 | * @brief: Software Filter for frame IDs 55 | * @param *frame : CAN peripheral instance 56 | * @return : True (if frame accepted) 57 | * : False (if frame rejected) 58 | */ 59 | bool CAN_filterFrame(can_message_t *frame); 60 | 61 | /* 62 | * @brief: Build PDU from CAN frame and pass to PDU router 63 | * @param *frame : Pointer to CAN frame 64 | * @return : none 65 | */ 66 | void CAN_buildPDU(can_message_t *response); 67 | 68 | /* 69 | * @brief: Implementation for updating ECU firmware over CAN with CAN bootloader 70 | * @param ecu : Pointer to ECU struct 71 | * @param fw : Pointer to FW File to use 72 | * @param secureUpdate : Secure update (yes/no) 73 | * @return : STATUS_SUCCESS, STATUS_ERROR 74 | */ 75 | status_t CAN_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate); 76 | 77 | /* 78 | * @brief: Send data via CAN to the specified mailbox with the specified message id 79 | * @param mailbox : Destination mailbox number 80 | * @param messageId : Message ID 81 | * @param data : Pointer to the TX data 82 | * @param len : Length of the TX data 83 | * @return : None 84 | */ 85 | void CAN_sendFrame(uint32_t instance, uint32_t messageId, uint8_t * data, uint32_t len); 86 | 87 | /* 88 | * @brief: CAN Error Handler. Called anytime CAN API call returns non SUCCESS 89 | * @param instance : CAN Instance 90 | * @param mailbox : MB ID 91 | * @param *msg : can_message_t pointer 92 | * @param stat : status 93 | * @return : None 94 | */ 95 | void CAN_errorHandler(const can_instance_t *instance, uint32_t mailbox, can_message_t *msg, status_t stat); 96 | /* 97 | * @brief: Constructs error message to print on debug console. 98 | * @param instance : CAN Instance 99 | * @param *msg : can_message_t pointer 100 | * @param stat : status 101 | * @return : None 102 | */ 103 | void CAN_printError(const can_instance_t *instance, can_message_t *msg, status_t stat); 104 | 105 | /* 106 | * @brief: CAN frame toString() and print to debug console. 107 | * @param instance : CAN Instance 108 | * @param *msg : can_message_t pointer 109 | * @param tx : true = Transmit, false = Receive 110 | * @return : None 111 | */ 112 | void CAN_printFrame(const can_instance_t *instance, can_message_t *msg, bool tx); 113 | 114 | /* User buffer containing CAN frame currently processed */ 115 | can_message_t user_rxBuff; 116 | 117 | #endif /* CAN_H_ */ 118 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/ethernet/ethernet.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ethernet.c 3 | * 4 | * Created on: 20 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #include "ethernet.h" 9 | #include "config.h" 10 | 11 | void ETH_socketServer(void* pvParameters) 12 | { 13 | //int socket = pvParameters[0]; 14 | 15 | //vTaskDelete(NULL); 16 | } 17 | 18 | void ETH_sendCommand(uint8_t ecu_id, ecu_cmd cmd) 19 | { 20 | // uint8_t socket = ecu->interface; 21 | // uint32_t ret; 22 | // ret = lwip_write(socket, (void*) cmd, sizeof(cmd)); 23 | } 24 | 25 | 26 | 27 | status_t ETH_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate) 28 | { 29 | //uint8_t socket = ecu->interface; 30 | 31 | return STATUS_SUCCESS; 32 | } 33 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/ethernet/ethernet.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ethernet.h 3 | * 4 | * Created on: 20 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef ETHERNET_H_ 9 | #define ETHERNET_H_ 10 | 11 | #include 12 | #include "ecu.h" 13 | 14 | 15 | void ETH_socketServer(void* pvParameters); 16 | void ETH_sendCommand(uint8_t ecu_id, ecu_cmd cmd); 17 | status_t ETH_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate); 18 | 19 | #endif /* ETHERNET_H_ */ 20 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/lin/lin.c: -------------------------------------------------------------------------------- 1 | /* 2 | * lin.c 3 | * 4 | * Created on: 6 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #include 9 | #include "Cpu.h" 10 | #include "config.h" 11 | 12 | #define TIMEOUT 1000 13 | 14 | uart_instance_t uart_ip_type; 15 | 16 | 17 | void LIN_initialise(const uart_instance_t *instance, const uart_user_config_t *config) 18 | { 19 | UART_Init(instance, config); 20 | 21 | /* Save the UART IP type used by the device */ 22 | uart_ip_type.instType = instance->instType; 23 | } 24 | 25 | /* 26 | * @brief: Implementation requesting information from ECU on LIN network 27 | * @param ecu : Pointer to ECU struct 28 | * @param fw : Type of request 29 | * @return : STATUS_SUCCESS, STATUS_ERROR 30 | */ 31 | void LIN_sendFrame(uint32_t instance, uint32_t messageId, uint8_t * data, uint32_t len) 32 | { 33 | uint8_t txBuff[30]; 34 | 35 | uart_instance_t uart_instance = { 36 | .instType = uart_ip_type.instType, 37 | .instIdx = instance 38 | }; 39 | 40 | 41 | //UART_SetTxBuffer(&uart_instance, txBuff, sizeof(txBuff)); 42 | // or 43 | //UART_SendDataBlocking(&uart_instance, txBuff, sizeof(txBuff), TIMEOUT); 44 | 45 | } 46 | 47 | /* 48 | * @brief: Implementation for updating ECU firmware over LIN with LIN bootloader 49 | * @param ecu : Pointer to ECU struct 50 | * @param fw : Pointer to FW File to use 51 | * @param secureUpdate : Secure update (yes/no) 52 | * @return : STATUS_SUCCESS, STATUS_ERROR 53 | */ 54 | status_t LIN_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate) 55 | { 56 | return 0; 57 | } 58 | 59 | 60 | /* 61 | * @brief: Parse ECU response to extract information 62 | * @param response : Pointer to response to be parsed 63 | * @return : non 64 | */ 65 | void LIN_parseResponse(uint8_t *response, uint32_t length) 66 | { 67 | 68 | } 69 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/lin/lin.h: -------------------------------------------------------------------------------- 1 | /* 2 | * lin.h 3 | * 4 | * Created on: 6 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef LIN_H_ 9 | #define LIN_H_ 10 | 11 | #include 12 | #include "Cpu.h" 13 | #include "ecu.h" 14 | #include "status.h" 15 | 16 | void LIN_initialise(const uart_instance_t *instance, const uart_user_config_t *config); 17 | void LIN_sendFrame(uint32_t instance, uint32_t messageId, uint8_t * data, uint32_t len); 18 | void LIN_parseResponse(uint8_t *response, uint32_t length); 19 | status_t LIN_updateFirmware(uint8_t ecu_id, FIL *fw, bool secureUpdate); 20 | 21 | #endif /* LIN_H_ */ 22 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/sdhc/sdhc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * sdhc.c 3 | * 4 | * Created on: 6 Feb 2018 5 | * Author: B49855 6 | */ 7 | #include "sdhc.h" 8 | #include "config.h" 9 | #include "status.h" 10 | 11 | 12 | void SD_initialise() 13 | { 14 | FRESULT stat; 15 | 16 | /* Mount SD card to the device */ 17 | stat = SD_initCard(); 18 | 19 | if(FR_OK == stat) 20 | { 21 | /* Copy contents of ECU list held in RAM to SD card */ 22 | stat = SD_storeAllECU(); 23 | } 24 | 25 | 26 | /* Copy contents of ECU list held in SD card to RAM */ 27 | /* stat = SD_LoadAllECU(); */ 28 | 29 | /* Build list of ECUs by loading ECU data from SD card, and querying ECUs for latest information */ 30 | /* ECU_initList(); */ 31 | } 32 | 33 | 34 | /* 35 | * @brief: Initialise SD card by mounting FAT FS 36 | * @return : STATUS_SUCCESS, STATUS_ERROR 37 | */ 38 | FRESULT SD_initCard() 39 | { 40 | uSDHC_fatfs_user_initialize(); 41 | 42 | /* File function return code */ 43 | FRESULT status; 44 | TCHAR string[] = DRIVE0; 45 | 46 | /* Immediate mount. */ 47 | status = f_mount(&fs,string, 1U); 48 | return status; 49 | } 50 | 51 | /* 52 | * @brief: Store ECU info from RAM buffer (ecu_list) to SD card 53 | * @param ecu : Pointer to ECU struct 54 | * @return : STATUS_SUCCESS, STATUS_ERROR 55 | */ 56 | status_t SD_storeECU(uint8_t ecu_id) 57 | { 58 | FIL fdst; 59 | FRESULT res; 60 | UINT bw; 61 | 62 | char path[50]; 63 | 64 | ECU *ecu = ECU_getECU(ecu_id); 65 | 66 | sprintf(path, "%d", ecu_id); /* Open ECU info file */ 67 | res = f_mkdir(path); /* Create directory if it does not exist already */ 68 | 69 | sprintf(path, "%d/%d.bin", ecu_id, ecu_id); /* Open ECU info file */ 70 | res = f_open(&fdst, path, FA_CREATE_ALWAYS | FA_WRITE); 71 | 72 | if(res == FR_OK) { 73 | 74 | res = f_write(&fdst, ecu, sizeof(ECU), &bw); /* Write ecu_info struct to bin file */ 75 | 76 | if(bw < sizeof(ECU) || res != FR_OK) { 77 | return STATUS_ERROR; 78 | } 79 | 80 | f_close(&fdst); 81 | } 82 | 83 | return STATUS_SUCCESS; 84 | } 85 | 86 | /* 87 | * @brief: Load ECU info from SD card to RAM buffer (ecu_list) 88 | * @param ecu : Pointer to ECU struct 89 | * @return : STATUS_SUCCESS, STATUS_ERROR 90 | */ 91 | status_t SD_loadECU(uint8_t ecu_id) 92 | { 93 | FIL fsrc; 94 | FRESULT res; 95 | UINT br; 96 | char path[50]; 97 | ECU *ecu = &ecu_list[ecu_id]; 98 | 99 | sprintf(path, "%d/%d.bin", ecu_id, ecu_id); 100 | 101 | res = f_open(&fsrc, path, FA_OPEN_EXISTING | FA_READ); 102 | 103 | if(res == FR_OK) 104 | { 105 | /* Load ECU info directly into ecu_info struct */ 106 | res = f_read(&fsrc, ecu, sizeof(ECU), &br); 107 | f_close(&fsrc); 108 | 109 | if(br != sizeof(ECU) || res != FR_OK) { 110 | printf("ERROR: ECU %d. (Status Code: %03x) \n\r", ecu_id, res); 111 | return STATUS_ERROR; 112 | } 113 | 114 | } else return STATUS_ERROR; 115 | 116 | return STATUS_SUCCESS; 117 | } 118 | 119 | /* 120 | * @brief: Store whole list of ECUs in RAM buffer onto SD 121 | * @return : STATUS_SUCCESS, STATUS_ERROR 122 | */ 123 | status_t SD_storeAllECU() 124 | { 125 | uint32_t i; 126 | status_t stat = STATUS_SUCCESS; 127 | 128 | for(i = 0 ; i < NUM_OF_ECUS ; i++) 129 | { 130 | if(SD_storeECU(i) != STATUS_SUCCESS) 131 | { 132 | stat = STATUS_ERROR; 133 | } 134 | } 135 | return stat; 136 | } 137 | 138 | /* 139 | * @brief: Load all ECUs found on SD card into RAM buffer (ecu_list) 140 | * @return : STATUS_SUCCESS, STATUS_ERROR 141 | */ 142 | status_t SD_loadAllECU() 143 | { 144 | /* Open FW file */ 145 | char path[50]; 146 | FRESULT res; 147 | FIL fsrc; 148 | UINT br; 149 | 150 | uint32_t current_ecu = 0; 151 | uint32_t next_ecu = current_ecu + 1; 152 | 153 | while(1) 154 | { 155 | sprintf(path, "%d/%d.bin", current_ecu, current_ecu); 156 | res = f_open(&fsrc, path, FA_OPEN_EXISTING | FA_READ); 157 | 158 | if(FR_OK == res) 159 | { 160 | f_read(&fsrc, &ecu_list[current_ecu], sizeof(ecu_list[0]), &br); 161 | f_close(&fsrc); 162 | 163 | next_ecu++; /* Found file, try searching for newer file */ 164 | } 165 | else if(FR_NO_FILE == res) break; 166 | } 167 | return STATUS_SUCCESS; 168 | } 169 | 170 | ///* 171 | // * @brief: Loads all ECU info held on SD into RAM buffer (ecu_list) 172 | // * @return : STATUS_SUCCESS, STATUS_ERROR 173 | // */ 174 | //status_t SD_LoadAllECUIDs() 175 | //{ 176 | // FRESULT res; 177 | // FILINFO fno; 178 | // DIR dir; 179 | // 180 | // char buff[30]; 181 | // char *ptr; 182 | // 183 | // uint32_t no_ecus = 0; 184 | // 185 | // res = f_opendir(&dir, "/"); 186 | // if(res == FR_OK) 187 | // { 188 | // f_readdir(&dir, &fno); 189 | // 190 | // while(&fno.fname[0] != 0) /* Loop until no more items found */ 191 | // { 192 | // strncpy(&buff, &fno.fname, sizeof(fno.fname)); 193 | // 194 | // uint8_t ecu_id = strtol(&buff, ptr, 10); 195 | // 196 | // ecu_list[no_ecus].id = strtol(&buff, ptr, 10); 197 | // 198 | // f_readdir(&dir, &fno); 199 | // no_ecus++; 200 | // } 201 | // 202 | // f_closedir(&dir); 203 | // } 204 | // return STATUS_SUCCESS; 205 | //} 206 | 207 | /* 208 | * @brief: Open latest FW file for a given ECU 209 | * @param ecu : Pointer to ECU struct 210 | * @param fw : Pointer to FIL object to reference 211 | * @return : FRESULT 212 | */ 213 | //FRESULT SD_OpenLatestFW(ECU *ecu, FIL *fw) 214 | //{ 215 | // return SD_OpenFW(ecu, ecu->fw_ver_new, fw); 216 | //} 217 | 218 | /* 219 | * @brief: Open a given ECU FW file based on version 220 | * @param ecu : Pointer to ECU struct 221 | * @param ver : Version of FW to open 222 | * @param fw : Pointer to FIL object to reference 223 | * @return : FRESULT 224 | */ 225 | FRESULT SD_openFW(uint8_t ecu_id, uint32_t ver, FIL *fw) 226 | { 227 | char path[30]; 228 | FRESULT res; 229 | 230 | sprintf(path, "0:%d/%d_fw_%d.bin", ecu_id, ecu_id, ver); 231 | res = f_open(fw, path, FA_OPEN_EXISTING | FA_READ); 232 | return res; 233 | } 234 | 235 | FRESULT SD_openLatestFW(uint8_t ecu_id, FIL *fw) 236 | { 237 | 238 | ECU *ecu = &ecu_list[ecu_id]; 239 | 240 | FRESULT res; 241 | uint32_t current_ecu_ver = ecu->fw_version; 242 | uint32_t ver_pointer = current_ecu_ver + 1; 243 | 244 | while(1) 245 | { 246 | /* Open FW file */ 247 | res = SD_openFW(ecu_id, ver_pointer, fw); 248 | 249 | if(FR_OK == res) 250 | { 251 | ver_pointer++; /* Found file, try searching for newer file */ 252 | f_close(fw); 253 | } 254 | else if(FR_NO_FILE == res) 255 | { 256 | ver_pointer--; /* No newer file, move pointer back to latest file */ 257 | break; 258 | } 259 | } 260 | 261 | if(ver_pointer >= current_ecu_ver) { 262 | res = SD_OpenFW(ecu_id, ver_pointer, fw); 263 | } 264 | 265 | return res; 266 | } 267 | 268 | void uSDHC_fatfs_user_initialize(void) 269 | { 270 | uSDHC_fatfs_initialize(); 271 | g_fatfsCallbacks[FATFS_DISKIO_READ] 272 | .postFunction = FatFs_DiskIo_Read_Callback; 273 | g_fatfsCallbacks[FATFS_DISKIO_WRITE] 274 | .postFunction = FatFs_DiskIo_Write_Callback; 275 | } 276 | 277 | void FatFs_DiskIo_Read_Callback(uint32_t status, void *param) 278 | { 279 | // (void)param; 280 | // if(STATUS_SUCCESS == status) 281 | // { 282 | // PINS_DRV_TogglePins(PTA, (pins_channel_type_t)(1U << 7)); 283 | // } 284 | } 285 | 286 | void FatFs_DiskIo_Write_Callback(uint32_t status, void *param) 287 | { 288 | // (void)param; 289 | // if(STATUS_SUCCESS == status) 290 | // { 291 | // PINS_DRV_TogglePins(PTA, (pins_channel_type_t)(1U << 10)); 292 | // } 293 | } 294 | 295 | -------------------------------------------------------------------------------- /_old/Framework/interfaces/sdhc/sdhc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * sdhc.h 3 | * 4 | * Created on: 6 Feb 2018 5 | * Author: B49855 6 | */ 7 | #ifndef SDHC_H_ 8 | #define SDHC_H_ 9 | 10 | #include "usdhc1.h" 11 | #include "fatfs/usdhc_fatfs_impl.h" 12 | #include "common/fatfs_impl.h" 13 | #include "ff.h" 14 | #include "ecu.h" 15 | 16 | void SD_initialise(); 17 | FRESULT SD_initCard(); 18 | status_t SD_storeECU(uint8_t ecu_id); 19 | status_t SD_loadECU(uint8_t ecu_id); 20 | status_t SD_storeAllECU(); 21 | status_t SD_loadAllECU(); 22 | FRESULT SD_openLatestFW(uint8_t ecu_id, FIL *fw); 23 | FRESULT SD_openFW(uint8_t ecu_id, uint32_t ver, FIL *fw); 24 | 25 | void FatFs_DiskIo_Read_Callback(uint32_t status, void *param); 26 | void FatFs_DiskIo_Write_Callback(uint32_t status, void *param); 27 | void uSDHC_fatfs_user_initialize(void); 28 | 29 | #define DRIVE0 "0:" 30 | #define DRIVE0_INST (0U) 31 | 32 | FATFS fs; 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /_old/Framework/pdu_router/pdu_router.c: -------------------------------------------------------------------------------- 1 | /* 2 | * router.c 3 | * 4 | * Created on: 21 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #include "pdu_router.h" 9 | #include "FreeRTOS.h" 10 | #include "gateway.h" 11 | #include "config.h" 12 | #include "dbg_console.h" 13 | #include "can.h" 14 | #include 15 | 16 | #define TIMEOUT 1000 17 | 18 | 19 | void PDU_discardPDU(PDU *pdu); 20 | /* 21 | * @brief: Initialise the PDU router by creating FreeRTOS task 22 | * and creating the queues which hold PDUs. 23 | * @param void : none 24 | * @return : none 25 | */ 26 | void PDU_initialise() 27 | { 28 | /* Create queue to hold PDU objects */ 29 | PDU_queue = xQueueCreate(PDU_QUEUE_SIZE, sizeof(PDU)); 30 | 31 | /* Create queue to hold 'FW Update' specific PDUs */ 32 | fw_update_queue = xQueueCreate(FW_QUEUE_SIZE, sizeof(PDU)); 33 | 34 | /* Add the PDU Router task to the FreeRTOS scheduler */ 35 | xTaskCreate(PDU_Task, "PDU Router", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY_PDU, NULL); 36 | } 37 | 38 | /* 39 | * @brief: PDU Router (FreeRTOS task). This is responsible for recieving PDUs 40 | * from the PDU queue and forwarding them to the correct ECU. 41 | * @param *pvParameters : void parameter 42 | * @return : none 43 | */ 44 | void PDU_Task(void *pvParameters) 45 | { 46 | PDU pdu; 47 | uint8_t i, ecu_id = 0; 48 | 49 | BaseType_t stat; 50 | /********************* PDU ROUTER THREAD *******************/ 51 | /***********************************************************/ 52 | /* 53 | * 1. Receive PDU from queue. 54 | * 2. Mask PDU ID to determine type (Normal, Req/Resp, FW). 55 | * 2. Consult PDU table to find destinations of PDU. 56 | * 3. Send PDU to correct ECU interface. 57 | * NOTE: Only route PDU if it is on different interface. (Only possible if Publish ECU is recorded?) 58 | */ 59 | while(1) 60 | { 61 | stat = xQueueReceive(PDU_queue, &pdu, portMAX_DELAY); 62 | if( stat == pdTRUE ) /* PDU available */ 63 | { 64 | 65 | #ifdef DEBUG_ENABLE 66 | PDU_printPDU(&pdu, false); 67 | #endif 68 | 69 | /****************** PDU Type = NORMAL ******************/ 70 | if(pdu.id & PDU_ID_MASK_TYPE_DATA) 71 | { 72 | /* Remove PDU_TYPE field, leaving only the Frame ID */ 73 | uint32_t pdu_id = pdu.id & ~PDU_ID_MASK_TYPE_DATA; 74 | 75 | for(i = 0 ; i < PDU_Descriptors[pdu_id].destCount ; i++) 76 | { 77 | ecu_id = PDU_Descriptors[pdu_id].dest[i]; 78 | 79 | /* Send PDU to ECU */ 80 | ECU_sendPDU(ecu_id, &pdu); 81 | } 82 | 83 | PDU_discardPDU(&pdu); 84 | } 85 | /***************** PDU Type = COMMAND *****************/ 86 | else if(pdu.id & PDU_ID_MASK_TYPE_CMD) 87 | { 88 | /* Send CMD PDU to upper GW layer for further processing */ 89 | if(errQUEUE_FULL == xQueueSendToBack(gateway_queue, &pdu, 0)) 90 | { 91 | /* The queue is full so the PDU is dropped and will never 92 | * be processed. In this case, immediately free() the memory 93 | * for another Rx Frame. 94 | */ 95 | PDU_discardPDU(&pdu); 96 | CONSOLE_printError("ERROR: Gateway queue is full!"); 97 | } else { 98 | /* The PDU has been successfully added to the Gateway queue for processing. 99 | * WARNING: Upper layers must free() the buffer space once PDU has been processed. 100 | */ 101 | } 102 | } 103 | /***************** PDU Type = FIRMWARE ****************/ 104 | else if(pdu.id & PDU_ID_MASK_TYPE_FW) 105 | { 106 | /* 107 | * Send PDU directly to FW update queue. 108 | */ 109 | if(errQUEUE_FULL == xQueueSendToBack(fw_update_queue, &pdu, 0)) 110 | { 111 | /* The queue is full so the PDU is dropped and will never 112 | * be processed. In this case, immediately free() the memory 113 | * for another Rx Frame. 114 | */ 115 | PDU_discardPDU(&pdu); 116 | CONSOLE_printError("ERROR: Firmware queue is full!"); 117 | } else { 118 | /* The PDU has been successfully added to the firmware queue for processing. 119 | * WARNING: Upper layers must free() the buffer space once PDU has been processed. 120 | */ 121 | } 122 | } 123 | else 124 | { 125 | /* PDU did not fall into any of the conditions for further processing. 126 | * Discard the PDU and free() the data buffer. 127 | */ 128 | PDU_discardPDU(&pdu); 129 | } 130 | } 131 | } 132 | /****************** END PDU ROUTER THREAD ******************/ 133 | /***********************************************************/ 134 | } 135 | 136 | /* 137 | * @brief: Convert PDU to string equivalent and print to debug console. 138 | * @param *PDU : Pointer to PDU struct 139 | * @param tx : True = Transmit, False = Receive 140 | * @return : none 141 | */ 142 | void PDU_printPDU(PDU *pdu, bool tx) 143 | { 144 | char buff[50 + (pdu->length)*3]; 145 | char *dir; 146 | char *colour; 147 | char *label; 148 | uint8_t i; 149 | 150 | /* Set direction of message */ 151 | switch(tx) 152 | { 153 | case true: dir = "Tx"; colour = "\e[33m"; break; /* Yellow foreground */ 154 | case false: dir = "Rx"; colour = "\e[0m"; break; /* White foreground */ 155 | } 156 | 157 | uint32_t ecuId = pdu->id & PDU_ID_MASK_ECU_ID; 158 | 159 | if(pdu->id & PDU_ID_MASK_TYPE_DATA) { 160 | label = PDU_Descriptors[ecuId].label; 161 | } 162 | else if(pdu->id & PDU_ID_MASK_TYPE_CMD) { 163 | label = "COMMAND "; 164 | } 165 | else if(pdu->id & PDU_ID_MASK_TYPE_FW) { 166 | label = "FIRMWARE "; 167 | } 168 | else { 169 | label = "N/A"; 170 | } 171 | 172 | sprintf(buff, "\n\r%s[PDU ][%s] %s\t0x%08x\t0x%02x\t", colour, dir, label, pdu->id, pdu->length); 173 | CONSOLE_printString(buff); 174 | 175 | for (i = 0; i < pdu->length; i++) 176 | { 177 | sprintf(&buff[i*3], "%02X ", pdu->data[i]); 178 | } 179 | CONSOLE_printString(buff); 180 | } 181 | 182 | 183 | /* 184 | * @brief: This function frees the memory which was previously malloc()'d by interface. 185 | * it is IMPORTANT this operation is not interrupted by a context switch 186 | * or else an IVOR1 will be triggered. 187 | * @param *PDU : Pointer to PDU struct 188 | * @return : none 189 | */ 190 | void PDU_discardPDU(PDU *pdu) 191 | { 192 | taskENTER_CRITICAL(); 193 | free(pdu->data); 194 | //vPortFree(pdu->data); 195 | taskEXIT_CRITICAL(); 196 | } 197 | -------------------------------------------------------------------------------- /_old/Framework/pdu_router/pdu_router.h: -------------------------------------------------------------------------------- 1 | /* 2 | * pdu_router.h 3 | * 4 | * Created on: 22 Feb 2018 5 | * Author: B49855 6 | */ 7 | 8 | #ifndef PDU_ROUTER_H_ 9 | #define PDU_ROUTER_H_ 10 | 11 | #include 12 | #include "FreeRTOS.h" 13 | #include "queue.h" 14 | 15 | #define PDU_ID_MASK_TYPE_DATA 0x10000000U 16 | #define PDU_ID_MASK_TYPE_CMD 0x08000000U 17 | #define PDU_ID_MASK_TYPE_FW 0x04000000U 18 | #define PDU_ID_MASK_ECU_ID 0x000000FFU 19 | 20 | /* PDU object which is processed by the PDU Router */ 21 | typedef struct { 22 | uint32_t id; /* PDU ID */ 23 | uint8_t length; /* Data length */ 24 | uint8_t *data; /* Pointer to data */ 25 | } PDU; 26 | 27 | /* The PDU_Desc struct defines a routing entry to the PDU routing table 28 | * which described how a PDU should be routed by the PDU router. 29 | */ 30 | typedef struct { 31 | char *label; /* PDU label for user readability */ 32 | uint8_t destCount; /* Num of destinations of PDU */ 33 | uint8_t *dest; /* Pointer to list of ECU IDs to route PDU */ 34 | } PDU_Desc; 35 | 36 | 37 | //typedef struct { 38 | // uint32_t pdu_id; /* PDU ID which signal is to be copied too */ 39 | // uint32_t position; /* Position within the PDU where signal should be copied */ 40 | //} tSignalDestDescr; 41 | // 42 | // 43 | //typedef struct { 44 | // uint32_t position; /* Position of the signal within the PDU */ 45 | // uint32_t size; /* Size of the signal within the PDU */ 46 | // tSignalDestDescr *destinations; /* List of destinations where signal should be copied */ 47 | //} tSignalDescr; 48 | // 49 | //typedef struct { 50 | // 51 | // uint32_t id; /* ID of frame */ 52 | // uint32_t length; /* Expected length of frame */ 53 | // 54 | // uint8_t num_of_signals; /* 0 = no signals (PDU routing) */ 55 | // tSignalDescr *signalDesc; 56 | // 57 | //} tRxPDUDesc; 58 | // 59 | //typedef struct { 60 | // uint32_t id; 61 | // uint8_t *dest; 62 | // 63 | //} tTxPDUDescr; 64 | 65 | /* 66 | * @brief: PDU Router (FreeRTOS task). This is responsible for recieving PDUs 67 | * from the PDU queue and forwarding them to the correct ECU. 68 | * @param *pvParameters : void parameter 69 | * @return : none 70 | */ 71 | void PDU_Task(void *pvParameters); 72 | /* 73 | * @brief: Initialise the PDU router by creating FreeRTOS task 74 | * and creating the queues which hold PDUs. 75 | * @param void : none 76 | * @return : none 77 | */ 78 | void PDU_initialise(void); 79 | /* 80 | * @brief: Convert PDU to string equivalent and print to debug console. 81 | * @param *PDU : Pointer to PDU struct 82 | * @param tx : True = Transmit, False = Receive 83 | * @return : none 84 | */ 85 | void PDU_printPDU(PDU *pdu, bool tx); 86 | 87 | /* 88 | * @brief: This function frees the memory which was previously malloc()'d by interface. 89 | * it is IMPORTANT this operation is not interrupted by a context switch 90 | * or else an IVOR1 will be triggered. 91 | * @param *PDU : Pointer to PDU struct 92 | * @return : none 93 | */ 94 | void PDU_discardPDU(PDU *pdu); 95 | 96 | /* FreeRTOS Queue object which holds all PDUs to be processed by PDU router */ 97 | QueueHandle_t PDU_queue; 98 | /* FreeRTOS Queue object which holds all PDUs specific to FW update process */ 99 | QueueHandle_t fw_update_queue; 100 | 101 | 102 | #endif /* PDU_ROUTER_H_ */ 103 | -------------------------------------------------------------------------------- /_old/Framework/security/hsm_she.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 - 2016 , Freescale Semiconductor, Inc. 3 | * Copyright 2016-2017 NXP 4 | * All rights reserved. 5 | * 6 | * THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED OR 7 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 8 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 9 | * IN NO EVENT SHALL NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 10 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 11 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 12 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 13 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 14 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 15 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 16 | * THE POSSIBILITY OF SUCH DAMAGE. 17 | */ 18 | /* 19 | * HSM_utils.c 20 | * 21 | * Created on: Nov 10, 2016 22 | * Author: B50609 23 | */ 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | #include "hsm_she.h" 30 | #include "config.h" 31 | 32 | /* AuthId is the MASTER_ECU key */ 33 | uint8_t g_emptyKey[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 34 | uint8_t g_authIdKey[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; 35 | /* Constants defined by the SHE spec */ 36 | uint8_t key_update_enc_c[16] = {0x01, 0x01, 0x53, 0x48, 0x45, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0}; 37 | uint8_t key_update_mac_c[16] = {0x01, 0x02, 0x53, 0x48, 0x45, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0}; 38 | uint8_t key_debug_key_c[16] = {0x01, 0x03, 0x53, 0x48, 0x45, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0}; 39 | security_key_id_t g_authId = SECURITY_MASTER_ECU; 40 | 41 | /* Global variables */ 42 | static security_user_config_t g_tSecurityUserConfig; 43 | 44 | 45 | void HSM_initialise() 46 | { 47 | uint8_t BOOT_MAC_KEY[16] = BOOT_MAC_KEY_VALUE; 48 | uint8_t KEY_1[16] = KEY_1_VALUE; 49 | 50 | SECURITY_Init(SECURITY_INSTANCE0, &g_tSecurityUserConfig); 51 | 52 | /* Set the AuthID key (MASTER_ECU_KEY) for the first time */ 53 | HSM_SetAuthKey(); 54 | 55 | /* Load key into HSM_KEY_1 slot */ 56 | HSM_LoadKey(SECURITY_KEY_1, KEY_1, 3); /* 3 = counter value */ 57 | 58 | /* Load key into HSM_BOOT_MAC_KEY slot */ 59 | HSM_LoadKey(SECURITY_BOOT_MAC_KEY, BOOT_MAC_KEY, 2); 60 | } 61 | 62 | /* Derives a key with a given constant */ 63 | status_t HSM_DeriveKey(const uint8_t *key, uint8_t *constant, uint8_t *derivedKey) 64 | { 65 | uint8_t concat[32]; 66 | int i; 67 | 68 | for (i = 0; i < 16; i++) 69 | { 70 | concat[i] = key[i]; 71 | concat[i+16] = constant[i]; 72 | } 73 | 74 | return SECURITY_MPCompress(SECURITY_INSTANCE0, concat, 32U, derivedKey, 500U); 75 | } 76 | 77 | /* Computes the M1-M3 values */ 78 | status_t HSM_ComputeM1M2M3(uint8_t *authKey, security_key_id_t authId, security_key_id_t keyId, const uint8_t *key, uint32_t counter, 79 | uint8_t *uid, uint8_t *m1, uint8_t *m2, uint8_t *m3) 80 | { 81 | status_t stat; 82 | int i; 83 | uint8_t iv[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 84 | 85 | uint8_t k1[16]; 86 | uint8_t k2[16]; 87 | 88 | uint8_t m2Plain[32]; 89 | 90 | uint8_t m1m2[48]; 91 | 92 | /* Derive K1 and K2 from AuthID */ 93 | HSM_DeriveKey(authKey, key_update_enc_c, k1); 94 | HSM_DeriveKey(authKey, key_update_mac_c, k2); 95 | 96 | /* Compute M1 = UID | ID | AuthID */ 97 | for (i = 0; i < 15; i++) 98 | { 99 | m1[i] = uid[i]; 100 | } 101 | m1[15] = ((keyId & 0xF) << 4) | (authId & 0xF); 102 | 103 | /* Compute M2 (C = counter, F = 0) */ 104 | for(i = 0; i < 16; i++) 105 | { 106 | m2Plain[i] = 0; 107 | m2Plain[16 + i] = key[i]; 108 | } 109 | m2Plain[0] = (counter & 0xFF00000) >> 20; 110 | m2Plain[1] = (counter & 0xFF000) >> 12; 111 | m2Plain[2] = (counter & 0xFF0) >> 4; 112 | m2Plain[3] = (counter & 0xF) << 4; 113 | 114 | /* Encrypt M2 */ 115 | stat = SECURITY_LoadPlainKey(SECURITY_INSTANCE0, k1, 500U); 116 | if (stat != STATUS_SUCCESS) 117 | return stat; 118 | 119 | stat = SECURITY_EncryptCbcBlocking(SECURITY_INSTANCE0, SECURITY_RAM_KEY, m2Plain, 32U, iv, m2, 500U); 120 | if (stat != STATUS_SUCCESS) 121 | return stat; 122 | 123 | /* Compute M3 as CMAC(key=k2, m1|m2)*/ 124 | for (i = 0; i < 16; i++) 125 | { 126 | m1m2[i] = m1[i]; 127 | } 128 | for(i = 0; i < 32; i++) 129 | { 130 | m1m2[16 + i] = m2[i]; 131 | } 132 | 133 | stat = SECURITY_LoadPlainKey(SECURITY_INSTANCE0, k2, 500U); 134 | if (stat != STATUS_SUCCESS) 135 | return stat; 136 | 137 | stat = SECURITY_GenerateMacBlocking(SECURITY_INSTANCE0, SECURITY_RAM_KEY, m1m2, 384U, m3, 500U); 138 | if (stat != STATUS_SUCCESS) 139 | return stat; 140 | 141 | return STATUS_SUCCESS; 142 | } 143 | 144 | /* Computes the M4 and M5 values */ 145 | status_t HSM_ComputeM4M5(security_key_id_t authId, security_key_id_t keyId, const uint8_t *key, uint32_t counter, 146 | uint8_t *uid, uint8_t *m4, uint8_t *m5) 147 | { 148 | status_t stat; 149 | int i; 150 | 151 | uint8_t k3[16]; 152 | uint8_t k4[16]; 153 | 154 | uint8_t m4StarPlain[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 155 | uint8_t m4StarCipher[16]; 156 | 157 | /* Derive K4 and K5 from key ID */ 158 | HSM_DeriveKey(key, key_update_enc_c, k3); 159 | HSM_DeriveKey(key, key_update_mac_c, k4); 160 | 161 | m4StarPlain[0] = (counter & 0xFF00000) >> 20; 162 | m4StarPlain[1] = (counter & 0xFF000) >> 12; 163 | m4StarPlain[2] = (counter & 0xFF0) >> 4; 164 | m4StarPlain[3] = ((counter & 0xF) << 4) | 0x8; 165 | 166 | /* Encrypt M4* */ 167 | stat = SECURITY_LoadPlainKey(SECURITY_INSTANCE0, k3, 500U); 168 | if (stat != STATUS_SUCCESS) 169 | return stat; 170 | 171 | stat = SECURITY_EncryptEcbBlocking(SECURITY_INSTANCE0, SECURITY_RAM_KEY, m4StarPlain, 16U, m4StarCipher, 500U); 172 | if (stat != STATUS_SUCCESS) 173 | return stat; 174 | 175 | /* Compute M4 = UID | ID | AuthID | M4* */ 176 | for (i = 0; i < 15; i++) 177 | { 178 | m4[i] = uid[i]; 179 | } 180 | m4[15] = ((keyId & 0xF) << 4) | (authId & 0xF); 181 | for (i = 0; i < 16; i++) 182 | { 183 | m4[16 + i] = m4StarCipher[i]; 184 | } 185 | 186 | stat = SECURITY_LoadPlainKey(SECURITY_INSTANCE0, k4, 500U); 187 | if (stat != STATUS_SUCCESS) 188 | return stat; 189 | 190 | stat = SECURITY_GenerateMacBlocking(SECURITY_INSTANCE0, SECURITY_RAM_KEY, m4, 256U, m5, 500U); 191 | if (stat != STATUS_SUCCESS) 192 | return stat; 193 | 194 | return STATUS_SUCCESS; 195 | } 196 | 197 | /* Sets the AuthID key (MASTER_ECU_KEY) for the first time */ 198 | bool HSM_SetAuthKey(void) 199 | { 200 | uint8_t uid[15] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 201 | uint8_t m1[16]; 202 | uint8_t m2[32]; 203 | uint8_t m3[16]; 204 | uint8_t m4[32]; 205 | uint8_t m5[16]; 206 | 207 | status_t stat; 208 | 209 | stat = HSM_ComputeM1M2M3(g_emptyKey, g_authId, SECURITY_MASTER_ECU, g_authIdKey, 1, uid, m1, m2, m3); 210 | if (stat != STATUS_SUCCESS) 211 | return false; 212 | 213 | stat = SECURITY_LoadKey(SECURITY_INSTANCE0, SECURITY_MASTER_ECU, m1, m2, m3, m4, m5, 500U); 214 | if (stat != STATUS_SUCCESS) 215 | return false; 216 | 217 | return true; 218 | } 219 | 220 | /* Extracts the UID. */ 221 | bool HSM_GetUID(uint8_t *uid) 222 | { 223 | status_t stat; 224 | uint8_t challenge[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 225 | uint8_t sreg; 226 | uint8_t mac[16]; 227 | uint8_t verif[32]; 228 | bool verifStatus; 229 | uint8_t i; 230 | 231 | stat = SECURITY_GetId(SECURITY_INSTANCE0, challenge, uid, &sreg, mac, 1U); 232 | if (stat != STATUS_SUCCESS) 233 | return false; 234 | 235 | for (i = 0; i < 16; i++) { 236 | verif[i] = challenge[i]; 237 | } 238 | for (i = 0; i < 15; i++) { 239 | verif[16 + i] = uid[i]; 240 | } 241 | verif[31] = sreg; 242 | 243 | stat = SECURITY_LoadPlainKey(SECURITY_INSTANCE0, g_authIdKey, 500U); 244 | if (stat != STATUS_SUCCESS) 245 | return false; 246 | 247 | stat = SECURITY_VerifyMacBlocking(SECURITY_INSTANCE0, SECURITY_RAM_KEY, verif, 256U, mac, 128U, &verifStatus, 500U); 248 | if (stat != STATUS_SUCCESS) 249 | return false; 250 | 251 | return verifStatus; 252 | } 253 | 254 | /* Erases all the keys. */ 255 | bool HSM_EraseKeys(void) 256 | { 257 | status_t stat; 258 | uint8_t challenge[16]; 259 | uint8_t auth[16]; 260 | uint8_t authPlain[31]; 261 | uint8_t k[16]; 262 | uint8_t uid[15]; 263 | 264 | uint8_t i; 265 | 266 | SECURITY_InitRng(SECURITY_INSTANCE0, 500u); 267 | 268 | HSM_GetUID(uid); 269 | 270 | HSM_DeriveKey(g_authIdKey, key_debug_key_c, k); 271 | 272 | stat = SECURITY_LoadPlainKey(SECURITY_INSTANCE0, k, 500U); 273 | if (stat != STATUS_SUCCESS) 274 | return false; 275 | 276 | stat = SECURITY_DbgChal(SECURITY_INSTANCE0, challenge, 500U); 277 | if (stat != STATUS_SUCCESS) 278 | return false; 279 | 280 | for (i = 0; i < 16; i++) 281 | { 282 | authPlain[i] = challenge[i]; 283 | } 284 | for (i = 0; i < 15; i++) 285 | { 286 | authPlain[i + 16] = uid[i]; 287 | } 288 | 289 | stat = SECURITY_GenerateMacBlocking(SECURITY_INSTANCE0, SECURITY_RAM_KEY, authPlain, 248U, auth, 500U); 290 | if (stat != STATUS_SUCCESS) 291 | return false; 292 | 293 | stat = SECURITY_DbgAuth(SECURITY_INSTANCE0, auth, 500U); 294 | if (stat != STATUS_SUCCESS) 295 | return false; 296 | 297 | return true; 298 | } 299 | 300 | /* Loads/updates a non-volatile key. */ 301 | bool HSM_LoadKey(security_key_id_t keyId, uint8_t *keyNew, uint8_t counter) 302 | { 303 | uint8_t uid[15] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 304 | uint8_t m1[16]; 305 | uint8_t m2[32]; 306 | uint8_t m3[16]; 307 | uint8_t m4[32]; 308 | uint8_t m5[16]; 309 | 310 | status_t stat; 311 | 312 | stat = HSM_ComputeM1M2M3(g_authIdKey, g_authId, keyId, keyNew, counter, uid, m1, m2, m3); 313 | if (stat != STATUS_SUCCESS) 314 | return false; 315 | 316 | 317 | stat = SECURITY_LoadKey(SECURITY_INSTANCE0, keyId, m1, m2, m3, m4, m5, 500u); 318 | if (stat != STATUS_SUCCESS) 319 | return false; 320 | 321 | return true; 322 | } 323 | -------------------------------------------------------------------------------- /_old/Framework/security/hsm_she.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 - 2016 , Freescale Semiconductor, Inc. 3 | * Copyright 2016-2017 NXP 4 | * All rights reserved. 5 | * 6 | * THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED OR 7 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 8 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 9 | * IN NO EVENT SHALL NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 10 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 11 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 12 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 13 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 14 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 15 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 16 | * THE POSSIBILITY OF SUCH DAMAGE. 17 | */ 18 | /* 19 | * csec_utils.h 20 | * 21 | * Created on: Nov 10, 2016 22 | * Author: B50609 23 | */ 24 | 25 | #ifndef HSM_SHE_H_ 26 | #define HSM_SHE_H_ 27 | 28 | //#include "hsm_driver.h" 29 | 30 | /* This function sets the MASTER_ECU key with a key (g_authIdKey) defined in the 31 | * csec_utils.c file. This key will be used as an authorization secret for updating 32 | * user keys. 33 | * Setting the MASTER_ECU key will work only for the first time, in order to use 34 | * another value for the key, there are two options: 35 | * - erase the keys and then update g_authIdKey; 36 | * - use loadKey with counter > 1 and then update g_authIdKey; 37 | * */ 38 | bool HSM_SetAuthKey(void); 39 | 40 | /* This function erases all the key. After using it, the Flash needs to be partitioned 41 | * again. 42 | * */ 43 | bool HSM_EraseKeys(void); 44 | 45 | /* This function loads/updates a non-volatile key. 46 | * When updating the key, the counter needs to be greater then the previous one. 47 | * */ 48 | bool HSM_LoadKey(security_key_id_t keyId, uint8_t *keyNew, uint8_t counter); 49 | 50 | ///* Extracts the UID. */ 51 | //bool HSM_GetUID(uint8_t *uid); 52 | // 53 | ///* Derives a key with a given constant */ 54 | //status_t HSM_DeriveKey(const uint8_t *key, uint8_t *constant, uint8_t *derivedKey); 55 | // 56 | ///* Computes the M1-M3 values */ 57 | //status_t HSM_ComputeM1M2M3(uint8_t *authKey, hsm_key_id_t authId, hsm_key_id_t keyId, const uint8_t *key, uint32_t counter, 58 | // uint8_t *uid, uint8_t *m1, uint8_t *m2, uint8_t *m3); 59 | // 60 | ///* Computes the M4 and M5 values */ 61 | //status_t HSM_ComputeM4M5(hsm_key_id_t authId, hsm_key_id_t keyId, const uint8_t *key, uint32_t counter, 62 | // uint8_t *uid, uint8_t *m4, uint8_t *m5); 63 | 64 | 65 | void HSM_initialise(void); 66 | 67 | #endif /* SOURCES_CSEC_UTILS_H_ */ 68 | 69 | -------------------------------------------------------------------------------- /_old/Sources/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 - 2015, Freescale Semiconductor, Inc. 3 | * Copyright 2016-2017 NXP 4 | * All rights reserved. 5 | * 6 | * THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED OR 7 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 8 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 9 | * IN NO EVENT SHALL NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 10 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 11 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 12 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 13 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 14 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 15 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 16 | * THE POSSIBILITY OF SUCH DAMAGE. 17 | */ 18 | #include 19 | #include 20 | #include 21 | 22 | #include "Cpu.h" 23 | #include "task.h" 24 | #include "framework.h" /* Gateway Framework */ 25 | 26 | volatile int exit_code = 0; 27 | 28 | // Enable when CUT3.0 arrives: 29 | // #define FEATURE_CAN_HAS_ISOCANFDEN_ENABLE 1 30 | 31 | #define TASK_PRIORITY_APP (tskIDLE_PRIORITY + 7) 32 | 33 | /* GPIO User Buttons & LEDs */ 34 | #define SW1_PORT PTA 35 | #define SW1_PIN 3 36 | #define SW2_PORT PTE 37 | #define SW2_PIN 10 38 | 39 | /* Function Prototypes */ 40 | void App_task(void* pvParameters); 41 | void initClocks(); 42 | void initPeripherals(); 43 | void keyOff(); 44 | 45 | /* Application demo task. When button A is pressed, GW will request updated information from all ECUs on network. 46 | * When button B is pressed, GW will update FW of all ECUs that have new FW in SD card 47 | */ 48 | void App_Task(void* pvParameters) 49 | { 50 | /* Initialise all peripherals: CAN, LIN, HSM, ETH, .. */ 51 | initPeripherals(); 52 | 53 | /* Add Gateway Heartbeat task to the FreeRTOS scheduler */ 54 | //xTaskCreate(Heartbeat_Task, "GW_Heartbeat", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY_HEART, NULL); 55 | 56 | while(1) 57 | { 58 | vTaskDelay(1000); /* Delay for 10 seconds */ 59 | } 60 | } 61 | 62 | 63 | int main(void) 64 | { 65 | /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/ 66 | #ifdef PEX_RTOS_INIT 67 | PEX_RTOS_INIT(); /* Initialization of the selected RTOS. Macro is defined by the RTOS component. */ 68 | #endif 69 | /*** End of Processor Expert internal initialization. ***/ 70 | 71 | /* 1. Initialise device clocking */ 72 | initClocks(); 73 | 74 | /* 2. Initialise the SW layers of the gateway framework */ 75 | //GW_initialise(); /* Initialise GW layer & FreeRTOS task */ 76 | PDU_initialise(); /* Initialise PDU layer & FreeRTOS task */ 77 | 78 | /* Start using DEV ASSERTS */ 79 | //DEV_ASSERT(status == STATUS_SUCCESS); 80 | 81 | /* Main user application task */ 82 | xTaskCreate(App_Task, "Application", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY_APP, NULL); 83 | // xTaskCreate(LWIP_Task, "LWIP", configMINIMAL_STACK_SIZE, NULL, TASK_PRIORITY_LWIP, NULL); 84 | 85 | 86 | /* The user must lastly initialise all lower level peripherals & interfaces 87 | * within their application task, for two reasons: 88 | * 89 | * 1. Interrupts (which are required by some modules) are not enabled until 90 | * the FreeRTOS scheduler has begun. 91 | * 2. It is important that all upper SW layers are in a prepared state to 92 | * receive and process packets. 93 | */ 94 | 95 | /* Start the tasks and timer running. */ 96 | vTaskStartScheduler(); 97 | 98 | /* If all is well, the scheduler will now be running, and the following 99 | line will never be reached. If the following line does execute, then 100 | there was insufficient FreeRTOS heap memory available for the idle and/or 101 | timer tasks to be created. See the memory management section on the 102 | FreeRTOS web site for more details. */ 103 | for (;; ); 104 | 105 | /*** Don't write any code pass this line, or it will be deleted during code generation. ***/ 106 | /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/ 107 | #ifdef PEX_RTOS_START 108 | PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */ 109 | #endif 110 | /*** End of RTOS startup code. ***/ 111 | /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ 112 | for(;;) { 113 | if(exit_code != 0) { 114 | break; 115 | } 116 | } 117 | return exit_code; 118 | /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ 119 | } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/ 120 | 121 | /* END main */ 122 | 123 | 124 | void initClocks() 125 | { 126 | CLOCK_SYS_Init(g_clockManConfigsArr, CLOCK_MANAGER_CONFIG_CNT, g_clockManCallbacksArr, CLOCK_MANAGER_CALLBACK_CNT); 127 | CLOCK_SYS_UpdateConfiguration(0U, CLOCK_MANAGER_POLICY_AGREEMENT); 128 | } 129 | void initPeripherals() 130 | { 131 | /* Initialisation of some of these peripherals must be done within a 132 | * FreeRTOS task when the FreeRTOS component is used in S32 DS project. 133 | * This is because all interrupts are disabled until FreeRTOS begins 134 | * the scheduler */ 135 | 136 | /***** Initialise all pins: ENET, CAN, UART, SDHC, LEDs *****/ 137 | PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr); 138 | //PINS_DRV_SetOutputBuffer(PTH, 8, 0, 0); 139 | SIUL2->MSCR[120] = 0x300B0005; 140 | 141 | vTaskDelay(100); /* Small delay to allow pins to stabilise */ 142 | 143 | #ifdef DEBUG_ENABLE 144 | /***** Initialise UART DEBUG Terminal *****/ 145 | CONSOLE_initialise(&CONSOLE_instance, &CONSOLE_Config0); 146 | #endif 147 | 148 | /***** Initialise Ethernet *****/ 149 | // This is performed within LWIP thread 150 | 151 | PINS_DRV_WritePin(PTD, 12, 1); // ON-OFF-CAN, 5V Vreg ON 152 | PINS_DRV_WritePin(PTD, 13, 1); // ON-OFF-ETH, 12V Vreg ON 153 | 154 | /***** Initialise SD Card ****/ 155 | SD_initialise(); 156 | 157 | /***** Initialise HSM/SHE ****/ 158 | HSM_initialise(); 159 | 160 | 161 | /***** Initialise LIN Interfaces *****/ 162 | //LIN_initialise(INST_LIN_0, &lin_1_State, &lin_1_InitConfig0); 163 | 164 | /***** Initialise CAN Interfaces ****/ 165 | CAN_initialise(&CAN0_instance, &CAN0_Config0); 166 | CAN_initialise(&CAN1_instance, &CAN1_Config0); 167 | CAN_initialise(&CAN2_instance, &CAN2_Config0); 168 | CAN_initialise(&CAN3_instance, &CAN3_Config0); 169 | 170 | /***** Switch on peripheral PHYs & Vregs ****/ 171 | PINS_DRV_WritePin(PTD, 12, 1); // ON-OFF-CAN, 5V Vreg ON 172 | PINS_DRV_WritePin(PTD, 13, 1); // ON-OFF-ETH, 12V Vreg ON 173 | //PINS_DRV_WritePin(PTF, 11, 1); // LIN1 SLP_N, Initialise low 174 | //PINS_DRV_WritePin(PTF, 13, 1); // LIN6 SLP_N, Initialise low 175 | 176 | } 177 | 178 | ///* Trigger event for updating FW of all ECUs requiring update */ 179 | //void keyOff() 180 | //{ 181 | // FIL fw; /* FW update of ECU */ 182 | // FRESULT res; 183 | // status_t status; 184 | // uint16_t i; 185 | // 186 | // /* Loop through all ECUs to check which require to be updated */ 187 | // for(i = 0 ; i < NUM_OF_ECUS ; i++) 188 | // { 189 | // res = SD_openLatestFW(i, &fw); 190 | // 191 | // if(FR_OK == res) 192 | // { 193 | // status = ECU_updateFirmware(i, &fw, true); 194 | // 195 | // if(status == STATUS_SUCCESS) 196 | // { 197 | // ECU_sendCommand(i, ECU_CMD_REQ_FWVER); /* Update FW version of ECU */ 198 | // 199 | // SD_storeECUInfo(i); /* Update ECU information on SD card */ 200 | // } 201 | // else { 202 | // printf("Failed to UPDATE firmware of ECU %d", i); 203 | // } 204 | // } 205 | // else if(FR_NO_FILE == res) 206 | // { 207 | // printf("ECU %d : new firmware not found", i); 208 | // } 209 | // f_close(&fw); 210 | // } 211 | //} 212 | -------------------------------------------------------------------------------- /_old/Sources/tables/can_filter.c: -------------------------------------------------------------------------------- 1 | /* 2 | * can_filter.c 3 | * 4 | * Created on: 28 Mar 2018 5 | * Author: B49855 6 | */ 7 | #include "config.h" 8 | 9 | /* The CAN MSG ID filter table performs one function: 10 | * 1. Acept frames with a MSG ID found within the filter table. 11 | */ 12 | /********************* CAN FILTER TABLE ********************/ 13 | /***********************************************************/ 14 | uint32_t CAN_ID_FilterTable[NUM_OF_CANID_FILTERS] = {0, 1, 2, 3, 4, 5, 7, 8, 9}; 15 | /***********************************************************/ 16 | -------------------------------------------------------------------------------- /_old/Sources/tables/ecu_table.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ecu_table.c 3 | * 4 | * Created on: 28 Mar 2018 5 | * Author: B49855 6 | */ 7 | #include "config.h" 8 | #include "Cpu.h" 9 | 10 | /* @brief: This is the global list of ECUs within the vehicle. It is maintained in RAM 11 | * and is backed up to SD card on key-off signal. 12 | */ 13 | /*********************** ECU DATABASE **********************/ 14 | /***********************************************************/ 15 | ECU ecu_list[NUM_OF_ECUS] = 16 | { 17 | { 18 | /* 0: Engine ECU */ 19 | .protocol = PROTOCOL_CAN, /* CAN Protocol */ 20 | .instance = 0, /* CAN_0 Instance */ 21 | .fw_version = 1 22 | }, 23 | { 24 | /* 1: Drive Control ECU */ 25 | .protocol = PROTOCOL_CAN, /* CAN Protocol */ 26 | .instance = 1, /* CAN_1 Instance */ 27 | .fw_version = 1 28 | }, 29 | { 30 | /* 2: Cluster ECU */ 31 | .protocol = PROTOCOL_CAN, /* CAN Protocol */ 32 | .instance = 2, /* CAN_2 Instance */ 33 | .fw_version = 1 34 | }, 35 | { 36 | /* 3: Diagnostics ECU */ 37 | .protocol = PROTOCOL_CAN, /* CAN Protocol */ 38 | .instance = 3, /* CAN_3 Instance */ 39 | .fw_version = 1 40 | } 41 | }; 42 | 43 | -------------------------------------------------------------------------------- /_old/Sources/tables/pdu_table.c: -------------------------------------------------------------------------------- 1 | /* 2 | * pdu_table.c 3 | * 4 | * Created on: 28 Mar 2018 5 | * Author: B49855 6 | */ 7 | #include "config.h" 8 | 9 | /* # The PDUs IDs are implicitly defined by their index within the array. 10 | * # PDUs MUST be arranged in an ascending order with no missing values. 11 | * # PDUs for resquest/respond command protocol are derived from ECU ID to 12 | * to save RAM in PDU_Table. 13 | */ 14 | /******************** PDU ROUTING TABLE ********************/ 15 | /***********************************************************/ 16 | PDU_Desc PDU_Descriptors[NUM_OF_PDU_TYPES] = 17 | { 18 | { 19 | .label = "Engine RPM", 20 | .destCount = 2, 21 | .dest = (uint8_t[]) {3, 2} // ... 22 | //.destCount = 1, 23 | //.dest = (uint8_t[]) {2} // ... 24 | }, 25 | { 26 | .label = "Engine Temp", 27 | .destCount = 2, 28 | .dest = (uint8_t[]) {3, 2} // ... 29 | }, 30 | { 31 | .label = "Ignition Switch", 32 | .destCount = 2, 33 | .dest = (uint8_t[]) {3, 0} // ... 34 | }, 35 | { 36 | .label = "Acceleration Pedal", 37 | .destCount = 2, 38 | .dest = (uint8_t[]) {3, 0} // ... 39 | }, 40 | { 41 | .label = "Handbrake", 42 | .destCount = 2, 43 | .dest = (uint8_t[]) {3, 2} // ... 44 | } 45 | }; 46 | /***********************************************************/ 47 | 48 | 49 | 50 | //tRxPDUDesc PDU_Desc[1] = 51 | //{ 52 | // { 53 | // .id = 0x5A5A5A5A, 54 | // .length = 15, 55 | // .num_of_signals = 2, 56 | // .signalDesc = (tSignalDescr[]) { } 57 | // 58 | // } 59 | //}; 60 | -------------------------------------------------------------------------------- /_old/gateway.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Gateway.h* 3 | * 4 | * Created on: 18 Sep 2018 5 | * Author: nxa20140 6 | */ 7 | 8 | #ifndef GATEWAY_H_ 9 | #define GATEWAY_H_ 10 | 11 | /*! 12 | * @brief The event for uSDHC. This enumeration is used to register the callback function. 13 | * Implements : usdhc_event_t_Class 14 | */ 15 | typedef enum 16 | { 17 | /* Gateway events */ 18 | GW_EVENT_FRAME_RECEIVED, /* Transfer completion event */ 19 | GW_EVENT_FRAME_TRANSMITTED, 20 | GW_EVENT_FRAME_ACCEPTED, /* Card insertion event */ 21 | GW_EVENT_FRAME_REJECTED, /* Card removal event */ 22 | /* Gateway CAN events */ 23 | GW_EVENT_CAN_TIMEOUT, 24 | } gw_event_t; 25 | 26 | typedef enum 27 | { 28 | GW_STATUS_IDLE, /* Gateway is idle */ 29 | GW_STATUS_RECEIVING_FRAME, /* Gateway is currently receiving a frame */ 30 | GW_STATUS_TRANSMITING_FRAME, /* Gateway is currently transmitting a frame */ 31 | GW_STATUS_FILTERING_FRAME, /* Gateway is currently filtering a frame */ 32 | GW_STATUS_ROUTING_FRAME /* Gateway is currently routing a frame */ 33 | } gw_status_t; 34 | 35 | 36 | 37 | typedef void (*gw_event_callback_t)(gw_state_t *gwState, 38 | gw_event_t eventType); 39 | 40 | typedef bool (*gw_filter_callback_t)(gw_state_t *gwState, 41 | gw_event_t eventType, 42 | uint32_t channelID, 43 | uint32_t frameID); 44 | 45 | typedef uint32_t (*gw_routing_callback_t)(gw_state_t *gwState, 46 | gw_event_t eventType, 47 | uint32_t channelID, 48 | uint32_t frameID); 49 | 50 | 51 | typedef struct 52 | { 53 | volatile gw_status_t status; /* Current status of gateway */ 54 | gw_event_callback_t eventCallback; /* Callback function for events */ 55 | gw_filter_callback_t filterCallback; /* Callback function for filtering operation */ 56 | gw_routing_callback_t lookupCallback; /* Callback function for lookup operation */ 57 | } gw_state_t; 58 | 59 | 60 | /*! @brief Data structure to initialise the uSDHC 61 | * Implements : usdhc_config_t_Class 62 | */ 63 | typedef struct 64 | { 65 | void * routingTable; /*!< ADMA table for transferring with ADMA1 and ADMA2 mode. */ 66 | uint32_t routingTableSize; /*!< The size of ADMA table in bytes */ 67 | void * canConfigTable; 68 | uint32_t canConfigTableSize; 69 | } gw_config_t; 70 | 71 | void GW_Initialise(gw_config_t *config); /* Initialise the Gateway core */ 72 | void GW_Deinitialise(void); /* De-initialise the Gateway core */ 73 | void GW_EnableInput(uint8_t canInstance); /* Enable CAN channel's input */ 74 | void GW_EnableOutput(uint8_t canInstance); /* Enable CAN channel's output */ 75 | void GW_DisableInput(uint8_t canInstance); /* Disable CAN channel's input */ 76 | void GW_DisableOutput(uint8_t canInstance); /* Disable CAN channel's output */ 77 | //void GW_EnableTimer(void); 78 | //void GW_Tick(void); 79 | 80 | /*! 81 | * @brief Installs a callback function for the IRQ handler. 82 | * @param callback The callback function. 83 | */ 84 | void GW_InstallEventCallback(gw_event_callback_t callback); 85 | /*! 86 | * @brief Installs an error callback function for the IRQ handler and enables error interrupts. 87 | * @param callback The error callback function. 88 | */ 89 | void GW_InstallRoutingCallback(gw_routing_callback_t callback); 90 | /*! 91 | * @brief Installs an error callback function for the IRQ handler and enables error interrupts. 92 | * @param callback The error callback function. 93 | */ 94 | void GW_InstallFilterCallback(gw_filter_callback_t callback); 95 | 96 | 97 | #endif /* GATEWAY_H_ */ 98 | -------------------------------------------------------------------------------- /examples/linux/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "xcan_stack.h" 5 | #include "xcan_dev_socketcan.h" 6 | 7 | extern struct xcan_routing_table routing_table; 8 | 9 | int main(int argc, char *argv[]) 10 | { 11 | struct xcan_device *dev0, *dev1; 12 | 13 | printf("***** XXCAN Linux Example *****\n"); 14 | #ifdef DEBUG 15 | printf("Debug: Enabled\n\n"); 16 | #else 17 | printf("Debug: Disabled\n\n"); 18 | #endif 19 | 20 | /** 21 | * Initialise XCAN stack. 22 | */ 23 | xcan_stack_init(&routing_table); 24 | 25 | /** 26 | * Register CAN-bus interfaces. 27 | */ 28 | dev0 = xcan_socketcan_create(0, "vcan0"); 29 | if(!dev0) 30 | return -1; 31 | 32 | dev1 = xcan_socketcan_create(1, "vcan1"); 33 | if(!dev1) 34 | return -1; 35 | 36 | /** 37 | * Process CAN frames. 38 | */ 39 | while(1) 40 | { 41 | xcan_stack_tick(); 42 | sleep(2); 43 | } 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /examples/linux/routing_table.c: -------------------------------------------------------------------------------- 1 | #include "xcan_router.h" 2 | 3 | struct xcan_routing_table routing_table = { 4 | .no_entries = 3, 5 | .entry = (struct xcan_routing_entry[]) { 6 | { 7 | .can_id = 0, 8 | .no_interfaces = 2, 9 | .interface_id = (uint8_t[]) { 1, 2 } 10 | }, 11 | { 12 | .can_id = 1, 13 | .no_interfaces = 2, 14 | .interface_id = (uint8_t[]) { 0, 1 } 15 | 16 | }, 17 | { 18 | .can_id = 2, 19 | .no_interfaces = 2, 20 | .interface_id = (uint8_t[]) { 0, 2 } 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /modules/xcan_dev_socketcan.c: -------------------------------------------------------------------------------- 1 | #include "xcan_dev_socketcan.h" 2 | #include "xcan_stack.h" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | 16 | struct xcan_device_socketcan { 17 | struct xcan_device dev; 18 | // Anything else specific to SocketCAN 19 | int fd; 20 | }; 21 | 22 | 23 | /* ================================================================= */ 24 | /* ======================= PRIVATE ======================= */ 25 | /* ================================================================= */ 26 | 27 | int prv_link_state(struct xcan_device *dev) 28 | { 29 | struct xcan_device_socketcan *sc = (struct xcan_device_socketcan *) dev; 30 | (void)sc; 31 | 32 | return 1; 33 | } 34 | 35 | int prv_send(struct xcan_device *self, uint32_t id, uint8_t flags, uint8_t *data, uint8_t len) 36 | { 37 | struct xcan_device_socketcan *sc = (struct xcan_device_socketcan *) self; 38 | 39 | struct canfd_frame frame; 40 | frame.can_id = id; 41 | frame.flags = flags; 42 | frame.len = len; 43 | memcpy(frame.data, data, len); 44 | 45 | int frame_len = 0; 46 | int nbytes; 47 | 48 | if(len > 8) { 49 | frame_len = sizeof(struct canfd_frame); 50 | } else{ 51 | frame_len = sizeof(struct can_frame); 52 | } 53 | 54 | nbytes = write(sc->fd, &frame, frame_len); 55 | dbg("SocketCAN (%s): Sent %d bytes\n", sc->dev.name, nbytes); 56 | return nbytes; 57 | } 58 | 59 | int prv_poll(struct xcan_device *self, int loop_score) 60 | { 61 | struct xcan_device_socketcan *sc = (struct xcan_device_socketcan *) self; 62 | 63 | struct canfd_frame f; 64 | int nbytes; 65 | 66 | nbytes = read(sc->fd, &f, sizeof(struct can_frame)); 67 | 68 | if(nbytes == CAN_MTU) { 69 | dbg("SocketCAN (%s): Received CAN frame\n", sc->dev.name); 70 | } else if(nbytes == CANFD_MTU) { 71 | dbg("SocketCAN (%s): Received CAN-FD frame\n", sc->dev.name); 72 | } else { 73 | dbg("SocketCAN (%s): Received unknown frame\n", sc->dev.name); 74 | } 75 | 76 | xcan_stack_recv(self, f.can_id, f.flags, f.data, f.len); 77 | 78 | return 0; 79 | } 80 | 81 | /* ================================================================= */ 82 | /* ======================= PUBLIC ======================== */ 83 | /* ================================================================= */ 84 | 85 | 86 | void xcan_socketcan_destroy(struct xcan_device *dev) 87 | { 88 | struct xcan_device_socketcan *sc = (struct xcan_device_socketcan *) dev; 89 | 90 | if(close(sc->fd) < 0) { 91 | dbg("SocketCAN (%s): Failed to close socket\n", sc->dev.name); 92 | } 93 | 94 | free(sc); 95 | dbg("SocketCAN (%s): Destroyed.\n", sc->dev.name); 96 | } 97 | 98 | 99 | struct xcan_device* xcan_socketcan_create(uint8_t id, char *name) 100 | { 101 | struct xcan_device_socketcan *sc = XCAN_ZALLOC(sizeof(struct xcan_device_socketcan)); 102 | 103 | struct sockaddr_can addr; 104 | struct ifreq ifr; 105 | 106 | if(!sc) 107 | return NULL; 108 | 109 | /* Initialise SocketCAN interface */ 110 | if((sc->fd = socket(PF_CAN, SOCK_RAW, CAN_RAW_FD_FRAMES)) < 0) { 111 | dbg("SocketCAN (%s): Failed to open socket", name); 112 | return NULL; 113 | } 114 | 115 | /* Retrieve the correct interface name */ 116 | strcpy(ifr.ifr_name, name); 117 | ioctl(sc->fd, SIOCGIFINDEX, &ifr); 118 | 119 | /* Bind socket */ 120 | addr.can_family = AF_CAN; 121 | addr.can_ifindex = ifr.ifr_ifindex; 122 | if(bind(sc->fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { 123 | perror("SocketCAN: Failed to bind socket"); 124 | return NULL; 125 | } 126 | 127 | /* Register SocketCAN interface as XCAN device */ 128 | if( 0 != xcan_device_init((struct xcan_device *) sc, id, name)) { 129 | dbg("SocketCAN (%s): Failed to init XCAN device\n", name); 130 | xcan_socketcan_destroy((struct xcan_device*) sc); 131 | return NULL; 132 | } 133 | 134 | /* Fill in vtable */ 135 | sc->dev.link_state = prv_link_state; 136 | sc->dev.send = prv_send; 137 | sc->dev.poll = prv_poll; 138 | sc->dev.destroy = xcan_socketcan_destroy; 139 | dbg("SocketCAN (%s): XCAN Device created\n", name); 140 | return (struct xcan_device *) sc; 141 | } 142 | -------------------------------------------------------------------------------- /modules/xcan_dev_socketcan.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_DEV_SOCKETCAN_H 2 | #define XCAN_DEV_SOCKETCAN_H 3 | 4 | #include "xcan_device.h" 5 | 6 | void xcan_socketcan_destroy(struct xcan_device *dev); 7 | 8 | struct xcan_device* xcan_socketcan_create(uint8_t id, char *name); 9 | 10 | #endif /* XCAN_DEV_SOCKETXCAN_H */ 11 | -------------------------------------------------------------------------------- /stack/include/xcan_config.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_CONFIG_H 2 | #define XCAN_CONFIG_H 3 | 4 | #ifndef __KERNEL__ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #else 11 | #include 12 | #endif /* __KERNEL__ */ 13 | 14 | #ifdef DEBUG 15 | #include 16 | #define dbg printf 17 | #else 18 | #define dbg 19 | #endif 20 | 21 | #define XCAN_ZALLOC(x) calloc(x, 0) 22 | #define XCAN_FREE(x) free(x) 23 | 24 | #endif /* XCAN_CONFIG_H */ -------------------------------------------------------------------------------- /stack/include/xcan_device.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_DEVICE_H 2 | #define XCAN_DEVICE_H 3 | 4 | #include "xcan_config.h" 5 | #include "xcan_queue.h" 6 | #include "xcan_frame.h" 7 | 8 | #define XCAN_MAX_DEVICE_NAME 16 9 | 10 | #define XCAN_MAX_DEVICES 4 11 | 12 | struct xcan_device { 13 | uint8_t id; 14 | char name[XCAN_MAX_DEVICE_NAME]; 15 | struct xcan_queue *q_in; 16 | struct xcan_queue *q_out; 17 | int (*link_state)(struct xcan_device *self); 18 | int (*send)(struct xcan_device *self, uint32_t id, uint8_t flags, uint8_t *data, uint8_t len); 19 | int (*poll)(struct xcan_device *self, int loop_score); 20 | void (*destroy)(struct xcan_device *self); 21 | }; 22 | 23 | int xcan_device_init(struct xcan_device *dev, uint8_t id, const char *name); 24 | 25 | void xcan_device_destroy(struct xcan_device *dev); 26 | 27 | int xcan_devices_loop(int loop_score, int direction); 28 | 29 | struct xcan_device* xcan_get_device(uint8_t id); 30 | 31 | int xcan_device_link_state(struct xcan_device *dev); 32 | 33 | #endif /* XCAN_DEVICE_H */ 34 | -------------------------------------------------------------------------------- /stack/include/xcan_frame.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_FRAME_H 2 | #define XCAN_FRAME_H 3 | 4 | #include "xcan_config.h" 5 | 6 | struct xcan_frame { 7 | 8 | /* Connect for queues */ 9 | struct xcan_frame *next; 10 | 11 | /* Pointer to XCAN device this frame belongs to */ 12 | struct xcan_device *dev; 13 | 14 | uint32_t id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ 15 | uint8_t flags; /* Flags */ 16 | uint16_t len; /* Frame payload length in bytes */ 17 | uint8_t *data; /* Frame payload buffer */ 18 | 19 | /* Pointer to frame usage count, which is stored in the last byte 20 | after the frame buffer */ 21 | uint8_t *usage_count; 22 | }; 23 | 24 | void xcan_frame_discard(struct xcan_frame *f); 25 | 26 | struct xcan_frame* xcan_frame_alloc(uint32_t size); 27 | 28 | struct xcan_frame* xcan_frame_copy(struct xcan_frame *f); 29 | 30 | struct xcan_frame* xcan_frame_deepcopy(struct xcan_frame *f); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /stack/include/xcan_queue.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_QUEUE_H 2 | #define XCAN_QUEUE_H 3 | 4 | #include "xcan_config.h" 5 | #include "xcan_frame.h" 6 | 7 | struct xcan_queue { 8 | uint32_t frames; 9 | uint32_t max_frames; 10 | struct xcan_frame *head; 11 | struct xcan_frame *tail; 12 | }; 13 | 14 | static inline int xcan_enqueue(struct xcan_queue *q, struct xcan_frame *f) 15 | { 16 | if((q->max_frames) && (q->frames >= q->max_frames)) { 17 | /* Queue full */ 18 | return -1; 19 | } 20 | 21 | f->next = NULL; 22 | if(!q->head) { 23 | /* Queue is empty */ 24 | q->head = f; 25 | q->tail = f; 26 | q->frames = 0; 27 | } else { 28 | /* Add frame to tail */ 29 | q->tail->next = f; 30 | q->tail = f; 31 | } 32 | 33 | q->frames++; 34 | return 0; 35 | } 36 | 37 | static inline struct xcan_frame* xcan_dequeue(struct xcan_queue *q) 38 | { 39 | struct xcan_frame *f = q->head; 40 | 41 | if(!f) 42 | return NULL; 43 | 44 | if(q->frames < 1) 45 | return NULL; 46 | 47 | /* New head is 1 before frame */ 48 | q->head = f->next; 49 | q->frames--; 50 | 51 | if(q->head == NULL) 52 | q->tail = NULL; 53 | 54 | f->next = NULL; 55 | return f; 56 | } 57 | 58 | static inline struct xcan_frame* xcan_queue_peek(struct xcan_queue *q) 59 | { 60 | struct xcan_frame *f = q->head; 61 | if(q->frames < 1) 62 | return NULL; 63 | 64 | return f; 65 | } 66 | 67 | static inline void xcan_queue_empty(struct xcan_queue *q) 68 | { 69 | struct xcan_frame *f = xcan_dequeue(q); 70 | while(f) { 71 | xcan_frame_discard(f); 72 | f = xcan_dequeue(q); 73 | } 74 | } 75 | 76 | #endif /* XCAN_QUEUE_H */ -------------------------------------------------------------------------------- /stack/include/xcan_router.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_ROUTER_H 2 | #define XCAN_ROUTER_H 3 | 4 | #include "xcan_config.h" 5 | #include "xcan_frame.h" 6 | 7 | 8 | struct xcan_routing_table { 9 | struct xcan_routing_entry *entry; 10 | uint32_t no_entries; 11 | }; 12 | 13 | struct xcan_routing_entry { 14 | uint32_t can_id; 15 | uint8_t *interface_id; 16 | uint8_t no_interfaces; 17 | }; 18 | 19 | int xcan_router_init(struct xcan_routing_table *routing_table); 20 | 21 | int xcan_router_receive(struct xcan_frame *f); 22 | 23 | 24 | int xcan_router_loop(int loop_score); 25 | 26 | #endif -------------------------------------------------------------------------------- /stack/include/xcan_stack.h: -------------------------------------------------------------------------------- 1 | #ifndef XCAN_STACK_H 2 | #define XCAN_STACK_H 3 | 4 | #include "xcan_config.h" 5 | #include "xcan_device.h" 6 | 7 | /******************************************************************************* 8 | * DATALINK LAYER 9 | ******************************************************************************/ 10 | 11 | int xcan_datalink_receive(struct xcan_frame *f); 12 | 13 | int xcan_datalink_send(struct xcan_frame *f); 14 | 15 | /******************************************************************************* 16 | * PHYSICAL LAYER 17 | ******************************************************************************/ 18 | 19 | int xcan_stack_recv(struct xcan_device * dev, 20 | uint32_t can_id, 21 | uint8_t flags, 22 | uint8_t const * data, 23 | uint8_t len); 24 | 25 | 26 | 27 | int xcan_sendto_dev() 28 | 29 | 30 | /* ------- Initialisation ------- */ 31 | int xcan_stack_init(struct xcan_routing_table *routing_table); 32 | 33 | /* ------- Loop Function -------- */ 34 | void xcan_stack_tick(void); 35 | 36 | #endif -------------------------------------------------------------------------------- /stack/xcan_device.c: -------------------------------------------------------------------------------- 1 | #include "xcan_device.h" 2 | #include "xcan_stack.h" 3 | 4 | struct xcan_device *devices[XCAN_MAX_DEVICES]; 5 | 6 | static int devloop_in(struct xcan_device *dev, int loop_score) 7 | { 8 | struct xcan_frame *f; 9 | 10 | if(!dev) 11 | return loop_score; 12 | 13 | while(loop_score > 0) 14 | { 15 | if(dev->q_in->frames == 0) 16 | break; 17 | 18 | f = xcan_dequeue(dev->q_in); 19 | if(f) { 20 | xcan_datalink_receive(f); 21 | loop_score--; 22 | } 23 | } 24 | 25 | return loop_score; 26 | } 27 | 28 | static int devloop_out(struct xcan_device *dev, int loop_score) 29 | { 30 | struct xcan_frame *f; 31 | 32 | if(!dev) 33 | return loop_score; 34 | 35 | while(loop_score > 0) 36 | { 37 | if(dev->q_out->frames == 0) 38 | break; 39 | 40 | /* We just peek incase device is unable to send frame, 41 | then we retain it */ 42 | f = xcan_queue_peek(dev->q_out); 43 | if(!f) 44 | break; 45 | 46 | if(dev->send(dev, f->id, f->flags, f->data, f->len) == 0) { 47 | /* Frame successfully sent */ 48 | f = xcan_dequeue(dev->q_out); 49 | xcan_frame_discard(f); 50 | loop_score--; 51 | } else { 52 | /* Failed to send frame, try again next time round */ 53 | break; 54 | } 55 | } 56 | 57 | return loop_score; 58 | } 59 | 60 | 61 | int xcan_device_init(struct xcan_device *dev, uint8_t id, const char *name) 62 | { 63 | if(id >= XCAN_MAX_DEVICES) 64 | return -1; 65 | 66 | dev->id = id; 67 | strncpy(dev->name, name, XCAN_MAX_DEVICE_NAME); 68 | 69 | dev->q_in = XCAN_ZALLOC(sizeof(struct xcan_queue)); 70 | if(!dev->q_in) 71 | return -1; 72 | 73 | dev->q_out = XCAN_ZALLOC(sizeof(struct xcan_queue)); 74 | if(!dev->q_out) { 75 | XCAN_FREE(dev->q_in); 76 | return -1; 77 | } 78 | 79 | /* Register device with device pool */ 80 | devices[id] = dev; 81 | return 0; 82 | } 83 | 84 | 85 | void xcan_device_destroy(struct xcan_device *dev) 86 | { 87 | /* Unregister device with device pool */ 88 | devices[dev->id] = NULL; 89 | 90 | /* Call device specific destroyer */ 91 | dev->destroy(dev); 92 | } 93 | 94 | 95 | 96 | int xcan_devices_loop(int loop_score, int direction) 97 | { 98 | /** @todo */ 99 | 100 | while(loop_score > 0) 101 | { 102 | if(direction == 0) 103 | { 104 | /* Receiving frames into the stack */ 105 | for(int i = 0 ; i < XCAN_MAX_DEVICES ; i++) { 106 | loop_score = devloop_in(devices[i], loop_score); 107 | } 108 | } 109 | else if(direction == 1) 110 | { 111 | /* Sending frames out of the stack */ 112 | for(int i = 0 ; i < XCAN_MAX_DEVICES ; i++) { 113 | loop_score = devloop_out(devices[i], loop_score); 114 | } 115 | } 116 | 117 | loop_score--; 118 | } 119 | 120 | return loop_score; 121 | } 122 | 123 | struct xcan_device* xcan_get_device(uint8_t id) 124 | { 125 | for(int i = 0 ; i < XCAN_MAX_DEVICES ; i++) { 126 | if(devices[i]->id == id) { 127 | return devices[i]; 128 | } 129 | } 130 | return NULL; 131 | } 132 | 133 | int xcan_device_link_state(struct xcan_device *dev) 134 | { 135 | return dev->link_state(dev); 136 | } -------------------------------------------------------------------------------- /stack/xcan_frame.c: -------------------------------------------------------------------------------- 1 | #include "xcan_frame.h" 2 | 3 | static struct xcan_frame* xcan_frame_do_alloc(uint32_t size) 4 | { 5 | struct xcan_frame *f = XCAN_ZALLOC(sizeof(struct xcan_frame)); 6 | 7 | if(!f) 8 | return NULL; 9 | 10 | /* Allocate space for frame payload and usage counter */ 11 | f->data = XCAN_ZALLOC(size + sizeof(uint8_t)); 12 | if(!f->data) 13 | XCAN_FREE(f); 14 | 15 | f->len = size; 16 | f->flags = 0; 17 | f->usage_count = (f->data + size); 18 | return f; 19 | } 20 | 21 | void xcan_frame_discard(struct xcan_frame *f) 22 | { 23 | if(!f) 24 | return; 25 | 26 | *(f->usage_count) += -1; 27 | 28 | if(*f->usage_count == 0) { 29 | XCAN_FREE(f->data); 30 | XCAN_FREE(f); 31 | } 32 | } 33 | 34 | struct xcan_frame* xcan_frame_alloc(uint32_t size) 35 | { 36 | return xcan_frame_do_alloc(size); 37 | } 38 | 39 | /* Only copies frame descriptor, not frame payload. */ 40 | struct xcan_frame* xcan_frame_copy(struct xcan_frame *f) 41 | { 42 | struct xcan_frame *new = XCAN_ZALLOC(sizeof(struct xcan_frame)); 43 | 44 | if(!new) 45 | return NULL; 46 | 47 | memcpy(new, f, sizeof(struct xcan_frame)); 48 | *(new->usage_count) += 1; 49 | new->next = NULL; 50 | return new; 51 | } 52 | 53 | struct xcan_frame* xcan_frame_deepcopy(struct xcan_frame *f) 54 | { 55 | struct xcan_frame *new = xcan_frame_copy(f); 56 | 57 | if(!f) 58 | return NULL; 59 | 60 | new->data = XCAN_ZALLOC(new->len + sizeof(uint8_t)); 61 | memcpy(new->data, f->data, new->len); 62 | 63 | new->usage_count = new->data + new->len; 64 | *(new->usage_count) = 1; 65 | return new; 66 | } 67 | -------------------------------------------------------------------------------- /stack/xcan_router.c: -------------------------------------------------------------------------------- 1 | #include "xcan_router.h" 2 | #include "xcan_device.h" 3 | #include "xcan_queue.h" 4 | 5 | static struct xcan_routing_table *m_tbl; 6 | 7 | 8 | static int route_frame(struct xcan_frame, int loop_score) 9 | { 10 | for(int i = 0 ; i < m_tbl->no_entries ; i++) 11 | { 12 | if(m_tbl->entry[i].can_id == f->id) 13 | { 14 | for(int i = 0 ; i < m_tbl->entry[i].no_interfaces ; i++) 15 | { 16 | if(xcan_enqueue(m_tbl->entry[i].interface_id[i]) == 0) { 17 | loop_score--; 18 | } 19 | xcan_device_send 20 | } 21 | } 22 | } 23 | loop_score--; 24 | 25 | return loop_score; 26 | } 27 | 28 | 29 | int xcan_router_init(struct xcan_routing_table *routing_table) 30 | { 31 | m_tbl = routing_table; 32 | } 33 | 34 | 35 | int xcan_router_receive(struct xcan_frame *f) 36 | { 37 | dbg("XCAN Router: Received a frame!"); 38 | return 0; 39 | } 40 | 41 | 42 | int xcan_router_loop(int loop_score) 43 | { 44 | struct xcan_frame *f; 45 | 46 | while(loop_score > 0) 47 | { 48 | if(dev->q_in->frames == 0) 49 | break; 50 | 51 | f = xcan_dequeue(dev->q_in); 52 | if(f) { 53 | loop_score = route_frame(f, loop_score); 54 | } 55 | } 56 | 57 | return loop_score; 58 | } -------------------------------------------------------------------------------- /stack/xcan_stack.c: -------------------------------------------------------------------------------- 1 | #include "xcan_stack.h" 2 | #include "xcan_router.h" 3 | 4 | #define XCAN_LOOP_DIR_IN 0 5 | #define XCAN_LOOP_DIR_OUT 1 6 | 7 | 8 | /******************************************************************************* 9 | * DATALINK LAYER 10 | ******************************************************************************/ 11 | 12 | int xcan_datalink_receive(struct xcan_frame *f) 13 | { 14 | return xcan_router_receive(f); 15 | } 16 | 17 | int xcan_datalink_send(struct xcan_frame *f) 18 | { 19 | return 0; 20 | } 21 | 22 | /******************************************************************************* 23 | * PHYSICAL LAYER 24 | ******************************************************************************/ 25 | 26 | int xcan_stack_recv(struct xcan_device * dev, 27 | uint32_t can_id, 28 | uint8_t flags, 29 | uint8_t const * data, 30 | uint8_t len) 31 | { 32 | struct xcan_frame *f = xcan_frame_alloc(len); 33 | 34 | if(!f) 35 | return 1; 36 | 37 | f->dev = dev; 38 | f->id = can_id; 39 | memcpy(f->data, data, len); 40 | 41 | if(xcan_enqueue(dev->q_in, f) != 0) { 42 | xcan_frame_discard(f); 43 | return 1; 44 | } 45 | 46 | return 0; 47 | } 48 | 49 | 50 | /* ------- Initialisation ------- */ 51 | int xcan_stack_init(struct xcan_routing_table *routing_table) 52 | { 53 | /* Initialise XCAN Router */ 54 | if(!xcan_router_init(routing_table)) 55 | return 1; 56 | 57 | return 0; 58 | } 59 | 60 | /* ------- Loop Function -------- */ 61 | void xcan_stack_tick(void) 62 | { 63 | int loop_score = 20; 64 | 65 | /* Receive up to 10 CAN frames into the stack */ 66 | loop_score = xcan_devices_loop(loop_score, XCAN_LOOP_DIR_IN); 67 | 68 | /* Send up to 10 CAN frames out of the stack */ 69 | loop_score = xcan_devices_loop(loop_score, XCAN_LOOP_DIR_OUT); 70 | } --------------------------------------------------------------------------------