├── .gitignore ├── .gitmodules ├── AUTHORS ├── CHANGELOG.md ├── CMakeLists.txt ├── COPYING ├── HOWTO ├── INSTALL ├── LICENSE ├── LICENSE.BSD3Clause ├── README.md ├── TODO ├── doc ├── Doxyfile ├── mainpage.dox └── protocol.txt ├── hdlcd.kdev4 └── src ├── CMakeLists.txt ├── Config.h.in ├── HdlcdServer ├── AliveGuard.h ├── HdlcdServerHandler.cpp ├── HdlcdServerHandler.h ├── HdlcdServerHandlerCollection.cpp ├── HdlcdServerHandlerCollection.h ├── LockGuard.cpp └── LockGuard.h ├── SerialPort ├── BaudRate.h ├── HDLC │ ├── AliveState.cpp │ ├── AliveState.h │ ├── BufferType.h │ ├── FCS16.cpp │ ├── FCS16.h │ ├── FrameGenerator.cpp │ ├── FrameGenerator.h │ ├── FrameParser.cpp │ ├── FrameParser.h │ ├── HdlcFrame.cpp │ ├── HdlcFrame.h │ ├── ISerialPortHandler.h │ ├── ProtocolState.cpp │ └── ProtocolState.h ├── SerialPortHandler.cpp ├── SerialPortHandler.h ├── SerialPortHandlerCollection.cpp ├── SerialPortHandlerCollection.h ├── SerialPortLock.cpp └── SerialPortLock.h └── main-hdlcd.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | .kdev4/ 3 | html/ 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libs/framing"] 2 | path = libs/framing 3 | url = https://github.com/Strunzdesign/framing.git 4 | [submodule "libs/hdlcd-devel"] 5 | path = libs/hdlcd-devel 6 | url = https://github.com/Strunzdesign/hdlcd-devel.git 7 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Original author: 2 | Florian Evers 3 | 4 | Contributors: 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | 4 | ## [Unreleased] 5 | - Nothing yet 6 | 7 | 8 | ## [1.4] - 2016-11-22 9 | ### Added 10 | - Added this Changelog 11 | 12 | ### Changed 13 | - Git framing submodule tag v1.1 14 | - Git hdlcd-devel submodule tag v1.1 15 | 16 | ### Removed 17 | - Removed changelog information from file README.md 18 | 19 | ### Fixed 20 | - Fixed minor issues in the documentation and messages 21 | 22 | 23 | ## [1.3] - 2016-10-06 24 | ### Added 25 | - Added AUTHORS file 26 | - Added licencing information 27 | 28 | ### Changed 29 | - Makes use of git submodules for "externals" 30 | - Makes use of unified frame handling infrastructure 31 | 32 | ### Removed 33 | - The shared header files were moved to the hdlcd-devel repository at https://github.com/Strunzdesign/hdlcd-devel 34 | 35 | ### Fixed 36 | - Multiple bug fixes and stability improvements 37 | 38 | 39 | ## [1.2] - 2016-08-23 40 | ### Changed 41 | - Documentation updates 42 | - The client side offers a fully asynchronous send path now 43 | 44 | ### Removed 45 | - The HDLCd tools were moved to the "hdlcd-tools" repository at https://github.com/Strunzdesign/hdlcd-tools 46 | - The s-net(r) tools were moved to the "snet-tools" repository at https://github.com/Strunzdesign/snet-tools 47 | 48 | ### Fixed 49 | - Fixed installation issues on Microsoft Windows / MinGW 50 | 51 | 52 | ## [1.1] - 2016-06-16 53 | ### Added 54 | - Works well with s-net(r) BASE release 3.6 55 | 56 | ### Fixed 57 | - Fixed compiler error triggered with GCC 6.1 / nuwen MinGW 14.0 58 | 59 | 60 | ## [1.0] - 2016-06-10 61 | ### Added 62 | - First tested version without any open issues 63 | 64 | 65 | [Unreleased]: https://github.com/Strunzdesign/hdlcd/compare/v1.4...HEAD 66 | [1.4]: https://github.com/Strunzdesign/hdlcd/compare/v1.3...v1.4 67 | [1.3]: https://github.com/Strunzdesign/hdlcd/compare/v1.2...v1.3 68 | [1.2]: https://github.com/Strunzdesign/hdlcd/compare/v1.1...v1.2 69 | [1.1]: https://github.com/Strunzdesign/hdlcd/compare/v1.0...v1.1 70 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.6) 2 | 3 | project(hdlcd) 4 | 5 | include(CheckCXXCompilerFlag) 6 | CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) 7 | CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) 8 | if(COMPILER_SUPPORTS_CXX11) 9 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") 10 | elseif(COMPILER_SUPPORTS_CXX0X) 11 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") 12 | else() 13 | message(FATAL_ERROR "Compiler ${CMAKE_CXX_COMPILER} has no C++11 support.") 14 | endif() 15 | 16 | # Add custom cxx flags 17 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -Wextra") 18 | set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -Wextra") 19 | 20 | # Automatically set the version number 21 | set(HDLCD_VERSION_MAJOR \"1\") 22 | set(HDLCD_VERSION_MINOR \"5pre\") 23 | include_directories( 24 | "${PROJECT_BINARY_DIR}/src" 25 | "${PROJECT_SOURCE_DIR}/libs/framing/src" 26 | "${PROJECT_SOURCE_DIR}/libs/hdlcd-devel/src" 27 | ) 28 | configure_file ( 29 | "${PROJECT_SOURCE_DIR}/src/Config.h.in" 30 | "${PROJECT_BINARY_DIR}/src/Config.h" 31 | ) 32 | 33 | add_subdirectory(src) 34 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | The source code files provided in this project differ in their licences. 2 | All source code files of this project are under the GPLv3 or later (see file LICENSE), EXCEPT: 3 | - All source code files in the folder "src/hdlcd/SerialPort/HDLC", which are under the "BSD 3 Clause" licence (see file LICENSE.BSD3Clause). 4 | 5 | The author permits the use of all files under the "BSD 3 Clause" licence for the development of proprietary software. 6 | However, any restictions of the licences of involved toolkits, i.e., the boost libraries, must be followed as long 7 | as the respective toolkits are used. 8 | -------------------------------------------------------------------------------- /HOWTO: -------------------------------------------------------------------------------- 1 | This file gives some examples how to use the HDLC Daemon 2 | === 3 | Simply start the HDLC daemon (hdlcd / hdlcd.exe) and provide the TCP port number as its first parameter. 4 | The daemon does not require a configuration file and will run until either SIGINT ("CTRL-C") or SIGTERM are received. 5 | The baud rate of the attached device may be 9600 baud or 115200 baud and is auto detected. 6 | 7 | Example (GNU/Linux): 8 | --- 9 | cd build/src/hdlcd 10 | ./hdlcd --port 10000 11 | 12 | Example (Microsoft Windows): 13 | --- 14 | cd build\src\hdlcd 15 | hdlcd.exe --port 10000 16 | 17 | Try creating a symbolic link to hdlcd.exe. This allows to specify the command line parameter and offers 18 | you a very quick possibility to start the HDLC Daemon with one click. 19 | -------------------------------------------------------------------------------- /INSTALL: -------------------------------------------------------------------------------- 1 | === 2 | How to install the HDLC Daemon "hdlcd" and the header files 3 | === 4 | 5 | Initial download and setup on GNU/Linux: 6 | --- 7 | On GNU/Linux systems, installation is easy, as long as the required tools are available. 8 | 9 | Preparations: 10 | - Install the "GCC toolchain" 11 | - Install the "Boost Libraries" 12 | - Install the "CMake" build system 13 | 14 | To compile and to install the HDLC daemon, just follow these steps: 15 | 1.) git clone --recursive https://github.com/Strunzdesign/hdlcd.git 16 | 2.) cd hdlcd 17 | 3.) mkdir build 18 | 4.) cd build 19 | 5.) cmake .. 20 | 6.) make 21 | 7.) make install (as root) 22 | 23 | The "hdlcd" binary will be installed to "/usr/local/bin/" 24 | 25 | 26 | 27 | Initial download and setup on Microsoft Windows 7: 28 | --- 29 | For Microsoft Windows, one has to install the toolchain first. 30 | 31 | Preparations: 32 | - Download the latest "nuwen MinGW" distribution from https://nuwen.net/mingw.html 33 | - Assure that you pick a MinGW distribution that already includes "Git" and the "Boost Libraries" 34 | - Follow the installation guide, e.g., unpack MinGW to C:\MinGW 35 | - Add MinGW to the path according to the installation guide 36 | - Download and install "CMake" from https://cmake.org/download 37 | 38 | To compile and to install the HDLC daemon, just follow these steps: 39 | 1.) Go to your projects' folder and open a shell there 40 | 2.) git clone --recursive https://github.com/Strunzdesign/hdlcd.git 41 | 3.) cd hdlcd 42 | 4.) mkdir build 43 | 5.) cd build 44 | 6.) Pick yourself a directory to install the compiled files, e.g., consider C:\hdlcd 45 | 7.) cmake -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=/c/hdlcd .. 46 | 8.) If you get an error message on step 8, repeat step 8 once 47 | 9.) make 48 | 10.) make install 49 | 50 | The "hdlcd" binary will be installed to "C:\hdlcd\bin\" if not specified differently. 51 | 52 | 53 | 54 | Update and recompile your local repository (same for all OS): 55 | --- 56 | 1.) cd hdlcd 57 | 2.) git pull 58 | 3.) git submodule update 59 | 4.) cd build 60 | 5.) make 61 | 6.) make install 62 | 63 | Have fun :-) 64 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /LICENSE.BSD3Clause: -------------------------------------------------------------------------------- 1 | Redistribution and use in source and binary forms, with or without 2 | modification, are permitted provided that the following conditions are 3 | met: 4 | 5 | (1) Redistributions of source code must retain the above copyright 6 | notice, this list of conditions and the following disclaimer. 7 | 8 | (2) Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in 10 | the documentation and/or other materials provided with the 11 | distribution. 12 | 13 | (3)The name of the author may not be used to 14 | endorse or promote products derived from this software without 15 | specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 21 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 22 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 25 | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 26 | IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 | POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The HDLC Daemon (HDLCd) 2 | The HDLC Daemon (HDLCd) implement the HDLC protocol to easily talk to devices connected via serial communications. 3 | 4 | This package offers the "HDLC Daemon" (HDLCd) that implements the "High-level Data Link Control" protocol (HDLC). 5 | The purpose of this deamon is to easily use serial devices that make use of the HDLC protocol for communication. 6 | Currently it is tailored to the stripped-down flavor of HDLC offered by the s-net(r) sensor tags by the Fraunhofer-Institute 7 | for Integrated Circuits (IIS). The HDLCd itself offers TCP-based connectivity using framing for the control- and user-plane. 8 | 9 | This software is intended to be portable and makes use of the boost libraries. It was tested on GNU/Linux (GCC toolchain) 10 | and Microsoft Windows (nuwen MinGW). 11 | 12 | ## Latest stable release of the HDLCd: 13 | - v1.4 from 22.11.2016 14 | - Works well with s-net(r) BASE release 3.6 15 | 16 | ## Required libraries and tools: 17 | - GCC, the only tested compiler collection thus far (tested: GCC 4.9.3, GCC 6.1) 18 | - Boost, a platform-independent toolkit for development of C++ applications 19 | - CMake, the build system 20 | - Doxygen, for development 21 | - nuwen MinGW, to compile the software on Microsoft Windows (tested: 13.4, 14.0) 22 | 23 | ## Documentation 24 | - See online doxygen documentation at http://strunzdesign.github.io/hdlcd/ 25 | - Check the change log at https://github.com/Strunzdesign/hdlcd/blob/master/CHANGELOG.md 26 | - Read the specification of the HDLCd access protocol at https://github.com/Strunzdesign/hdlcd/blob/master/doc/protocol.txt 27 | 28 | ## Try multiple client-like tools to access the HDLCd for multiple use-cases: 29 | - https://github.com/Strunzdesign/hdlcd-tools 30 | - https://github.com/Strunzdesign/snet-tools 31 | - https://github.com/Strunzdesign/snet-gateway 32 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Issues to be resolved before a first release: 2 | - Doxygen (STARTED) 3 | - Fix all the TODOs in the source code 4 | - Check: Session confirmation with error reporting? 5 | 6 | 7 | 8 | Issues to be resolved after the first release: 9 | - Sophisticated HDLC support as specified by the extensive AX.25 documentation at http://www.ax25.net/AX25.2.2-Jul%2098-2.pdf (STARTED in branch hdlc-vanilla) 10 | - Currently there is no ARQ for data sent by the device to the HDLCd! 11 | - Currently there is no congestion control for data sent by the device to the HDLCd! 12 | - Also check both TODOs in HdlcdPacketEndpoint.h from the hdlcd-devel repository when fixing that... can and should be made asynchronous-only (via callbacks) 13 | - New session type to obtain global status information of the HDLC daemon 14 | - New session type to obtain status information regarding a specific serial interface 15 | - New session type for remote logging 16 | - Authentication, maybe? 17 | - Communicate the baud rate (initial and on any change) via control packets 18 | - Support for SNMP, maybe? 19 | 20 | 21 | 22 | // DONE 23 | - Add command line switches and online help ("-h --help") to the HDLCd (DONE) 24 | - Added doxygen files for creation of HTML files and online documention (DONE) 25 | - Periodically test idle HDLC links via U-TEST packets; check if the baud rate is still correct, or start another detection procedure. (DONE) 26 | - Add hint to spec: even if s-net(r)-messages indicate non-reliable transfer, reliable transmission via HDLC should be demanded for! (DONE) 27 | - Implement polling-based scheduler to query data packets to be transmitted, distinguish "unreliable-only" and "all data" (DONE) 28 | -> - Allow TCP sockets to become congested if the serial port is busy (no data loss on arrival of data bursts) (DONE) 29 | - Stop reading subsequent data packets from the TCP socket if the serial port is currently not open (DONE) 30 | - Implement transmission of U-frames, even for busy peers (RNR condition) (DONE) 31 | - States: deliver nothing (not alive), deliver U-Frames (alive, but stalled), deliver I- and U-Frames (alive and open) (DONE) 32 | - The "flow suspended" status flag must be set if the serial port is locked (DONE) 33 | - Implement keep alive packet handling, automatic transmission every 60 seconds (DONE) 34 | - Implement port kill request (DONE) 35 | - Implement echo service in ClientHandler (DONE) 36 | - Add subsequent tool solely for monitoring the status of a serial port (DONE) 37 | - Communicate the HDLC state (initial and on any change; whether "connected") via control packets (Spec: DONE, Code: DONE) 38 | - Logic to suspend / resume serial interfaces via control packets (logic: DONE, via TCP: DONE, tool: DONE) 39 | - Propagate direction of arrival flag (DONE) and the validity flag (DONE) via the access protocol (DONE) 40 | - HDLC retransmissions (specific to the current limitations of the s-net(r) sensor nodes by Fraunhofer IIS) (WONTFIX, impossible) 41 | - Rudimentary HDLC protocol is sufficient for the s-net(r) sensor nodes by Fraunhofer IIS (DONE) 42 | - Refactoring of the shared header files (DONE) 43 | - Modular acceptor / connector logic (DONE) 44 | - Implement the final specification of the TCP-based access protocol (DONE) 45 | - Dedicated access protocol entities for HDLCd and the client side. (DONE) 46 | - Better buffer handling to get rid of all remaining memmove and memcpy statements (DONE) 47 | - Implement baud rate detection by probing with TEST frames (DONE) 48 | - Complete specification of the TCP-based access protocol (DONE) 49 | - Tests on recent versions of MS Windows (DONE) 50 | - Fix HDLC send logic, the current send queue implementation is invalid and causes data loss (DONE) 51 | - Send appropriate S-frames (requires send queue) (DONE: RR and SREJ) 52 | - Remove bloated bunch of unnecessary include statements (DONE) 53 | - All tools have to handle direction of arrival flag and the validity flag, i.e., adjust their output messages (DONE) 54 | - Use enums in the ClientHandler to specify the kinds of data to be delivered (DONE) 55 | - Reduce code clones in ClientHandler.cpp (DONE) 56 | - Proper shutdown of the hdlc-hexchanger tool on ioservice shutdown, requires a fix for std::cin.getline() (DONE) 57 | -------------------------------------------------------------------------------- /doc/mainpage.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @brief Documentation 3 | @author Florian Evers, florian-evers@gmx.de 4 | @file*/ 5 | /** 6 | @mainpage Doxygen Test 7 | Test of Doxygen 8 | */ 9 | -------------------------------------------------------------------------------- /doc/protocol.txt: -------------------------------------------------------------------------------- 1 | Description of the HDLCd access protocol 2 | 3 | 1.) Connect a TCP socket to the specified listener port of the HDLCd 4 | 2.) Send a session header describing the type of data exchange 5 | 3.) Send and receive encapsulated packets as well as control packets describing the state of the hdlc protocol 6 | 7 | 8 | 9 | Overview: You just want to implement a simple gateway? 10 | --- 11 | At first, not all of the session types and flags that are part of this specification are relevant if you 12 | just want to implement a simple gateway software to exchange data via the HDLCd. In its simplest form, 13 | you just need a single TCP socket for the exchange of data packets containing payload. During session setup, 14 | you should specify that invalid frames are not of interest. After session setup, there is no need to create 15 | any control packet, and the client can safely ignore all incoming control packets, as long as locking the serial 16 | port is not an issue. 17 | 18 | However, it is beneficial to have two distinct TCP sockets per client to split the flow of data packets and 19 | the flow of control packets. As TCP is able to buffer large amounts of data, a dedicated TCP socket for control 20 | packets assures that you have a low-latency path for locking and unlocking commands regarding your serial port. 21 | Furthermore, it is no problem anymore to send data packets to a locked serial port if you have second socket 22 | dedicated to control packets. 23 | 24 | Be warned: if you transmit LOTS of data towards the HDLCd and then close the TCP socket, all pending data will 25 | stay in the TCP socket for delivery, even if the sending application was terminated! Thus, the respective burst 26 | of data will have an impact to the attached device. However, at the latest, the socket will be closed by the HDLCd 27 | when it tries to transmit the next "echo" control packet, which will fail as the socket was already closed by the peer. 28 | 29 | 30 | 31 | General: 32 | --- 33 | - Byte order: all multi-byte fields are in network byte order. 34 | - Error handling: on any error, the TCP socket is closed immediately without any notification! 35 | - Multiple clients can access the same device, just specify the same serial port name. 36 | - Serial ports can be "locked" by using dedicated control packets (see below). 37 | - Clients are encouraged to always demand for reliable transmission. Otherwise data loss due to an overwhelmed device is very probable! 38 | 39 | 40 | 41 | Locking ("suspend") and unlocking ("resume") of serial ports: 42 | --- 43 | Each client can acquire a lock on its currently used serial port in order to suspend the respective HDLC entity. 44 | In suspended mode, the serial port is temporarily released and no data are written to or read from the serial port. 45 | This allows "other software" besides the HDLCd to have full and undisturbed access to the serial port without 46 | risking data corruption, e.g., to deliver a firmware image to the attached device via third-party software ("flash tools"). 47 | Each client can acquire an own lock to its serial port, resulting in serial ports that may be locked by multiple clients. 48 | In order to resume a serial port to restart HDLC traffic, each of the held locks have to be released. Dedicated control 49 | packets inform the client regarding the current status of the serial port, i.e., whether _this_ client currently 50 | possesses a lock, and whether subsequent locks by other clients currently exist. 51 | 52 | A held lock is automatically released if the TCP socket to the respective client holding the lock is closed. 53 | Furthermore, it has no effect if a client tries to acquire the same lock multiple times: a lock can be acquired only once. 54 | 55 | The default status of a serial port is unlocked / resumed state. If a client connects to a serial port that is currently 56 | suspended, the first packet delivered via the TCP socket is a control packet indicating suspended state. 57 | 58 | In suspended state, the HDLCd reads control packets from the TCP sockets, but does not consume any data packets. 59 | Thus, it is dangerous to send a control packet to acquire a lock, then send a data packet, and finally send a control 60 | packet to release the lock. As the data packet will not be consumed, the HDLCd will never read the second control 61 | packet causing a deadlock. 62 | 63 | As a consequence, if a single TCP socket is used for exchange of both data and control packets, assure that the client 64 | does never send a data packet after a control packet that locks the serial port! 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | ===================== 76 | Session header 77 | ===================== 78 | The session header must and can only be sent once after initiation of the TCP socket. It must be sent by the client. 79 | 80 | Session header format: 81 | +---------+--------+------------------------------+--------------------+ 82 | | 1 Byte | 1 Byte | 1 Byte | x Byte | 83 | | Version | SAP | Length of serial port string | Serial port string | 84 | +---------+--------+------------------------------+--------------------+ 85 | Version: 86 | - 0x00 is currently the only supported version 87 | 88 | SAP: 89 | - Specifies the "service access point", i.e., which data to be exchanged 90 | 91 | Length of serial port string: 92 | - The length of the following device name, without any null termination. 93 | - 0 up to 255 bytes are allowed. However, not all lengths make sense :-) 94 | 95 | Serial port string: 96 | - The device name, without null termination. 97 | - Examples: /dev/ttyUSB0 or "//./COM1" 98 | 99 | 100 | Service access point specifier: 101 | ++------------------------------------------------------++ 102 | || Service access point specifier (1 byte) || 103 | ++--------------+----------+----------+-----------------++ 104 | || Bits 7...4 | Bit 3 | Bit 2 | Bits 1...0 || 105 | || Type of data | Reserved | Invalids | Direction flags || 106 | ++--------------+----------+----------+-----------------++ 107 | Type of data: 108 | - 0x0*: Payload, data read and write, port status read and write 109 | - 0x1*: Port status only, no data exchange, port status read and write 110 | - 0x2*: Payload Raw, data read only, port status read only 111 | - 0x3*: HDLC Raw, data read only, port status read only 112 | - 0x4*: HDLC dissected, data read only, port status read only 113 | - 0x5*-0xF*: reserved for future use 114 | 115 | Reserved: 116 | - Bit 3: must be set to "0" 117 | 118 | Invalids: 119 | - Bit 2: set to "1" if invalid data should be delivered, "0" if not 120 | 121 | Direction flags: 122 | - Bit 1: Set to "1" to subscribe for sent data, i.e., data sent to the HDLCd by other clients are delivered also. 123 | - Bit 0: Set to "1" to subscribe for received data, i.e., data sent by the serially attached device received by the HDLCd. 124 | - Assure that at least one of the bits 1 and 0 are set for data packet reception. Otherwise no data packets are delivered. 125 | --> - Bits: "------00" : No data packets are delivered ("quiet mode"). 126 | - Bits: "------01" : Only data packets that were sent by the device and received by the HDLCd are delivered ("gateway mode") 127 | - Bits: "------10" : Only data packets that were sent by the HDLCd to the device are delivered. 128 | - Bits: "------11" : All data packets that are either sent or received via HDLC are delivered ("payload sniffer mode") 129 | 130 | 131 | 132 | 133 | Description of the two most important session types: 134 | - 0x01: Payload: 135 | --> - this one is used for any client dedicated to data exchange, e.g., gateways. 136 | - Can also suspend / resume serial ports. 137 | - Notifications regarding state of the serial port 138 | - Easy to implement, but control packets may be stuck within the sended multiplex if the HDLCd stalled the transmission! 139 | 140 | - 0x10: Port status only: 141 | --> - this one /should/ used by any client dedicated to data exchange, e.g., gateways. 142 | - have a dedicated low-latency (no preceeding data packets) path for control packets to suspend / resume serial ports 143 | 144 | ==> best practice of implementing a gateway is to use two TCP-based access sockets per serial port: 145 | - one solely for data transmission and reception while ignoring all intertwined control packets, and 146 | - a second dedicated solely to control packets, providing a low-latency non-blocking control path. 147 | 148 | The reference implementation within this toolbox internally provides exactly this, but this is not visible to 149 | the user of the provided interface. 150 | 151 | 152 | 153 | 154 | 155 | Exemplary session headers: 156 | --- 157 | An exemplary session header to open /dev/ttyUSB0 for Payload RX/TX. Only received data is delivered (gateway mode) 158 | 00 01 0c 2f 64 65 76 2f 74 74 79 55 53 42 30 159 | 160 | An exemplary session header to open /dev/ttyUSB0 for the control path. Both direction flags are unset. 161 | 00 10 0c 2f 64 65 76 2f 74 74 79 55 53 42 30 162 | 163 | More interesting stuff: an exemplary session header to open /dev/ttyUSB1 for RO dissected HDLC frames RX and TX 164 | 00 43 0c 2f 64 65 76 2f 74 74 79 55 53 42 31 165 | 166 | 167 | 168 | After the session header was transmitted, the TCP socket is solely used for exchange of packets. 169 | The kind of exchanged packets depends on the provided session header: not all packets are 170 | allowed / seen in each of the possible session types! 171 | Before closing a TCP socket, one should assure to perform a shutdown procedure for correct teardown. 172 | 173 | 174 | ====================== 175 | Packets 176 | ====================== 177 | 178 | Packets can be "data packets" or "control packets" 179 | 180 | Packet header format: 181 | ++--------------------------------------------------------++-------------------------- 182 | || 1 Byte Type || 0...N subsequent bytes 183 | ++------------+----------+----------+----------+----------++-------------------------- 184 | || Bits 7...4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 || 185 | || Content | Reserved | Reliable | Invalid | Was sent || Depends on content field 186 | ++------------+----------+----------+----------+----------++-------------------------- 187 | Content: 188 | - 0x0*: Data packet 189 | - 0x1*: Control packet 190 | - 0x2*-0xF*: reserved for future use 191 | 192 | Reserved: 193 | - Bit 3: will be "0" and must be set to "0". 194 | 195 | Reliable flag: 196 | - Bit 2: is set to "1" if the packet was / has to be transmitted reliably by the HDLCd via HDLC. 197 | 198 | Invalid flag: 199 | - Bit 1: is set to "1" if the packet is damaged, "0" if it is valid. Must be "0" on transmission. 200 | 201 | Was sent: 202 | - Bit 0: is set to "1" if the packet was sent via HDLC, "0" if it was received via HDLC. Must be "0" on transmission. 203 | 204 | 205 | 206 | 207 | 208 | Data packet format: 209 | +--------+--------------+---------+ 210 | | 1 Byte | 2 Bytes | N Bytes | 211 | | 0x0* | Payload size | Payload | 212 | +--------+--------------+---------+ 213 | Data packets, if transmitted via TCP to be sent via HDLC, must have: 214 | - the "reserved" bit set to "0", 215 | - the "reliable" flag set to "0" or "1" to demand for U-Frames (unreliable) or I-Frames (reliable), respectively, 216 | - the "invalid" flag set to "0", 217 | - the "was sent" flags set to "0". 218 | ==> Thus, the type byte must be either 0x00 (unreliable) or 0x04 (reliable). 219 | 220 | 221 | Data packets, if received, have: 222 | - the "reserved" bit set to "0", 223 | - the "reliable" flag indicates whether the packet was received via "0": U-Frames (unreliable) or "1": I-Frames (reliable), 224 | - the "invalid" flag set to "0" if the packet was ok, "1" if it was damaged / invalid (CRC error or junk), 225 | - the "was sent"-flag packet set to "1" if the packet was sent via HDLC (by the HDLC daemon), "0" if it was received via HDLC, 226 | ==> The lower nibble of the type byte should be used to filter unwanted types of packets. 227 | 228 | 229 | 230 | 231 | 232 | Control packet format: 233 | ++--------++----------------------------------++ 234 | || 1 Byte || 1 Byte || 235 | ++--------++--------------+-------------------++ 236 | || 8 Bits || Bits 7...4 | Bits 3...0 || 237 | || 0x10 || Command type | Depend on Command || 238 | ++--------++--------------+-------------------++ 239 | Control packets, either if received or sent, must have: 240 | - the "reserved" bit set to "0", 241 | - the "reliable" flag set to "0", 242 | - the "invalid" bit set to "0", 243 | - the "was sent" flag set to "0". 244 | ==> Thus, the type byte _must_ be and will be always 0x10. 245 | 246 | 247 | 248 | Control packet, list of command types (upper nibble): 249 | --- 250 | 1.) Requests: are sent by a client to the HDLCd 251 | - 0x0*: Set port status request. The lower nibble has to be set accordingly. 252 | - 0x10: Echo request without payload. The HDLCd will reply with an echo confirmation (see below). 253 | - 0x20: Keep alive packet. These are dropped by the HDLCd. These should be sent periodically to detect stale TCP connections. 254 | - 0x30: Port kill request (immediate shutdown serial port handler and terminate all related TCP connections) 255 | - 0x4*-0xF*: reserved for future use 256 | 257 | 258 | 259 | 0x0*: Set port status request: 260 | --- 261 | ++--------++-----------------------------------------------++ 262 | || 1 Byte || 1 Byte: control -> set port status request || 263 | ++--------++---------------+-------+-------+-------+-------++ 264 | || 8 Bits || Bits 7...4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 || 265 | || 0x10 || 0 | 0 | 0 | 0 | Rsvd. | Rsvd. | Rsvd. | Lock || 266 | ++--------++---+---+---+---+-------+-------+-------+-------++ 267 | Rsvd flags: all reserved bits have to be set to "0" 268 | Lock flag: set to "1" if the serial port has to be suspended and locked; "0" to release the lock, the serial port /may/ resume. 269 | 270 | 271 | 2.) Indications / confirmations: are sent by the HDLCd to a client 272 | --- 273 | - 0x0*: Port status indication. The lower nibble has to be evaluated. 274 | - 0x10: Echo confirmation (a reply to an echo request) 275 | - 0x20: Keep alive packet. Just drop them. These are sent periodically to detect stale TCP connections. 276 | - 0x3*-0xF*: reserved for future use 277 | 278 | 279 | 280 | 281 | 282 | 283 | 0x0*: Port status indication: 284 | --- 285 | ++--------++-----------------------------------------------++ 286 | || 1 Byte || 1 Byte: control -> port status indication || 287 | ++--------++---------------+-------+-------+-------+-------++ 288 | || 8 Bits || Bits 7...4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 || 289 | || 0x10 || 0 | 0 | 0 | 0 | Rsvd. | Alive | PlbO | PlbS || 290 | ++--------++---+---+---+---+-------+-------+-------+-------++ 291 | - "Reserved": is set to "0" 292 | - Alive flag: is set to "1" if the HDLC association is alive (baud rate, session up, echos ok), "0" if not 293 | - PlbO flag: is set to "1" if the serial port is currently locked by others. 294 | - PlbS flag: is set to "1" if the serial port is currently locked by self. 295 | 296 | -------------------------------------------------------------------------------- /hdlcd.kdev4: -------------------------------------------------------------------------------- 1 | [Project] 2 | Name=hdlcd 3 | Manager=KDevCMakeManager 4 | VersionControl=kdevgit 5 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(Boost_USE_STATIC_LIBS OFF) 2 | set(Boost_USE_MULTITHREADED ON) 3 | set(Boost_USE_STATIC_RUNTIME OFF) 4 | find_package(Boost REQUIRED COMPONENTS system signals program_options) 5 | include_directories(${Boost_INCLUDE_DIR}) 6 | include_directories("${PROJECT_SOURCE_DIR}/src/include") 7 | include_directories( 8 | "HdlcdServer" 9 | "SerialPort" 10 | "SerialPort/HDLC" 11 | ) 12 | 13 | find_package(Threads) 14 | 15 | add_executable(hdlcd 16 | main-hdlcd.cpp 17 | HdlcdServer/HdlcdServerHandler.cpp 18 | HdlcdServer/HdlcdServerHandlerCollection.cpp 19 | HdlcdServer/LockGuard.cpp 20 | SerialPort/HDLC/AliveState.cpp 21 | SerialPort/HDLC/FCS16.cpp 22 | SerialPort/HDLC/HdlcFrame.cpp 23 | SerialPort/HDLC/FrameGenerator.cpp 24 | SerialPort/HDLC/FrameParser.cpp 25 | SerialPort/HDLC/ProtocolState.cpp 26 | SerialPort/SerialPortLock.cpp 27 | SerialPort/SerialPortHandler.cpp 28 | SerialPort/SerialPortHandlerCollection.cpp 29 | ) 30 | 31 | if(WIN32) 32 | set(ADDITIONAL_LIBRARIES wsock32 ws2_32) 33 | else() 34 | set(ADDITIONAL_LIBRARIES "") 35 | endif() 36 | 37 | target_link_libraries(hdlcd 38 | ${Boost_LIBRARIES} 39 | ${CMAKE_THREAD_LIBS_INIT} 40 | ${ADDITIONAL_LIBRARIES} 41 | ) 42 | 43 | install(TARGETS hdlcd RUNTIME DESTINATION bin) 44 | -------------------------------------------------------------------------------- /src/Config.h.in: -------------------------------------------------------------------------------- 1 | // The configured options and settings for the HDLC Daemon 2 | #include "HdlcdConfig.h" 3 | #define HDLCD_VERSION_MAJOR @HDLCD_VERSION_MAJOR@ 4 | #define HDLCD_VERSION_MINOR @HDLCD_VERSION_MINOR@ 5 | -------------------------------------------------------------------------------- /src/HdlcdServer/AliveGuard.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file AliveGuard.h 3 | * \brief This file contains the header declaration of class AliveGuard 4 | * \author Florian Evers, florian-evers@gmx.de 5 | * \copyright GNU Public License version 3. 6 | * 7 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 8 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | */ 23 | 24 | #ifndef ALIVE_GUARD_H 25 | #define ALIVE_GUARD_H 26 | 27 | /*! \class AliveGuard 28 | * \brief Class AliveGuard 29 | * 30 | * This guard object tracks whether a device attached via serial connections is alive, i.e., the baud rate is known and the HDLC protocol is initialized 31 | */ 32 | class AliveGuard { 33 | public: 34 | /*! \brief The constructor of AccessGuard objects 35 | * 36 | * On creation, a serial port is considered as alive 37 | */ 38 | AliveGuard(): m_bAlive(true) { 39 | } 40 | 41 | /*! \brief Change the serial port state 42 | * 43 | * Change the serial port state 44 | * 45 | * \param a_bAlive the new state of the related serial device 46 | * \return bool indicates whether the state of the related serial device was changed by the call 47 | */ 48 | bool UpdateSerialPortState(bool a_bAlive) { 49 | bool l_bStateChanged = (m_bAlive != a_bAlive); 50 | m_bAlive = a_bAlive; 51 | return l_bStateChanged; 52 | } 53 | 54 | /*! \brief Query whether the related serial port is currently alive 55 | * 56 | * Query whether the related serial device is currently alive 57 | * 58 | * \return bool indicating whether the related serial device is currently alive 59 | */ 60 | bool IsAlive() const { return m_bAlive; } 61 | 62 | private: 63 | // Members 64 | bool m_bAlive; //!< The alive state of the related device 65 | }; 66 | 67 | #endif // ALIVE_GUARD_H 68 | -------------------------------------------------------------------------------- /src/HdlcdServer/HdlcdServerHandler.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file HdlcdServerHandler.cpp 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #include "HdlcdServerHandler.h" 23 | #include "HdlcdServerHandlerCollection.h" 24 | #include "SerialPortHandlerCollection.h" 25 | #include "SerialPortHandler.h" 26 | #include "HdlcdPacketData.h" 27 | #include "HdlcdPacketCtrl.h" 28 | #include "HdlcdPacketEndpoint.h" 29 | #include "HdlcdSessionHeader.h" 30 | #include "FrameEndpoint.h" 31 | #include 32 | 33 | HdlcdServerHandler::HdlcdServerHandler(boost::asio::io_service& a_IOService, std::weak_ptr a_HdlcdServerHandlerCollection, boost::asio::ip::tcp::socket& a_TcpSocket): m_IOService(a_IOService), m_HdlcdServerHandlerCollection(a_HdlcdServerHandlerCollection) { 34 | // Initialize members 35 | m_Registered = false; 36 | m_bDeliverInitialState = true; 37 | m_eBufferType = BUFFER_TYPE_UNSET; 38 | m_bDeliverSent = false; 39 | m_bDeliverRcvd = false; 40 | m_bDeliverInvalidData = false; 41 | m_bSerialPortHandlerAwaitsPacket = false; 42 | 43 | // Prepare frame endpoint 44 | m_FrameEndpoint = std::make_shared(a_IOService, a_TcpSocket); 45 | m_FrameEndpoint->RegisterFrameFactory(0x00, []()->std::shared_ptr{ return HdlcdSessionHeader::CreateDeserializedFrame(); }); 46 | m_FrameEndpoint->SetOnFrameCallback([this](std::shared_ptr a_Frame)->bool{ return OnFrame(a_Frame); }); 47 | m_FrameEndpoint->SetOnClosedCallback ([this](){ OnClosed(); }); 48 | } 49 | 50 | void HdlcdServerHandler::DeliverBufferToClient(E_BUFFER_TYPE a_eBufferType, const std::vector &a_Payload, bool a_bReliable, bool a_bInvalid, bool a_bWasSent) { 51 | // Check whether this buffer is of interest to this specific client 52 | bool l_bDeliver = (a_eBufferType == m_eBufferType); 53 | if ((a_bWasSent && !m_bDeliverSent) || (!a_bWasSent && !m_bDeliverRcvd)) { 54 | l_bDeliver = false; 55 | } // if 56 | 57 | if ((m_bDeliverInvalidData == false) && (a_bInvalid)) { 58 | l_bDeliver = false; 59 | } // if 60 | 61 | if (l_bDeliver) { 62 | m_PacketEndpoint->Send(HdlcdPacketData::CreatePacket(a_Payload, a_bReliable, a_bInvalid, a_bWasSent)); 63 | } // if 64 | } 65 | 66 | void HdlcdServerHandler::UpdateSerialPortState(bool a_bAlive, size_t a_LockHolders) { 67 | bool l_bDeliverChangedState = m_bDeliverInitialState; 68 | m_bDeliverInitialState = false; 69 | l_bDeliverChangedState |= m_AliveGuard.UpdateSerialPortState(a_bAlive); 70 | l_bDeliverChangedState |= m_LockGuard.UpdateSerialPortState(a_LockHolders); 71 | if (l_bDeliverChangedState) { 72 | // The state of the serial port state changed. Communicate the new state to the client. 73 | m_PacketEndpoint->Send(HdlcdPacketCtrl::CreatePortStatusResponse(m_AliveGuard.IsAlive(), m_LockGuard.IsLockedByOthers(), m_LockGuard.IsLockedBySelf())); 74 | } // if 75 | } 76 | 77 | void HdlcdServerHandler::QueryForPayload(bool a_bQueryReliable, bool a_bQueryUnreliable) { 78 | // Checks 79 | assert(a_bQueryReliable || a_bQueryUnreliable); 80 | if (!m_Registered) { 81 | return; 82 | } // if 83 | 84 | // Deliver a pending incoming data packet, dependend on the state of packets accepted by the serial port handler. 85 | // If no suitable packet is pending, set a flag that allows immediate delivery of the next packet. 86 | if (m_PendingIncomingPacketData) { 87 | bool l_bDeliver = (a_bQueryReliable && m_PendingIncomingPacketData->GetReliable()); 88 | l_bDeliver |= (a_bQueryUnreliable && !m_PendingIncomingPacketData->GetReliable()); 89 | if (l_bDeliver) { 90 | m_SerialPortHandler->DeliverPayloadToHDLC(m_PendingIncomingPacketData->GetData(), m_PendingIncomingPacketData->GetReliable()); 91 | m_PendingIncomingPacketData.reset(); 92 | m_PacketEndpoint->TriggerNextDataPacket(); 93 | } // if 94 | } else { 95 | // No packet was pending, but we want to receive more! 96 | m_bSerialPortHandlerAwaitsPacket = true; 97 | m_PacketEndpoint->TriggerNextDataPacket(); 98 | } // else 99 | } 100 | 101 | void HdlcdServerHandler::Start(std::shared_ptr a_SerialPortHandlerCollection) { 102 | assert(m_Registered == false); 103 | assert(a_SerialPortHandlerCollection); 104 | m_SerialPortHandlerCollection = a_SerialPortHandlerCollection; 105 | if (auto lock = m_HdlcdServerHandlerCollection.lock()) { 106 | m_Registered = true; 107 | m_bSerialPortHandlerAwaitsPacket = true; 108 | lock->RegisterHdlcdServerHandler(shared_from_this()); 109 | } else { 110 | assert(false); 111 | } // else 112 | 113 | // Start waiting for the session header 114 | m_FrameEndpoint->Start(); 115 | } 116 | 117 | void HdlcdServerHandler::Stop() { 118 | // Keep this object alive 119 | auto self(shared_from_this()); 120 | m_SerialPortHandler.reset(); 121 | if (m_Registered) { 122 | m_Registered = false; 123 | m_bSerialPortHandlerAwaitsPacket = false; 124 | if (m_PacketEndpoint) { 125 | assert(!m_FrameEndpoint); 126 | m_PacketEndpoint->Close(); 127 | m_PacketEndpoint.reset(); 128 | } else { 129 | m_FrameEndpoint->Shutdown(); 130 | m_FrameEndpoint->Close(); 131 | m_FrameEndpoint.reset(); 132 | } // else 133 | 134 | if (auto lock = m_HdlcdServerHandlerCollection.lock()) { 135 | lock->DeregisterHdlcdServerHandler(self); 136 | } // if 137 | } // if 138 | } 139 | 140 | bool HdlcdServerHandler::OnFrame(const std::shared_ptr a_Frame) { 141 | // Checks 142 | assert(a_Frame); 143 | assert(m_FrameEndpoint); 144 | assert(!m_PacketEndpoint); 145 | 146 | // Parse the session header 147 | auto l_HdlcdSessionHeader = std::dynamic_pointer_cast(a_Frame); 148 | if (l_HdlcdSessionHeader) { 149 | // The session header is now available. Check service access point specifier: type of data 150 | uint8_t l_SAP = l_HdlcdSessionHeader->GetServiceAccessPointSpecifier(); 151 | switch (l_SAP & 0xF0) { 152 | case 0x00: { 153 | m_eBufferType = BUFFER_TYPE_PAYLOAD; 154 | break; 155 | } 156 | case 0x10: { 157 | m_eBufferType = BUFFER_TYPE_PORT_STATUS; 158 | break; 159 | } 160 | case 0x20: { 161 | m_eBufferType = BUFFER_TYPE_PAYLOAD; 162 | break; 163 | } 164 | case 0x30: { 165 | m_eBufferType = BUFFER_TYPE_RAW; 166 | break; 167 | } 168 | case 0x40: { 169 | m_eBufferType = BUFFER_TYPE_DISSECTED; 170 | break; 171 | } 172 | default: 173 | // Unknown session type 174 | std::cerr << "Unknown session type rejected: " << (int)(l_SAP & 0xF0) << std::endl; 175 | Stop(); 176 | return false; 177 | } // switch 178 | 179 | // Check service access point specifier: reserved bit 180 | if (l_SAP & 0x08) { 181 | // The reserved bit was set... aborting 182 | std::cerr << "Invalid reserved bit within SAP specifier of session header: " << (int)l_SAP << std::endl; 183 | Stop(); 184 | return false; 185 | } // if 186 | 187 | // Check service access point specifier: invalids, deliver sent, and deliver rcvd 188 | m_bDeliverInvalidData = (l_SAP & 0x04); 189 | m_bDeliverSent = (l_SAP & 0x02); 190 | m_bDeliverRcvd = (l_SAP & 0x01); 191 | 192 | // Start the PacketEndpoint. It takes full control over the TCP socket. 193 | m_PacketEndpoint = std::make_shared(m_IOService, m_FrameEndpoint); 194 | m_PacketEndpoint->SetOnDataCallback([this](std::shared_ptr a_PacketData){ return OnDataReceived(a_PacketData); }); 195 | m_PacketEndpoint->SetOnCtrlCallback([this](const HdlcdPacketCtrl& a_PacketCtrl){ OnCtrlReceived(a_PacketCtrl); }); 196 | m_PacketEndpoint->SetOnClosedCallback([this](){ OnClosed(); }); 197 | m_FrameEndpoint.reset(); 198 | auto l_SerialPortHandlerStopper = m_SerialPortHandlerCollection->GetSerialPortHandler(l_HdlcdSessionHeader->GetSerialPortName(), shared_from_this()); 199 | if (l_SerialPortHandlerStopper) { 200 | m_SerialPortHandlerStopper = l_SerialPortHandlerStopper; 201 | m_SerialPortHandler = (*m_SerialPortHandlerStopper.get()); 202 | m_LockGuard.Init(m_SerialPortHandler); 203 | m_SerialPortHandler->PropagateSerialPortState(); // Sends initial port status message 204 | m_PacketEndpoint->Start(); 205 | } else { 206 | // This object is dead now! -> Close() was already called by the SerialPortHandler 207 | } // else 208 | } else { 209 | // Instead of a session header we received junk! This is impossible. 210 | assert(false); 211 | Stop(); 212 | } // else 213 | 214 | // In each case: stall the receiver! The HdlcdPacketEndpoint continues... 215 | return false; 216 | } 217 | 218 | bool HdlcdServerHandler::OnDataReceived(std::shared_ptr a_PacketData) { 219 | // Checks 220 | assert(a_PacketData); 221 | assert(!m_PendingIncomingPacketData); 222 | 223 | // Store the incoming packet, but try to deliver it now 224 | m_PendingIncomingPacketData = a_PacketData; 225 | if (m_bSerialPortHandlerAwaitsPacket) { 226 | // One packet can be delivered, regardless of its reliablility status and the kind of packets that are accepted. 227 | m_bSerialPortHandlerAwaitsPacket = false; 228 | m_SerialPortHandler->DeliverPayloadToHDLC(m_PendingIncomingPacketData->GetData(), m_PendingIncomingPacketData->GetReliable()); 229 | m_PendingIncomingPacketData.reset(); 230 | return true; // continue receiving, we stall with the next data packet 231 | } // if 232 | 233 | // Stall the receiver now! 234 | return false; 235 | } 236 | 237 | void HdlcdServerHandler::OnCtrlReceived(const HdlcdPacketCtrl& a_PacketCtrl) { 238 | // Check control packet: suspend / resume? Port kill request? 239 | switch(a_PacketCtrl.GetPacketType()) { 240 | case HdlcdPacketCtrl::CTRL_TYPE_PORT_STATUS: { 241 | if (a_PacketCtrl.GetDesiredLockState()) { 242 | // Acquire a lock, if not already held. On acquisition, suspend the serial port 243 | m_LockGuard.AcquireLock(); 244 | } else { 245 | // Release lock and resume serial port 246 | m_LockGuard.ReleaseLock(); 247 | } // else 248 | break; 249 | } 250 | case HdlcdPacketCtrl::CTRL_TYPE_ECHO: { 251 | // Respond with an echo reply control packet: simply send it back 252 | m_PacketEndpoint->Send(a_PacketCtrl); 253 | break; 254 | } 255 | case HdlcdPacketCtrl::CTRL_TYPE_PORT_KILL: { 256 | // Kill the serial port immediately and detach all related clients 257 | m_SerialPortHandler->Stop(); 258 | break; 259 | } 260 | default: 261 | break; 262 | } // switch 263 | } 264 | 265 | void HdlcdServerHandler::OnClosed() { 266 | Stop(); 267 | } 268 | -------------------------------------------------------------------------------- /src/HdlcdServer/HdlcdServerHandler.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file HdlcdServerHandler.h 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #ifndef HDLCD_SERVER_HANDLER_H 23 | #define HDLCD_SERVER_HANDLER_H 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include "AliveGuard.h" 32 | #include "LockGuard.h" 33 | #include "BufferType.h" 34 | class Frame; 35 | class HdlcdPacketData; 36 | class HdlcdPacketCtrl; 37 | class HdlcdPacketEndpoint; 38 | class FrameEndpoint; 39 | class HdlcdServerHandlerCollection; 40 | class SerialPortHandler; 41 | class SerialPortHandlerCollection; 42 | 43 | class HdlcdServerHandler: public std::enable_shared_from_this { 44 | public: 45 | HdlcdServerHandler(boost::asio::io_service& a_IOService, std::weak_ptr a_HdlcdServerHandlerCollection, boost::asio::ip::tcp::socket& a_TcpSocket); 46 | 47 | E_BUFFER_TYPE GetBufferType() const { return m_eBufferType; } 48 | void DeliverBufferToClient(E_BUFFER_TYPE a_eBufferType, const std::vector &a_Payload, bool a_bReliable, bool a_bInvalid, bool a_bWasSent); 49 | void UpdateSerialPortState(bool a_bAlive, size_t a_LockHolders); 50 | void QueryForPayload(bool a_bQueryReliable, bool a_bQueryUnreliable); 51 | 52 | void Start(std::shared_ptr a_SerialPortHandlerCollection); 53 | void Stop(); 54 | 55 | private: 56 | // Callbacks 57 | bool OnFrame(const std::shared_ptr a_Frame); // To parse the session header 58 | bool OnDataReceived(std::shared_ptr a_PacketData); 59 | void OnCtrlReceived(const HdlcdPacketCtrl& a_PacketCtrl); 60 | void OnClosed(); 61 | 62 | // Members 63 | boost::asio::io_service& m_IOService; 64 | std::weak_ptr m_HdlcdServerHandlerCollection; 65 | std::shared_ptr m_FrameEndpoint; 66 | std::shared_ptr m_PacketEndpoint; 67 | 68 | bool m_Registered; 69 | std::shared_ptr m_SerialPortHandlerCollection; 70 | std::shared_ptr> m_SerialPortHandlerStopper; 71 | std::shared_ptr m_SerialPortHandler; 72 | 73 | // Pending incoming data packets 74 | bool m_bSerialPortHandlerAwaitsPacket; 75 | std::shared_ptr m_PendingIncomingPacketData; 76 | 77 | // Track the status of the serial port, communicate changes 78 | bool m_bDeliverInitialState; 79 | AliveGuard m_AliveGuard; 80 | LockGuard m_LockGuard; 81 | 82 | // SAP specification 83 | E_BUFFER_TYPE m_eBufferType; 84 | bool m_bDeliverSent; 85 | bool m_bDeliverRcvd; 86 | bool m_bDeliverInvalidData; 87 | }; 88 | 89 | #endif // HDLCD_SERVER_HANDLER_H 90 | -------------------------------------------------------------------------------- /src/HdlcdServer/HdlcdServerHandlerCollection.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file HdlcdServerHandlerCollection.cpp 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #include "HdlcdServerHandlerCollection.h" 23 | #include "HdlcdServerHandler.h" 24 | #include 25 | using boost::asio::ip::tcp; 26 | 27 | HdlcdServerHandlerCollection::HdlcdServerHandlerCollection(boost::asio::io_service& a_IOService, std::shared_ptr a_SerialPortHandlerCollection, uint16_t a_TcpPortNbr): 28 | m_IOService(a_IOService), m_SerialPortHandlerCollection(a_SerialPortHandlerCollection), m_TcpAcceptor(a_IOService, tcp::endpoint(tcp::v4(), a_TcpPortNbr)), m_TcpSocket(a_IOService) { 29 | // Checks 30 | assert(m_SerialPortHandlerCollection); 31 | 32 | // Trigger activity 33 | DoAccept(); 34 | } 35 | 36 | void HdlcdServerHandlerCollection::Shutdown() { 37 | // Stop accepting subsequent TCP connections 38 | m_TcpAcceptor.close(); 39 | 40 | // Release all client handler objects. They deregister themselves. 41 | while (!m_HdlcdServerHandlerList.empty()) { 42 | (*m_HdlcdServerHandlerList.begin())->Stop(); 43 | } // while 44 | 45 | // Drop all shared pointers 46 | assert(m_HdlcdServerHandlerList.empty()); 47 | m_SerialPortHandlerCollection.reset(); 48 | } 49 | 50 | void HdlcdServerHandlerCollection::RegisterHdlcdServerHandler(std::shared_ptr a_HdlcdServerHandler) { 51 | m_HdlcdServerHandlerList.emplace_back(std::move(a_HdlcdServerHandler)); 52 | } 53 | 54 | void HdlcdServerHandlerCollection::DeregisterHdlcdServerHandler(std::shared_ptr a_HdlcdServerHandler) { 55 | m_HdlcdServerHandlerList.remove(a_HdlcdServerHandler); 56 | } 57 | 58 | void HdlcdServerHandlerCollection::DoAccept() { 59 | m_TcpAcceptor.async_accept(m_TcpSocket, [this](boost::system::error_code a_ErrorCode) { 60 | if (!a_ErrorCode) { 61 | // Create a HDLCd server handler object and start it. It registers itself to the HDLCd server handler collection 62 | auto l_HdlcdServerHandler = std::make_shared(m_IOService, shared_from_this(), m_TcpSocket); 63 | l_HdlcdServerHandler->Start(m_SerialPortHandlerCollection); 64 | } // if 65 | 66 | // Wait for subsequent TCP connections 67 | DoAccept(); 68 | }); // async_accept 69 | } 70 | -------------------------------------------------------------------------------- /src/HdlcdServer/HdlcdServerHandlerCollection.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file HdlcdServerHandlerCollection.h 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #ifndef HDLCD_SERVER_HANDLER_COLLECTION_H 23 | #define HDLCD_SERVER_HANDLER_COLLECTION_H 24 | 25 | #include 26 | #include 27 | #include 28 | class SerialPortHandlerCollection; 29 | class HdlcdServerHandler; 30 | 31 | class HdlcdServerHandlerCollection: public std::enable_shared_from_this { 32 | public: 33 | // CTOR and resetter 34 | HdlcdServerHandlerCollection(boost::asio::io_service& a_IOService, std::shared_ptr a_SerialPortHandlerCollection, uint16_t a_TcpPortNbr); 35 | void Shutdown(); 36 | 37 | // Self-registering and -deregistering of HDLCd server handler objects 38 | void RegisterHdlcdServerHandler (std::shared_ptr a_HdlcdServerHandler); 39 | void DeregisterHdlcdServerHandler(std::shared_ptr a_HdlcdServerHandler); 40 | 41 | private: 42 | // Internal helpers 43 | void DoAccept(); 44 | 45 | // Members 46 | boost::asio::io_service& m_IOService; 47 | std::shared_ptr m_SerialPortHandlerCollection; 48 | std::list> m_HdlcdServerHandlerList; 49 | 50 | // Accept incoming TCP connections 51 | boost::asio::ip::tcp::tcp::acceptor m_TcpAcceptor; //!< The TCP listener 52 | boost::asio::ip::tcp::tcp::socket m_TcpSocket; //!< One incoming TCP socket 53 | }; 54 | 55 | #endif // HDLCD_SERVER_HANDLER_COLLECTION_H 56 | -------------------------------------------------------------------------------- /src/HdlcdServer/LockGuard.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file LockGuard.cpp 3 | * \brief This file contains the implementation of class LockGuard 4 | * \author Florian Evers, florian-evers@gmx.de 5 | * \copyright GNU Public License version 3. 6 | * 7 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 8 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | */ 23 | 24 | #include "LockGuard.h" 25 | #include "SerialPortHandler.h" 26 | 27 | /*! \brief The constructor of LockGuard objects 28 | * 29 | * On creation, the serial port is "unlocked" / resumed 30 | */ 31 | LockGuard::LockGuard() { 32 | // No active locks known on creation 33 | m_bLockedBySelf = false; 34 | m_bLockedByOthers = false; 35 | m_bLastLockedBySelf = false; 36 | m_bLastLockedByOthers = false; 37 | } 38 | 39 | /*! \brief The destructor of LockGuard objects 40 | * 41 | * Held locks are automatically released on deletion 42 | */ 43 | LockGuard::~LockGuard() { 44 | if (m_bLockedBySelf) { 45 | m_SerialPortHandler->ResumeSerialPort(); 46 | } // if 47 | } 48 | 49 | /*! \brief Initializer method to register subsequent objects 50 | * 51 | * Registers the serial port handler object that is not available yet on construction 52 | * 53 | * \param a_SerialPortHandler the serial port handler object 54 | */ 55 | void LockGuard::Init(std::shared_ptr a_SerialPortHandler) { 56 | // Checks 57 | assert(m_bLockedBySelf == false); 58 | assert(m_bLockedByOthers == false); 59 | m_SerialPortHandler = a_SerialPortHandler; 60 | } 61 | 62 | /*! \brief Method to aquire a lock 63 | * 64 | * Each ClientAcceptor can aquired a lock only once, subsequent calls have no impact. The serial port handler 65 | * has a lock counter, so only the first lock attempt will suspend the serial port. 66 | */ 67 | void LockGuard::AcquireLock() { 68 | if (!m_bLockedBySelf) { 69 | // Increases lock counter, may actually suspend the serial port 70 | m_bLockedBySelf = true; 71 | m_SerialPortHandler->SuspendSerialPort(); 72 | } // if 73 | } 74 | 75 | /*! \brief Method to release a lock 76 | * 77 | * Each ClientAcceptor can release a held lock only once, subsequent calls have no impact. The serial port handler 78 | * has a lock counter, so it may resume after this call, but this happens only if this was the last lock. 79 | */ 80 | void LockGuard::ReleaseLock() { 81 | if (m_bLockedBySelf) { 82 | // Decreases lock counter, may actually resume the serial port 83 | m_bLockedBySelf = false; 84 | m_SerialPortHandler->ResumeSerialPort(); 85 | } // if 86 | } 87 | 88 | /*! \brief Update the effective lock state of the related serial port 89 | * 90 | * This method gets the amount of locks regarding the related serial port. Thus, this entity is able to derive 91 | * whether subsequent locks by other entities exist. 92 | * 93 | * \param a_LockHolders the amount of locks that currently force the related serial port to be suspended 94 | * \return bool indicates whether the internal state of this object changed 95 | */ 96 | bool LockGuard::UpdateSerialPortState(size_t a_LockHolders) { 97 | // This call is caused by ourselves 98 | if (m_bLockedBySelf) { 99 | m_bLockedByOthers = (a_LockHolders > 1); 100 | } else { 101 | m_bLockedByOthers = (a_LockHolders > 0); 102 | } // else 103 | 104 | if ((m_bLastLockedBySelf != m_bLockedBySelf) || 105 | (m_bLastLockedByOthers != m_bLockedByOthers)) { 106 | m_bLastLockedBySelf = m_bLockedBySelf; 107 | m_bLastLockedByOthers = m_bLockedByOthers; 108 | return true; 109 | } else { 110 | return false; 111 | } // else 112 | } 113 | -------------------------------------------------------------------------------- /src/HdlcdServer/LockGuard.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file LockGuard.h 3 | * \brief This file contains the header declaration of class LockGuard 4 | * \author Florian Evers, florian-evers@gmx.de 5 | * \copyright GNU Public License version 3. 6 | * 7 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 8 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | */ 23 | 24 | #ifndef LOCK_GUARD_H 25 | #define LOCK_GUARD_H 26 | 27 | #include 28 | class SerialPortHandler; 29 | 30 | /*! \class LockGuard 31 | * \brief Class LockGuard 32 | * 33 | * This guard object tracks whether a related device attached via serial connections is currently "locked" / suspended or "unlocked" / resumed 34 | */ 35 | class LockGuard { 36 | public: 37 | // CTOR, DTOR, and initializer 38 | LockGuard(); 39 | ~LockGuard(); 40 | void Init(std::shared_ptr a_SerialPortHandler); 41 | 42 | // Influende the serial port, obtain and release locks, called by a ClientHandler 43 | void AcquireLock(); 44 | void ReleaseLock(); 45 | 46 | // Update the effective state of a serial port 47 | bool UpdateSerialPortState(size_t a_LockHolders); 48 | 49 | 50 | /*! \brief Query the lock state of the related serial device 51 | * 52 | * Query the lock state of the related serial device 53 | * 54 | * \return bool indicates whether the serial port is currently "locked" / suspended or "unlocked" / resumed 55 | */ 56 | bool IsLocked() const { return (m_bLockedBySelf || m_bLockedByOthers); } 57 | 58 | /*! \brief Query whether the serial device is currently "locked" by the responsible AccessClient entity 59 | * 60 | * Query whether the serial device is currently locked" by the responsible AccessClient entity 61 | * 62 | * \return bool indicates whether the serial port is currently "locked" by the responsible AccessClient entity 63 | */ 64 | bool IsLockedBySelf() const { return m_bLockedBySelf; } 65 | 66 | /*! \brief Query whether the serial device is currently "locked" by at least one other AccessClient entity 67 | * 68 | * Query whether the serial device is currently "locked" by at least one other AccessClient entity 69 | * 70 | * \return bool indicates whether the serial port is currently "locked" by at least one other AccessClient entity 71 | */ 72 | bool IsLockedByOthers() const { return m_bLockedByOthers; } 73 | 74 | private: 75 | // Members 76 | std::shared_ptr m_SerialPortHandler; //!< The serial port handler responsible for the serial device 77 | bool m_bLockedBySelf; //!< This flag indicates whether the serial device is locked by this entity 78 | bool m_bLockedByOthers; //!< This flag indicates whether the serial device is locked by other entities 79 | bool m_bLastLockedBySelf; //!< The last known effective state whether the serial device is locked by this entity, to detect changes 80 | bool m_bLastLockedByOthers; //!< The last known effective state whether the serial device is locked by other entities, to detect changes 81 | }; 82 | 83 | #endif // LOCK_GUARD_H 84 | -------------------------------------------------------------------------------- /src/SerialPort/BaudRate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file BaudRate.h 3 | * \brief This file contains the header declaration of class BaudRate 4 | * \author Florian Evers, florian-evers@gmx.de 5 | * \copyright GNU Public License version 3. 6 | * 7 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 8 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | */ 23 | 24 | #ifndef BAUD_RATE_H 25 | #define BAUD_RATE_H 26 | 27 | /*! \class BaudRate 28 | * \brief Class BaudRate 29 | * 30 | * This class is responsible for selecting and iterating through multiple pre-defined baud rate settings 31 | */ 32 | class BaudRate { 33 | public: 34 | /*! \brief The constructor of BaudRate objects 35 | * 36 | * On creation, a rate of 9600 baud is selected 37 | */ 38 | BaudRate(): m_CurrentBaudrateIndex(0) {} 39 | 40 | /*! \brief Deliver the currently used baud rate setting 41 | * 42 | * Deliver the currently used baud rate setting 43 | */ 44 | unsigned int GetBaudRate() const { 45 | switch (m_CurrentBaudrateIndex) { 46 | case 0: 47 | return 9600; 48 | default: 49 | case 1: 50 | return 115200; 51 | } // switch 52 | } 53 | 54 | /*! \brief Iterate to another baud rate setting 55 | * 56 | * All available baud rates are used, then it starts over with the first setting 57 | */ 58 | void ToggleBaudRate() { 59 | switch (m_CurrentBaudrateIndex) { 60 | case 0: 61 | m_CurrentBaudrateIndex = 1; 62 | break; 63 | default: 64 | case 1: 65 | m_CurrentBaudrateIndex = 0; 66 | break; 67 | } // switch 68 | } 69 | 70 | private: 71 | unsigned int m_CurrentBaudrateIndex; //!< The current baud rate index 72 | }; 73 | 74 | #endif // BAUD_RATE_H 75 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/AliveState.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file AliveState.cpp 3 | * \brief This file contains the implementation of class AliveState 4 | * \author Florian Evers, florian-evers@gmx.de 5 | * \copyright BSD 3-Clause License. 6 | * 7 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 8 | * All rights reserved. 9 | * 10 | * Redistribution and use in source and binary forms, with or without 11 | * modification, are permitted provided that the following conditions are 12 | * met: 13 | * 14 | * (1) Redistributions of source code must retain the above copyright 15 | * notice, this list of conditions and the following disclaimer. 16 | * 17 | * (2) Redistributions in binary form must reproduce the above copyright 18 | * notice, this list of conditions and the following disclaimer in 19 | * the documentation and/or other materials provided with the 20 | * distribution. 21 | * 22 | * (3)The name of the author may not be used to 23 | * endorse or promote products derived from this software without 24 | * specific prior written permission. 25 | * 26 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 27 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 28 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 29 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 30 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 31 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 32 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 34 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 35 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36 | * POSSIBILITY OF SUCH DAMAGE. 37 | */ 38 | 39 | #include "AliveState.h" 40 | #include 41 | 42 | /*! \brief The constructor of AliveState objects 43 | * 44 | * The constructor of AliveState objects 45 | */ 46 | AliveState::AliveState(boost::asio::io_service& a_IOService): m_StateTimer(a_IOService), m_ProbeTimer(a_IOService) { 47 | Reset(); 48 | } 49 | 50 | /*! \brief The destructor of AliveState objects 51 | * 52 | * The destructor of AliveState objects 53 | */ 54 | AliveState::~AliveState() { 55 | Stop(); 56 | } 57 | 58 | /*! \brief Internal helper to reset most of the members (excluding callbacks) to sane values 59 | * 60 | * Internal helper to reset most of the members (excluding callbacks) to sane values 61 | */ 62 | void AliveState::Reset() { 63 | m_eAliveState = ALIVESTATE_PROBING; 64 | m_bFrameWasReceived = false; 65 | m_ProbeCounter = 0; 66 | } 67 | 68 | /*! \brief Start all activities 69 | * 70 | * This method starts all activities of this class, such as sending probe request and testing different baud rate settings 71 | */ 72 | void AliveState::Start() { 73 | assert(m_SendProbeCallback); 74 | assert(m_ChangeBaudrateCallback); 75 | m_ProbeCounter = 0; 76 | m_eAliveState = ALIVESTATE_PROBING; 77 | m_bFrameWasReceived = false; 78 | m_StateTimer.cancel(); 79 | m_ProbeTimer.cancel(); 80 | StartStateTimer(); 81 | StartProbeTimer(); 82 | m_SendProbeCallback(); // send first probe 83 | } 84 | 85 | /*! \brief Stop all activities 86 | * 87 | * This method stops all activities of this class, such as sending probe request and testing different baud rate settings 88 | */ 89 | void AliveState::Stop() { 90 | m_StateTimer.cancel(); 91 | m_ProbeTimer.cancel(); 92 | Reset(); 93 | } 94 | 95 | /*! \brief Register callback method for sending a probe request via HDLC 96 | * 97 | * The provided callback is called each time a probe has to be sent via HDLC. 98 | * 99 | * \param a_SendProbeCallback the callback method to send a probe request via HDLC 100 | */ 101 | void AliveState::SetSendProbeCallback(std::function a_SendProbeCallback) { 102 | m_SendProbeCallback = a_SendProbeCallback; 103 | } 104 | 105 | /*! \brief Register callback method for changing the baud rate of the related serial port 106 | * 107 | * The provided callback is called each time the baud rate of the serial port has to be changed. 108 | * 109 | * \param a_ChangeBaudrateCallback the callback method to switch to another baud rate setting 110 | */ 111 | void AliveState::SetChangeBaudrateCallback(std::function a_ChangeBaudrateCallback) { 112 | m_ChangeBaudrateCallback = a_ChangeBaudrateCallback; 113 | } 114 | 115 | /*! \brief Indicate that a HDLC frame was received via the related serial port 116 | * 117 | * On each valid received HDLC frame this method is called to indicate that the baud rate is ok and that 118 | * the connected device is alive. 119 | * 120 | * \return bool indicates whether the internal state changed 121 | */ 122 | bool AliveState::OnFrameReceived() { 123 | // We received an HDLC frame 124 | m_bFrameWasReceived = true; 125 | if (m_eAliveState == ALIVESTATE_PROBING) { 126 | // Reprobing succeeded 127 | m_eAliveState = ALIVESTATE_FOUND; 128 | return true; 129 | } else { 130 | m_eAliveState = ALIVESTATE_FOUND; 131 | return false; // TODO: Why false? Seems to be correct, but check again and add a comment! 132 | } // else 133 | } 134 | 135 | /*! \brief Query whether the related serialport is currently considered alive 136 | * 137 | * A serial port is alive if the baud rate is correct and HDLC frames are received. 138 | * 139 | * \return bool indicates whether the related serial port is currently alive 140 | */ 141 | bool AliveState::IsAlive() const { 142 | // Return true if transmission of data is currently allowed 143 | return ((m_eAliveState == ALIVESTATE_FOUND) || (m_eAliveState == ALIVESTATE_REPROBING)); 144 | } 145 | 146 | /*! \brief Internal helper method to start the state timeout timer 147 | * 148 | * Internal helper method to start the state timeout timer 149 | */ 150 | void AliveState::StartStateTimer() { 151 | auto self(shared_from_this()); 152 | m_StateTimer.expires_from_now(boost::posix_time::seconds(15)); 153 | m_StateTimer.async_wait([this, self](const boost::system::error_code& ec) { 154 | if (!ec) { 155 | // A state timeout occured 156 | OnStateTimeout(); 157 | StartStateTimer(); // start again 158 | } // if 159 | }); 160 | } 161 | 162 | /*! \brief Internal helper method to start the probe timeout timer 163 | * 164 | * Internal helper method to start the probe timeout timer 165 | */ 166 | void AliveState::StartProbeTimer() { 167 | auto self(shared_from_this()); 168 | m_ProbeTimer.expires_from_now(boost::posix_time::milliseconds(500)); 169 | m_ProbeTimer.async_wait([this, self](const boost::system::error_code& ec) { 170 | if (!ec) { 171 | // A probe timeout occured 172 | OnProbeTimeout(); 173 | StartProbeTimer(); // start again 174 | } // if 175 | }); 176 | } 177 | 178 | /*! \brief Internal helper method to handle state timeouts 179 | * 180 | * This method implements the state machine regarding the alive state 181 | */ 182 | void AliveState::OnStateTimeout() { 183 | if (m_eAliveState == ALIVESTATE_FOUND) { 184 | if (m_bFrameWasReceived) { 185 | m_bFrameWasReceived = false; 186 | } else { 187 | m_eAliveState = ALIVESTATE_REPROBING; 188 | } // else 189 | } else if (m_eAliveState == ALIVESTATE_REPROBING) { 190 | if (!m_bFrameWasReceived) { 191 | m_eAliveState = ALIVESTATE_PROBING; 192 | } else { 193 | // This must not happen 194 | assert(false); 195 | } // else 196 | } // else 197 | } 198 | 199 | /*! \brief Internal helper method to handle probe timeouts 200 | * 201 | * This method triggers transmission of probe requests and toggles the baud rate if no HDLC frames were received 202 | */ 203 | void AliveState::OnProbeTimeout() { 204 | if (m_eAliveState == ALIVESTATE_PROBING) { 205 | // For each fourth probe we select another baud rate 206 | if ((m_ProbeCounter = ((m_ProbeCounter + 1) & 0x03)) == 0) { 207 | m_ChangeBaudrateCallback(); 208 | } // if 209 | 210 | m_SendProbeCallback(); 211 | } else if (m_eAliveState == ALIVESTATE_REPROBING) { 212 | m_SendProbeCallback(); 213 | } // else 214 | } 215 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/AliveState.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file AliveState.h 3 | * \brief This file contains the header declaration of class AliveState 4 | * \author Florian Evers, florian-evers@gmx.de 5 | * \copyright BSD 3-Clause License. 6 | * 7 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 8 | * All rights reserved. 9 | * 10 | * Redistribution and use in source and binary forms, with or without 11 | * modification, are permitted provided that the following conditions are 12 | * met: 13 | * 14 | * (1) Redistributions of source code must retain the above copyright 15 | * notice, this list of conditions and the following disclaimer. 16 | * 17 | * (2) Redistributions in binary form must reproduce the above copyright 18 | * notice, this list of conditions and the following disclaimer in 19 | * the documentation and/or other materials provided with the 20 | * distribution. 21 | * 22 | * (3)The name of the author may not be used to 23 | * endorse or promote products derived from this software without 24 | * specific prior written permission. 25 | * 26 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 27 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 28 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 29 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 30 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 31 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 32 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 34 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 35 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36 | * POSSIBILITY OF SUCH DAMAGE. 37 | */ 38 | 39 | #ifndef ALIVE_STATE_H 40 | #define ALIVE_STATE_H 41 | 42 | #include 43 | #include 44 | 45 | /*! \class AliveState 46 | * \brief Class AliveState 47 | * 48 | * This class is responsible for keeping track of the HDLC message exchange, periodically sends HDLC keep alive packets ("probes") 49 | * if no other HDLC PDUs were exchanged, and cycles through all available baud rates if no messages were received from a serially 50 | * attached device. 51 | */ 52 | class AliveState: public std::enable_shared_from_this { 53 | public: 54 | // CTOR and DTOR 55 | AliveState(boost::asio::io_service& a_IOService); 56 | ~AliveState(); 57 | 58 | // Register callback methods 59 | void SetSendProbeCallback(std::function a_SendProbeCallback); 60 | void SetChangeBaudrateCallback(std::function a_ChangeBaudrateCallback); 61 | 62 | // Start and stop processing 63 | void Start(); 64 | void Stop(); 65 | 66 | // Notification regarding incoming data, and query methods 67 | bool OnFrameReceived(); 68 | bool IsAlive() const; 69 | 70 | private: 71 | // Helpers 72 | void Reset(); 73 | void StartStateTimer(); 74 | void StartProbeTimer(); 75 | 76 | // Members 77 | /*! \enum E_ALIVESTATE 78 | * \brief Enum E_ALIVESTATE 79 | * 80 | * This enum names the different states that the baud rate and alive state detection scheme makes use of. 81 | */ 82 | typedef enum { 83 | ALIVESTATE_PROBING = 0, //!< The baud rate is currently unknown, only HDLC probes are sent. The serial port is not alive. 84 | ALIVESTATE_FOUND = 1, //!< The baud rate is known, normal operation. The serial port is alive. 85 | ALIVESTATE_REPROBING = 2, //!< The baud rate is still known, but no packets were received. Reprobing is required to keep alive state. 86 | } E_ALIVESTATE; 87 | E_ALIVESTATE m_eAliveState; //!< the current alive state 88 | 89 | // Callbacks 90 | std::function m_SendProbeCallback; //!< This callback method is invoked if a subsequent probe has to be sent 91 | std::function m_ChangeBaudrateCallback; //!< This callback method is invoked if the baud rate has to be changed 92 | 93 | // Timer and timer handlers 94 | boost::asio::deadline_timer m_StateTimer; //!< Timeout timer for state handling 95 | boost::asio::deadline_timer m_ProbeTimer; //!< Timeout timer to trigger the next probe 96 | void OnStateTimeout(); 97 | void OnProbeTimeout(); 98 | 99 | // Observation 100 | bool m_bFrameWasReceived; //!< This flag indicates that data were received via HDLC since the last check 101 | int m_ProbeCounter; //!< A counter to keep track of sent probes without the respective replies 102 | }; 103 | 104 | #endif // ALIVE_STATE_H 105 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/BufferType.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file BufferType.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef BUFFER_TYPE_H 38 | #define BUFFER_TYPE_H 39 | 40 | typedef enum { 41 | BUFFER_TYPE_RAW = 0, 42 | BUFFER_TYPE_DISSECTED = 1, 43 | BUFFER_TYPE_PAYLOAD = 2, 44 | BUFFER_TYPE_PORT_STATUS = 3, 45 | 46 | // Bookkeeping 47 | BUFFER_TYPE_ARITHMETIC_ENDMARKER = 4, 48 | BUFFER_TYPE_UNSET = 0xFF 49 | } E_BUFFER_TYPE; 50 | 51 | #endif // BUFFER_TYPE_H 52 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/FCS16.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file FCS16.cpp 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #include "FCS16.h" 38 | 39 | uint16_t fcstab[256] = { 40 | 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 41 | 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 42 | 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 43 | 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 44 | 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 45 | 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 46 | 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 47 | 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 48 | 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 49 | 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 50 | 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 51 | 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 52 | 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 53 | 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 54 | 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 55 | 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 56 | 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 57 | 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 58 | 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 59 | 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 60 | 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 61 | 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 62 | 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 63 | 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 64 | 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 65 | 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 66 | 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 67 | 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 68 | 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 69 | 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 70 | 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 71 | 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 72 | }; 73 | 74 | uint16_t pppfcs16(uint16_t fcs, unsigned char* cp, size_t len) { 75 | while (len--) { 76 | fcs = (fcs >> 8) ^ fcstab[(fcs ^ *cp++) & 0xff]; 77 | } // while 78 | 79 | return (fcs); 80 | } 81 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/FCS16.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file FCS16.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef FCS16_H 38 | #define FCS16_H 39 | 40 | #include 41 | #include 42 | 43 | #define PPPINITFCS16 0xffff 44 | #define PPPGOODFCS16 0xf0b8 45 | 46 | uint16_t pppfcs16(uint16_t fcs, unsigned char* cp, size_t len); 47 | 48 | #endif // FCS16_H 49 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/FrameGenerator.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file FrameGenerator.cpp 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #include "FrameGenerator.h" 38 | #include 39 | #include "FCS16.h" 40 | 41 | const std::vector FrameGenerator::SerializeFrame(const HdlcFrame& a_HdlcFrame) { 42 | unsigned char l_ControlField = 0; 43 | bool l_bAppendPayload = false; 44 | switch (a_HdlcFrame.GetHDLCFrameType()) { 45 | case HdlcFrame::HDLC_FRAMETYPE_I: { 46 | l_ControlField = (((a_HdlcFrame.GetSSeq() & 0x07) << 1) | ((a_HdlcFrame.GetRSeq() & 0x07) << 5)); // I-Frame, PF=0 47 | l_bAppendPayload = true; 48 | break; 49 | } 50 | case HdlcFrame::HDLC_FRAMETYPE_S_RR: { 51 | l_ControlField = (0x01 | ((a_HdlcFrame.GetRSeq() & 0x07) << 5)); 52 | break; 53 | } 54 | case HdlcFrame::HDLC_FRAMETYPE_S_RNR: { 55 | l_ControlField = (0x05 | ((a_HdlcFrame.GetRSeq() & 0x07) << 5)); 56 | break; 57 | } 58 | case HdlcFrame::HDLC_FRAMETYPE_S_REJ: { 59 | l_ControlField = (0x09 | ((a_HdlcFrame.GetRSeq() & 0x07) << 5)); 60 | break; 61 | } 62 | case HdlcFrame::HDLC_FRAMETYPE_S_SREJ: { 63 | l_ControlField = (0x0d | ((a_HdlcFrame.GetRSeq() & 0x07) << 5)); 64 | break; 65 | } 66 | case HdlcFrame::HDLC_FRAMETYPE_U_UI: { 67 | l_ControlField = 0x03; 68 | l_bAppendPayload = true; 69 | break; 70 | } 71 | case HdlcFrame::HDLC_FRAMETYPE_U_SABM: { 72 | l_ControlField = 0x2F; 73 | break; 74 | } 75 | case HdlcFrame::HDLC_FRAMETYPE_U_DISC: { 76 | l_ControlField = 0x43; 77 | break; 78 | } 79 | case HdlcFrame::HDLC_FRAMETYPE_U_UA: { 80 | l_ControlField = 0x63; 81 | break; 82 | } 83 | case HdlcFrame::HDLC_FRAMETYPE_U_CMDR: { 84 | l_ControlField = 0x83; 85 | break; 86 | } 87 | case HdlcFrame::HDLC_FRAMETYPE_U_TEST: { 88 | l_ControlField = 0xE3; 89 | break; 90 | } 91 | case HdlcFrame::HDLC_FRAMETYPE_U_SIM: 92 | case HdlcFrame::HDLC_FRAMETYPE_U_SARM: 93 | case HdlcFrame::HDLC_FRAMETYPE_U_UP: 94 | case HdlcFrame::HDLC_FRAMETYPE_U_SNRM: 95 | case HdlcFrame::HDLC_FRAMETYPE_U_XID: { 96 | // Unknown structure, not implemented yet 97 | assert(false); 98 | break; 99 | } 100 | default: 101 | assert(false); 102 | } // switch 103 | 104 | // Assemble Frame 105 | std::vector l_HDLCFrame; 106 | l_HDLCFrame.reserve(a_HdlcFrame.GetPayload().size() + 6); // 6 = FD, ADDR, TYPE, FCS, FCS, FD 107 | l_HDLCFrame.emplace_back(0x7E); 108 | l_HDLCFrame.emplace_back(a_HdlcFrame.GetAddress()); 109 | if (a_HdlcFrame.IsPF()) { 110 | l_ControlField |= 0x10; 111 | } // if 112 | 113 | l_HDLCFrame.emplace_back(l_ControlField); 114 | if (l_bAppendPayload) { 115 | l_HDLCFrame.insert(l_HDLCFrame.end(), &(a_HdlcFrame.GetPayload())[0], &(a_HdlcFrame.GetPayload())[0] + a_HdlcFrame.GetPayload().size()); 116 | } // if 117 | 118 | // Calculate FCS, perform escaping, and deliver 119 | ApplyFCS(l_HDLCFrame); // Plus 2 bytes 120 | l_HDLCFrame.emplace_back(0x7E); 121 | return l_HDLCFrame; 122 | } 123 | 124 | void FrameGenerator::ApplyFCS(std::vector &a_HDLCFrame) { 125 | uint16_t trialfcs = pppfcs16(PPPINITFCS16, &a_HDLCFrame[1], (a_HDLCFrame.size() - 1)); 126 | trialfcs ^= 0xffff; 127 | a_HDLCFrame.emplace_back(trialfcs & 0x00ff); 128 | a_HDLCFrame.emplace_back((trialfcs >> 8) & 0x00ff); 129 | } 130 | 131 | std::vector FrameGenerator::EscapeFrame(const std::vector &a_HDLCFrame) { 132 | // Obtain required amount of memory for the fully escaped HDLC frame 133 | size_t l_NbrOfBytesToEscapeMax = 0; 134 | for (size_t l_Index = 1; l_Index < (a_HDLCFrame.size() - 1); ++l_Index) { 135 | if ((a_HDLCFrame[l_Index] == 0x7D) || (a_HDLCFrame[l_Index] == 0x7E)) { 136 | ++l_NbrOfBytesToEscapeMax; 137 | } // if 138 | } // for 139 | 140 | // Prepare return buffer 141 | std::vector l_EscapedHDLCFrame; 142 | l_EscapedHDLCFrame.reserve(a_HDLCFrame.size() + l_NbrOfBytesToEscapeMax); 143 | l_EscapedHDLCFrame.emplace_back(0x7E); 144 | for (std::vector::const_iterator it = (a_HDLCFrame.begin() + 1); it < (a_HDLCFrame.end() - 1); ++it) { 145 | if (*it == 0x7D) { 146 | l_EscapedHDLCFrame.emplace_back(0x7D); 147 | l_EscapedHDLCFrame.emplace_back(0x5D); 148 | } else if (*it == 0x7E) { 149 | l_EscapedHDLCFrame.emplace_back(0x7D); 150 | l_EscapedHDLCFrame.emplace_back(0x5E); 151 | } else { 152 | l_EscapedHDLCFrame.emplace_back(*it); 153 | } // else 154 | } // for 155 | 156 | l_EscapedHDLCFrame.emplace_back(0x7E); 157 | return l_EscapedHDLCFrame; 158 | } 159 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/FrameGenerator.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file FrameGenerator.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef HDLC_FRAME_GENERATOR_H 38 | #define HDLC_FRAME_GENERATOR_H 39 | 40 | #include 41 | #include "HdlcFrame.h" 42 | 43 | class FrameGenerator { 44 | public: 45 | static const std::vector SerializeFrame(const HdlcFrame& a_HdlcFrame); 46 | static std::vector EscapeFrame(const std::vector &a_HDLCFrame); 47 | 48 | private: 49 | // Internal Helpers 50 | static void ApplyFCS(std::vector &a_HDLCFrame); 51 | }; 52 | 53 | #endif // HDLC_FRAME_GENERATOR_H 54 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/FrameParser.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file FrameParser.cpp 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #include "FrameParser.h" 38 | #include "ProtocolState.h" 39 | #include "FCS16.h" 40 | 41 | FrameParser::FrameParser(ProtocolState& a_ProtocolState): m_ProtocolState(a_ProtocolState) { 42 | Reset(); 43 | } 44 | 45 | void FrameParser::Reset() { 46 | // Prepare assembly buffer 47 | m_Buffer.clear(); 48 | m_Buffer.reserve(max_length); 49 | m_Buffer.emplace_back(0x7E); 50 | m_bStartTokenSeen = false; 51 | } 52 | 53 | void FrameParser::AddReceivedRawBytes(const unsigned char* a_Buffer, size_t a_Bytes) { 54 | while (a_Bytes) { 55 | size_t l_ConsumedBytes = AddChunk(a_Buffer, a_Bytes); 56 | a_Buffer += l_ConsumedBytes; 57 | a_Bytes -= l_ConsumedBytes; 58 | } // while 59 | } 60 | 61 | size_t FrameParser::AddChunk(const unsigned char* a_Buffer, size_t a_Bytes) { 62 | if (m_bStartTokenSeen == false) { 63 | // No start token seen yet. Check if there is the start token available in the input buffer. 64 | const void* l_pStartTokenPtr = memchr((const void*)a_Buffer, 0x7E, a_Bytes); 65 | if (l_pStartTokenPtr) { 66 | // The start token was found in the input buffer. 67 | m_bStartTokenSeen = true; 68 | if (l_pStartTokenPtr == a_Buffer) { 69 | // The start token is at the beginning of the buffer. Clip it. 70 | return 1; 71 | } else { 72 | // Clip front of buffer containing junk, including the start token. 73 | return ((const unsigned char*)l_pStartTokenPtr - a_Buffer + 1); 74 | } // else 75 | } else { 76 | // No token found, and no token was seen yet. Dropping received buffer now. 77 | return a_Bytes; 78 | } // else 79 | } else { 80 | // We already have seen the start token. Check if there is the end token available in the input buffer. 81 | const void* l_pEndTokenPtr = memchr((const void*)a_Buffer, 0x7E, a_Bytes); 82 | if (l_pEndTokenPtr) { 83 | // The end token was found in the input buffer. At first, check if we receive to much data. 84 | size_t l_NbrOfBytes = ((const unsigned char*)l_pEndTokenPtr - a_Buffer + 1); 85 | if ((m_Buffer.size() + l_NbrOfBytes) <= (2 * max_length)) { 86 | // We did not exceed the maximum frame size yet. Copy all bytes including the end token. 87 | m_Buffer.insert(m_Buffer.end(), a_Buffer, a_Buffer + l_NbrOfBytes); 88 | if (RemoveEscapeCharacters()) { 89 | // The complete frame was valid and was consumed. 90 | m_bStartTokenSeen = false; 91 | } // if 92 | } // else 93 | 94 | m_Buffer.resize(1); // Already contains start token 0x7E 95 | return (l_NbrOfBytes); 96 | } else { 97 | // No end token found. Copy all bytes if we do not exceed the maximum frame size. 98 | if ((m_Buffer.size() + a_Bytes) > (2 * max_length)) { 99 | // Even if all these bytes were escaped, we have exceeded the maximum frame size. 100 | m_bStartTokenSeen = false; 101 | m_Buffer.resize(1); // Already contains start token 0x7E 102 | } else { 103 | // Add all bytes 104 | m_Buffer.insert(m_Buffer.end(), a_Buffer, a_Buffer + a_Bytes); 105 | } // else 106 | 107 | return a_Bytes; 108 | } // else 109 | } // else 110 | } 111 | 112 | bool FrameParser::RemoveEscapeCharacters() { 113 | // Checks 114 | assert(m_Buffer.front() == 0x7E); 115 | assert(m_Buffer.back() == 0x7E); 116 | assert(m_Buffer.size() >= 2); 117 | assert(m_bStartTokenSeen == true); 118 | 119 | if (m_Buffer.size() == 2) { 120 | // Remove junk, start again 121 | return false; 122 | } // if 123 | 124 | // Check for illegal escape sequence at the end of the buffer 125 | bool l_bMessageInvalid = false; 126 | if (m_Buffer[m_Buffer.size() - 2] == 0x7D) { 127 | l_bMessageInvalid = true; 128 | } else { 129 | // Remove escape sequences 130 | std::vector l_UnescapedBuffer; 131 | l_UnescapedBuffer.reserve(m_Buffer.size()); 132 | for (auto it = m_Buffer.begin(); it != m_Buffer.end(); ++it) { 133 | if (*it == 0x7D) { 134 | // This was the escape character 135 | ++it; 136 | if (*it == 0x5E) { 137 | l_UnescapedBuffer.emplace_back(0x7E); 138 | } else if (*it == 0x5D) { 139 | l_UnescapedBuffer.emplace_back(0x7D); 140 | } else { 141 | // Invalid character. Go ahead with an invalid frame. 142 | l_bMessageInvalid = true; 143 | l_UnescapedBuffer.emplace_back(*it); 144 | } // else 145 | } else { 146 | // Normal non-escaped character, or one of the frame delimiters 147 | l_UnescapedBuffer.emplace_back(*it); 148 | } // else 149 | } // while 150 | 151 | // Go ahead with the unescaped buffer 152 | m_Buffer = std::move(l_UnescapedBuffer); 153 | } // if 154 | 155 | // We now have the unescaped frame at hand. 156 | if ((m_Buffer.size() < 6) || (m_Buffer.size() > max_length)) { 157 | // To short or too long for a valid HDLC frame. We consider it as junk. 158 | return false; 159 | } // if 160 | 161 | if (l_bMessageInvalid == false) { 162 | // Check FCS 163 | l_bMessageInvalid = (pppfcs16(PPPINITFCS16, (m_Buffer.data() + 1), (m_Buffer.size() - 2)) != PPPGOODFCS16); 164 | } // if 165 | 166 | m_ProtocolState.InterpretDeserializedFrame(m_Buffer, DeserializeFrame(m_Buffer), l_bMessageInvalid); 167 | return (l_bMessageInvalid == false); 168 | } 169 | 170 | HdlcFrame FrameParser::DeserializeFrame(const std::vector &a_UnescapedBuffer) const { 171 | // Parse byte buffer to get the HDLC frame 172 | HdlcFrame l_HdlcFrame; 173 | l_HdlcFrame.SetAddress(a_UnescapedBuffer[1]); 174 | unsigned char l_ucCtrl = a_UnescapedBuffer[2]; 175 | l_HdlcFrame.SetPF((l_ucCtrl & 0x10) >> 4); 176 | bool l_bAppendPayload = false; 177 | if ((l_ucCtrl & 0x01) == 0) { 178 | // I-Frame 179 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_I); 180 | l_HdlcFrame.SetSSeq((l_ucCtrl & 0x0E) >> 1); 181 | l_HdlcFrame.SetRSeq((l_ucCtrl & 0xE0) >> 5); 182 | l_bAppendPayload = true; 183 | } else { 184 | // S-Frame or U-Frame 185 | if ((l_ucCtrl & 0x02) == 0x00) { 186 | // S-Frame 187 | l_HdlcFrame.SetRSeq((l_ucCtrl & 0xE0) >> 5); 188 | unsigned char l_ucType = ((l_ucCtrl & 0x0c) >> 2); 189 | if (l_ucType == 0x00) { 190 | // Receive-Ready (RR) 191 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_S_RR); 192 | } else if (l_ucType == 0x01) { 193 | // Receive-Not-Ready (RNR) 194 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_S_RNR); 195 | } else if (l_ucType == 0x02) { 196 | // Reject (REJ) 197 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_S_REJ); 198 | } else { 199 | // Selective Reject (SREJ) 200 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_S_SREJ); 201 | } // else 202 | } else { 203 | // U-Frame 204 | unsigned char l_ucType = (((l_ucCtrl & 0x0c) >> 2) | ((l_ucCtrl & 0xe0) >> 3)); 205 | switch (l_ucType) { 206 | case 0b00000: { 207 | // Unnumbered information (UI) 208 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_UI); 209 | l_bAppendPayload = true; 210 | break; 211 | } 212 | case 0b00001: { 213 | // Set Init. Mode (SIM) 214 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_SIM); 215 | break; 216 | } 217 | case 0b00011: { 218 | // Set Async. Response Mode (SARM) 219 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_SARM); 220 | break; 221 | } 222 | case 0b00100: { 223 | // Unnumbered Poll (UP) 224 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_UP); 225 | break; 226 | } 227 | case 0b00111: { 228 | // Set Async. Balance Mode (SABM) 229 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_SABM); 230 | break; 231 | } 232 | case 0b01000: { 233 | // Disconnect (DISC) 234 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_DISC); 235 | break; 236 | } 237 | case 0b01100: { 238 | // Unnumbered Ack. (UA) 239 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_UA); 240 | break; 241 | } 242 | case 0b10000: { 243 | // Set normal response mode (SNRM) 244 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_SNRM); 245 | break; 246 | } 247 | case 0b10001: { 248 | // Command reject (FRMR / CMDR) 249 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_CMDR); 250 | l_bAppendPayload = true; 251 | break; 252 | } 253 | case 0b11100: { 254 | // Test (TEST) 255 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_TEST); 256 | l_bAppendPayload = true; 257 | break; 258 | } 259 | case 0b11101: { 260 | // Exchange Identification (XID) 261 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_XID); 262 | l_bAppendPayload = true; 263 | break; 264 | } 265 | default: { 266 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_UNSET); 267 | break; 268 | } 269 | } // switch 270 | } // else 271 | } // else 272 | 273 | if (l_bAppendPayload) { 274 | // I-Frames and UI-Frames have additional payload 275 | std::vector l_Payload; 276 | l_Payload.assign(&a_UnescapedBuffer[3], (&a_UnescapedBuffer[3] + (a_UnescapedBuffer.size() - 6))); 277 | l_HdlcFrame.SetPayload(std::move(l_Payload)); 278 | } // if 279 | 280 | return l_HdlcFrame; 281 | } 282 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/FrameParser.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file FrameParser.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef HDLC_FRAME_PARSER_H 38 | #define HDLC_FRAME_PARSER_H 39 | 40 | #include 41 | #include "HdlcFrame.h" 42 | class ProtocolState; 43 | 44 | class FrameParser { 45 | public: 46 | FrameParser(ProtocolState& a_ProtocolState); 47 | void Reset(); 48 | void AddReceivedRawBytes(const unsigned char* a_Buffer, size_t a_Bytes); 49 | 50 | private: 51 | // Interal helpers 52 | size_t AddChunk(const unsigned char* a_Buffer, size_t a_Bytes); 53 | bool RemoveEscapeCharacters(); 54 | HdlcFrame DeserializeFrame(const std::vector &a_UnescapedBuffer) const; 55 | 56 | // Members 57 | ProtocolState& m_ProtocolState; 58 | 59 | enum { max_length = 1024 }; 60 | std::vector m_Buffer; 61 | bool m_bStartTokenSeen; 62 | }; 63 | 64 | #endif // HDLC_FRAME_PARSER_H 65 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/HdlcFrame.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file HdlcFrame.cpp 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #include "HdlcFrame.h" 38 | #include 39 | #include 40 | 41 | const std::vector HdlcFrame::Dissect() const { 42 | bool l_bHasPayload = false; 43 | std::stringstream l_Output; 44 | if (IsIFrame()) { 45 | l_bHasPayload = true; 46 | l_Output << "HDLC frame, Addr=0x" << std::hex << (int)GetAddress() << std::dec << ", "; 47 | l_Output << "I-Frame, PF=" << IsPF() << ", SSeq=" << (int)GetSSeq() << ", RSeq=" << (int)GetRSeq(); 48 | } else if (IsSFrame()) { 49 | l_Output << "HDLC frame, Addr=0x" << std::hex << (int)GetAddress() << std::dec << ", S-Frame: "; 50 | switch (GetHDLCFrameType()) { 51 | case HdlcFrame::HDLC_FRAMETYPE_S_RR: { 52 | l_Output << "RR"; 53 | break; 54 | } 55 | case HdlcFrame::HDLC_FRAMETYPE_S_RNR: { 56 | l_Output << "RNR"; 57 | break; 58 | } 59 | case HdlcFrame::HDLC_FRAMETYPE_S_REJ: { 60 | l_Output << "REJ"; 61 | break; 62 | } 63 | case HdlcFrame::HDLC_FRAMETYPE_S_SREJ: { 64 | l_Output << "SREJ"; 65 | break; 66 | } 67 | default: { 68 | break; 69 | } 70 | } // switch 71 | 72 | l_Output << ", PF=" << IsPF() << ", RSeq=" << (int)GetRSeq(); 73 | } else if (IsUFrame()) { 74 | l_Output << "HDLC frame, Addr=0x" << std::hex << (int)GetAddress() << std::dec << ", U-Frame: "; 75 | switch (GetHDLCFrameType()) { 76 | case HdlcFrame::HDLC_FRAMETYPE_U_UI: { 77 | l_bHasPayload = true; 78 | l_Output << "UI"; 79 | break; 80 | } 81 | case HdlcFrame::HDLC_FRAMETYPE_U_SIM: { 82 | l_Output << "SIM"; 83 | break; 84 | } 85 | case HdlcFrame::HDLC_FRAMETYPE_U_SARM: { 86 | l_Output << "SARM"; 87 | break; 88 | } 89 | case HdlcFrame::HDLC_FRAMETYPE_U_UP: { 90 | l_Output << "UP"; 91 | break; 92 | } 93 | case HdlcFrame::HDLC_FRAMETYPE_U_SABM: { 94 | l_Output << "SABM"; 95 | break; 96 | } 97 | case HdlcFrame::HDLC_FRAMETYPE_U_DISC: { 98 | l_Output << "DISC"; 99 | break; 100 | } 101 | case HdlcFrame::HDLC_FRAMETYPE_U_UA: { 102 | l_Output << "UA"; 103 | break; 104 | } 105 | case HdlcFrame::HDLC_FRAMETYPE_U_SNRM: { 106 | l_Output << "SNRM"; 107 | break; 108 | } 109 | case HdlcFrame::HDLC_FRAMETYPE_U_CMDR: { 110 | l_bHasPayload = true; 111 | l_Output << "FRMR/CMDR"; 112 | break; 113 | } 114 | case HdlcFrame::HDLC_FRAMETYPE_U_TEST: { 115 | l_bHasPayload = true; 116 | l_Output << "TEST"; 117 | break; 118 | } 119 | case HdlcFrame::HDLC_FRAMETYPE_U_XID: { 120 | l_bHasPayload = true; 121 | l_Output << "XID"; 122 | break; 123 | } 124 | default: { 125 | break; 126 | } 127 | } // switch 128 | 129 | l_Output << ", PF=" << IsPF(); 130 | } else { 131 | l_Output << "Unparseable HDLC frame"; 132 | } // else 133 | 134 | if (l_bHasPayload) { 135 | l_Output << ", with " << m_Payload.size() << " bytes payload:"; 136 | for (auto it = m_Payload.begin(); it != m_Payload.end(); ++it) { 137 | l_Output << " " << std::hex << std::setw(2) << std::setfill('0') << int(*it); 138 | } // for 139 | } // if 140 | 141 | std::vector l_DissectedFrame; 142 | std::string l_String(l_Output.str()); 143 | l_DissectedFrame.insert(l_DissectedFrame.begin(), l_String.data(), (l_String.data() + l_String.size())); 144 | return l_DissectedFrame; 145 | } 146 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/HdlcFrame.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file HdlcFrame.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef HDLC_FRAME_H 38 | #define HDLC_FRAME_H 39 | 40 | #include 41 | #include 42 | 43 | class HdlcFrame { 44 | public: 45 | HdlcFrame(): m_eHDLCFrameType(HDLC_FRAMETYPE_UNSET), m_PF(false), m_RSeq(0), m_SSeq(0) {} 46 | 47 | void SetAddress(unsigned char a_Address) { m_Address = a_Address; } 48 | unsigned char GetAddress() const { return m_Address; } 49 | 50 | typedef enum { 51 | HDLC_FRAMETYPE_UNSET = 0, 52 | HDLC_FRAMETYPE_I, 53 | HDLC_FRAMETYPE_S_RR, 54 | HDLC_FRAMETYPE_S_RNR, 55 | HDLC_FRAMETYPE_S_REJ, 56 | HDLC_FRAMETYPE_S_SREJ, 57 | HDLC_FRAMETYPE_U_UI, 58 | HDLC_FRAMETYPE_U_SIM, 59 | HDLC_FRAMETYPE_U_SARM, 60 | HDLC_FRAMETYPE_U_UP, 61 | HDLC_FRAMETYPE_U_SABM, 62 | HDLC_FRAMETYPE_U_DISC, 63 | HDLC_FRAMETYPE_U_UA, 64 | HDLC_FRAMETYPE_U_SNRM, 65 | HDLC_FRAMETYPE_U_CMDR, 66 | HDLC_FRAMETYPE_U_TEST, 67 | HDLC_FRAMETYPE_U_XID, 68 | } E_HDLC_FRAMETYPE; 69 | void SetHDLCFrameType(E_HDLC_FRAMETYPE a_eHDLCFrameType) { m_eHDLCFrameType = a_eHDLCFrameType; } 70 | E_HDLC_FRAMETYPE GetHDLCFrameType() const { return m_eHDLCFrameType; } 71 | bool IsEmpty() const { return m_eHDLCFrameType == HDLC_FRAMETYPE_UNSET; } 72 | bool IsIFrame() const { return (m_eHDLCFrameType == HDLC_FRAMETYPE_I); } 73 | bool IsSFrame() const { return ((m_eHDLCFrameType >= HDLC_FRAMETYPE_S_RR) && (m_eHDLCFrameType <= HDLC_FRAMETYPE_S_SREJ)); } 74 | bool IsUFrame() const { return ((m_eHDLCFrameType >= HDLC_FRAMETYPE_U_UI) && (m_eHDLCFrameType <= HDLC_FRAMETYPE_U_XID)); } 75 | 76 | void SetPF(bool a_PF) { if (a_PF) { m_PF = 0x10; } else { m_PF = 0; } } 77 | bool IsPF() const { return ( m_PF & 0x10); } 78 | 79 | void SetRSeq(unsigned char a_RSeq) { m_RSeq = a_RSeq; } 80 | unsigned char GetRSeq() const { return m_RSeq; } 81 | 82 | void SetSSeq(unsigned char a_SSeq) { m_SSeq = a_SSeq; } 83 | unsigned char GetSSeq() const { return m_SSeq; } 84 | 85 | void SetPayload(const std::vector &a_Payload) { m_Payload = a_Payload; } 86 | const std::vector& GetPayload() const { return m_Payload; } 87 | bool HasPayload() const { return (m_Payload.empty() == false); } 88 | 89 | const std::vector Dissect() const; 90 | 91 | private: 92 | // Members 93 | unsigned char m_Address; 94 | E_HDLC_FRAMETYPE m_eHDLCFrameType; 95 | unsigned char m_PF; 96 | unsigned char m_RSeq; 97 | unsigned char m_SSeq; 98 | std::vector m_Payload; 99 | }; 100 | 101 | #endif // HDLC_FRAME_H 102 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/ISerialPortHandler.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file ISerialPortHandler.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef ISERIAL_PORT_HANDLER_H 38 | #define ISERIAL_PORT_HANDLER_H 39 | 40 | #include 41 | #include "BufferType.h" 42 | 43 | class ISerialPortHandler { 44 | public: 45 | // DTOR 46 | virtual ~ISerialPortHandler(){} 47 | 48 | // Methods called by the HDLC ProtocolState object 49 | virtual bool RequiresBufferType(E_BUFFER_TYPE a_eBufferType) const = 0; 50 | virtual void DeliverBufferToClients(E_BUFFER_TYPE a_eBufferType, const std::vector &a_Payload, bool a_bReliable, bool a_bInvalid, bool a_bWasSent) = 0; 51 | virtual void ChangeBaudRate() = 0; 52 | virtual void PropagateSerialPortState() = 0; 53 | virtual void TransmitHDLCFrame(const std::vector &a_Payload) = 0; 54 | virtual void QueryForPayload(bool a_bQueryReliable, bool a_bQueryUnreliable) = 0; 55 | }; 56 | 57 | #endif // ISERIAL_PORT_HANDLER_H 58 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/ProtocolState.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file ProtocolState.cpp 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #include "ProtocolState.h" 38 | #include 39 | #include "FrameGenerator.h" 40 | #include "ISerialPortHandler.h" 41 | 42 | ProtocolState::ProtocolState(std::shared_ptr a_SerialPortHandler, boost::asio::io_service& a_IOService): m_SerialPortHandler(a_SerialPortHandler), m_FrameParser(*this), m_Timer(a_IOService) { 43 | // Initialize alive state helper 44 | m_AliveState = std::make_shared(a_IOService); 45 | m_AliveState->SetSendProbeCallback([this]() { 46 | m_bSendProbe = true; 47 | if (m_SerialPortHandler) { 48 | OpportunityForTransmission(); 49 | } else { 50 | // Already closed or shutdown was called 51 | } // else 52 | }); 53 | m_AliveState->SetChangeBaudrateCallback([this]() { 54 | if (m_SerialPortHandler) { 55 | m_SerialPortHandler->ChangeBaudRate(); 56 | m_SerialPortHandler->PropagateSerialPortState(); 57 | } else { 58 | // Already closed or shutdown was called 59 | } // else 60 | }); 61 | 62 | Reset(); 63 | } 64 | 65 | void ProtocolState::Reset() { 66 | m_AliveState->Stop(); 67 | m_Timer.cancel(); 68 | m_bStarted = false; 69 | m_bAwaitsNextHDLCFrame = true; 70 | m_SSeqOutgoing = 0; 71 | m_RSeqIncoming = 0; 72 | m_bSendProbe = false; 73 | m_bPeerStoppedFlow = false; 74 | m_bPeerStoppedFlowNew = false; 75 | m_bPeerStoppedFlowQueried = false; 76 | m_bPeerRequiresAck = false; 77 | m_bWaitForAck = false; 78 | m_SREJs.clear(); 79 | m_FrameParser.Reset(); 80 | } 81 | 82 | void ProtocolState::Start() { 83 | // Start the state machine 84 | Reset(); 85 | m_bStarted = true; 86 | m_AliveState->Start(); // trigger baud rate detection 87 | OpportunityForTransmission(); 88 | } 89 | 90 | void ProtocolState::Stop() { 91 | if (m_bStarted) { 92 | // Stop the state machine 93 | Reset(); 94 | m_SerialPortHandler->PropagateSerialPortState(); 95 | } // if 96 | } 97 | 98 | void ProtocolState::Shutdown() { 99 | if (m_bStarted) { 100 | // Stop the state machine, but do not emit any subsequent events 101 | Reset(); 102 | m_SerialPortHandler.reset(); 103 | } // if 104 | } 105 | 106 | void ProtocolState::SendPayload(const std::vector &a_Payload, bool a_bReliable) { 107 | // Queue payload for later framing 108 | if (a_bReliable) { 109 | // TODO: assure that the size does not grow without limits! 110 | m_WaitQueueReliable.emplace_back(std::move(a_Payload)); 111 | } else { 112 | // TODO: assure that the size does not grow without limits! 113 | m_WaitQueueUnreliable.emplace_back(std::move(a_Payload)); 114 | } // else 115 | 116 | bool l_bSendReliableFrames = m_bStarted; 117 | l_bSendReliableFrames |= (m_bPeerStoppedFlow == false); 118 | l_bSendReliableFrames |= (m_WaitQueueReliable.empty() == false); 119 | bool l_bSendUnreliableFrames = m_bStarted; 120 | l_bSendUnreliableFrames |= (m_WaitQueueUnreliable.empty() == false); 121 | if ((m_bAwaitsNextHDLCFrame) && ((l_bSendReliableFrames) || (l_bSendUnreliableFrames))) { 122 | OpportunityForTransmission(); 123 | } // if 124 | } 125 | 126 | void ProtocolState::TriggerNextHDLCFrame() { 127 | // Checks 128 | if (!m_bStarted) { 129 | return; 130 | } // if 131 | 132 | // The SerialPortHandler is ready to transmit the next HDLC frame 133 | m_bAwaitsNextHDLCFrame = true; 134 | OpportunityForTransmission(); 135 | } 136 | 137 | void ProtocolState::AddReceivedRawBytes(const unsigned char* a_Buffer, size_t a_Bytes) { 138 | // Checks 139 | if (!m_bStarted) { 140 | return; 141 | } // if 142 | 143 | m_FrameParser.AddReceivedRawBytes(a_Buffer, a_Bytes); 144 | } 145 | 146 | void ProtocolState::InterpretDeserializedFrame(const std::vector &a_Payload, const HdlcFrame& a_HdlcFrame, bool a_bMessageInvalid) { 147 | // Checks 148 | if (!m_bStarted) { 149 | return; 150 | } // if 151 | 152 | // Deliver raw frame to clients that have interest 153 | if (m_SerialPortHandler->RequiresBufferType(BUFFER_TYPE_RAW)) { 154 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_RAW, a_Payload, false, a_bMessageInvalid, false); // not escaped 155 | } // if 156 | 157 | if (m_SerialPortHandler->RequiresBufferType(BUFFER_TYPE_DISSECTED)) { 158 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_DISSECTED, a_HdlcFrame.Dissect(), false, a_bMessageInvalid, false); 159 | } // if 160 | 161 | // Stop here if the frame was considered broken 162 | if (a_bMessageInvalid) { 163 | return; 164 | } // if 165 | 166 | // A valid frame was received 167 | if (m_AliveState->OnFrameReceived()) { 168 | m_SerialPortHandler->PropagateSerialPortState(); 169 | } // if 170 | 171 | // Go ahead interpreting the frame we received 172 | if (a_HdlcFrame.HasPayload()) { 173 | // I-Frame or U-Frame with UI 174 | if (m_SerialPortHandler->RequiresBufferType(BUFFER_TYPE_PAYLOAD)) { 175 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_PAYLOAD, a_HdlcFrame.GetPayload(), a_HdlcFrame.IsIFrame(), a_bMessageInvalid, false); 176 | } // if 177 | 178 | // If it is an I-Frame, the data may have to be acked 179 | if (a_HdlcFrame.IsIFrame()) { 180 | if (m_RSeqIncoming != a_HdlcFrame.GetSSeq()) { 181 | m_SREJs.clear(); 182 | for (unsigned char it = m_RSeqIncoming; (it & 0x07) != a_HdlcFrame.GetSSeq(); ++it) { 183 | m_SREJs.emplace_back(it); 184 | } // for 185 | } // if 186 | 187 | m_RSeqIncoming = ((a_HdlcFrame.GetSSeq() + 1) & 0x07); 188 | m_bPeerRequiresAck = true; 189 | } // if 190 | } // if 191 | 192 | // Check the various types of ACKs and NACKs 193 | if ((a_HdlcFrame.IsIFrame()) || (a_HdlcFrame.IsSFrame())) { 194 | if ((a_HdlcFrame.IsIFrame()) || (a_HdlcFrame.GetHDLCFrameType() == HdlcFrame::HDLC_FRAMETYPE_S_RR)) { 195 | if ((m_bPeerStoppedFlow) && (a_HdlcFrame.GetHDLCFrameType() == HdlcFrame::HDLC_FRAMETYPE_S_RR)) { 196 | // The peer restarted the flow: RR clears RNR condition 197 | m_bPeerStoppedFlow = false; 198 | m_bWaitForAck = false; 199 | m_Timer.cancel(); 200 | } // if 201 | 202 | // Currently, we send only one I-frame at a time and wait until the respective ACK is received 203 | if ((m_bWaitForAck) && (a_HdlcFrame.GetRSeq() == ((m_SSeqOutgoing + 1) & 0x07))) { 204 | // We found the respective sequence number to the last transmitted I-frame 205 | m_bWaitForAck = false; 206 | m_Timer.cancel(); 207 | m_WaitQueueReliable.pop_front(); 208 | } // if 209 | 210 | m_SSeqOutgoing = a_HdlcFrame.GetRSeq(); 211 | } else if (a_HdlcFrame.GetHDLCFrameType() == HdlcFrame::HDLC_FRAMETYPE_S_RNR) { 212 | // The peer wants us to stop sending subsequent data 213 | if (!m_bPeerStoppedFlow) { 214 | // Start periodical query 215 | m_bPeerStoppedFlow = true; 216 | m_bPeerStoppedFlowNew = true; 217 | m_bPeerStoppedFlowQueried = false; 218 | } // if 219 | 220 | if (m_bWaitForAck) { 221 | m_bWaitForAck = false; 222 | m_Timer.cancel(); 223 | if (a_HdlcFrame.GetRSeq() == ((m_SSeqOutgoing + 1) & 0x07)) { 224 | // We found the respective sequence number to the last transmitted I-frame 225 | m_WaitQueueReliable.pop_front(); 226 | } // if 227 | } // if 228 | 229 | // Now we know which SeqNr the peer awaits next... after the RNR condition was cleared 230 | m_SSeqOutgoing = a_HdlcFrame.GetRSeq(); 231 | } else if (a_HdlcFrame.GetHDLCFrameType() == HdlcFrame::HDLC_FRAMETYPE_S_REJ) { 232 | if (m_bPeerStoppedFlow) { 233 | // The peer restarted the flow: REJ clears RNR condition 234 | m_bPeerStoppedFlow = false; 235 | m_bWaitForAck = false; 236 | m_Timer.cancel(); 237 | } // if 238 | 239 | // The peer requests for go-back-N. We have to retransmit all affected packets, but not with this version of HDLC. 240 | if (a_HdlcFrame.GetRSeq() == m_SSeqOutgoing) { 241 | // We found the respective sequence number to the last transmitted I-frame 242 | m_bWaitForAck = false; 243 | m_Timer.cancel(); 244 | } // if 245 | 246 | m_SSeqOutgoing = ((a_HdlcFrame.GetRSeq() + 0x07) & 0x07); 247 | } else { 248 | assert(a_HdlcFrame.GetHDLCFrameType() == HdlcFrame::HDLC_FRAMETYPE_S_SREJ); 249 | if (m_bPeerStoppedFlow) { 250 | // The peer restarted the flow: SREJ clears RNR condition 251 | m_bPeerStoppedFlow = false; 252 | m_bWaitForAck = false; 253 | m_Timer.cancel(); 254 | } // if 255 | 256 | // The peer requests for the retransmission of a single segment with a specific sequence number 257 | // This cannot be implemented using this reduced version of HDLC! 258 | if ((m_bWaitForAck) && (a_HdlcFrame.GetRSeq() == m_SSeqOutgoing)) { 259 | // We found the respective sequence number to the last transmitted I-frame. 260 | // In this version of HDLC, this should not happen! 261 | m_bWaitForAck = false; 262 | m_Timer.cancel(); 263 | } // if 264 | } // else 265 | } // if 266 | 267 | if (m_bAwaitsNextHDLCFrame) { 268 | // Check if we have to send something now 269 | OpportunityForTransmission(); 270 | } // if 271 | } 272 | 273 | void ProtocolState::OpportunityForTransmission() { 274 | // Checks 275 | if (!m_bAwaitsNextHDLCFrame) { 276 | return; 277 | } // if 278 | 279 | HdlcFrame l_HdlcFrame; 280 | if (m_bSendProbe) { 281 | // The correct baud rate setting is unknown yet, or it has to be checked again. Send an U-TEST frame. 282 | m_bSendProbe = false; 283 | l_HdlcFrame = PrepareUFrameTEST(); 284 | } // if 285 | 286 | if (l_HdlcFrame.IsEmpty() && m_AliveState->IsAlive()) { 287 | // The serial link to the device is alive. Send all outstanding S-SREJs first. 288 | if (m_SREJs.empty() == false) { 289 | // Send SREJs first 290 | l_HdlcFrame = PrepareSFrameSREJ(); 291 | } // if 292 | 293 | // Check if packets are waiting for reliable transmission 294 | if (l_HdlcFrame.IsEmpty() && (m_WaitQueueReliable.empty() == false) && (!m_bWaitForAck) && (!m_bPeerStoppedFlow)) { 295 | // Send an I-Frame now 296 | l_HdlcFrame = PrepareIFrame(); 297 | m_bWaitForAck = true; 298 | 299 | // I-frames carry an ACK 300 | m_bPeerRequiresAck = false; 301 | 302 | // Start retransmission timer 303 | auto self(shared_from_this()); 304 | m_Timer.expires_from_now(boost::posix_time::milliseconds(500)); 305 | m_Timer.async_wait([this, self](const boost::system::error_code& ec) { 306 | if (!ec) { 307 | // Send the head element of the wait queue again 308 | m_bWaitForAck = false; 309 | OpportunityForTransmission(); 310 | } // if 311 | }); 312 | } // if 313 | 314 | // Send outstanding RR? 315 | if (l_HdlcFrame.IsEmpty() && ((m_bPeerRequiresAck) || m_bPeerStoppedFlowNew)) { 316 | bool l_bStartTimer = false; 317 | if (m_bPeerStoppedFlowNew) { 318 | m_bPeerStoppedFlowNew = false; 319 | l_bStartTimer = true; 320 | } else { 321 | // Prepare RR 322 | l_HdlcFrame = PrepareSFrameRR(); 323 | m_bPeerRequiresAck = false; 324 | if (m_bPeerStoppedFlow && !m_bPeerStoppedFlowQueried) { 325 | // During the RNR confition at the peer, we query it periodically 326 | l_HdlcFrame.SetPF(true); // This is a hack due to missing command/response support 327 | m_bPeerStoppedFlowQueried = true; 328 | l_bStartTimer = true; 329 | } // if 330 | } // else 331 | 332 | if (l_bStartTimer) { 333 | m_Timer.cancel(); 334 | auto self(shared_from_this()); 335 | m_Timer.expires_from_now(boost::posix_time::milliseconds(500)); 336 | m_Timer.async_wait([this, self](const boost::system::error_code& ec) { 337 | if (!ec) { 338 | if (m_bPeerStoppedFlow) { 339 | m_bPeerRequiresAck = true; 340 | m_bPeerStoppedFlowQueried = false; 341 | OpportunityForTransmission(); 342 | } // if 343 | } // if 344 | }); 345 | } // if 346 | } // if 347 | 348 | // Check if packets are waiting for unreliable transmission 349 | if (l_HdlcFrame.IsEmpty() && (m_WaitQueueUnreliable.empty() == false)) { 350 | l_HdlcFrame = PrepareUFrameUI(); 351 | m_WaitQueueUnreliable.pop_front(); 352 | } // if 353 | 354 | // If there is nothing to send, try to fill the wait queues, but only if necessary. 355 | if (l_HdlcFrame.IsEmpty()) { 356 | // These expressions are the result of some boolean logic 357 | bool l_bQueryReliable = (m_WaitQueueUnreliable.empty() && m_WaitQueueReliable.empty() && (!m_bPeerStoppedFlow)); 358 | bool l_bQueryUnreliable = (m_WaitQueueUnreliable.empty() && (m_WaitQueueReliable.empty() || m_bPeerStoppedFlow)); 359 | if (l_bQueryReliable || l_bQueryUnreliable) { 360 | m_SerialPortHandler->QueryForPayload(l_bQueryReliable, l_bQueryUnreliable); 361 | } // if 362 | } // if 363 | } // if 364 | 365 | if (l_HdlcFrame.IsEmpty() == false) { 366 | // Deliver unescaped frame to clients that have interest 367 | m_bAwaitsNextHDLCFrame = false; 368 | auto l_HDLCFrameBuffer = FrameGenerator::SerializeFrame(l_HdlcFrame); 369 | if (m_SerialPortHandler->RequiresBufferType(BUFFER_TYPE_RAW)) { 370 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_RAW, l_HDLCFrameBuffer, l_HdlcFrame.IsIFrame(), false, true); // not escaped 371 | } // if 372 | 373 | if (m_SerialPortHandler->RequiresBufferType(BUFFER_TYPE_DISSECTED)) { 374 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_DISSECTED, l_HdlcFrame.Dissect(), l_HdlcFrame.IsIFrame(), false, true); 375 | } // if 376 | 377 | m_SerialPortHandler->TransmitHDLCFrame(std::move(FrameGenerator::EscapeFrame(l_HDLCFrameBuffer))); 378 | } // if 379 | } 380 | 381 | HdlcFrame ProtocolState::PrepareIFrame() { 382 | // Fresh Payload to be sent is available. 383 | assert(m_WaitQueueReliable.empty() == false); 384 | if (m_SerialPortHandler->RequiresBufferType(BUFFER_TYPE_PAYLOAD)) { 385 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_PAYLOAD, m_WaitQueueReliable.front(), true, false, true); 386 | } // if 387 | 388 | // Prepare I-Frame 389 | HdlcFrame l_HdlcFrame; 390 | l_HdlcFrame.SetAddress(0x30); 391 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_I); 392 | l_HdlcFrame.SetPF(false); 393 | l_HdlcFrame.SetSSeq(m_SSeqOutgoing); 394 | l_HdlcFrame.SetRSeq(m_RSeqIncoming); 395 | l_HdlcFrame.SetPayload(m_WaitQueueReliable.front()); 396 | return(l_HdlcFrame); 397 | } 398 | 399 | HdlcFrame ProtocolState::PrepareSFrameRR() { 400 | HdlcFrame l_HdlcFrame; 401 | l_HdlcFrame.SetAddress(0x30); 402 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_S_RR); 403 | l_HdlcFrame.SetPF(false); 404 | l_HdlcFrame.SetRSeq(m_RSeqIncoming); 405 | return(l_HdlcFrame); 406 | } 407 | 408 | HdlcFrame ProtocolState::PrepareSFrameSREJ() { 409 | HdlcFrame l_HdlcFrame; 410 | l_HdlcFrame.SetAddress(0x30); 411 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_S_SREJ); 412 | l_HdlcFrame.SetPF(false); 413 | l_HdlcFrame.SetRSeq(m_SREJs.front()); 414 | m_SREJs.pop_front(); 415 | return(l_HdlcFrame); 416 | } 417 | 418 | HdlcFrame ProtocolState::PrepareUFrameUI() { 419 | assert(m_WaitQueueUnreliable.empty() == false); 420 | m_SerialPortHandler->DeliverBufferToClients(BUFFER_TYPE_PAYLOAD, m_WaitQueueUnreliable.front(), false, false, true); 421 | 422 | // Prepare UI-Frame 423 | HdlcFrame l_HdlcFrame; 424 | l_HdlcFrame.SetAddress(0x30); 425 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_UI); 426 | l_HdlcFrame.SetPF(false); 427 | l_HdlcFrame.SetPayload(m_WaitQueueUnreliable.front()); 428 | return(l_HdlcFrame); 429 | } 430 | 431 | HdlcFrame ProtocolState::PrepareUFrameTEST() { 432 | HdlcFrame l_HdlcFrame; 433 | l_HdlcFrame.SetAddress(0x30); 434 | l_HdlcFrame.SetHDLCFrameType(HdlcFrame::HDLC_FRAMETYPE_U_TEST); 435 | l_HdlcFrame.SetPF(false); 436 | return(l_HdlcFrame); 437 | } 438 | -------------------------------------------------------------------------------- /src/SerialPort/HDLC/ProtocolState.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file ProtocolState.h 3 | * \brief 4 | * 5 | * Copyright (c) 2016, Florian Evers, florian-evers@gmx.de 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are 10 | * met: 11 | * 12 | * (1) Redistributions of source code must retain the above copyright 13 | * notice, this list of conditions and the following disclaimer. 14 | * 15 | * (2) Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in 17 | * the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * (3)The name of the author may not be used to 21 | * endorse or promote products derived from this software without 22 | * specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 28 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 32 | * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 33 | * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #ifndef PROTOCOL_STATE_H 38 | #define PROTOCOL_STATE_H 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include "AliveState.h" 45 | #include "HdlcFrame.h" 46 | #include "FrameParser.h" 47 | class ISerialPortHandler; 48 | 49 | class ProtocolState: public std::enable_shared_from_this { 50 | public: 51 | ProtocolState(std::shared_ptr a_SerialPortHandler, boost::asio::io_service& a_IOService); 52 | 53 | void Start(); 54 | void Stop(); 55 | void Shutdown(); 56 | 57 | void SendPayload(const std::vector &a_Payload, bool a_bReliable); 58 | void TriggerNextHDLCFrame(); 59 | void AddReceivedRawBytes(const unsigned char* a_Buffer, size_t a_Bytes); 60 | void InterpretDeserializedFrame(const std::vector &a_Payload, const HdlcFrame& a_HdlcFrame, bool a_bMessageInvalid); 61 | 62 | // Query state 63 | bool IsAlive() const { return m_AliveState->IsAlive(); } 64 | bool IsRunning() const { return m_bStarted; } 65 | 66 | private: 67 | // Internal helpers 68 | void Reset(); 69 | void OpportunityForTransmission(); 70 | HdlcFrame PrepareIFrame(); 71 | HdlcFrame PrepareSFrameRR(); 72 | HdlcFrame PrepareSFrameSREJ(); 73 | HdlcFrame PrepareUFrameUI(); 74 | HdlcFrame PrepareUFrameTEST(); 75 | 76 | // Members 77 | bool m_bStarted; 78 | bool m_bAwaitsNextHDLCFrame; 79 | unsigned char m_SSeqOutgoing; // The sequence number we are going to use for the transmission of the next packet 80 | unsigned char m_RSeqIncoming; // The start of the RX window we offer our peer, defines which packets we expect 81 | 82 | // State of pending actions 83 | bool m_bSendProbe; 84 | bool m_bPeerStoppedFlow; // RNR condition 85 | bool m_bPeerStoppedFlowNew; // RNR condition 86 | bool m_bPeerStoppedFlowQueried; // RNR condition 87 | bool m_bPeerRequiresAck; 88 | bool m_bWaitForAck; 89 | std::deque m_SREJs; 90 | 91 | // Parser and generator 92 | std::shared_ptr m_SerialPortHandler; 93 | FrameParser m_FrameParser; 94 | 95 | // Wait queues 96 | std::deque> m_WaitQueueReliable; 97 | std::deque> m_WaitQueueUnreliable; 98 | 99 | // Alive state 100 | std::shared_ptr m_AliveState; 101 | 102 | // Timer 103 | boost::asio::deadline_timer m_Timer; 104 | bool m_bAliveReceivedSometing; 105 | }; 106 | 107 | #endif // PROTOCOL_STATE_H 108 | -------------------------------------------------------------------------------- /src/SerialPort/SerialPortHandler.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file SerialPortHandler.cpp 3 | * \brief 4 | * 5 | * The hdlc-tools implement the HDLC protocol to easily talk to devices connected via serial communications 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #include "SerialPortHandler.h" 23 | #include 24 | #include "HdlcdServerHandler.h" 25 | #include "SerialPortHandlerCollection.h" 26 | #include "ProtocolState.h" 27 | #include 28 | 29 | SerialPortHandler::SerialPortHandler(const std::string &a_SerialPortName, std::shared_ptr a_SerialPortHandlerCollection, boost::asio::io_service &a_IOService): m_SerialPort(a_IOService), m_IOService(a_IOService) { 30 | m_Registered = true; 31 | m_SerialPortName = a_SerialPortName; 32 | m_SerialPortHandlerCollection = a_SerialPortHandlerCollection; 33 | m_SendBufferOffset = 0; 34 | ::memset(m_BufferTypeSubscribers, 0x00, sizeof(m_BufferTypeSubscribers)); 35 | } 36 | 37 | SerialPortHandler::~SerialPortHandler() { 38 | Stop(); 39 | } 40 | 41 | void SerialPortHandler::AddHdlcdServerHandler(std::shared_ptr a_HdlcdServerHandler) { 42 | assert(a_HdlcdServerHandler->GetBufferType() < BUFFER_TYPE_ARITHMETIC_ENDMARKER); 43 | ++(m_BufferTypeSubscribers[a_HdlcdServerHandler->GetBufferType()]); 44 | m_HdlcdServerHandlerList.push_back(a_HdlcdServerHandler); 45 | if ((m_ProtocolState) && (m_ProtocolState->IsRunning())) { 46 | // Trigger state update messages, to inform the freshly added client 47 | PropagateSerialPortState(); 48 | } // if 49 | } 50 | 51 | void SerialPortHandler::SuspendSerialPort() { 52 | if (m_Registered == false) { 53 | return; 54 | } // if 55 | 56 | if (m_SerialPortLock.SuspendSerialPort()) { 57 | // The serial port is now suspended! 58 | m_ProtocolState->Stop(); 59 | m_SerialPort.cancel(); 60 | m_SerialPort.close(); 61 | } // if 62 | 63 | PropagateSerialPortState(); 64 | } 65 | 66 | void SerialPortHandler::ResumeSerialPort() { 67 | if (m_Registered == false) { 68 | return; 69 | } // if 70 | 71 | if (m_SerialPortLock.ResumeSerialPort()) { 72 | // The serial port is now resumed. Restart activity. 73 | OpenSerialPort(); 74 | } else { 75 | PropagateSerialPortState(); 76 | } // else 77 | } 78 | 79 | void SerialPortHandler::PropagateSerialPortState() { 80 | ForEachHdlcdServerHandler([this](std::shared_ptr a_HdlcdServerHandler) { 81 | a_HdlcdServerHandler->UpdateSerialPortState(m_ProtocolState->IsAlive(), m_SerialPortLock.GetLockHolders()); 82 | }); 83 | } 84 | 85 | void SerialPortHandler::DeliverPayloadToHDLC(const std::vector &a_Payload, bool a_bReliable) { 86 | m_ProtocolState->SendPayload(a_Payload, a_bReliable); 87 | } 88 | 89 | bool SerialPortHandler::RequiresBufferType(E_BUFFER_TYPE a_eBufferType) const { 90 | assert(a_eBufferType < BUFFER_TYPE_ARITHMETIC_ENDMARKER); 91 | return (m_BufferTypeSubscribers[a_eBufferType] != 0); 92 | } 93 | 94 | void SerialPortHandler::DeliverBufferToClients(E_BUFFER_TYPE a_eBufferType, const std::vector &a_Payload, bool a_bReliable, bool a_bInvalid, bool a_bWasSent) { 95 | ForEachHdlcdServerHandler([a_eBufferType, &a_Payload, a_bReliable, a_bInvalid, a_bWasSent](std::shared_ptr a_HdlcdServerHandler) { 96 | a_HdlcdServerHandler->DeliverBufferToClient(a_eBufferType, a_Payload, a_bReliable, a_bInvalid, a_bWasSent); 97 | }); 98 | } 99 | 100 | bool SerialPortHandler::Start() { 101 | m_ProtocolState = std::make_shared(shared_from_this(), m_IOService); 102 | return OpenSerialPort(); 103 | } 104 | 105 | void SerialPortHandler::Stop() { 106 | if (m_Registered) { 107 | m_Registered = false; 108 | 109 | // Keep a copy here to keep this object alive! 110 | auto self(shared_from_this()); 111 | m_SerialPort.cancel(); 112 | m_SerialPort.close(); 113 | m_ProtocolState->Shutdown(); 114 | if (auto l_SerialPortHandlerCollection = m_SerialPortHandlerCollection.lock()) { 115 | l_SerialPortHandlerCollection->DeregisterSerialPortHandler(self); 116 | } // if 117 | 118 | ForEachHdlcdServerHandler([](std::shared_ptr a_HdlcdServerHandler) { 119 | a_HdlcdServerHandler->Stop(); 120 | }); 121 | } // if 122 | } 123 | 124 | bool SerialPortHandler::OpenSerialPort() { 125 | bool l_bResult = true; 126 | try { 127 | // Open the serial port and start processing 128 | m_SerialPort.open(m_SerialPortName); 129 | m_SerialPort.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::none)); 130 | m_SerialPort.set_option(boost::asio::serial_port::character_size(boost::asio::serial_port::character_size(8))); 131 | m_SerialPort.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::one)); 132 | m_SerialPort.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::none)); 133 | m_SerialPort.set_option(boost::asio::serial_port::baud_rate(m_BaudRate.GetBaudRate())); 134 | 135 | // Start processing 136 | m_ProtocolState->Start(); 137 | DoRead(); 138 | 139 | // Trigger first state update message 140 | PropagateSerialPortState(); 141 | } catch (boost::system::system_error& error) { 142 | std::cerr << error.what() << std::endl; 143 | l_bResult = false; 144 | m_Registered = false; 145 | 146 | // TODO: ugly, code duplication. We must assure that cancel is not called! 147 | auto self(shared_from_this()); 148 | m_ProtocolState->Shutdown(); 149 | if (auto l_SerialPortHandlerCollection = m_SerialPortHandlerCollection.lock()) { 150 | l_SerialPortHandlerCollection->DeregisterSerialPortHandler(self); 151 | } // if 152 | 153 | ForEachHdlcdServerHandler([](std::shared_ptr a_HdlcdServerHandler) { 154 | a_HdlcdServerHandler->Stop(); 155 | }); 156 | } // catch 157 | 158 | return l_bResult; 159 | } 160 | 161 | void SerialPortHandler::ChangeBaudRate() { 162 | if (m_Registered) { 163 | m_BaudRate.ToggleBaudRate(); 164 | m_SerialPort.set_option(boost::asio::serial_port::baud_rate(m_BaudRate.GetBaudRate())); 165 | } // if 166 | } 167 | 168 | void SerialPortHandler::TransmitHDLCFrame(const std::vector &a_Payload) { 169 | // Copy buffer holding the escaped HDLC frame for transmission via the serial interface 170 | assert(m_SendBufferOffset == 0); 171 | assert(m_SerialPortLock.GetSerialPortState() == false); 172 | m_SendBuffer = std::move(a_Payload); 173 | 174 | // Trigger transmission 175 | DoWrite(); 176 | } 177 | 178 | void SerialPortHandler::QueryForPayload(bool a_bQueryReliable, bool a_bQueryUnreliable) { 179 | ForEachHdlcdServerHandler([a_bQueryReliable, a_bQueryUnreliable](std::shared_ptr a_HdlcdServerHandler) { 180 | a_HdlcdServerHandler->QueryForPayload(a_bQueryReliable, a_bQueryUnreliable); 181 | }); 182 | } 183 | 184 | void SerialPortHandler::DoRead() { 185 | auto self(shared_from_this()); 186 | m_SerialPort.async_read_some(boost::asio::buffer(m_ReadBuffer, max_length),[this, self](boost::system::error_code a_ErrorCode, std::size_t a_BytesRead) { 187 | if (!a_ErrorCode) { 188 | m_ProtocolState->AddReceivedRawBytes(m_ReadBuffer, a_BytesRead); 189 | if (m_SerialPortLock.GetSerialPortState() == false) { 190 | DoRead(); 191 | } // if 192 | } else { 193 | if (m_SerialPortLock.GetSerialPortState() == false) { 194 | std::cerr << "SERIAL READ ERROR:" << a_ErrorCode << std::endl; 195 | Stop(); 196 | } // if 197 | } 198 | }); 199 | } 200 | 201 | void SerialPortHandler::DoWrite() { 202 | auto self(shared_from_this()); 203 | m_SerialPort.async_write_some(boost::asio::buffer(&m_SendBuffer[m_SendBufferOffset], (m_SendBuffer.size() - m_SendBufferOffset)),[this, self](boost::system::error_code a_ErrorCode, std::size_t a_BytesSent) { 204 | if (!a_ErrorCode) { 205 | m_SendBufferOffset += a_BytesSent; 206 | if (m_SendBufferOffset == m_SendBuffer.size()) { 207 | // Indicate that we are ready to transmit the next HDLC frame 208 | m_SendBufferOffset = 0; 209 | if (m_SerialPortLock.GetSerialPortState() == false) { 210 | m_ProtocolState->TriggerNextHDLCFrame(); 211 | } // if 212 | } else { 213 | // Only a partial transmission. We are not done yet. 214 | if (m_SerialPortLock.GetSerialPortState() == false) { 215 | DoWrite(); 216 | } // if 217 | } // else 218 | } else { 219 | if (m_SerialPortLock.GetSerialPortState() == false) { 220 | std::cerr << "SERIAL WRITE ERROR:" << a_ErrorCode << std::endl; 221 | Stop(); 222 | } // if 223 | } // else 224 | }); 225 | } 226 | 227 | void SerialPortHandler::ForEachHdlcdServerHandler(std::function)> a_Function) { 228 | assert(a_Function); 229 | bool l_RebuildSubscriptions = false; 230 | static bool s_bCyclicCallGuard = false; 231 | for (auto cur = m_HdlcdServerHandlerList.begin(); cur != m_HdlcdServerHandlerList.end();) { 232 | auto next = cur; 233 | ++next; 234 | if (auto l_ClientHandler = cur->lock()) { 235 | // Be careful here, as there are cyclic calls back to this method resulting in an invalid "next" iterator! 236 | bool l_bGuardLocked = false; 237 | if (!s_bCyclicCallGuard) { 238 | s_bCyclicCallGuard = true; 239 | l_bGuardLocked = true; 240 | } // if 241 | 242 | a_Function(l_ClientHandler); 243 | if (l_bGuardLocked) { 244 | s_bCyclicCallGuard = false; 245 | } // if 246 | } else { 247 | // Outdated entry. Only remove it if this is not a cyclic call 248 | if (!s_bCyclicCallGuard) { 249 | m_HdlcdServerHandlerList.erase(cur); 250 | l_RebuildSubscriptions = true; 251 | } // if 252 | } // else 253 | 254 | cur = next; 255 | } // for 256 | 257 | if (l_RebuildSubscriptions) { 258 | // Rebuild the subscription database 259 | ::memset(m_BufferTypeSubscribers, 0x00, sizeof(m_BufferTypeSubscribers)); 260 | ForEachHdlcdServerHandler([this](std::shared_ptr a_HdlcdServerHandler) { 261 | assert(a_HdlcdServerHandler->GetBufferType() < BUFFER_TYPE_ARITHMETIC_ENDMARKER); 262 | ++(m_BufferTypeSubscribers[a_HdlcdServerHandler->GetBufferType()]); 263 | }); 264 | } // if 265 | } 266 | -------------------------------------------------------------------------------- /src/SerialPort/SerialPortHandler.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file SerialPortHandler.h 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #ifndef SERIAL_PORT_HANDLER_H 23 | #define SERIAL_PORT_HANDLER_H 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "ISerialPortHandler.h" 31 | #include "SerialPortLock.h" 32 | #include "BaudRate.h" 33 | class SerialPortHandlerCollection; 34 | class HdlcdServerHandler; 35 | class ProtocolState; 36 | 37 | class SerialPortHandler: public ISerialPortHandler, public std::enable_shared_from_this { 38 | public: 39 | // CTOR and DTOR 40 | SerialPortHandler(const std::string &a_SerialPortName, std::shared_ptr a_SerialPortHandlerCollection, boost::asio::io_service& a_IOService); 41 | ~SerialPortHandler(); 42 | 43 | void AddHdlcdServerHandler(std::shared_ptr a_HdlcdServerHandler); 44 | void DeliverPayloadToHDLC(const std::vector &a_Payload, bool a_bReliable); 45 | 46 | bool Start(); 47 | void Stop(); 48 | 49 | // Suspend / resume serial port 50 | void SuspendSerialPort(); 51 | void ResumeSerialPort(); 52 | 53 | void PropagateSerialPortState(); 54 | 55 | private: 56 | // Called by a ProtocolState object 57 | bool RequiresBufferType(E_BUFFER_TYPE a_eBufferType) const; 58 | void DeliverBufferToClients(E_BUFFER_TYPE a_eBufferType, const std::vector &a_Payload, bool a_bReliable, bool a_bInvalid, bool a_bWasSent); 59 | bool OpenSerialPort(); 60 | void ChangeBaudRate(); 61 | void TransmitHDLCFrame(const std::vector &a_Payload); 62 | void QueryForPayload(bool a_bQueryReliable, bool a_bQueryUnreliable); 63 | 64 | // Internal helpers 65 | void DoRead(); 66 | void DoWrite(); 67 | void ForEachHdlcdServerHandler(std::function)> a_Function); 68 | 69 | // Members 70 | bool m_Registered; 71 | boost::asio::serial_port m_SerialPort; 72 | boost::asio::io_service &m_IOService; 73 | std::shared_ptr m_ProtocolState; 74 | std::string m_SerialPortName; 75 | std::weak_ptr m_SerialPortHandlerCollection; 76 | std::list> m_HdlcdServerHandlerList; 77 | enum { max_length = 1024 }; 78 | unsigned char m_ReadBuffer[max_length]; 79 | 80 | std::vector m_SendBuffer; 81 | size_t m_SendBufferOffset; 82 | SerialPortLock m_SerialPortLock; 83 | BaudRate m_BaudRate; 84 | 85 | // Track all subscribed clients 86 | size_t m_BufferTypeSubscribers[BUFFER_TYPE_ARITHMETIC_ENDMARKER]; 87 | }; 88 | 89 | #endif // SERIAL_PORT_HANDLER_H 90 | -------------------------------------------------------------------------------- /src/SerialPort/SerialPortHandlerCollection.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file SerialPortHandlerCollection.cpp 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #include "SerialPortHandlerCollection.h" 23 | #include "SerialPortHandler.h" 24 | #include "HdlcdServerHandler.h" 25 | 26 | SerialPortHandlerCollection::SerialPortHandlerCollection(boost::asio::io_service& a_IOService): m_IOService(a_IOService) { 27 | } 28 | 29 | void SerialPortHandlerCollection::Shutdown() { 30 | // No need to cleanup, this class possesses only weak pointers 31 | } 32 | 33 | std::shared_ptr> SerialPortHandlerCollection::GetSerialPortHandler(const std::string &a_SerialPortName, std::shared_ptr a_HdlcdServerHandler) { 34 | std::shared_ptr> l_SerialPortHandler; 35 | bool l_HasToBeStarted = false; 36 | { 37 | // This is some magic here to implement automatic cleanup 38 | auto& l_SerialPortHandlerWeak(m_SerialPortHandlerMap[a_SerialPortName]); 39 | l_SerialPortHandler = l_SerialPortHandlerWeak.lock(); 40 | if (!l_SerialPortHandler) { 41 | auto l_NewSerialPortHandler = std::make_shared(a_SerialPortName, shared_from_this(), m_IOService); 42 | std::shared_ptr> l_NewSerialPortHandlerStopper(new std::shared_ptr(l_NewSerialPortHandler), [=](std::shared_ptr* todelete){ (*todelete)->Stop(); delete(todelete); }); 43 | l_SerialPortHandler = l_NewSerialPortHandlerStopper; 44 | l_SerialPortHandlerWeak = l_SerialPortHandler; 45 | l_HasToBeStarted = true; 46 | } // if 47 | } 48 | 49 | l_SerialPortHandler.get()->get()->AddHdlcdServerHandler(a_HdlcdServerHandler); 50 | if (l_HasToBeStarted) { 51 | if (l_SerialPortHandler.get()->get()->Start() == false) { 52 | l_SerialPortHandler.reset(); 53 | } // if 54 | } // if 55 | 56 | return l_SerialPortHandler; 57 | } 58 | 59 | void SerialPortHandlerCollection::DeregisterSerialPortHandler(std::shared_ptr a_SerialPortHandler) { 60 | assert(a_SerialPortHandler); 61 | for (auto it = m_SerialPortHandlerMap.begin(); it != m_SerialPortHandlerMap.end(); ++it) { 62 | if (auto cph = it->second.lock()) { 63 | if (*(cph.get()) == a_SerialPortHandler) { 64 | m_SerialPortHandlerMap.erase(it); 65 | break; 66 | } // if 67 | } // if 68 | } // for 69 | } 70 | -------------------------------------------------------------------------------- /src/SerialPort/SerialPortHandlerCollection.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file SerialPortHandlerCollection.h 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #ifndef SERIAL_PORT_HANDLER_COLLECTION_H 23 | #define SERIAL_PORT_HANDLER_COLLECTION_H 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | class HdlcdServerHandler; 30 | class SerialPortHandler; 31 | 32 | class SerialPortHandlerCollection: public std::enable_shared_from_this { 33 | public: 34 | // CTOR and resetter 35 | SerialPortHandlerCollection(boost::asio::io_service& a_IOService); 36 | void Shutdown(); 37 | 38 | std::shared_ptr> GetSerialPortHandler(const std::string &a_SerialPortName, std::shared_ptr a_HdlcdServerHandler); 39 | 40 | // To be called by a SerialPortHandler 41 | void DeregisterSerialPortHandler(std::shared_ptr a_SerialPortHandler); 42 | 43 | private: 44 | // Members 45 | boost::asio::io_service& m_IOService; 46 | std::map>> m_SerialPortHandlerMap; 47 | }; 48 | 49 | #endif // SERIAL_PORT_HANDLER_COLLECTION_H 50 | -------------------------------------------------------------------------------- /src/SerialPort/SerialPortLock.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file SerialPortLock.cpp 3 | * \brief 4 | * 5 | * The hdlc-tools implement the HDLC protocol to easily talk to devices connected via serial communications 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #include "SerialPortLock.h" 23 | 24 | SerialPortLock::SerialPortLock() { 25 | m_NbrOfLocks = 0; 26 | } 27 | 28 | bool SerialPortLock::SuspendSerialPort() { 29 | return ((++m_NbrOfLocks) == 1); 30 | } 31 | 32 | bool SerialPortLock::ResumeSerialPort() { 33 | return ((--m_NbrOfLocks) == 0); 34 | } 35 | 36 | bool SerialPortLock::GetSerialPortState() const { 37 | return (m_NbrOfLocks != 0); 38 | } 39 | -------------------------------------------------------------------------------- /src/SerialPort/SerialPortLock.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file SerialPortLock.h 3 | * \brief 4 | * 5 | * The HDLC Deamon implements the HDLC protocol to easily talk to devices connected via serial communications. 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #ifndef SERIAL_PORT_LOCK_H 23 | #define SERIAL_PORT_LOCK_H 24 | 25 | #include 26 | 27 | class SerialPortLock { 28 | public: 29 | // CTOR 30 | SerialPortLock(); 31 | 32 | // Influende the serial port 33 | bool SuspendSerialPort(); 34 | bool ResumeSerialPort(); 35 | bool GetSerialPortState() const; 36 | size_t GetLockHolders() const { return m_NbrOfLocks; } 37 | 38 | private: 39 | // Members 40 | size_t m_NbrOfLocks; 41 | }; 42 | 43 | #endif // SERIAL_PORT_LOCK_H 44 | -------------------------------------------------------------------------------- /src/main-hdlcd.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file main-hdlcd.cpp 3 | * \brief 4 | * 5 | * The hdlc-tools implement the HDLC protocol to easily talk to devices connected via serial communications 6 | * Copyright (C) 2016 Florian Evers, florian-evers@gmx.de 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | */ 21 | 22 | #include "Config.h" 23 | #include 24 | #include 25 | #include 26 | #include "SerialPortHandlerCollection.h" 27 | #include "HdlcdServerHandlerCollection.h" 28 | 29 | int main(int argc, char **argv) { 30 | try { 31 | // Declare the supported options. 32 | boost::program_options::options_description l_Description("Allowed options"); 33 | l_Description.add_options() 34 | ("help,h", "produce this help message") 35 | ("version,v", "show version information") 36 | ("port,p", boost::program_options::value(), 37 | "the TCP port to accept clients on") 38 | ; 39 | 40 | // Parse the command line 41 | boost::program_options::variables_map l_VariablesMap; 42 | boost::program_options::store(boost::program_options::parse_command_line(argc, argv, l_Description), l_VariablesMap); 43 | boost::program_options::notify(l_VariablesMap); 44 | if (l_VariablesMap.count("version")) { 45 | std::cerr << "HDLC daemon version " << HDLCD_VERSION_MAJOR << "." << HDLCD_VERSION_MINOR 46 | << " built with hdlcd-devel version " << HDLCD_DEVEL_VERSION_MAJOR << "." << HDLCD_DEVEL_VERSION_MINOR << std::endl; 47 | } // if 48 | 49 | if (l_VariablesMap.count("help")) { 50 | std::cout << l_Description << std::endl; 51 | std::cout << "The HDLC Daemon is Copyright (C) 2016, and GNU GPL'd, by Florian Evers." << std::endl; 52 | std::cout << "Bug reports, feedback, admiration, abuse, etc, to: https://github.com/Strunzdesign/hdlcd" << std::endl; 53 | return 1; 54 | } // if 55 | 56 | if (!l_VariablesMap.count("port")) { 57 | std::cout << "hdlcd: you have to specify the TCP listener port" << std::endl; 58 | std::cout << "hdlcd: Use --help for more information." << std::endl; 59 | return 1; 60 | } // if 61 | 62 | // Install signal handlers 63 | boost::asio::io_service l_IoService; 64 | boost::asio::signal_set l_Signals(l_IoService); 65 | l_Signals.add(SIGINT); 66 | l_Signals.add(SIGTERM); 67 | l_Signals.async_wait([&l_IoService](boost::system::error_code, int){ l_IoService.stop(); }); 68 | 69 | // Create and initialize components 70 | auto l_SerialPortHandlerCollection = std::make_shared (l_IoService); 71 | auto l_HdlcdServerHandlerCollection = std::make_shared(l_IoService, l_SerialPortHandlerCollection, l_VariablesMap["port"].as()); 72 | 73 | // Start event processing 74 | l_IoService.run(); 75 | 76 | // Shutdown 77 | l_HdlcdServerHandlerCollection->Shutdown(); 78 | l_SerialPortHandlerCollection->Shutdown(); 79 | 80 | } catch (std::exception& a_Error) { 81 | std::cerr << "Exception: " << a_Error.what() << "\n"; 82 | return 1; 83 | } // catch 84 | 85 | return 0; 86 | } 87 | --------------------------------------------------------------------------------