├── .gitignore ├── LICENSE ├── Makefile ├── README.md └── src ├── Daemon.c ├── Daemon.h ├── Makefile ├── README ├── calendar.c ├── calendar.h ├── debugfl.h ├── dreamflower_app.c ├── fdebug.c ├── fdebug.h ├── gpio.c ├── mqtt ├── Clients.c ├── Clients.h ├── Heap.c ├── Heap.h ├── LinkedList.c ├── LinkedList.h ├── Log.c ├── Log.h ├── MQTTClient.c ├── MQTTClient.h ├── MQTTClientPersistence.h ├── MQTTPacket.c ├── MQTTPacket.h ├── MQTTPacketOut.c ├── MQTTPacketOut.h ├── MQTTPersistence.c ├── MQTTPersistence.h ├── MQTTPersistenceDefault.c ├── MQTTPersistenceDefault.h ├── MQTTProtocol.h ├── MQTTProtocolClient.c ├── MQTTProtocolClient.h ├── MQTTProtocolOut.c ├── MQTTProtocolOut.h ├── Makefile ├── Messages.c ├── Messages.h ├── SSLSocket.c ├── SSLSocket.h ├── Socket.c ├── Socket.h ├── SocketBuffer.c ├── SocketBuffer.h ├── StackTrace.c ├── StackTrace.h ├── Thread.c ├── Thread.h ├── Tree.c ├── Tree.h ├── mqtt_client.c ├── mqtt_client.h ├── utf-8.c └── utf-8.h ├── mqtt_publish.c ├── mqtt_publish.h ├── mqtt_subscribe.c ├── mqtt_subscribe.h ├── tcpdump.c ├── tcpdump.h ├── tcpdump └── Makefile ├── thread.c ├── uart1.c ├── uart1.h ├── uart_1_app.c └── uart_1_app.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ##Copyright (C) 2012 OpenWrt.org 2 | # 3 | # This is free software, licensed under the GNU General Public License v2. 4 | # See /LICENSE for more information. 5 | # 6 | 7 | include $(TOPDIR)/rules.mk 8 | 9 | PKG_NAME:=dreamflower_app 10 | PKG_RELEASE:=1 11 | 12 | PKG_BUILD_DIR := $(BUILD_DIR)/$(PKG_NAME) 13 | 14 | include $(INCLUDE_DIR)/package.mk 15 | 16 | define Package/dreamflower_app 17 | SECTION:=utils 18 | CATEGORY:=Utilities 19 | TITLE:=Frame buffer device testing tool 20 | DEPENDS:=+libncurses +libpcap +libpthread 21 | endef 22 | 23 | define Build/Prepare 24 | mkdir -p $(PKG_BUILD_DIR) 25 | $(CP) ./src/* $(PKG_BUILD_DIR)/ 26 | endef 27 | 28 | define Build/Configure 29 | endef 30 | 31 | TARGET_LDFLAGS := 32 | 33 | define Build/Compile 34 | $(MAKE) -C $(PKG_BUILD_DIR) \ 35 | CC="$(TARGET_CC)" \ 36 | CFLAGS="$(TARGET_CFLAGS) -Wall" \ 37 | LDFLAGS="$(TARGET_LDFLAGS)" 38 | endef 39 | 40 | define Package/dreamflower_app/install 41 | $(INSTALL_DIR) $(1)/usr/sbin 42 | $(INSTALL_BIN) $(PKG_BUILD_DIR)/dreamflower_app $(1)/usr/sbin/ 43 | endef 44 | 45 | $(eval $(call BuildPackage,dreamflower_app)) 46 | 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mqtt_uart_based_on_openwrt 2 | Build a typical gateway framework : Cloud<-mqtt->Openwrt<-uart->PAN(Ble.Zibgee.Thread) 3 | -------------------------------------------------------------------------------- /src/Daemon.c: -------------------------------------------------------------------------------- 1 | /* 2 | 此文件作为守护进程的独立文件,所有实际内容都在这里处理,说明也在这里 3 | */ 4 | //-2016/3/9 23:03:56 5 | /* 6 | 现在我需要实现gpio功能,但是不能像以前那样简单的移植了,需要知道怎么实现的 7 | 首先是框架实现 8 | */ 9 | 10 | #include "debugfl.h" 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | //-#include 23 | //-#include "ralink_gpio.h" 24 | 25 | //-下面定义了一个设备节点,在使用之前需要创建这样一个节点使用"mknod /dev/gpio c 252 0"的语句 26 | #define GPIO_DEV "/dev/gpio" 27 | 28 | #define MAXFILE 65535 29 | void sigterm_handler(int arg); 30 | volatile sig_atomic_t _running = 1; 31 | 32 | 33 | 34 | 35 | void sigterm_handler(int arg) //-kill发出的signal信号处理,达到进程的正常退出。 36 | { 37 | _running = 0; 38 | } 39 | 40 | 41 | /* 42 | 现在需要实现运行灯的闪耀,就不用负责的方法了,就是定时改变电平,以最简单的方法来实现功能就行. 43 | 44 | 1.控制FL_EM7688EVB开发板SEC灯的亮灭 45 | 控制引脚38 GPIO_0 输出0灯亮 46 | 首先实现了灯的亮灭,下面需要实现脱离终端自动亮灭,实现守护进程. 47 | */ 48 | int daemon_init(void) //?参数如何传递过来的,在终端输入命令的时候就带入了参数 49 | { 50 | pid_t pc,pid; 51 | int i; 52 | 53 | 54 | //-开始实现守护进程 55 | pc = fork(); //第一步 56 | if(pc<0){ 57 | printf("error fork\n"); 58 | exit(1); 59 | } 60 | else if(pc>0) 61 | exit(0); //-这里父进程的退出,就是实现首护进程的第一步 62 | 63 | pid = setsid(); //第二步,,setsid函数用于创建一个新的会话,并担任该会话组的组长。其实就是使进程完全独立出来,从而摆脱其他进程的控制。 64 | if (pid < 0) 65 | perror("setsid error"); 66 | 67 | chdir("/"); //第三步,,改变当前目录为根目录 68 | 69 | umask(0); //第四步,,重设文件权限掩码 70 | 71 | for(i=0;i 27 | #include //需要sys目录 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | int calendar_sub(int argc,char* argv[]) 34 | { 35 | long i = 1000000000L; 36 | clock_t start_c, finish_c; 37 | time_t start_t,finish_t; 38 | struct timeval start_stv,finish_stv; //对time_t类型的封装 39 | struct tms start_stms,finish_stms;//对clock_t类型的封装 40 | struct tm *start_stm,*finish_stm; //对time_t进行变体,类型为int 41 | double duration; 42 | long luration; 43 | 44 | /* 测量一个事件持续的时间*/ 45 | printf( "Time to do %ld empty loops is \n", i ); 46 | 47 | start_c = times(&start_stms); //从后面可以看出times和clock取得的clock_t的数量级不一样,一个为毫秒*10,一个为微妙 48 | start_c = clock();//进程时间测量,进程开始时调用时返回为0 49 | 50 | start_t = time(NULL); //只能精确到秒,,timer = time(NULL);//这一句也可以改成time(&timer); 51 | gettimeofday(&start_stv,NULL); //-它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间 52 | 53 | 54 | start_stm = localtime(&start_t); //时钟向日历时间的转换,mktime为其逆向过程函数,日历的函数有很多,我一般用这个记那么多格式也累,用的时候再man 55 | 56 | //也可以通过ctime直接打印出时间来。 57 | printf("====\nstart time:%04d-%02d-%02d %02d:%02d:%02d\n", 58 | start_stm->tm_year+1900, 59 | start_stm->tm_mon+1, 60 | start_stm->tm_mday, 61 | start_stm->tm_hour, 62 | start_stm->tm_min, 63 | start_stm->tm_sec); 64 | printf("start time:%s",ctime(&start_t)); 65 | 66 | while( i-- ) ; 67 | 68 | finish_c = times(&finish_stms); 69 | finish_c = clock(); 70 | 71 | finish_t = time(NULL); 72 | gettimeofday(&finish_stv,NULL); 73 | 74 | 75 | duration = (double)(finish_c - start_c)/CLOCKS_PER_SEC; //-这个是获得程序的实际运行时间(秒) 76 | printf( "1. [clock_t] get %f secondes,start = %u,finish =%u\n",duration,start_c,finish_c ); 77 | 78 | luration = (finish_t - start_t); 79 | printf("2. [time_t] get %u seconds,start = %u, finish = %u\n",luration,start_t,finish_t); 80 | 81 | luration = (finish_stv.tv_sec - start_stv.tv_sec)*1000 + ( finish_stv.tv_usec - start_stv.tv_usec)/1000; 82 | printf("3. [struct timeval] get %u ms,start=%u,finish=%u\n",luration,start_stv.tv_sec,finish_stv.tv_sec); 83 | 84 | long clktck=sysconf(_SC_CLK_TCK); //-该函数是获取一些系统的参数,,这里获得The number of clock ticks per second 85 | 86 | printf("================_SC_CLK_TCK=%d,CLOCKS_PER_SEC=%d\n",clktck,CLOCKS_PER_SEC); 87 | 88 | 89 | printf("4. [struct tms] get user= %7.2f,sys=%7.2f,child_user=%7.2f,child_sys=%7.2f\n", 90 | (finish_stms.tms_utime - start_stms.tms_utime)/(double)clktck, 91 | (finish_stms.tms_stime - start_stms.tms_stime)/(double)clktck, 92 | (finish_stms.tms_cutime - start_stms.tms_cutime)/(double)clktck, 93 | (finish_stms.tms_cstime - start_stms.tms_cstime)/(double)clktck ); 94 | 95 | //-exit(0); 96 | 97 | } 98 | 99 | 100 | 101 | 102 | 103 | //-  int tm_sec; /* 秒–取值区间为[0,59] */ 104 | //-  int tm_min; /* 分 - 取值区间为[0,59] */ 105 | //-  int tm_hour; /* 时 - 取值区间为[0,23] */ 106 | //-  int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */ 107 | //-  int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */ 108 | //-  int tm_year; /* 年份,其值从1900开始 */ 109 | //-  int tm_wday; /* 星期–取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */ 110 | //-  int tm_yday; /* 从每年的1月1日开始的天数–取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */ 111 | //-  int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/ 112 | 113 | //-  time_t tv_sec; /* seconds */ 114 | //-  suseconds_t tv_usec; /* microseconds */ 115 | -------------------------------------------------------------------------------- /src/calendar.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef CALENDAR_H 4 | #define CALENDAR_H 5 | 6 | int calendar_sub(int argc,char* argv[]); 7 | 8 | #endif /* CALENDAR_H */ 9 | -------------------------------------------------------------------------------- /src/debugfl.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef DEBUGFL_H 4 | #define DEBUGFL_H 5 | 6 | #include 7 | 8 | #if 1 9 | #define DEBUG(...) do{ fprintf(stderr, " ");printf(__VA_ARGS__);} while(0) 10 | #define API() fprintf(stderr, " api: %s.\n", __FUNCTION__) 11 | #else 12 | #define DEBUG(...) 13 | #define API() 14 | #endif 15 | 16 | #endif /* DEBUGFL_H */ 17 | -------------------------------------------------------------------------------- /src/dreamflower_app.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2006,2007 Stefan Bethke 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | static const char __rcsid[] = 18 | "$Header: /cvsroot/serialconsole/sc/sc.c,v 1.12 2007/12/04 02:34:46 doj Exp $"; 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | #include "debugfl.h" 39 | #include "Daemon.h" 40 | #include "uart1.h" 41 | #include "uart_1_app.h" 42 | #include "fdebug.h" 43 | #include "calendar.h" 44 | #include "tcpdump.h" 45 | #include "mqtt_publish.h" 46 | #include "mqtt_subscribe.h" 47 | 48 | 49 | /* functions */ 50 | int parse_options(int argc, char *argv[]); 51 | 52 | #if !defined(SC_VERSION) 53 | #define SC_VERSION "0.9-dev" 54 | #endif 55 | #if !defined(DEFAULTDEVICE) 56 | #define DEFAULTDEVICE "cuad0" 57 | #endif 58 | #if !defined(DEFAULTSPEED) 59 | #define DEFAULTSPEED "9600" 60 | #endif 61 | #if !defined(DEFAULTPARMS) 62 | #define DEFAULTPARMS "8n1" 63 | #endif 64 | #if !defined(PATH_DEV) 65 | #define PATH_DEV "/dev" 66 | #endif 67 | 68 | #if B2400 == 2400 && B9600 == 9600 && B38400 == 38400 69 | #define TERMIOS_SPEED_IS_INT 70 | #endif 71 | 72 | #if !defined(TERMIOS_SPEED_IS_INT) 73 | struct termios_speed { 74 | long code; 75 | long speed; 76 | }; 77 | struct termios_speed termios_speeds[] = { 78 | { B50, 50 }, 79 | { B75, 75 }, 80 | { B110, 110 }, 81 | { B134, 134 }, 82 | { B150, 150 }, 83 | { B200, 200 }, 84 | { B300, 300 }, 85 | { B600, 600 }, 86 | { B1200, 1200 }, 87 | { B1800, 1800 }, 88 | { B2400, 2400 }, 89 | { B4800, 4800 }, 90 | #if defined(B7200) 91 | { B7200, 7200 }, 92 | #endif 93 | { B9600, 9600 }, 94 | #if defined(B14400) 95 | { B14400, 14400 }, 96 | #endif 97 | { B19200, 19200 }, 98 | #if defined(B28800) 99 | { B28800, 28800 }, 100 | #endif 101 | { B38400, 38400 }, 102 | #if defined(B57600) 103 | { B57600, 57600 }, 104 | #endif 105 | #if defined(B76800) 106 | { B76800, 76800 }, 107 | #endif 108 | #if defined(B115200) 109 | { B115200, 115200 }, 110 | #endif 111 | #if defined(B153600) 112 | { B153600, 153600 }, 113 | #endif 114 | #if defined(B230400) 115 | { B230400, 230400 }, 116 | #endif 117 | #if defined(B307200) 118 | { B307200, 307200 }, 119 | #endif 120 | #if defined(B460800) 121 | { B460800, 460800 }, 122 | #endif 123 | #if defined(B500000) 124 | { B500000, 500000 }, 125 | #endif 126 | #if defined(B576000) 127 | { B576000, 576000 }, 128 | #endif 129 | #if defined(B921600) 130 | { B921600, 921600 }, 131 | #endif 132 | #if defined(B1000000) 133 | { B1000000, 1000000 }, 134 | #endif 135 | #if defined(B1152000) 136 | { B1152000, 1152000 }, 137 | #endif 138 | #if defined(B1500000) 139 | { B1500000, 1500000 }, 140 | #endif 141 | #if defined(B2000000) 142 | { B2000000, 2000000 }, 143 | #endif 144 | #if defined(B2500000) 145 | { B2500000, 2500000 }, 146 | #endif 147 | #if defined(B3000000) 148 | { B3000000, 3000000 }, 149 | #endif 150 | #if defined(B3500000) 151 | { B3500000, 3500000 }, 152 | #endif 153 | #if defined(B4000000) 154 | { B4000000, 4000000 }, 155 | #endif 156 | { 0, 0 } 157 | }; 158 | #endif 159 | 160 | 161 | enum escapestates { 162 | ESCAPESTATE_WAITFORCR = 0, 163 | ESCAPESTATE_WAITFOREC, 164 | ESCAPESTATE_PROCESSCMD, 165 | ESCAPESTATE_WAITFOR1STHEXDIGIT, 166 | ESCAPESTATE_WAITFOR2NDHEXDIGIT, 167 | }; 168 | 169 | 170 | static int scrunning = 1; 171 | static char *path_dev = PATH_DEV "/"; 172 | static int qflag = 0; 173 | 174 | /////////////////////////////////////////////////////////////////////////////// 175 | extern volatile sig_atomic_t _running; 176 | 177 | 178 | 179 | /////////////////////////////////////////////////////////////////////////////// 180 | 181 | /////////////////////////////////////////////////////////////////////////////// 182 | char run_flag = 0; //-0表示正常运行 1表示进入调试模式,在终端的监控下运行 183 | char test_branch = 0; //-0 184 | 185 | 186 | 187 | /////////////////////////////////////////////////////////////////////////////// 188 | 189 | #ifdef __CYGWIN__ 190 | static int 191 | cfmakeraw(struct termios *termios_p) 192 | { 193 | termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON); 194 | termios_p->c_oflag &= ~OPOST; 195 | termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN); 196 | termios_p->c_cflag &= ~(CSIZE|PARENB); 197 | termios_p->c_cflag |= CS8; 198 | return 0; 199 | } 200 | 201 | static int 202 | cfsetspeed(struct termios *termios_p, speed_t speed) 203 | { 204 | int r=cfsetospeed(termios_p, speed); 205 | if(r<0) return r; 206 | return cfsetispeed(termios_p, speed); 207 | } 208 | #endif 209 | 210 | static void 211 | sighandler(int sig) 212 | { 213 | scrunning = 0; 214 | } 215 | 216 | 217 | static speed_t 218 | parsespeed(char *speed) 219 | { 220 | long s; 221 | char *ep; 222 | #if !defined(TERMIOS_SPEED_IS_INT) 223 | struct termios_speed *ts = termios_speeds; 224 | #endif 225 | 226 | s = strtol(speed, &ep, 0); 227 | if (ep == speed || ep[0] != '\0') { 228 | warnx("Unable to parse speed \"%s\"", speed); 229 | return(B9600); 230 | } 231 | #if defined(TERMIOS_SPEED_IS_INT) 232 | return s; 233 | #else 234 | while(ts->speed != 0) { 235 | if (ts->speed == s) 236 | return ts->code; 237 | ts++; 238 | } 239 | warnx("Undefined speed \"%s\"", speed); 240 | return(B9600); 241 | #endif 242 | } 243 | 244 | 245 | static int 246 | parseparms(tcflag_t *c, char *p, int f, int m) 247 | { 248 | if (strlen(p) != 3) { 249 | warnx("Invalid parameter specification \"%s\"", p); 250 | return 1; 251 | } 252 | *c &= ~CSIZE; 253 | switch(p[0]) { 254 | case '5': *c |= CS5; break; 255 | case '6': *c |= CS6; break; 256 | case '7': *c |= CS7; break; 257 | case '8': *c |= CS8; break; 258 | default: 259 | warnx("Invalid character size \"%c\": must be 5, 6, 7, or 8", 260 | p[0]); 261 | return 1; 262 | } 263 | switch(tolower(p[1])) { 264 | case 'e': *c |= PARENB; *c &= ~PARODD; break; 265 | case 'n': *c &= ~PARENB; break; 266 | case 'o': *c |= PARENB | PARODD; break; 267 | default: 268 | warnx("Invalid parity \"%c\": must be E, N, or O", p[1]); 269 | return 1; 270 | } 271 | switch(p[2]) { 272 | case '1': *c &= ~CSTOPB; break; 273 | case '2': *c |= CSTOPB; break; 274 | default: 275 | warnx("Invalid stop bit \"%c\": must be 1 or 2", p[2]); 276 | return 1; 277 | } 278 | *c &= ~CRTSCTS; 279 | if (f) *c |= CRTSCTS; 280 | *c |= CLOCAL; 281 | if (m) *c &= ~CLOCAL; 282 | return 0; 283 | } 284 | 285 | 286 | static void 287 | printparms(struct termios *ti, char *tty) 288 | { 289 | long sp = 0; 290 | char bits, parity, stops; 291 | #if !defined(TERMIOS_SPEED_IS_INT) 292 | struct termios_speed *ts = termios_speeds; 293 | speed_t sc; 294 | #endif 295 | 296 | #if defined(TERMIOS_SPEED_IS_INT) 297 | sp = cfgetispeed(ti); 298 | #else 299 | sc = cfgetispeed(ti); 300 | while (ts->speed != 0) { 301 | if (ts->code == sc) { 302 | sp = ts->speed; 303 | break; 304 | } 305 | ts++; 306 | } 307 | #endif 308 | switch(ti->c_cflag & CSIZE) { 309 | case CS5: bits = '5'; break; 310 | case CS6: bits = '6'; break; 311 | case CS7: bits = '7'; break; 312 | case CS8: bits = '8'; break; 313 | default: 314 | bits ='?'; 315 | } 316 | if (ti->c_cflag & PARENB) { 317 | parity = ti->c_cflag & PARODD ? 'O' : 'E'; 318 | } else { 319 | parity = 'N'; 320 | } 321 | stops = ti->c_cflag & CSTOPB ? '2' : '1'; 322 | 323 | fprintf(stderr, "Connected to %s at %ld %c%c%c, modem status %s, %shardware handshake\n", 324 | tty, sp, bits, parity, stops, 325 | ti->c_cflag & CLOCAL ? "ignored" : "observed", 326 | ti->c_cflag & CRTSCTS ? "" : "no "); 327 | } 328 | 329 | static int 330 | hex2dec(char c) 331 | { 332 | switch(c) 333 | { 334 | case '0': return 0; 335 | case '1': return 1; 336 | case '2': return 2; 337 | case '3': return 3; 338 | case '4': return 4; 339 | case '5': return 5; 340 | case '6': return 6; 341 | case '7': return 7; 342 | case '8': return 8; 343 | case '9': return 9; 344 | case 'a': return 10; 345 | case 'b': return 11; 346 | case 'c': return 12; 347 | case 'd': return 13; 348 | case 'e': return 14; 349 | case 'f': return 15; 350 | case 'A': return 10; 351 | case 'B': return 11; 352 | case 'C': return 12; 353 | case 'D': return 13; 354 | case 'E': return 14; 355 | case 'F': return 15; 356 | } 357 | return -1; 358 | } 359 | 360 | static int 361 | loop(int sfd, int escchr, int msdelay) 362 | { 363 | enum escapestates escapestate = ESCAPESTATE_WAITFOREC; 364 | unsigned char escapedigit; 365 | int i; 366 | char c; 367 | #if defined(HAS_BROKEN_POLL) 368 | /* use select(2) */ 369 | fd_set fds[2]; 370 | 371 | FD_ZERO(fds+1); 372 | FD_SET(STDIN_FILENO, fds+1); 373 | FD_SET(sfd, fds+1); 374 | while (scrunning) { 375 | bcopy(fds+1, fds, sizeof(*fds)); 376 | if ((i = select(sfd+1, fds, NULL, NULL, NULL)) < 0 377 | && errno != EINTR) { 378 | warn("select()"); 379 | return EX_OSERR; 380 | } 381 | #else 382 | struct pollfd pfds[2]; 383 | 384 | bzero(pfds, sizeof(pfds)); 385 | pfds[0].fd = STDIN_FILENO; 386 | pfds[0].events = POLLIN; 387 | pfds[1].fd = sfd; 388 | pfds[1].events = POLLIN; 389 | while (scrunning) { 390 | if ((i = poll(pfds, sizeof(pfds)/sizeof(pfds[0]), -1)) < 0 391 | && errno != EINTR) { 392 | warn("poll()"); 393 | return EX_OSERR; 394 | } 395 | if ((pfds[0].revents | pfds[1].revents) & POLLNVAL) { 396 | warnx("poll() does not support devices"); 397 | return EX_OSERR; 398 | } 399 | if (pfds[0].revents & (POLLERR|POLLHUP)) { 400 | read(STDIN_FILENO, &c, 1); 401 | warn("poll mask %04x read(tty)", pfds[0].revents); 402 | return(EX_OSERR); 403 | } 404 | if (pfds[1].revents & (POLLERR|POLLHUP)) { 405 | read(sfd, &c, 1); 406 | warn("poll mask %04x read(serial)", pfds[1].revents); 407 | return(EX_OSERR); 408 | } 409 | #endif 410 | #if defined(HAS_BROKEN_POLL) 411 | if (FD_ISSET(STDIN_FILENO, fds)) { 412 | #else 413 | if (pfds[0].revents & POLLIN) { 414 | #endif 415 | if ((i = read(STDIN_FILENO, &c, 1)) > 0) { 416 | switch (escapestate) { 417 | case ESCAPESTATE_WAITFORCR: 418 | if (c == '\r') { 419 | escapestate = ESCAPESTATE_WAITFOREC; 420 | } 421 | break; 422 | 423 | case ESCAPESTATE_WAITFOREC: 424 | if (escchr != -1 && ((unsigned char)c) == escchr) { 425 | escapestate = ESCAPESTATE_PROCESSCMD; 426 | continue; 427 | } 428 | if (c != '\r') { 429 | escapestate = ESCAPESTATE_WAITFORCR; 430 | } 431 | break; 432 | 433 | case ESCAPESTATE_PROCESSCMD: 434 | escapestate = ESCAPESTATE_WAITFORCR; 435 | switch (c) { 436 | case '.': 437 | scrunning = 0; 438 | continue; 439 | 440 | case 'b': 441 | case 'B': 442 | if(!qflag) 443 | fprintf(stderr, "->sending a break<-\r\n"); 444 | tcsendbreak(sfd, 0); 445 | continue; 446 | 447 | case 'x': 448 | case 'X': 449 | escapestate = ESCAPESTATE_WAITFOR1STHEXDIGIT; 450 | continue; 451 | 452 | default: 453 | if (((unsigned char)c) != escchr) { 454 | write(sfd, &escchr, 1); 455 | } 456 | } 457 | break; 458 | 459 | case ESCAPESTATE_WAITFOR1STHEXDIGIT: 460 | if (isxdigit(c)) { 461 | escapedigit = hex2dec(c) * 16; 462 | escapestate = ESCAPESTATE_WAITFOR2NDHEXDIGIT; 463 | } else { 464 | escapestate = ESCAPESTATE_WAITFORCR; 465 | if(!qflag) 466 | fprintf(stderr, "->invalid hex digit '%c'<-\r\n", c); 467 | } 468 | continue; 469 | 470 | case ESCAPESTATE_WAITFOR2NDHEXDIGIT: 471 | escapestate = ESCAPESTATE_WAITFORCR; 472 | if(isxdigit(c)) { 473 | escapedigit += hex2dec(c); 474 | write(sfd, &escapedigit, 1); 475 | if(!qflag) 476 | fprintf(stderr, "->wrote 0x%02X character '%c'<-\r\n", escapedigit, isprint(escapedigit)?escapedigit:'.'); 477 | } else { 478 | if(!qflag) 479 | fprintf(stderr, "->invalid hex digit '%c'<-\r\n", c); 480 | } 481 | continue; 482 | } 483 | i = write(sfd, &c, 1); 484 | if(c == '\n' && msdelay > 0) 485 | usleep(msdelay*1000); 486 | } 487 | if (i < 0) { 488 | warn("read/write"); 489 | return(EX_OSERR); 490 | } 491 | } 492 | #if defined(HAS_BROKEN_POLL) 493 | if (FD_ISSET(sfd, fds)) { 494 | #else 495 | if (pfds[1].revents & POLLIN) { 496 | #endif 497 | if ((i = read(sfd, &c, 1)) > 0) { 498 | i = write(STDOUT_FILENO, &c, 1); 499 | } 500 | if (i < 0) { 501 | warn("read/write"); 502 | return(EX_OSERR); 503 | } 504 | } 505 | } 506 | return(0); 507 | } 508 | 509 | 510 | static void 511 | modemcontrol(int sfd, int dtr) 512 | { 513 | #if defined(TIOCSDTR) 514 | ioctl(sfd, dtr ? TIOCSDTR : TIOCCDTR); 515 | #elif defined(TIOCMSET) && defined(TIOCM_DTR) 516 | int flags; 517 | if (ioctl(sfd, TIOCMGET, &flags) >= 0) { 518 | if (dtr) 519 | flags |= TIOCM_DTR; 520 | else 521 | flags &= ~TIOCM_DTR; 522 | ioctl(sfd, TIOCMSET, &flags); 523 | } 524 | #endif 525 | } 526 | 527 | 528 | static void 529 | usage(void) 530 | { 531 | fprintf(stderr, "Connect to a serial device, using this system as a console. Version %s.\n" 532 | "usage:\tsc [-fmq] [-d ms] [-e escape] [-p parms] [-s speed] device\n" 533 | "\t-f: use hardware flow control (CRTSCTS)\n" 534 | "\t-m: use modem lines (!CLOCAL)\n" 535 | "\t-q: don't show connect, disconnect and escape action messages\n" 536 | "\t-d: delay in milliseconds after each newline character\n" 537 | "\t-e: escape char or \"none\", default '~'\n" 538 | "\t-p: bits per char, parity, stop bits, default \"%s\"\n" 539 | "\t-s: speed, default \"%s\"\n" 540 | "\tdevice, default \"%s\"\n", 541 | SC_VERSION, DEFAULTPARMS, DEFAULTSPEED, DEFAULTDEVICE); 542 | fprintf(stderr, "escape actions are started with the 3 character combination: CR + ~ +\n" 543 | "\t~ - send '~' character\n" 544 | "\t. - disconnect\n" 545 | "\tb - send break\n" 546 | "\tx<2 hex digits> - send decoded character\n"); 547 | #if defined(TERMIOS_SPEED_IS_INT) 548 | fprintf(stderr, "available speeds depend on device\n"); 549 | #else 550 | { 551 | struct termios_speed *ts = termios_speeds; 552 | 553 | fprintf(stderr, "available speeds: "); 554 | while (ts->speed != 0) { 555 | fprintf(stderr, "%ld ", ts->speed); 556 | ts++; 557 | } 558 | fprintf(stderr, "\n"); 559 | } 560 | #endif 561 | exit(EX_USAGE); 562 | } 563 | 564 | /////////////////////////////////////////////////////////////////////////////// 565 | 566 | 567 | /* 568 | 最原始的一个main函数,这个简单的可以预示着程序可以正常运行即可。 569 | 比如在终端输出一个hello word! 570 | 571 | 1.增加一个功能到现有的框架之中整个测试都在一个新的文件之中完成,实现函数 572 | 2.关于命令行参数 argc 和 argv的说明 573 | argc 以空格为界技术命令行有几个参数从1开始 574 | argv 指针数据,偏移量从0开始,分界还是空格 575 | */ 576 | int 577 | main(int argc,char *argv[]) 578 | { 579 | int fd_uart1; 580 | 581 | printf("Hello World!\n"); 582 | 583 | //-首先对接收到的命令进行解析,然后根据命令进行程序运行. 584 | if (parse_options(argc, argv) != 0) 585 | goto close; 586 | #if 1 587 | //-打印出输入命令 588 | int32_t i = 0; 589 | printf("argc: %d \n",argc); 590 | for(i=0; i= 0) 627 | uart_1_Main(fd_uart1); 628 | 629 | } 630 | 631 | close: 632 | return 0; 633 | 634 | } 635 | 636 | 637 | 638 | int parse_options(int argc, char *argv[]) 639 | { 640 | int c; 641 | char *pLen; 642 | 643 | while ((c = getopt(argc, argv, "a:b:DTSXMR")) != -1) 644 | { 645 | switch(c) 646 | { 647 | case 'a': 648 | //-port_opts.bus_addr = strtoul(optarg, NULL, 0); 649 | break; 650 | 651 | case 'b': 652 | //-port_opts.baudRate = serial_get_baud(strtoul(optarg, NULL, 0)); 653 | 654 | break; 655 | 656 | case 'D': 657 | run_flag = 1; 658 | break; 659 | case 'T': 660 | test_branch = 2; 661 | break; 662 | case 'S': 663 | test_branch = 3; 664 | break; 665 | case 'X': 666 | test_branch = 4; 667 | break; 668 | case 'M': 669 | test_branch = 5; 670 | break; 671 | case 'R': 672 | test_branch = 6; 673 | break; 674 | 675 | case 'h': 676 | usage(); 677 | exit(0); //?这里值得思考 678 | 679 | default: 680 | break; 681 | } 682 | } 683 | 684 | 685 | //-if (!wr && verify) { 686 | //- fprintf(stderr, "ERROR: Invalid usage, -v is only valid when writing\n"); 687 | //- show_help(argv[0]); 688 | //- return 1; //-出现了错误,程序需要终止了,返回1 689 | //-} 690 | 691 | return 0; //-正常结束,可以继续运行等于0 692 | } 693 | 694 | 695 | 696 | 697 | 698 | 699 | /////////////////////////////////////////////////////////////////////////////// 700 | int 701 | main_one(int argc, char **argv) 702 | { 703 | int escchr = '~'; 704 | char *tty = DEFAULTDEVICE; 705 | char *speed = DEFAULTSPEED; 706 | char *parms = DEFAULTPARMS; 707 | int fflag = 0; 708 | int mflag = 0; 709 | int sfd = -1; 710 | char buffer[PATH_MAX+1]; 711 | struct termios serialti, consoleti, tempti; 712 | int ec = 0; 713 | int msdelay = 0; 714 | int i; 715 | char c; 716 | 717 | while ((c = getopt(argc, argv, "d:e:fhmp:qs:?")) != -1) { 718 | switch (c) { 719 | case 'd': 720 | msdelay=atoi(optarg); 721 | if(msdelay <= 0) 722 | fprintf(stderr, "warning: ignoring negative or zero delay: %i\n", msdelay); 723 | break; 724 | case 'e': 725 | if (strcmp(optarg, "none") == 0) { 726 | escchr = -1; 727 | } else if (strlen(optarg) == 1) { 728 | escchr = (unsigned char)optarg[0]; 729 | } else if (strlen(optarg) == 2 && optarg[0] == '^' && 730 | toupper(optarg[1]) >= '@' && toupper(optarg[1]) <= '_') { 731 | escchr = toupper(optarg[1]) & 0x1f; 732 | } else { 733 | errx(EX_USAGE, "Invalid escape character \"%s\"", optarg); 734 | } 735 | break; 736 | case 'f': 737 | fflag = 1; 738 | break; 739 | case 'm': 740 | mflag = 1; 741 | break; 742 | case 'p': 743 | parms = optarg; 744 | break; 745 | case 'q': 746 | qflag = 1; 747 | case 's': 748 | speed = optarg; 749 | break; 750 | case 'h': 751 | case '?': 752 | default: 753 | usage(); 754 | } 755 | } 756 | argc -= optind; 757 | argv += optind; 758 | if (argc == 1) { 759 | tty = argv[0]; 760 | } 761 | if (argc > 1) { 762 | usage(); 763 | } 764 | 765 | if (strchr(tty, '/') == NULL) { 766 | if (strlen(path_dev) + strlen(tty) > PATH_MAX) { 767 | errx(EX_USAGE, "Device name \"%s\" is too long.", tty); 768 | } 769 | bcopy(path_dev, buffer, strlen(path_dev)+1); 770 | bcopy(tty, buffer+strlen(path_dev), strlen(tty)+1); 771 | tty = buffer; 772 | } 773 | sfd = open(tty, O_RDWR); 774 | if (sfd < 0) { 775 | err(EX_OSERR, "open %s", tty); 776 | } 777 | /* save tty configuration */ 778 | if (tcgetattr(STDIN_FILENO, &consoleti)) { 779 | close(sfd); 780 | err(EX_OSERR, "tcgetattr() tty"); 781 | } 782 | /* save serial port configuration */ 783 | if (tcgetattr(sfd, &serialti)) { 784 | close(sfd); 785 | err(EX_OSERR, "tcgetattr(%s)", tty); 786 | } 787 | /* configure serial port */ 788 | bcopy(&serialti, &tempti, sizeof(tempti)); 789 | cfmakeraw(&tempti); 790 | tempti.c_cc[VMIN] = 1; 791 | tempti.c_cc[VTIME] = 0; 792 | if (cfsetspeed(&tempti, parsespeed(speed))) { 793 | ec = EX_OSERR; 794 | warn("cfsetspeed(%s)", tty); 795 | goto error; 796 | } 797 | if (parseparms(&tempti.c_cflag, parms, fflag, mflag)) { 798 | ec = EX_USAGE; 799 | goto error; 800 | } 801 | if (tcsetattr(sfd, TCSANOW, &tempti)) { 802 | ec = EX_OSERR; 803 | warn("tcsetattr(%s)", tty); 804 | goto error; 805 | } 806 | signal(SIGHUP, sighandler); 807 | signal(SIGINT, sighandler); 808 | signal(SIGQUIT, sighandler); 809 | signal(SIGTERM, sighandler); 810 | 811 | if (!qflag) { 812 | /* re-read serial port configuration */ 813 | if (tcgetattr(sfd, &tempti)) { 814 | close(sfd); 815 | err(EX_OSERR, "tcgetattr(%s)", tty); 816 | } 817 | printparms(&tempti, tty); 818 | fflush(stderr); 819 | } 820 | /* put tty into raw mode */ 821 | i = fcntl(STDIN_FILENO, F_GETFL); 822 | if (i == -1 || fcntl(STDIN_FILENO, F_SETFL, i | O_NONBLOCK)) { 823 | close(sfd); 824 | err(EX_OSERR, "fcntl() tty"); 825 | } 826 | bcopy(&consoleti, &tempti, sizeof(tempti)); 827 | cfmakeraw(&tempti); 828 | if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tempti)) { 829 | ec = EX_OSERR; 830 | warn("tcsetattr() tty"); 831 | goto error; 832 | } 833 | modemcontrol(sfd, 1); 834 | 835 | ec = loop(sfd, escchr, msdelay); 836 | 837 | error: 838 | if (sfd >= 0) { 839 | modemcontrol(sfd, 0); 840 | tcsetattr(sfd, TCSAFLUSH, &serialti); 841 | tcsetattr(STDIN_FILENO, TCSAFLUSH, &consoleti); 842 | close(sfd); 843 | } 844 | fprintf(stderr, "\n"); 845 | if (!qflag) fprintf(stderr, "Connection closed.\n"); 846 | return ec; 847 | } 848 | -------------------------------------------------------------------------------- /src/fdebug.c: -------------------------------------------------------------------------------- 1 | /* 2 | 此文件用于文件的创建和读写,使用这种方法可以进行信息的输出,用于辅助调试 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | 11 | 12 | //输出目录 13 | #define DIR_OUT_FILE "/tmp/out" 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | void f_debug(char *data) 22 | { 23 | int fd; 24 | 25 | //查看程序是否运行 26 | //新建输出文件 27 | system("touch "DIR_OUT_FILE); 28 | //打开输出文件 29 | fd = open(DIR_OUT_FILE,O_CREAT|O_RDWR,0777); 30 | //-char buf[100] = {'1','2',3}; 31 | //-strcpy(buf,argv[2]); 32 | //-sprintf(buf, "%d", fd_uart1); 33 | //全部 34 | //-write(fd,buf,100); 35 | write(fd,data,100); 36 | 37 | //删除输出文件 38 | //-system("rm "DIR_OUT_FILE); 39 | } -------------------------------------------------------------------------------- /src/fdebug.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef FDEBUG_H 4 | #define FDEBUG_H 5 | 6 | void f_debug(char *data); 7 | 8 | #endif /* FDEBUG_H */ 9 | -------------------------------------------------------------------------------- /src/gpio.c: -------------------------------------------------------------------------------- 1 | //-2016/3/9 23:03:56 2 | /* 3 | 现在我需要实现gpio功能,但是不能像以前那样简单的移植了,需要知道怎么实现的 4 | 首先是框架实现 5 | */ 6 | 7 | #include "debugfl.h" 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | //-#include 17 | //-#include "ralink_gpio.h" 18 | 19 | //-下面定义了一个设备节点,在使用之前需要创建这样一个节点使用"mknod /dev/gpio c 252 0"的语句 20 | #define GPIO_DEV "/dev/gpio" 21 | 22 | 23 | enum { 24 | gpio_in, 25 | gpio_out, 26 | }; 27 | enum { 28 | gpio3100, //-0 29 | gpio6332, //-1 30 | gpio9564, //-2 31 | }; 32 | 33 | /* 34 | int gpio_set_dir(int r, int dir) //-前面一个是引脚号 后面是方向 35 | { 36 | int fd, req; 37 | 38 | //-增加打印语句方便知道程序进程 39 | printf("boot000\n"); 40 | 41 | //-打开设备GPIO 42 | fd = open(GPIO_DEV, O_RDONLY); //-这里打开了一个文件,也许由于IO的简单就是一个空文件而已没有任何描述 43 | if(fd < 0) 44 | { 45 | system("mknod /dev/gpio c 252 0"); 46 | fd = open(GPIO_DEV, O_RDONLY); 47 | } 48 | 49 | if (fd < 0) { 50 | //-perror( ) 用来将上一个函数发生错误的原因输出到标准设备(stderr)。参数 s 所指的字符 51 | //-串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量errno 的值来决定要输出的字符串。 52 | perror(GPIO_DEV); 53 | return -1; 54 | } 55 | //-增加打印语句方便知道程序进程 56 | printf("boot001\n"); 57 | 58 | if (dir == gpio_in) { 59 | 60 | if (r == gpio9564) 61 | req = RALINK_GPIO9564_SET_DIR_IN; 62 | else if (r == gpio6332) 63 | req = RALINK_GPIO6332_SET_DIR_IN; 64 | else 65 | req = RALINK_GPIO_SET_DIR_IN; 66 | } 67 | else { 68 | if (r == gpio9564) 69 | req = RALINK_GPIO9564_SET_DIR_OUT; //-这里的取出是为了,模块之间减少耦合性 70 | else if (r == gpio6332) 71 | req = RALINK_GPIO6332_SET_DIR_OUT; 72 | else 73 | req = RALINK_GPIO_SET_DIR_OUT; 74 | } 75 | //-增加打印语句方便知道程序进程 76 | printf("boot002\n"); 77 | if (ioctl(fd, req, 0xffffffff) < 0) //-这里设置了输入或者输出特定的引脚,具体实现是如何的需要思考 78 | { 79 | perror("ioctl"); 80 | close(fd); 81 | return -1; 82 | } 83 | //-增加打印语句方便知道程序进程 84 | printf("boot003\n"); 85 | close(fd); 86 | return 0; 87 | } 88 | 89 | int gpio_write_int(int r, int value) //-实现了向IO口输出指定电平 90 | { 91 | int fd, req; 92 | 93 | fd = open(GPIO_DEV, O_RDONLY); 94 | if (fd < 0) { 95 | perror(GPIO_DEV); 96 | return -1; 97 | } 98 | 99 | 100 | if (r == gpio9564) 101 | req = RALINK_GPIO9564_WRITE; 102 | else if (r == gpio6332) 103 | req = RALINK_GPIO6332_WRITE; 104 | else 105 | req = RALINK_GPIO_WRITE; 106 | //-上面根据标志得到了一个变量值 107 | if (ioctl(fd, req, value) < 0) //-不同的标志对应不同的数值输出 108 | { 109 | perror("ioctl"); 110 | close(fd); 111 | return -1; 112 | } 113 | close(fd); 114 | return 0; 115 | } 116 | 117 | 118 | void gpio_test_write(int data) //-调用的一个子函数,其中一个流程 119 | { 120 | int i = 0; 121 | 122 | //set gpio direction to output 123 | gpio_set_dir(gpio3100, gpio_out); 124 | 125 | if(data != 0) 126 | { 127 | printf("turn off SEC LED = 0x%x\n", data); 128 | //turn off LEDs 129 | gpio_write_int(gpio3100, data); //-GPIO_0 熄灭使用的值是0x00000800,,输入指令时显示的是十进制数据 130 | sleep(3); 131 | } 132 | else 133 | { 134 | printf("turn on SEC LED = 0x%x\n", data); 135 | //turn on all LEDs 136 | gpio_write_int(gpio3100, 0); 137 | } 138 | 139 | //-测试用 140 | //-while(1) 141 | //-{ 142 | //- gpio_write_int(gpio3100, 0x00000800); 143 | //- sleep(1); //-单位是秒 144 | //- gpio_write_int(gpio3100, 0x00000000); 145 | //- sleep(1); 146 | //-} 147 | 148 | } 149 | 150 | void gpio_led_blink(void) 151 | { 152 | gpio_write_int(gpio3100, 0x00000800); 153 | sleep(1); //-单位是秒 154 | gpio_write_int(gpio3100, 0x00000000); 155 | //-usleep(1000*500); 156 | sleep(1); 157 | } 158 | */ 159 | 160 | 161 | 162 | 163 | void usage(char *cmd) 164 | {//-作为一个系统中的应用,下面的信息打印就不需要去深究了,知道使用的前提和效果就好 165 | printf("Usage: %s w - writing test (output)\n", cmd); 166 | printf(" %s r - reading test (input)\n", cmd); 167 | printf(" %s i () - interrupt test for gpio number\n", cmd); 168 | printf(" %s l \n", cmd); 169 | printf(" - set led on (0~24) on/off interval, no. of blinking/resting cycles, times of blinking\n"); 170 | exit(0); 171 | } 172 | 173 | /* 174 | 现在需要实现运行灯的闪耀,就不用负责的方法了,就是定时改变电平,以最简单的方法来实现功能就行. 175 | 176 | 1.控制FL_EM7688EVB开发板SEC灯的亮灭 177 | 控制引脚38 GPIO_0 输出0灯亮 178 | 首先实现了灯的亮灭,下面需要实现脱离终端自动亮灭,实现守护进程. 179 | */ 180 | int ate_sub(void) //?参数如何传递过来的,在终端输入命令的时候就带入了参数 181 | { 182 | pid_t pc,pid; 183 | int i; 184 | 185 | 186 | 187 | 188 | return 0; 189 | } -------------------------------------------------------------------------------- /src/mqtt/Clients.c: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs - add SSL support 16 | *******************************************************************************/ 17 | 18 | /** 19 | * @file 20 | * \brief functions which apply to client structures 21 | * */ 22 | 23 | 24 | #include "Clients.h" 25 | 26 | #include 27 | #include 28 | 29 | 30 | /** 31 | * List callback function for comparing clients by clientid 32 | * @param a first integer value 33 | * @param b second integer value 34 | * @return boolean indicating whether a and b are equal 35 | */ 36 | int clientIDCompare(void* a, void* b) 37 | { 38 | Clients* client = (Clients*)a; 39 | /*printf("comparing clientdIDs %s with %s\n", client->clientID, (char*)b);*/ 40 | return strcmp(client->clientID, (char*)b) == 0; 41 | } 42 | 43 | 44 | /** 45 | * List callback function for comparing clients by socket 46 | * @param a first integer value 47 | * @param b second integer value 48 | * @return boolean indicating whether a and b are equal 49 | */ 50 | int clientSocketCompare(void* a, void* b) 51 | { 52 | Clients* client = (Clients*)a; 53 | /*printf("comparing %d with %d\n", (char*)a, (char*)b); */ 54 | return client->net.socket == *(int*)b; 55 | } 56 | -------------------------------------------------------------------------------- /src/mqtt/Clients.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Clients.h -------------------------------------------------------------------------------- /src/mqtt/Heap.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Heap.c -------------------------------------------------------------------------------- /src/mqtt/Heap.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs - use tree data structure instead of list 16 | *******************************************************************************/ 17 | 18 | 19 | #if !defined(HEAP_H) 20 | #define HEAP_H 21 | 22 | #if defined(HIGH_PERFORMANCE) 23 | #define NO_HEAP_TRACKING 1 24 | #endif 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #if !defined(NO_HEAP_TRACKING) 31 | /** 32 | * redefines malloc to use "mymalloc" so that heap allocation can be tracked 33 | * @param x the size of the item to be allocated 34 | * @return the pointer to the item allocated, or NULL 35 | */ 36 | #define malloc(x) mymalloc(__FILE__, __LINE__, x) 37 | 38 | /** 39 | * redefines realloc to use "myrealloc" so that heap allocation can be tracked 40 | * @param a the heap item to be reallocated 41 | * @param b the new size of the item 42 | * @return the new pointer to the heap item 43 | */ 44 | #define realloc(a, b) myrealloc(__FILE__, __LINE__, a, b) 45 | 46 | /** 47 | * redefines free to use "myfree" so that heap allocation can be tracked 48 | * @param x the size of the item to be freed 49 | */ 50 | #define free(x) myfree(__FILE__, __LINE__, x) 51 | 52 | #endif 53 | 54 | /** 55 | * Information about the state of the heap. 56 | */ 57 | typedef struct 58 | { 59 | int current_size; /**< current size of the heap in bytes */ 60 | int max_size; /**< max size the heap has reached in bytes */ 61 | } heap_info; 62 | 63 | 64 | void* mymalloc(char*, int, size_t size); 65 | void* myrealloc(char*, int, void* p, size_t size); 66 | void myfree(char*, int, void* p); 67 | 68 | void Heap_scan(FILE* file); 69 | int Heap_initialize(void); 70 | void Heap_terminate(void); 71 | heap_info* Heap_get_info(void); 72 | int HeapDump(FILE* file); 73 | int HeapDumpString(FILE* file, char* str); 74 | void* Heap_findItem(void* p); 75 | void Heap_unlink(char* file, int line, void* p); 76 | 77 | #endif 78 | -------------------------------------------------------------------------------- /src/mqtt/LinkedList.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/LinkedList.c -------------------------------------------------------------------------------- /src/mqtt/LinkedList.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/LinkedList.h -------------------------------------------------------------------------------- /src/mqtt/Log.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Log.c -------------------------------------------------------------------------------- /src/mqtt/Log.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs - updates for the async client 16 | *******************************************************************************/ 17 | 18 | #if !defined(LOG_H) 19 | #define LOG_H 20 | 21 | /*BE 22 | map LOG_LEVELS 23 | { 24 | "TRACE_MAXIMUM" 1 25 | "TRACE_MEDIUM" 2 26 | "TRACE_MINIMUM" 3 27 | "TRACE_PROTOCOL" 4 28 | 29 | "ERROR" 5 30 | "SEVERE" 6 31 | "FATAL" 7 32 | } 33 | BE*/ 34 | 35 | enum LOG_LEVELS { 36 | TRACE_MAXIMUM = 1, 37 | TRACE_MEDIUM, 38 | TRACE_MINIMUM, 39 | TRACE_PROTOCOL, 40 | LOG_ERROR, 41 | LOG_SEVERE, 42 | LOG_FATAL, 43 | } Log_levels; 44 | 45 | 46 | /*BE 47 | def trace_settings_type 48 | { 49 | n32 map LOG_LEVELS "trace_level" 50 | n32 dec "max_trace_entries" 51 | n32 dec "trace_output_level" 52 | } 53 | BE*/ 54 | typedef struct 55 | { 56 | int trace_level; /**< trace level */ 57 | int max_trace_entries; /**< max no of entries in the trace buffer */ 58 | int trace_output_level; /**< trace level to output to destination */ 59 | } trace_settings_type; 60 | 61 | extern trace_settings_type trace_settings; 62 | 63 | #define LOG_PROTOCOL TRACE_PROTOCOL 64 | #define TRACE_MAX TRACE_MAXIMUM 65 | #define TRACE_MIN TRACE_MINIMUM 66 | #define TRACE_MED TRACE_MEDIUM 67 | 68 | typedef struct 69 | { 70 | const char* name; 71 | const char* value; 72 | } Log_nameValue; 73 | 74 | int Log_initialize(Log_nameValue*); 75 | void Log_terminate(); 76 | 77 | void Log(int, int, char *, ...); 78 | void Log_stackTrace(int, int, int, int, const char*, int, int*); 79 | 80 | typedef void Log_traceCallback(enum LOG_LEVELS level, char* message); 81 | void Log_setTraceCallback(Log_traceCallback* callback); 82 | void Log_setTraceLevel(enum LOG_LEVELS level); 83 | 84 | #endif 85 | -------------------------------------------------------------------------------- /src/mqtt/MQTTClient.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTClient.c -------------------------------------------------------------------------------- /src/mqtt/MQTTClientPersistence.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2012 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | *******************************************************************************/ 16 | 17 | /** 18 | * @file 19 | * \brief This structure represents a persistent data store, used to store 20 | * outbound and inbound messages, in order to achieve reliable messaging. 21 | * 22 | * The MQTT Client persists QoS1 and QoS2 messages in order to meet the 23 | * assurances of delivery associated with these @ref qos levels. The messages 24 | * are saved in persistent storage 25 | * The type and context of the persistence implementation are specified when 26 | * the MQTT client is created (see MQTTClient_create()). The default 27 | * persistence type (::MQTTCLIENT_PERSISTENCE_DEFAULT) uses a file system-based 28 | * persistence mechanism. The persistence_context argument passed to 29 | * MQTTClient_create() when using the default peristence is a string 30 | * representing the location of the persistence directory. If the context 31 | * argument is NULL, the working directory will be used. 32 | * 33 | * To use memory-based persistence, an application passes 34 | * ::MQTTCLIENT_PERSISTENCE_NONE as the persistence_type to 35 | * MQTTClient_create(). This can lead to message loss in certain situations, 36 | * but can be appropriate in some cases (see @ref qos). 37 | * 38 | * Client applications can provide their own persistence mechanism by passing 39 | * ::MQTTCLIENT_PERSISTENCE_USER as the persistence_type. To implement a 40 | * custom persistence mechanism, the application must pass an initialized 41 | * ::MQTTClient_persistence structure as the persistence_context 42 | * argument to MQTTClient_create(). 43 | * 44 | * If the functions defined return an ::MQTTCLIENT_PERSISTENCE_ERROR then the 45 | * state of the persisted data should remain as it was prior to the function 46 | * being called. For example, if Persistence_put() returns 47 | * ::MQTTCLIENT_PERSISTENCE_ERROR, then it is assumed tha tthe persistent store 48 | * does not contain the data that was passed to the function. Similarly, if 49 | * Persistence_remove() returns ::MQTTCLIENT_PERSISTENCE_ERROR then it is 50 | * assumed that the data to be removed is still held in the persistent store. 51 | * 52 | * It is up to the persistence implementation to log any error information that 53 | * may be required to diagnose a persistence mechanism failure. 54 | */ 55 | 56 | /// @cond EXCLUDE 57 | #if !defined(MQTTCLIENTPERSISTENCE_H) 58 | #define MQTTCLIENTPERSISTENCE_H 59 | /// @endcond 60 | 61 | /** 62 | * This persistence_type value specifies the default file system-based 63 | * persistence mechanism (see MQTTClient_create()). 64 | */ 65 | #define MQTTCLIENT_PERSISTENCE_DEFAULT 0 66 | /** 67 | * This persistence_type value specifies a memory-based 68 | * persistence mechanism (see MQTTClient_create()). 69 | */ 70 | #define MQTTCLIENT_PERSISTENCE_NONE 1 71 | /** 72 | * This persistence_type value specifies an application-specific 73 | * persistence mechanism (see MQTTClient_create()). 74 | */ 75 | #define MQTTCLIENT_PERSISTENCE_USER 2 76 | 77 | /** 78 | * Application-specific persistence functions must return this error code if 79 | * there is a problem executing the function. 80 | */ 81 | #define MQTTCLIENT_PERSISTENCE_ERROR -2 82 | 83 | /** 84 | * @brief Initialize the persistent store. 85 | * 86 | * Either open the existing persistent store for this client ID or create a new 87 | * one if one doesn't exist. If the persistent store is already open, return 88 | * without taking any action. 89 | * 90 | * An application can use the same client identifier to connect to many 91 | * different servers. The clientid in conjunction with the 92 | * serverURI uniquely identifies the persistence store required. 93 | * 94 | * @param handle The address of a pointer to a handle for this persistence 95 | * implementation. This function must set handle to a valid reference to the 96 | * persistence following a successful return. 97 | * The handle pointer is passed as an argument to all the other 98 | * persistence functions. It may include the context parameter and/or any other 99 | * data for use by the persistence functions. 100 | * @param clientID The client identifier for which the persistent store should 101 | * be opened. 102 | * @param serverURI The connection string specified when the MQTT client was 103 | * created (see MQTTClient_create()). 104 | * @param context A pointer to any data required to initialize the persistent 105 | * store (see ::MQTTClient_persistence). 106 | * @return Return 0 if the function completes successfully, otherwise return 107 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 108 | */ 109 | typedef int (*Persistence_open)(void** handle, const char* clientID, const char* serverURI, void* context); 110 | 111 | /** 112 | * @brief Close the persistent store referred to by the handle. 113 | * 114 | * @param handle The handle pointer from a successful call to 115 | * Persistence_open(). 116 | * @return Return 0 if the function completes successfully, otherwise return 117 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 118 | */ 119 | typedef int (*Persistence_close)(void* handle); 120 | 121 | /** 122 | * @brief Put the specified data into the persistent store. 123 | * 124 | * @param handle The handle pointer from a successful call to 125 | * Persistence_open(). 126 | * @param key A string used as the key for the data to be put in the store. The 127 | * key is later used to retrieve data from the store with Persistence_get(). 128 | * @param bufcount The number of buffers to write to the persistence store. 129 | * @param buffers An array of pointers to the data buffers associated with 130 | * this key. 131 | * @param buflens An array of lengths of the data buffers. buflen[n] 132 | * gives the length of buffer[n]. 133 | * @return Return 0 if the function completes successfully, otherwise return 134 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 135 | */ 136 | typedef int (*Persistence_put)(void* handle, char* key, int bufcount, char* buffers[], int buflens[]); 137 | 138 | /** 139 | * @brief Retrieve the specified data from the persistent store. 140 | * 141 | * @param handle The handle pointer from a successful call to 142 | * Persistence_open(). 143 | * @param key A string that is the key for the data to be retrieved. This is 144 | * the same key used to save the data to the store with Persistence_put(). 145 | * @param buffer The address of a pointer to a buffer. This function sets the 146 | * pointer to point at the retrieved data, if successful. 147 | * @param buflen The address of an int that is set to the length of 148 | * buffer by this function if successful. 149 | * @return Return 0 if the function completes successfully, otherwise return 150 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 151 | */ 152 | typedef int (*Persistence_get)(void* handle, char* key, char** buffer, int* buflen); 153 | 154 | /** 155 | * @brief Remove the data for the specified key from the store. 156 | * 157 | * @param handle The handle pointer from a successful call to 158 | * Persistence_open(). 159 | * @param key A string that is the key for the data to be removed from the 160 | * store. This is the same key used to save the data to the store with 161 | * Persistence_put(). 162 | * @return Return 0 if the function completes successfully, otherwise return 163 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 164 | */ 165 | typedef int (*Persistence_remove)(void* handle, char* key); 166 | 167 | /** 168 | * @brief Returns the keys in this persistent data store. 169 | * 170 | * @param handle The handle pointer from a successful call to 171 | * Persistence_open(). 172 | * @param keys The address of a pointer to pointers to strings. Assuming 173 | * successful execution, this function allocates memory to hold the returned 174 | * keys (strings used to store the data with Persistence_put()). It also 175 | * allocates memory to hold an array of pointers to these strings. keys 176 | * is set to point to the array of pointers to strings. 177 | * @param nkeys A pointer to the number of keys in this persistent data store. 178 | * This function sets the number of keys, if successful. 179 | * @return Return 0 if the function completes successfully, otherwise return 180 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 181 | */ 182 | typedef int (*Persistence_keys)(void* handle, char*** keys, int* nkeys); 183 | 184 | /** 185 | * @brief Clears the persistence store, so that it no longer contains any 186 | * persisted data. 187 | * 188 | * @param handle The handle pointer from a successful call to 189 | * Persistence_open(). 190 | * @return Return 0 if the function completes successfully, otherwise return 191 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 192 | */ 193 | typedef int (*Persistence_clear)(void* handle); 194 | 195 | /** 196 | * @brief Returns whether any data has been persisted using the specified key. 197 | * 198 | * @param handle The handle pointer from a successful call to 199 | * Persistence_open(). 200 | * @param key The string to be tested for existence in the store. 201 | * @return Return 0 if the key was found in the store, otherwise return 202 | * ::MQTTCLIENT_PERSISTENCE_ERROR. 203 | */ 204 | typedef int (*Persistence_containskey)(void* handle, char* key); 205 | 206 | /** 207 | * @brief A structure containing the function pointers to a persistence 208 | * implementation and the context or state that will be shared across all 209 | * the persistence functions. 210 | */ 211 | typedef struct { 212 | /** 213 | * A pointer to any data required to initialize the persistent store. 214 | */ 215 | void* context; 216 | /** 217 | * A function pointer to an implementation of Persistence_open(). 218 | */ 219 | Persistence_open popen; 220 | /** 221 | * A function pointer to an implementation of Persistence_close(). 222 | */ 223 | Persistence_close pclose; 224 | /** 225 | * A function pointer to an implementation of Persistence_put(). 226 | */ 227 | Persistence_put pput; 228 | /** 229 | * A function pointer to an implementation of Persistence_get(). 230 | */ 231 | Persistence_get pget; 232 | /** 233 | * A function pointer to an implementation of Persistence_remove(). 234 | */ 235 | Persistence_remove premove; 236 | /** 237 | * A function pointer to an implementation of Persistence_keys(). 238 | */ 239 | Persistence_keys pkeys; 240 | /** 241 | * A function pointer to an implementation of Persistence_clear(). 242 | */ 243 | Persistence_clear pclear; 244 | /** 245 | * A function pointer to an implementation of Persistence_containskey(). 246 | */ 247 | Persistence_containskey pcontainskey; 248 | } MQTTClient_persistence; 249 | 250 | #endif 251 | -------------------------------------------------------------------------------- /src/mqtt/MQTTPacket.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTPacket.c -------------------------------------------------------------------------------- /src/mqtt/MQTTPacket.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTPacket.h -------------------------------------------------------------------------------- /src/mqtt/MQTTPacketOut.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTPacketOut.c -------------------------------------------------------------------------------- /src/mqtt/MQTTPacketOut.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2014 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs, Allan Stockdill-Mander - SSL updates 16 | * Ian Craggs - MQTT 3.1.1 support 17 | *******************************************************************************/ 18 | 19 | #if !defined(MQTTPACKETOUT_H) 20 | #define MQTTPACKETOUT_H 21 | 22 | #include "MQTTPacket.h" 23 | 24 | int MQTTPacket_send_connect(Clients* client, int MQTTVersion); 25 | void* MQTTPacket_connack(unsigned char aHeader, char* data, size_t datalen); 26 | 27 | int MQTTPacket_send_pingreq(networkHandles* net, const char* clientID); 28 | 29 | int MQTTPacket_send_subscribe(List* topics, List* qoss, int msgid, int dup, networkHandles* net, const char* clientID); 30 | void* MQTTPacket_suback(unsigned char aHeader, char* data, size_t datalen); 31 | 32 | int MQTTPacket_send_unsubscribe(List* topics, int msgid, int dup, networkHandles* net, const char* clientID); 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /src/mqtt/MQTTPersistence.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTPersistence.c -------------------------------------------------------------------------------- /src/mqtt/MQTTPersistence.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs - async client updates 16 | * Ian Craggs - fix for bug 432903 - queue persistence 17 | *******************************************************************************/ 18 | 19 | #if defined(__cplusplus) 20 | extern "C" { 21 | #endif 22 | 23 | #include "Clients.h" 24 | 25 | /** Stem of the key for a sent PUBLISH QoS1 or QoS2 */ 26 | #define PERSISTENCE_PUBLISH_SENT "s-" 27 | /** Stem of the key for a sent PUBREL */ 28 | #define PERSISTENCE_PUBREL "sc-" 29 | /** Stem of the key for a received PUBLISH QoS2 */ 30 | #define PERSISTENCE_PUBLISH_RECEIVED "r-" 31 | /** Stem of the key for an async client command */ 32 | #define PERSISTENCE_COMMAND_KEY "c-" 33 | /** Stem of the key for an async client message queue */ 34 | #define PERSISTENCE_QUEUE_KEY "q-" 35 | #define PERSISTENCE_MAX_KEY_LENGTH 8 36 | 37 | int MQTTPersistence_create(MQTTClient_persistence** per, int type, void* pcontext); 38 | int MQTTPersistence_initialize(Clients* c, const char* serverURI); 39 | int MQTTPersistence_close(Clients* c); 40 | int MQTTPersistence_clear(Clients* c); 41 | int MQTTPersistence_restore(Clients* c); 42 | void* MQTTPersistence_restorePacket(char* buffer, size_t buflen); 43 | void MQTTPersistence_insertInOrder(List* list, void* content, size_t size); 44 | int MQTTPersistence_put(int socket, char* buf0, size_t buf0len, int count, 45 | char** buffers, size_t* buflens, int htype, int msgId, int scr); 46 | int MQTTPersistence_remove(Clients* c, char* type, int qos, int msgId); 47 | void MQTTPersistence_wrapMsgID(Clients *c); 48 | 49 | typedef struct 50 | { 51 | char struct_id[4]; 52 | int struct_version; 53 | int payloadlen; 54 | void* payload; 55 | int qos; 56 | int retained; 57 | int dup; 58 | int msgid; 59 | } MQTTPersistence_message; 60 | 61 | typedef struct 62 | { 63 | MQTTPersistence_message* msg; 64 | char* topicName; 65 | int topicLen; 66 | unsigned int seqno; /* only used on restore */ 67 | } MQTTPersistence_qEntry; 68 | 69 | int MQTTPersistence_unpersistQueueEntry(Clients* client, MQTTPersistence_qEntry* qe); 70 | int MQTTPersistence_persistQueueEntry(Clients* aclient, MQTTPersistence_qEntry* qe); 71 | int MQTTPersistence_restoreMessageQueue(Clients* c); 72 | #ifdef __cplusplus 73 | } 74 | #endif 75 | -------------------------------------------------------------------------------- /src/mqtt/MQTTPersistenceDefault.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTPersistenceDefault.c -------------------------------------------------------------------------------- /src/mqtt/MQTTPersistenceDefault.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | *******************************************************************************/ 16 | 17 | /** 8.3 filesystem */ 18 | #define MESSAGE_FILENAME_LENGTH 8 19 | /** Extension of the filename */ 20 | #define MESSAGE_FILENAME_EXTENSION ".msg" 21 | 22 | /* prototypes of the functions for the default file system persistence */ 23 | int pstopen(void** handle, const char* clientID, const char* serverURI, void* context); 24 | int pstclose(void* handle); 25 | int pstput(void* handle, char* key, int bufcount, char* buffers[], int buflens[]); 26 | int pstget(void* handle, char* key, char** buffer, int* buflen); 27 | int pstremove(void* handle, char* key); 28 | int pstkeys(void* handle, char*** keys, int* nkeys); 29 | int pstclear(void* handle); 30 | int pstcontainskey(void* handle, char* key); 31 | 32 | int pstmkdir(char *pPathname); 33 | 34 | -------------------------------------------------------------------------------- /src/mqtt/MQTTProtocol.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTProtocol.h -------------------------------------------------------------------------------- /src/mqtt/MQTTProtocolClient.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTProtocolClient.c -------------------------------------------------------------------------------- /src/mqtt/MQTTProtocolClient.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs, Allan Stockdill-Mander - SSL updates 16 | * Ian Craggs - MQTT 3.1.1 updates 17 | * Rong Xiang, Ian Craggs - C++ compatibility 18 | *******************************************************************************/ 19 | 20 | #if !defined(MQTTPROTOCOLCLIENT_H) 21 | #define MQTTPROTOCOLCLIENT_H 22 | 23 | #include "LinkedList.h" 24 | #include "MQTTPacket.h" 25 | #include "Log.h" 26 | #include "MQTTProtocol.h" 27 | #include "Messages.h" 28 | 29 | #define MAX_MSG_ID 65535 30 | #define MAX_CLIENTID_LEN 65535 31 | 32 | int MQTTProtocol_startPublish(Clients* pubclient, Publish* publish, int qos, int retained, Messages** m); 33 | Messages* MQTTProtocol_createMessage(Publish* publish, Messages** mm, int qos, int retained); 34 | Publications* MQTTProtocol_storePublication(Publish* publish, int* len); 35 | int messageIDCompare(void* a, void* b); 36 | int MQTTProtocol_assignMsgId(Clients* client); 37 | void MQTTProtocol_removePublication(Publications* p); 38 | 39 | int MQTTProtocol_handlePublishes(void* pack, int sock); 40 | int MQTTProtocol_handlePubacks(void* pack, int sock); 41 | int MQTTProtocol_handlePubrecs(void* pack, int sock); 42 | int MQTTProtocol_handlePubrels(void* pack, int sock); 43 | int MQTTProtocol_handlePubcomps(void* pack, int sock); 44 | 45 | void MQTTProtocol_keepalive(time_t); 46 | void MQTTProtocol_retry(time_t, int, int); 47 | void MQTTProtocol_freeClient(Clients* client); 48 | void MQTTProtocol_emptyMessageList(List* msgList); 49 | void MQTTProtocol_freeMessageList(List* msgList); 50 | 51 | char* MQTTStrncpy(char *dest, const char* src, size_t num); 52 | char* MQTTStrdup(const char* src); 53 | #endif 54 | -------------------------------------------------------------------------------- /src/mqtt/MQTTProtocolOut.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/MQTTProtocolOut.c -------------------------------------------------------------------------------- /src/mqtt/MQTTProtocolOut.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2014 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | * Ian Craggs, Allan Stockdill-Mander - SSL updates 16 | * Ian Craggs - MQTT 3.1.1 support 17 | *******************************************************************************/ 18 | 19 | #if !defined(MQTTPROTOCOLOUT_H) 20 | #define MQTTPROTOCOLOUT_H 21 | 22 | #include "LinkedList.h" 23 | #include "MQTTPacket.h" 24 | #include "Clients.h" 25 | #include "Log.h" 26 | #include "Messages.h" 27 | #include "MQTTProtocol.h" 28 | #include "MQTTProtocolClient.h" 29 | 30 | #define DEFAULT_PORT 1883 31 | 32 | void MQTTProtocol_reconnect(const char* ip_address, Clients* client); 33 | #if defined(OPENSSL) 34 | int MQTTProtocol_connect(const char* ip_address, Clients* acClients, int ssl, int MQTTVersion); 35 | #else 36 | int MQTTProtocol_connect(const char* ip_address, Clients* acClients, int MQTTVersion); 37 | #endif 38 | int MQTTProtocol_handlePingresps(void* pack, int sock); 39 | int MQTTProtocol_subscribe(Clients* client, List* topics, List* qoss, int msgID); 40 | int MQTTProtocol_handleSubacks(void* pack, int sock); 41 | int MQTTProtocol_unsubscribe(Clients* client, List* topics, int msgID); 42 | int MQTTProtocol_handleUnsubacks(void* pack, int sock); 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /src/mqtt/Makefile: -------------------------------------------------------------------------------- 1 | 2 | all: mqtt_client.a 3 | 4 | mqtt_client.a: Clients.o Heap.o LinkedList.o Log.o Messages.o MQTTClient.o MQTTPacket.o MQTTPacketOut.o MQTTPersistence.o MQTTPersistenceDefault.o MQTTProtocolClient.o MQTTProtocolOut.o Socket.o SocketBuffer.o SSLSocket.o StackTrace.o Thread.o Tree.o utf-8.o mqtt_client.o 5 | $(AR) rc $@ Clients.o Heap.o LinkedList.o Log.o Messages.o MQTTClient.o MQTTPacket.o MQTTPacketOut.o MQTTPersistence.o MQTTPersistenceDefault.o MQTTProtocolClient.o MQTTProtocolOut.o Socket.o SocketBuffer.o SSLSocket.o StackTrace.o Thread.o Tree.o utf-8.o mqtt_client.o 6 | 7 | clean: 8 | rm -f *.o mqtt_client.a 9 | 10 | .PHONY: all clean 11 | -------------------------------------------------------------------------------- /src/mqtt/Messages.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Messages.c -------------------------------------------------------------------------------- /src/mqtt/Messages.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | *******************************************************************************/ 16 | 17 | #if !defined(MESSAGES_H) 18 | #define MESSAGES_H 19 | 20 | char* Messages_get(int, int); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /src/mqtt/SSLSocket.c: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2014 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs, Allan Stockdill-Mander - initial implementation 15 | * Ian Craggs - fix for bug #409702 16 | * Ian Craggs - allow compilation for OpenSSL < 1.0 17 | *******************************************************************************/ 18 | 19 | /** 20 | * @file 21 | * \brief SSL related functions 22 | * 23 | */ 24 | 25 | #if defined(OPENSSL) 26 | 27 | #include "SocketBuffer.h" 28 | #include "MQTTClient.h" 29 | #include "SSLSocket.h" 30 | #include "Log.h" 31 | #include "StackTrace.h" 32 | #include "Socket.h" 33 | 34 | #include "Heap.h" 35 | 36 | #include 37 | #include 38 | #include 39 | 40 | extern Sockets s; 41 | 42 | void SSLSocket_addPendingRead(int sock); 43 | 44 | static ssl_mutex_type* sslLocks = NULL; 45 | static ssl_mutex_type sslCoreMutex; 46 | 47 | #if defined(WIN32) || defined(WIN64) 48 | #define iov_len len 49 | #define iov_base buf 50 | #endif 51 | 52 | /** 53 | * Gets the specific error corresponding to SOCKET_ERROR 54 | * @param aString the function that was being used when the error occurred 55 | * @param sock the socket on which the error occurred 56 | * @return the specific TCP error code 57 | */ 58 | int SSLSocket_error(char* aString, SSL* ssl, int sock, int rc) 59 | { 60 | int error; 61 | 62 | FUNC_ENTRY; 63 | if (ssl) 64 | error = SSL_get_error(ssl, rc); 65 | else 66 | error = ERR_get_error(); 67 | if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) 68 | { 69 | Log(TRACE_MIN, -1, "SSLSocket error WANT_READ/WANT_WRITE"); 70 | } 71 | else 72 | { 73 | static char buf[120]; 74 | 75 | if (strcmp(aString, "shutdown") != 0) 76 | Log(TRACE_MIN, -1, "SSLSocket error %s(%d) in %s for socket %d rc %d errno %d %s\n", buf, error, aString, sock, rc, errno, strerror(errno)); 77 | ERR_print_errors_fp(stderr); 78 | if (error == SSL_ERROR_SSL || error == SSL_ERROR_SYSCALL) 79 | error = SSL_FATAL; 80 | } 81 | FUNC_EXIT_RC(error); 82 | return error; 83 | } 84 | 85 | static struct 86 | { 87 | int code; 88 | char* string; 89 | } 90 | X509_message_table[] = 91 | { 92 | { X509_V_OK, "X509_V_OK" }, 93 | { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT" }, 94 | { X509_V_ERR_UNABLE_TO_GET_CRL, "X509_V_ERR_UNABLE_TO_GET_CRL" }, 95 | { X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, "X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE" }, 96 | { X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, "X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE" }, 97 | { X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, "X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY" }, 98 | { X509_V_ERR_CERT_SIGNATURE_FAILURE, "X509_V_ERR_CERT_SIGNATURE_FAILURE" }, 99 | { X509_V_ERR_CRL_SIGNATURE_FAILURE, "X509_V_ERR_CRL_SIGNATURE_FAILURE" }, 100 | { X509_V_ERR_CERT_NOT_YET_VALID, "X509_V_ERR_CERT_NOT_YET_VALID" }, 101 | { X509_V_ERR_CERT_HAS_EXPIRED, "X509_V_ERR_CERT_HAS_EXPIRED" }, 102 | { X509_V_ERR_CRL_NOT_YET_VALID, "X509_V_ERR_CRL_NOT_YET_VALID" }, 103 | { X509_V_ERR_CRL_HAS_EXPIRED, "X509_V_ERR_CRL_HAS_EXPIRED" }, 104 | { X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD" }, 105 | { X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD" }, 106 | { X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, "X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD" }, 107 | { X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, "X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD" }, 108 | { X509_V_ERR_OUT_OF_MEM, "X509_V_ERR_OUT_OF_MEM" }, 109 | { X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, "X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT" }, 110 | { X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN" }, 111 | { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY" }, 112 | { X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, "X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE" }, 113 | { X509_V_ERR_CERT_CHAIN_TOO_LONG, "X509_V_ERR_CERT_CHAIN_TOO_LONG" }, 114 | { X509_V_ERR_CERT_REVOKED, "X509_V_ERR_CERT_REVOKED" }, 115 | { X509_V_ERR_INVALID_CA, "X509_V_ERR_INVALID_CA" }, 116 | { X509_V_ERR_PATH_LENGTH_EXCEEDED, "X509_V_ERR_PATH_LENGTH_EXCEEDED" }, 117 | { X509_V_ERR_INVALID_PURPOSE, "X509_V_ERR_INVALID_PURPOSE" }, 118 | { X509_V_ERR_CERT_UNTRUSTED, "X509_V_ERR_CERT_UNTRUSTED" }, 119 | { X509_V_ERR_CERT_REJECTED, "X509_V_ERR_CERT_REJECTED" }, 120 | { X509_V_ERR_SUBJECT_ISSUER_MISMATCH, "X509_V_ERR_SUBJECT_ISSUER_MISMATCH" }, 121 | { X509_V_ERR_AKID_SKID_MISMATCH, "X509_V_ERR_AKID_SKID_MISMATCH" }, 122 | { X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH, "X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH" }, 123 | { X509_V_ERR_KEYUSAGE_NO_CERTSIGN, "X509_V_ERR_KEYUSAGE_NO_CERTSIGN" }, 124 | { X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, "X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER" }, 125 | { X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION, "X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION" }, 126 | { X509_V_ERR_KEYUSAGE_NO_CRL_SIGN, "X509_V_ERR_KEYUSAGE_NO_CRL_SIGN" }, 127 | { X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION, "X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION" }, 128 | { X509_V_ERR_INVALID_NON_CA, "X509_V_ERR_INVALID_NON_CA" }, 129 | { X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED, "X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED" }, 130 | { X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE, "X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE" }, 131 | { X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED, "X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED" }, 132 | { X509_V_ERR_INVALID_EXTENSION, "X509_V_ERR_INVALID_EXTENSION" }, 133 | { X509_V_ERR_INVALID_POLICY_EXTENSION, "X509_V_ERR_INVALID_POLICY_EXTENSION" }, 134 | { X509_V_ERR_NO_EXPLICIT_POLICY, "X509_V_ERR_NO_EXPLICIT_POLICY" }, 135 | { X509_V_ERR_UNNESTED_RESOURCE, "X509_V_ERR_UNNESTED_RESOURCE" }, 136 | #if defined(X509_V_ERR_DIFFERENT_CRL_SCOPE) 137 | { X509_V_ERR_DIFFERENT_CRL_SCOPE, "X509_V_ERR_DIFFERENT_CRL_SCOPE" }, 138 | { X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE, "X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE" }, 139 | { X509_V_ERR_PERMITTED_VIOLATION, "X509_V_ERR_PERMITTED_VIOLATION" }, 140 | { X509_V_ERR_EXCLUDED_VIOLATION, "X509_V_ERR_EXCLUDED_VIOLATION" }, 141 | { X509_V_ERR_SUBTREE_MINMAX, "X509_V_ERR_SUBTREE_MINMAX" }, 142 | { X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE, "X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE" }, 143 | { X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX, "X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX" }, 144 | { X509_V_ERR_UNSUPPORTED_NAME_SYNTAX, "X509_V_ERR_UNSUPPORTED_NAME_SYNTAX" }, 145 | #endif 146 | }; 147 | 148 | #if !defined(ARRAY_SIZE) 149 | /** 150 | * Macro to calculate the number of entries in an array 151 | */ 152 | #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) 153 | #endif 154 | 155 | char* SSL_get_verify_result_string(int rc) 156 | { 157 | int i; 158 | char* retstring = "undef"; 159 | 160 | for (i = 0; i < ARRAY_SIZE(X509_message_table); ++i) 161 | { 162 | if (X509_message_table[i].code == rc) 163 | { 164 | retstring = X509_message_table[i].string; 165 | break; 166 | } 167 | } 168 | return retstring; 169 | } 170 | 171 | 172 | void SSL_CTX_info_callback(const SSL* ssl, int where, int ret) 173 | { 174 | if (where & SSL_CB_LOOP) 175 | { 176 | Log(TRACE_PROTOCOL, 1, "SSL state %s:%s:%s", 177 | (where & SSL_ST_CONNECT) ? "connect" : (where & SSL_ST_ACCEPT) ? "accept" : "undef", 178 | SSL_state_string_long(ssl), SSL_get_cipher_name(ssl)); 179 | } 180 | else if (where & SSL_CB_EXIT) 181 | { 182 | Log(TRACE_PROTOCOL, 1, "SSL %s:%s", 183 | (where & SSL_ST_CONNECT) ? "connect" : (where & SSL_ST_ACCEPT) ? "accept" : "undef", 184 | SSL_state_string_long(ssl)); 185 | } 186 | else if (where & SSL_CB_ALERT) 187 | { 188 | Log(TRACE_PROTOCOL, 1, "SSL alert %s:%s:%s", 189 | (where & SSL_CB_READ) ? "read" : "write", 190 | SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); 191 | } 192 | else if (where & SSL_CB_HANDSHAKE_START) 193 | { 194 | Log(TRACE_PROTOCOL, 1, "SSL handshake started %s:%s:%s", 195 | (where & SSL_CB_READ) ? "read" : "write", 196 | SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); 197 | } 198 | else if (where & SSL_CB_HANDSHAKE_DONE) 199 | { 200 | Log(TRACE_PROTOCOL, 1, "SSL handshake done %s:%s:%s", 201 | (where & SSL_CB_READ) ? "read" : "write", 202 | SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); 203 | Log(TRACE_PROTOCOL, 1, "SSL certificate verification: %s", 204 | SSL_get_verify_result_string(SSL_get_verify_result(ssl))); 205 | } 206 | else 207 | { 208 | Log(TRACE_PROTOCOL, 1, "SSL state %s:%s:%s", SSL_state_string_long(ssl), 209 | SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); 210 | } 211 | } 212 | 213 | 214 | char* SSLSocket_get_version_string(int version) 215 | { 216 | int i; 217 | static char buf[20]; 218 | char* retstring = NULL; 219 | static struct 220 | { 221 | int code; 222 | char* string; 223 | } 224 | version_string_table[] = 225 | { 226 | { SSL2_VERSION, "SSL 2.0" }, 227 | { SSL3_VERSION, "SSL 3.0" }, 228 | { TLS1_VERSION, "TLS 1.0" }, 229 | #if defined(TLS2_VERSION) 230 | { TLS2_VERSION, "TLS 1.1" }, 231 | #endif 232 | #if defined(TLS3_VERSION) 233 | { TLS3_VERSION, "TLS 1.2" }, 234 | #endif 235 | }; 236 | 237 | for (i = 0; i < ARRAY_SIZE(version_string_table); ++i) 238 | { 239 | if (version_string_table[i].code == version) 240 | { 241 | retstring = version_string_table[i].string; 242 | break; 243 | } 244 | } 245 | 246 | if (retstring == NULL) 247 | { 248 | sprintf(buf, "%i", version); 249 | retstring = buf; 250 | } 251 | return retstring; 252 | } 253 | 254 | 255 | void SSL_CTX_msg_callback(int write_p, int version, int content_type, const void* buf, size_t len, 256 | SSL* ssl, void* arg) 257 | { 258 | 259 | /* 260 | called by the SSL/TLS library for a protocol message, the function arguments have the following meaning: 261 | 262 | write_p 263 | This flag is 0 when a protocol message has been received and 1 when a protocol message has been sent. 264 | 265 | version 266 | The protocol version according to which the protocol message is interpreted by the library. Currently, this is one of SSL2_VERSION, SSL3_VERSION and TLS1_VERSION (for SSL 2.0, SSL 3.0 and TLS 1.0, respectively). 267 | 268 | content_type 269 | In the case of SSL 2.0, this is always 0. In the case of SSL 3.0 or TLS 1.0, this is one of the ContentType values defined in the protocol specification (change_cipher_spec(20), alert(21), handshake(22); but never application_data(23) because the callback will only be called for protocol messages). 270 | 271 | buf, len 272 | buf points to a buffer containing the protocol message, which consists of len bytes. The buffer is no longer valid after the callback function has returned. 273 | 274 | ssl 275 | The SSL object that received or sent the message. 276 | 277 | arg 278 | The user-defined argument optionally defined by SSL_CTX_set_msg_callback_arg() or SSL_set_msg_callback_arg(). 279 | 280 | */ 281 | 282 | Log(TRACE_PROTOCOL, -1, "%s %s %d buflen %d", (write_p ? "sent" : "received"), 283 | SSLSocket_get_version_string(version), 284 | content_type, (int)len); 285 | } 286 | 287 | 288 | int pem_passwd_cb(char* buf, int size, int rwflag, void* userdata) 289 | { 290 | int rc = 0; 291 | 292 | FUNC_ENTRY; 293 | if (!rwflag) 294 | { 295 | strncpy(buf, (char*)(userdata), size); 296 | buf[size-1] = '\0'; 297 | rc = strlen(buf); 298 | } 299 | FUNC_EXIT_RC(rc); 300 | return rc; 301 | } 302 | 303 | int SSL_create_mutex(ssl_mutex_type* mutex) 304 | { 305 | int rc = 0; 306 | 307 | FUNC_ENTRY; 308 | #if defined(WIN32) || defined(WIN64) 309 | *mutex = CreateMutex(NULL, 0, NULL); 310 | #else 311 | rc = pthread_mutex_init(mutex, NULL); 312 | #endif 313 | FUNC_EXIT_RC(rc); 314 | return rc; 315 | } 316 | 317 | int SSL_lock_mutex(ssl_mutex_type* mutex) 318 | { 319 | int rc = -1; 320 | 321 | /* don't add entry/exit trace points, as trace gets lock too, and it might happen quite frequently */ 322 | #if defined(WIN32) || defined(WIN64) 323 | if (WaitForSingleObject(*mutex, INFINITE) != WAIT_FAILED) 324 | #else 325 | if ((rc = pthread_mutex_lock(mutex)) == 0) 326 | #endif 327 | rc = 0; 328 | 329 | return rc; 330 | } 331 | 332 | int SSL_unlock_mutex(ssl_mutex_type* mutex) 333 | { 334 | int rc = -1; 335 | 336 | /* don't add entry/exit trace points, as trace gets lock too, and it might happen quite frequently */ 337 | #if defined(WIN32) || defined(WIN64) 338 | if (ReleaseMutex(*mutex) != 0) 339 | #else 340 | if ((rc = pthread_mutex_unlock(mutex)) == 0) 341 | #endif 342 | rc = 0; 343 | 344 | return rc; 345 | } 346 | 347 | void SSL_destroy_mutex(ssl_mutex_type* mutex) 348 | { 349 | int rc = 0; 350 | 351 | FUNC_ENTRY; 352 | #if defined(WIN32) || defined(WIN64) 353 | rc = CloseHandle(*mutex); 354 | #else 355 | rc = pthread_mutex_destroy(mutex); 356 | free(mutex); 357 | #endif 358 | FUNC_EXIT_RC(rc); 359 | } 360 | 361 | 362 | 363 | #if (OPENSSL_VERSION_NUMBER >= 0x010000000) 364 | extern void SSLThread_id(CRYPTO_THREADID *id) 365 | { 366 | #if defined(WIN32) || defined(WIN64) 367 | CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId()); 368 | #else 369 | CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self()); 370 | #endif 371 | } 372 | #else 373 | extern unsigned long SSLThread_id(void) 374 | { 375 | #if defined(WIN32) || defined(WIN64) 376 | return (unsigned long)GetCurrentThreadId(); 377 | #else 378 | return (unsigned long)pthread_self(); 379 | #endif 380 | } 381 | #endif 382 | 383 | extern void SSLLocks_callback(int mode, int n, const char *file, int line) 384 | { 385 | if (mode & CRYPTO_LOCK) 386 | SSL_lock_mutex(&sslLocks[n]); 387 | else 388 | SSL_unlock_mutex(&sslLocks[n]); 389 | } 390 | 391 | int SSLSocket_initialize() 392 | { 393 | int rc = 0; 394 | /*int prc;*/ 395 | int i; 396 | int lockMemSize; 397 | 398 | FUNC_ENTRY; 399 | 400 | if ((rc = SSL_library_init()) != 1) 401 | rc = -1; 402 | 403 | ERR_load_crypto_strings(); 404 | SSL_load_error_strings(); 405 | 406 | /* OpenSSL 0.9.8o and 1.0.0a and later added SHA2 algorithms to SSL_library_init(). 407 | Applications which need to use SHA2 in earlier versions of OpenSSL should call 408 | OpenSSL_add_all_algorithms() as well. */ 409 | 410 | OpenSSL_add_all_algorithms(); 411 | 412 | lockMemSize = CRYPTO_num_locks() * sizeof(ssl_mutex_type); 413 | 414 | sslLocks = malloc(lockMemSize); 415 | if (!sslLocks) 416 | { 417 | rc = -1; 418 | goto exit; 419 | } 420 | else 421 | memset(sslLocks, 0, lockMemSize); 422 | 423 | for (i = 0; i < CRYPTO_num_locks(); i++) 424 | { 425 | /* prc = */SSL_create_mutex(&sslLocks[i]); 426 | } 427 | 428 | #if (OPENSSL_VERSION_NUMBER >= 0x010000000) 429 | CRYPTO_THREADID_set_callback(SSLThread_id); 430 | #else 431 | CRYPTO_set_id_callback(SSLThread_id); 432 | #endif 433 | CRYPTO_set_locking_callback(SSLLocks_callback); 434 | 435 | SSL_create_mutex(&sslCoreMutex); 436 | 437 | exit: 438 | FUNC_EXIT_RC(rc); 439 | return rc; 440 | } 441 | 442 | void SSLSocket_terminate() 443 | { 444 | FUNC_ENTRY; 445 | free(sslLocks); 446 | FUNC_EXIT; 447 | } 448 | 449 | int SSLSocket_createContext(networkHandles* net, MQTTClient_SSLOptions* opts) 450 | { 451 | int rc = 1; 452 | const char* ciphers = NULL; 453 | 454 | FUNC_ENTRY; 455 | if (net->ctx == NULL) 456 | if ((net->ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) /* SSLv23 for compatibility with SSLv2, SSLv3 and TLSv1 */ 457 | { 458 | SSLSocket_error("SSL_CTX_new", NULL, net->socket, rc); 459 | goto exit; 460 | } 461 | 462 | if (opts->keyStore) 463 | { 464 | int rc1 = 0; 465 | 466 | if ((rc = SSL_CTX_use_certificate_chain_file(net->ctx, opts->keyStore)) != 1) 467 | { 468 | SSLSocket_error("SSL_CTX_use_certificate_chain_file", NULL, net->socket, rc); 469 | goto free_ctx; /*If we can't load the certificate (chain) file then loading the privatekey won't work either as it needs a matching cert already loaded */ 470 | } 471 | 472 | if (opts->privateKey == NULL) 473 | opts->privateKey = opts->keyStore; /* the privateKey can be included in the keyStore */ 474 | 475 | if (opts->privateKeyPassword != NULL) 476 | { 477 | SSL_CTX_set_default_passwd_cb(net->ctx, pem_passwd_cb); 478 | SSL_CTX_set_default_passwd_cb_userdata(net->ctx, (void*)opts->privateKeyPassword); 479 | } 480 | 481 | /* support for ASN.1 == DER format? DER can contain only one certificate? */ 482 | rc1 = SSL_CTX_use_PrivateKey_file(net->ctx, opts->privateKey, SSL_FILETYPE_PEM); 483 | if (opts->privateKey == opts->keyStore) 484 | opts->privateKey = NULL; 485 | if (rc1 != 1) 486 | { 487 | SSLSocket_error("SSL_CTX_use_PrivateKey_file", NULL, net->socket, rc); 488 | goto free_ctx; 489 | } 490 | } 491 | 492 | if (opts->trustStore) 493 | { 494 | if ((rc = SSL_CTX_load_verify_locations(net->ctx, opts->trustStore, NULL)) != 1) 495 | { 496 | SSLSocket_error("SSL_CTX_load_verify_locations", NULL, net->socket, rc); 497 | goto free_ctx; 498 | } 499 | } 500 | else if ((rc = SSL_CTX_set_default_verify_paths(net->ctx)) != 1) 501 | { 502 | SSLSocket_error("SSL_CTX_set_default_verify_paths", NULL, net->socket, rc); 503 | goto free_ctx; 504 | } 505 | 506 | if (opts->enabledCipherSuites == NULL) 507 | ciphers = "DEFAULT"; 508 | else 509 | ciphers = opts->enabledCipherSuites; 510 | 511 | if ((rc = SSL_CTX_set_cipher_list(net->ctx, ciphers)) != 1) 512 | { 513 | SSLSocket_error("SSL_CTX_set_cipher_list", NULL, net->socket, rc); 514 | goto free_ctx; 515 | } 516 | 517 | SSL_CTX_set_mode(net->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); 518 | 519 | goto exit; 520 | free_ctx: 521 | SSL_CTX_free(net->ctx); 522 | net->ctx = NULL; 523 | 524 | exit: 525 | FUNC_EXIT_RC(rc); 526 | return rc; 527 | } 528 | 529 | 530 | int SSLSocket_setSocketForSSL(networkHandles* net, MQTTClient_SSLOptions* opts) 531 | { 532 | int rc = 1; 533 | 534 | FUNC_ENTRY; 535 | 536 | if (net->ctx != NULL || (rc = SSLSocket_createContext(net, opts)) == 1) 537 | { 538 | int i; 539 | SSL_CTX_set_info_callback(net->ctx, SSL_CTX_info_callback); 540 | SSL_CTX_set_msg_callback(net->ctx, SSL_CTX_msg_callback); 541 | if (opts->enableServerCertAuth) 542 | SSL_CTX_set_verify(net->ctx, SSL_VERIFY_PEER, NULL); 543 | 544 | net->ssl = SSL_new(net->ctx); 545 | 546 | /* Log all ciphers available to the SSL sessions (loaded in ctx) */ 547 | for (i = 0; ;i++) 548 | { 549 | const char* cipher = SSL_get_cipher_list(net->ssl, i); 550 | if (cipher == NULL) 551 | break; 552 | Log(TRACE_PROTOCOL, 1, "SSL cipher available: %d:%s", i, cipher); 553 | } 554 | if ((rc = SSL_set_fd(net->ssl, net->socket)) != 1) 555 | SSLSocket_error("SSL_set_fd", net->ssl, net->socket, rc); 556 | } 557 | 558 | FUNC_EXIT_RC(rc); 559 | return rc; 560 | } 561 | 562 | 563 | int SSLSocket_connect(SSL* ssl, int sock) 564 | { 565 | int rc = 0; 566 | 567 | FUNC_ENTRY; 568 | 569 | rc = SSL_connect(ssl); 570 | if (rc != 1) 571 | { 572 | int error; 573 | error = SSLSocket_error("SSL_connect", ssl, sock, rc); 574 | if (error == SSL_FATAL) 575 | rc = error; 576 | if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) 577 | rc = TCPSOCKET_INTERRUPTED; 578 | } 579 | 580 | FUNC_EXIT_RC(rc); 581 | return rc; 582 | } 583 | 584 | 585 | 586 | /** 587 | * Reads one byte from a socket 588 | * @param socket the socket to read from 589 | * @param c the character read, returned 590 | * @return completion code 591 | */ 592 | int SSLSocket_getch(SSL* ssl, int socket, char* c) 593 | { 594 | int rc = SOCKET_ERROR; 595 | 596 | FUNC_ENTRY; 597 | if ((rc = SocketBuffer_getQueuedChar(socket, c)) != SOCKETBUFFER_INTERRUPTED) 598 | goto exit; 599 | 600 | if ((rc = SSL_read(ssl, c, (size_t)1)) < 0) 601 | { 602 | int err = SSLSocket_error("SSL_read - getch", ssl, socket, rc); 603 | if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) 604 | { 605 | rc = TCPSOCKET_INTERRUPTED; 606 | SocketBuffer_interrupted(socket, 0); 607 | } 608 | } 609 | else if (rc == 0) 610 | rc = SOCKET_ERROR; /* The return value from recv is 0 when the peer has performed an orderly shutdown. */ 611 | else if (rc == 1) 612 | { 613 | SocketBuffer_queueChar(socket, *c); 614 | rc = TCPSOCKET_COMPLETE; 615 | } 616 | exit: 617 | FUNC_EXIT_RC(rc); 618 | return rc; 619 | } 620 | 621 | 622 | 623 | /** 624 | * Attempts to read a number of bytes from a socket, non-blocking. If a previous read did not 625 | * finish, then retrieve that data. 626 | * @param socket the socket to read from 627 | * @param bytes the number of bytes to read 628 | * @param actual_len the actual number of bytes read 629 | * @return completion code 630 | */ 631 | char *SSLSocket_getdata(SSL* ssl, int socket, int bytes, int* actual_len) 632 | { 633 | int rc; 634 | char* buf; 635 | 636 | FUNC_ENTRY; 637 | if (bytes == 0) 638 | { 639 | buf = SocketBuffer_complete(socket); 640 | goto exit; 641 | } 642 | 643 | buf = SocketBuffer_getQueuedData(socket, bytes, actual_len); 644 | 645 | if ((rc = SSL_read(ssl, buf + (*actual_len), (size_t)(bytes - (*actual_len)))) < 0) 646 | { 647 | rc = SSLSocket_error("SSL_read - getdata", ssl, socket, rc); 648 | if (rc != SSL_ERROR_WANT_READ && rc != SSL_ERROR_WANT_WRITE) 649 | { 650 | buf = NULL; 651 | goto exit; 652 | } 653 | } 654 | else if (rc == 0) /* rc 0 means the other end closed the socket */ 655 | { 656 | buf = NULL; 657 | goto exit; 658 | } 659 | else 660 | *actual_len += rc; 661 | 662 | if (*actual_len == bytes) 663 | { 664 | SocketBuffer_complete(socket); 665 | /* if we read the whole packet, there might still be data waiting in the SSL buffer, which 666 | isn't picked up by select. So here we should check for any data remaining in the SSL buffer, and 667 | if so, add this socket to a new "pending SSL reads" list. 668 | */ 669 | if (SSL_pending(ssl) > 0) /* return no of bytes pending */ 670 | SSLSocket_addPendingRead(socket); 671 | } 672 | else /* we didn't read the whole packet */ 673 | { 674 | SocketBuffer_interrupted(socket, *actual_len); 675 | Log(TRACE_MAX, -1, "SSL_read: %d bytes expected but %d bytes now received", bytes, *actual_len); 676 | } 677 | exit: 678 | FUNC_EXIT; 679 | return buf; 680 | } 681 | 682 | void SSLSocket_destroyContext(networkHandles* net) 683 | { 684 | FUNC_ENTRY; 685 | if (net->ctx) 686 | SSL_CTX_free(net->ctx); 687 | net->ctx = NULL; 688 | FUNC_EXIT; 689 | } 690 | 691 | 692 | int SSLSocket_close(networkHandles* net) 693 | { 694 | int rc = 1; 695 | FUNC_ENTRY; 696 | if (net->ssl) { 697 | rc = SSL_shutdown(net->ssl); 698 | SSL_free(net->ssl); 699 | net->ssl = NULL; 700 | } 701 | SSLSocket_destroyContext(net); 702 | FUNC_EXIT_RC(rc); 703 | return rc; 704 | } 705 | 706 | 707 | /* No SSL_writev() provided by OpenSSL. Boo. */ 708 | int SSLSocket_putdatas(SSL* ssl, int socket, char* buf0, size_t buf0len, int count, char** buffers, size_t* buflens, int* frees) 709 | { 710 | int rc = 0; 711 | int i; 712 | char *ptr; 713 | iobuf iovec; 714 | int sslerror; 715 | 716 | FUNC_ENTRY; 717 | iovec.iov_len = buf0len; 718 | for (i = 0; i < count; i++) 719 | iovec.iov_len += buflens[i]; 720 | 721 | ptr = iovec.iov_base = (char *)malloc(iovec.iov_len); 722 | memcpy(ptr, buf0, buf0len); 723 | ptr += buf0len; 724 | for (i = 0; i < count; i++) 725 | { 726 | memcpy(ptr, buffers[i], buflens[i]); 727 | ptr += buflens[i]; 728 | } 729 | 730 | SSL_lock_mutex(&sslCoreMutex); 731 | if ((rc = SSL_write(ssl, iovec.iov_base, iovec.iov_len)) == iovec.iov_len) 732 | rc = TCPSOCKET_COMPLETE; 733 | else 734 | { 735 | sslerror = SSLSocket_error("SSL_write", ssl, socket, rc); 736 | 737 | if (sslerror == SSL_ERROR_WANT_WRITE) 738 | { 739 | int* sockmem = (int*)malloc(sizeof(int)); 740 | int free = 1; 741 | 742 | Log(TRACE_MIN, -1, "Partial write: incomplete write of %d bytes on SSL socket %d", 743 | iovec.iov_len, socket); 744 | SocketBuffer_pendingWrite(socket, ssl, 1, &iovec, &free, iovec.iov_len, 0); 745 | *sockmem = socket; 746 | ListAppend(s.write_pending, sockmem, sizeof(int)); 747 | FD_SET(socket, &(s.pending_wset)); 748 | rc = TCPSOCKET_INTERRUPTED; 749 | } 750 | else 751 | rc = SOCKET_ERROR; 752 | } 753 | SSL_unlock_mutex(&sslCoreMutex); 754 | 755 | if (rc != TCPSOCKET_INTERRUPTED) 756 | free(iovec.iov_base); 757 | else 758 | { 759 | int i; 760 | free(buf0); 761 | for (i = 0; i < count; ++i) 762 | { 763 | if (frees[i]) 764 | free(buffers[i]); 765 | } 766 | } 767 | FUNC_EXIT_RC(rc); 768 | return rc; 769 | } 770 | 771 | static List pending_reads = {NULL, NULL, NULL, 0, 0}; 772 | 773 | void SSLSocket_addPendingRead(int sock) 774 | { 775 | FUNC_ENTRY; 776 | if (ListFindItem(&pending_reads, &sock, intcompare) == NULL) /* make sure we don't add the same socket twice */ 777 | { 778 | int* psock = (int*)malloc(sizeof(sock)); 779 | *psock = sock; 780 | ListAppend(&pending_reads, psock, sizeof(sock)); 781 | } 782 | else 783 | Log(TRACE_MIN, -1, "SSLSocket_addPendingRead: socket %d already in the list", sock); 784 | 785 | FUNC_EXIT; 786 | } 787 | 788 | 789 | int SSLSocket_getPendingRead() 790 | { 791 | int sock = -1; 792 | 793 | if (pending_reads.count > 0) 794 | { 795 | sock = *(int*)(pending_reads.first->content); 796 | ListRemoveHead(&pending_reads); 797 | } 798 | return sock; 799 | } 800 | 801 | 802 | int SSLSocket_continueWrite(pending_writes* pw) 803 | { 804 | int rc = 0; 805 | 806 | FUNC_ENTRY; 807 | if ((rc = SSL_write(pw->ssl, pw->iovecs[0].iov_base, pw->iovecs[0].iov_len)) == pw->iovecs[0].iov_len) 808 | { 809 | /* topic and payload buffers are freed elsewhere, when all references to them have been removed */ 810 | free(pw->iovecs[0].iov_base); 811 | Log(TRACE_MIN, -1, "SSL continueWrite: partial write now complete for socket %d", pw->socket); 812 | rc = 1; 813 | } 814 | else 815 | { 816 | int sslerror = SSLSocket_error("SSL_write", pw->ssl, pw->socket, rc); 817 | if (sslerror == SSL_ERROR_WANT_WRITE) 818 | rc = 0; /* indicate we haven't finished writing the payload yet */ 819 | } 820 | FUNC_EXIT_RC(rc); 821 | return rc; 822 | } 823 | #endif 824 | -------------------------------------------------------------------------------- /src/mqtt/SSLSocket.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2014 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs, Allan Stockdill-Mander - initial implementation 15 | *******************************************************************************/ 16 | #if !defined(SSLSOCKET_H) 17 | #define SSLSOCKET_H 18 | 19 | #if defined(WIN32) || defined(WIN64) 20 | #define ssl_mutex_type HANDLE 21 | #else 22 | #include 23 | #include 24 | #define ssl_mutex_type pthread_mutex_t 25 | #endif 26 | 27 | #include 28 | #include "SocketBuffer.h" 29 | #include "Clients.h" 30 | 31 | #define URI_SSL "ssl://" 32 | 33 | int SSLSocket_initialize(); 34 | void SSLSocket_terminate(); 35 | int SSLSocket_setSocketForSSL(networkHandles* net, MQTTClient_SSLOptions* opts); 36 | int SSLSocket_getch(SSL* ssl, int socket, char* c); 37 | char *SSLSocket_getdata(SSL* ssl, int socket, int bytes, int* actual_len); 38 | 39 | int SSLSocket_close(networkHandles* net); 40 | int SSLSocket_putdatas(SSL* ssl, int socket, char* buf0, size_t buf0len, int count, char** buffers, size_t* buflens, int* frees); 41 | int SSLSocket_connect(SSL* ssl, int socket); 42 | 43 | int SSLSocket_getPendingRead(); 44 | int SSLSocket_continueWrite(pending_writes* pw); 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /src/mqtt/Socket.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Socket.c -------------------------------------------------------------------------------- /src/mqtt/Socket.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Socket.h -------------------------------------------------------------------------------- /src/mqtt/SocketBuffer.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/SocketBuffer.c -------------------------------------------------------------------------------- /src/mqtt/SocketBuffer.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/SocketBuffer.h -------------------------------------------------------------------------------- /src/mqtt/StackTrace.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/StackTrace.c -------------------------------------------------------------------------------- /src/mqtt/StackTrace.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/StackTrace.h -------------------------------------------------------------------------------- /src/mqtt/Thread.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Thread.c -------------------------------------------------------------------------------- /src/mqtt/Thread.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2014 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial implementation 15 | * Ian Craggs, Allan Stockdill-Mander - async client updates 16 | * Ian Craggs - fix for bug #420851 17 | *******************************************************************************/ 18 | 19 | #if !defined(THREAD_H) 20 | #define THREAD_H 21 | 22 | #if defined(WIN32) || defined(WIN64) 23 | #include 24 | #define thread_type HANDLE 25 | #define thread_id_type DWORD 26 | #define thread_return_type DWORD 27 | #define thread_fn LPTHREAD_START_ROUTINE 28 | #define mutex_type HANDLE 29 | #define cond_type HANDLE 30 | #define sem_type HANDLE 31 | #else 32 | #include 33 | #include 34 | #define thread_type pthread_t 35 | #define thread_id_type pthread_t 36 | #define thread_return_type void* 37 | typedef thread_return_type (*thread_fn)(void*); 38 | #define mutex_type pthread_mutex_t* 39 | typedef struct { pthread_cond_t cond; pthread_mutex_t mutex; } cond_type_struct; 40 | typedef cond_type_struct *cond_type; 41 | typedef sem_t *sem_type; 42 | 43 | cond_type Thread_create_cond(); 44 | int Thread_signal_cond(cond_type); 45 | int Thread_wait_cond(cond_type condvar, int timeout); 46 | int Thread_destroy_cond(cond_type); 47 | #endif 48 | 49 | thread_type Thread_start(thread_fn, void*); 50 | 51 | mutex_type Thread_create_mutex(); 52 | int Thread_lock_mutex(mutex_type); 53 | int Thread_unlock_mutex(mutex_type); 54 | void Thread_destroy_mutex(mutex_type); 55 | 56 | thread_id_type Thread_getid(); 57 | 58 | sem_type Thread_create_sem(); 59 | int Thread_wait_sem(sem_type sem, int timeout); 60 | int Thread_check_sem(sem_type sem); 61 | int Thread_post_sem(sem_type sem); 62 | int Thread_destroy_sem(sem_type sem); 63 | 64 | 65 | #endif 66 | -------------------------------------------------------------------------------- /src/mqtt/Tree.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Tree.c -------------------------------------------------------------------------------- /src/mqtt/Tree.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/Tree.h -------------------------------------------------------------------------------- /src/mqtt/mqtt_client.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/mqtt_client.c -------------------------------------------------------------------------------- /src/mqtt/mqtt_client.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/mqtt_client.h -------------------------------------------------------------------------------- /src/mqtt/utf-8.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt/utf-8.c -------------------------------------------------------------------------------- /src/mqtt/utf-8.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2009, 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Ian Craggs - initial API and implementation and/or initial documentation 15 | *******************************************************************************/ 16 | 17 | #if !defined(UTF8_H) 18 | #define UTF8_H 19 | 20 | int UTF8_validate(int len, char* data); 21 | int UTF8_validateString(const char* string); 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /src/mqtt_publish.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MQTT publish 3 | * 4 | * Author: JoStudio 5 | */ 6 | /* 7 | 主程序分为三个步骤: 8 | 9 | 1, 调用 mqtt_new()创建 客户端对象 10 | 11 | 2, 调用 mqtt_connect() 连接服务器 12 | 13 | 3, 调用 mqtt_publish() 发布消息 14 | 15 | */ 16 | 17 | 18 | #include 19 | #include 20 | #include 21 | #include "mqtt/mqtt_client.h"//这个是我对mqtt_client封装后的头文件 22 | 23 | 24 | int mqtt_publish_sub(int argc, char ** argv) { 25 | 26 | mqtt_client *m; //mqtt_client 对象指针 27 | int ret; //返回值 28 | char *host = "messagesight.demos.ibm.com:1883";//测试服务器 29 | char *topic = "test_topic"; //主题 30 | char *client_id = "clientid33883";//客户端ID; 对测试服务器,可以随便写 31 | char *username = NULL;//用户名,用于验证身份。对测试服务器,无。 32 | char *password = NULL;//密码,用于验证身份。对测试服务器,无。 33 | int Qos; //Quality of Service 34 | 35 | //create new mqtt client object 36 | m = mqtt_new(host, MQTT_PORT, client_id); //创建对象,MQTT_PORT = 1883 37 | if ( m == NULL ) { 38 | printf("mqtt client create failure, return code = %d\n", errno); 39 | return 1; 40 | } else { 41 | printf("mqtt client created\n"); 42 | } 43 | //-上面由于没有套接字的操作,所以即使我没有联网也是可以创建成功的,就是为了以后的操作准备了大量的信息和空间 44 | //-就是一次创建的,没有周期函数在里面 45 | //connect to server 46 | ret = mqtt_connect(m, username, password); //连接服务器,这里不仅仅有硬件连接还有MQTT协议连接 47 | if (ret != MQTT_SUCCESS ) { 48 | printf("mqtt client connect failure, return code = %d\n", ret); 49 | return 1; 50 | } else { 51 | printf("mqtt client connect\n"); 52 | } 53 | //-上面一个流程仅仅完成了连接请求,协议层的连接可能在另外一个线程中实现的 54 | //publish message 55 | Qos = QOS_EXACTLY_ONCE; //Qos 56 | ret = mqtt_publish(m, topic, "hello from Linkit 7688", Qos);//发布消息 57 | printf("mqtt client publish, return code = %d\n", ret); 58 | //-下面是和服务器断开连接,并且清除为了连接而建立的系列环境 59 | mqtt_disconnect(m); //disconnect 60 | mqtt_delete(m); //delete mqtt client object 61 | return 0; 62 | } 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /src/mqtt_publish.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef MQTT_PUBLISH_H 4 | #define MQTT_PUBLISH_H 5 | 6 | int mqtt_publish_sub(int argc, char ** argv); 7 | 8 | #endif /* MQTT_PUBLISH_H */ 9 | -------------------------------------------------------------------------------- /src/mqtt_subscribe.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/mqtt_subscribe.c -------------------------------------------------------------------------------- /src/mqtt_subscribe.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef MQTT_SUBSCRIBE_H 4 | #define MQTT_SUBSCRIBE_H 5 | 6 | int mqtt_subscribe_sub(int argc, char ** argv); 7 | 8 | #endif /* MQTT_SUBSCRIBE_H*/ 9 | -------------------------------------------------------------------------------- /src/tcpdump.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrianGuo/mqtt_uart_based_on_openwrt/1072c6b9c8a4e36adcd90c7d621d0944176e4e00/src/tcpdump.c -------------------------------------------------------------------------------- /src/tcpdump.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef TCPDUMP_H 4 | #define TCPDUMP_H 5 | 6 | int sniffer_sub(int argc,char* argv[]); 7 | 8 | #endif /* TCPDUMP_H */ 9 | -------------------------------------------------------------------------------- /src/tcpdump/Makefile: -------------------------------------------------------------------------------- 1 | all: tcpdump.a 2 | 3 | tcpdump.a: tcpdump.o 4 | $(AR) rc $@ tcpdump.o 5 | 6 | clean: 7 | rm -f *.o tcpdump.a 8 | -------------------------------------------------------------------------------- /src/thread.c: -------------------------------------------------------------------------------- 1 | /* 2 | 此文件作为线程的独立文件,所有实际内容都在这里处理,说明也在这里 3 | */ 4 | //-2016/10/25 09:48:56 5 | /* 6 | 线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的 7 | 基本单位。线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程 8 | 序计数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的 9 | 全部资源。 10 | 什么时候使用多线程? 当多个任务可以并行执行时,可以为每个任务启动一个线程。 11 | 12 | tips: 13 | pthread库不是linux默认的库,所以在编译时候需要指明libpthread.a库。 14 | 解决方法:在编译时,加上-lpthread参数。 15 | 16 | */ 17 | 18 | #include "debugfl.h" 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | 27 | 28 | static int num=0; //-前面的static表示仅仅这个文件中使用这个变量 29 | pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER; 30 | 31 | 32 | void *add(void *arg) 33 | {//线程执行函数,执行500次加法 34 | int i = 0,tmp; 35 | for (; i <500; i++) 36 | { 37 | pthread_mutex_lock(&mylock); 38 | tmp=num+1; 39 | num=tmp; 40 | printf("add+1,result is:%d\n",num); 41 | pthread_mutex_unlock(&mylock); 42 | } 43 | return ((void *)0); 44 | } 45 | 46 | void *sub(void *arg)//线程执行函数,执行500次减法 47 | { 48 | int i=0,tmp; 49 | for(;i<500;i++) 50 | { 51 | pthread_mutex_lock(&mylock); //-线程调用该函数让互斥锁上锁,如果该互斥锁已被另一个线程锁定和拥有,则调用该线程将阻塞,直到该互斥锁变为可用为止。 52 | tmp=num-1; 53 | num=tmp; 54 | printf("sub-1,result is:%d\n",num); 55 | pthread_mutex_unlock(&mylock); 56 | } 57 | return ((void *)0); 58 | } 59 | 60 | /* 61 | 输入运行命令:dreamflower_app -D -X 62 | */ 63 | int thread_sub(int argc, char** argv) //-这个是主线程,再开的就是子线程 64 | { 65 | 66 | pthread_t tid1,tid2; 67 | int err; 68 | void *tret; 69 | err=pthread_create(&tid1,NULL,add,NULL);//创建线程 70 | if(err!=0) 71 | { 72 | printf("pthread_create error:%s\n",strerror(err)); 73 | exit(-1); 74 | } 75 | err=pthread_create(&tid2,NULL,sub,NULL); 76 | if(err!=0) 77 | { 78 | printf("pthread_create error:%s\n",strerror(err)); 79 | exit(-1); 80 | } 81 | err=pthread_join(tid1,&tret);//阻塞等待线程id为tid1的线程,直到该线程退出 82 | if(err!=0) 83 | { 84 | printf("can not join with thread1:%s\n",strerror(err)); 85 | exit(-1); 86 | } 87 | printf("thread 1 exit code %d\n",(int)tret); 88 | err=pthread_join(tid2,&tret); 89 | if(err!=0) 90 | { 91 | printf("can not join with thread1:%s\n",strerror(err)); 92 | exit(-1); 93 | } 94 | printf("thread 2 exit code %d\n",(int)tret); 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /src/uart1.c: -------------------------------------------------------------------------------- 1 | //-2016/3/9 23:03:56 2 | /* 3 | 现在我需要实现gpio功能,但是不能像以前那样简单的移植了,需要知道怎么实现的 4 | 首先是框架实现 5 | */ 6 | 7 | #include "debugfl.h" 8 | 9 | //串口相关的头文件 10 | #include /*标准输入输出定义*/ 11 | #include /*标准函数库定义*/ 12 | #include /*Unix 标准函数定义*/ 13 | #include 14 | #include 15 | #include /*文件控制定义*/ 16 | #include /*PPSIX 终端控制定义*/ 17 | #include /*错误号定义*/ 18 | #include 19 | 20 | 21 | //宏定义 22 | #define FALSE -1 23 | #define TRUE 0 24 | 25 | /******************************************************************* 26 | * 名称: UART0_Open 27 | * 功能: 打开串口并返回串口设备文件描述 28 | * 入口参数: fd :文件描述符 port :串口号(/dev/ttyS0,/dev/ttyS1,/dev/ttyS2) 29 | * 出口参数: 正确返回为1,错误返回为0 30 | *******************************************************************/ 31 | int UART0_Open(int fd,char* port) //-目前程序如果成功的话就是阻塞的终端设备 32 | { 33 | //-O_NOCTTY:表示打开的是一个终端设备,程序不会成为该端口的控制终端。如果不使用此标志,任务一个输入(eg:键盘中止信号等)都将影响进程。 34 | //-O_NDELAY:表示不关心DCD信号线所处的状态(端口的另一端是否激活或者停止)。 35 | fd = open( port, O_RDWR|O_NOCTTY|O_NDELAY); 36 | //-fd = open( port, O_RDWR); 37 | if (FALSE == fd) 38 | { 39 | perror("Can't Open Serial Port"); 40 | return(FALSE); 41 | } 42 | //恢复串口为阻塞状态 43 | if(fcntl(fd, F_SETFL, 0) < 0) //-阻塞:fcntl(fd,F_SETFL,0) ,, 非阻塞:fcntl(fd,F_SETFL,FNDELAY) 44 | { 45 | printf("fcntl failed!\n"); 46 | return(FALSE); 47 | } 48 | else 49 | { 50 | printf("fcntl=%d\n",fcntl(fd, F_SETFL,0)); 51 | } 52 | //测试是否为终端设备 53 | if(0 == isatty(STDIN_FILENO)) 54 | { 55 | printf("standard input is not a terminal device\n"); 56 | return(FALSE); 57 | } 58 | else 59 | {//-到这里说明是终端设备 60 | printf("isatty success!\n"); 61 | } 62 | printf("fd->open=%d\n",fd); 63 | return fd; 64 | } 65 | /******************************************************************* 66 | * 名称: UART0_Close 67 | * 功能: 关闭串口并返回串口设备文件描述 68 | * 入口参数: fd :文件描述符 port :串口号(ttyS0,ttyS1,ttyS2) 69 | * 出口参数: void 70 | *******************************************************************/ 71 | 72 | void UART0_Close(int fd) 73 | { 74 | close(fd); 75 | } 76 | 77 | /******************************************************************* 78 | * 名称: UART0_Set 79 | * 功能: 设置串口数据位,停止位和效验位 80 | * 入口参数: fd 串口文件描述符 81 | * speed 串口速度 82 | * flow_ctrl 数据流控制 83 | * databits 数据位 取值为 7 或者8 84 | * stopbits 停止位 取值为 1 或者2 85 | * parity 效验类型 取值为N,E,O,,S 86 | *出口参数: 正确返回为1,错误返回为0 87 | *******************************************************************/ 88 | int UART0_Set(int fd,int speed,int flow_ctrl,int databits,int stopbits,int parity) 89 | { 90 | 91 | int i; 92 | int status; 93 | int speed_arr[] = { B115200, B57600, B19200, B9600, B4800, B2400, B1200, B300}; 94 | int name_arr[] = {115200, 57600, 19200, 9600, 4800, 2400, 1200, 300}; 95 | 96 | struct termios options; 97 | 98 | /*tcgetattr(fd,&options)得到与fd指向对象的相关参数,并将它们保存于options,该函数还可以测试配置是否正确,该串口是否可用等。若调用成功,函数返回值为0,若调用失败,函数返回值为1. 99 | */ 100 | if ( tcgetattr( fd,&options) != 0) //-获得串口指向termios结构的指针 101 | {//-调用失败,串口不可用 102 | perror("SetupSerial 1"); 103 | return(FALSE); 104 | } 105 | 106 | //设置串口输入波特率和输出波特率 107 | for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++) 108 | { 109 | if (speed == name_arr[i]) 110 | { 111 | cfsetispeed(&options, speed_arr[i]); 112 | cfsetospeed(&options, speed_arr[i]); 113 | } 114 | } 115 | 116 | //修改控制模式,保证程序不会占用串口 117 | options.c_cflag |= CLOCAL; 118 | //修改控制模式,使得能够从串口中读取输入数据 119 | options.c_cflag |= CREAD; 120 | 121 | //设置数据流控制 122 | switch(flow_ctrl) 123 | { 124 | 125 | case 0 ://不使用流控制 126 | options.c_cflag &= ~CRTSCTS; 127 | break; 128 | 129 | case 1 ://使用硬件流控制 130 | options.c_cflag |= CRTSCTS; 131 | break; 132 | case 2 ://使用软件流控制 133 | options.c_cflag |= IXON | IXOFF | IXANY; 134 | break; 135 | } 136 | //设置数据位 137 | //屏蔽其他标志位 138 | options.c_cflag &= ~CSIZE; 139 | switch (databits) 140 | { 141 | case 5 : 142 | options.c_cflag |= CS5; 143 | break; 144 | case 6 : 145 | options.c_cflag |= CS6; 146 | break; 147 | case 7 : 148 | options.c_cflag |= CS7; 149 | break; 150 | case 8: 151 | options.c_cflag |= CS8; 152 | break; 153 | default: 154 | fprintf(stderr,"Unsupported data size\n"); 155 | return (FALSE); 156 | } 157 | //设置校验位 158 | switch (parity) 159 | { 160 | case 'n': 161 | case 'N': //无奇偶校验位。 162 | options.c_cflag &= ~PARENB; 163 | options.c_iflag &= ~INPCK; 164 | break; 165 | case 'o': 166 | case 'O'://设置为奇校验 167 | options.c_cflag |= (PARODD | PARENB); 168 | options.c_iflag |= INPCK; 169 | break; 170 | case 'e': 171 | case 'E'://设置为偶校验 172 | options.c_cflag |= PARENB; 173 | options.c_cflag &= ~PARODD; 174 | options.c_iflag |= INPCK; 175 | break; 176 | case 's': 177 | case 'S': //设置为空格 178 | options.c_cflag &= ~PARENB; 179 | options.c_cflag &= ~CSTOPB; 180 | break; 181 | default: 182 | fprintf(stderr,"Unsupported parity\n"); 183 | return (FALSE); 184 | } 185 | // 设置停止位 186 | switch (stopbits) 187 | { 188 | case 1: 189 | options.c_cflag &= ~CSTOPB; break; 190 | case 2: 191 | options.c_cflag |= CSTOPB; break; 192 | default: 193 | fprintf(stderr,"Unsupported stop bits\n"); 194 | return (FALSE); 195 | } 196 | //-如果不是开发终端之类的,只是串口传输数据,而不需要串口来处理,那么使用原始模式(Raw Mode)方式来通讯 197 | //修改输出模式,原始数据输出 198 | options.c_oflag &= ~OPOST; /*Output*/ 199 | //-经典输入是以面向行设计的.在经典输入模式中输入字符会被放入一个缓冲之中,这样可以以与用户交互的方式编辑缓冲的内容,直到收到CR(carriage return)或者LF(line feed)字符. 200 | options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);//我加的 /*Input*/选择原始输入 201 | //options.c_lflag &= ~(ISIG | ICANON); 202 | 203 | 204 | //设置等待时间和最小接收字符 205 | options.c_cc[VTIME] = 1; /* 读取一个字符等待1*(1/10)s */ 206 | options.c_cc[VMIN] = 1; /* 读取字符的最少个数为1 */ 207 | 208 | //如果发生数据溢出,接收数据,但是不再读取 刷新收到的数据但是不读 209 | tcflush(fd,TCIFLUSH); 210 | 211 | //激活配置 (将修改后的termios数据设置到串口中) 212 | if (tcsetattr(fd,TCSANOW,&options) != 0) 213 | { 214 | perror("com set error!\n"); 215 | return (FALSE); 216 | } 217 | return (TRUE); 218 | } 219 | /******************************************************************* 220 | * 名称: UART0_Init() 221 | * 功能: 串口初始化 222 | * 入口参数: fd : 文件描述符 223 | * speed : 串口速度 224 | * flow_ctrl 数据流控制 225 | * databits 数据位 取值为 7 或者8 226 | * stopbits 停止位 取值为 1 或者2 227 | * parity 效验类型 取值为N,E,O,,S 228 | * 229 | * 出口参数: 正确返回为1,错误返回为0 230 | *******************************************************************/ 231 | int UART0_Init(int fd, int speed,int flow_ctrl,int databits,int stopbits,int parity) 232 | { 233 | int err; 234 | //设置串口数据帧格式 235 | if (UART0_Set(fd,speed,flow_ctrl,databits,stopbits,parity) == FALSE) 236 | { 237 | return FALSE; 238 | } 239 | else 240 | { 241 | return TRUE; 242 | } 243 | } 244 | 245 | /******************************************************************* 246 | * 名称: UART0_Recv 247 | * 功能: 接收串口数据 248 | * 入口参数: fd :文件描述符 249 | * rcv_buf :接收串口中数据存入rcv_buf缓冲区中 250 | * data_len :一帧数据的长度 251 | * 出口参数: 正确返回为1,错误返回为0 252 | *******************************************************************/ 253 | int UART0_Recv(int fd, char *rcv_buf,int data_len) 254 | { 255 | int len,fs_sel; 256 | fd_set fs_read; 257 | 258 | struct timeval time; 259 | 260 | FD_ZERO(&fs_read); //-将你的套节字集合清空 261 | FD_SET(fd,&fs_read); //-加入你感兴趣的套节字到集合,这里是一个读数据的套节字s,,其实就是给对应的位置1 262 | 263 | time.tv_sec = 10; 264 | time.tv_usec = 0; 265 | 266 | //使用select实现串口的多路通信 267 | fs_sel = select(fd+1,&fs_read,NULL,NULL,&time); //-对应的事件发生则返回对应的位为1 268 | if(fs_sel) 269 | { 270 | len = read(fd,rcv_buf,data_len); 271 | printf("I am right!(version1.2) len = %d fs_sel = %d\n",len,fs_sel); 272 | return len; 273 | } 274 | else 275 | { 276 | printf("Sorry,I am wrong!"); 277 | return FALSE; 278 | } 279 | } 280 | /******************************************************************** 281 | * 名称: UART0_Send 282 | * 功能: 发送数据 283 | * 入口参数: fd :文件描述符 284 | * send_buf :存放串口发送数据 285 | * data_len :一帧数据的个数 286 | * 出口参数: 正确返回为1,错误返回为0 287 | *******************************************************************/ 288 | int UART0_Send(int fd, char *send_buf,int data_len) 289 | { 290 | int len = 0; 291 | 292 | len = write(fd,send_buf,data_len); 293 | if (len == data_len ) 294 | { 295 | return len; 296 | } 297 | else 298 | {//-出错了清空处理 299 | tcflush(fd,TCOFLUSH); //-刷清(扔掉)输入缓存(终端驱动法度已接管到,但用户法度尚未读)或输出缓存(用户法度已经写,但尚未发送). 300 | return FALSE; 301 | } 302 | 303 | } 304 | 305 | 306 | /* 307 | 2016/3/18 10:12:52 308 | 目前这文件是可以运行的,并且对串口也可以操作了,但是还有部分功能不能实现,所以需要先理解透了,再寻找其他原因. 309 | */ 310 | int uart1_sub(int argc, char *argv[]) //?参数如何传递过来的,在终端输入命令的时候就带入了参数 311 | { 312 | int fd=0; //文件描述符 313 | int err; //返回调用函数的状态 314 | int len; 315 | int i; 316 | char rcv_buf[100]; 317 | char send_buf[20]="tiger john"; 318 | 319 | if(argc != 3) 320 | { 321 | printf("Usage: %s /dev/ttySn 0(send data)/1 (receive data) \n",argv[0]); 322 | return FALSE; 323 | } 324 | 325 | fd = UART0_Open(fd,argv[1]); //打开串口,返回文件描述符 326 | do{ 327 | err = UART0_Init(fd,57600,0,8,1,'N'); 328 | printf("Set Port Exactly!\n"); 329 | }while(FALSE == err || FALSE == fd); 330 | 331 | return fd; //-返回文件描述符,以便后面可用 332 | 333 | if(0 == strcmp(argv[2],"0")) 334 | { 335 | for(i = 0;i < 10;i++) 336 | { 337 | len = UART0_Send(fd,send_buf,10); 338 | if(len > 0) 339 | printf(" %d send data successful\n",i); 340 | else 341 | printf("send data failed!\n"); 342 | 343 | sleep(1); 344 | } 345 | UART0_Close(fd); 346 | } 347 | else 348 | { 349 | 350 | while (1) //循环读取数据 351 | { 352 | len = UART0_Recv(fd, rcv_buf,9); 353 | if(len > 0) 354 | { 355 | rcv_buf[len] = '\0'; 356 | printf("receive data is %s\n",rcv_buf); 357 | printf("len = %d\n",len); 358 | } 359 | else 360 | { 361 | printf("cannot receive data\n"); 362 | } 363 | sleep(2); 364 | } 365 | UART0_Close(fd); 366 | } 367 | 368 | 369 | return 0; 370 | } 371 | 372 | -------------------------------------------------------------------------------- /src/uart1.h: -------------------------------------------------------------------------------- 1 | //-为了方便调试定义了系列变量以便调试输出 2 | 3 | #ifndef UART_1_APP_H 4 | #define UART_1_APP_H 5 | 6 | void uart_1_Main(int fd); 7 | int UART0_Send(int fd, char *send_buf,int data_len); 8 | 9 | #endif /* UART_1_APP_H */ 10 | -------------------------------------------------------------------------------- /src/uart_1_app.c: -------------------------------------------------------------------------------- 1 | /* 2 | Linux串口操作中,特别以非阻塞的方式读取和发送数据,做好进程之间的同步很重要。有 3 | 时我们会发现这样一个问题,在进行read操作时,一次read不能获得一个完整的数据帧, 4 | 这就好比你买了一个电脑,送货的先把显示器送到你家,再把机箱送到,你会发现还少键盘 5 | 鼠标什么的,又要过几天才送,这会让你急死。很不幸,在串口操作的时候,接受数据很可 6 | 能就是这样分批收货的,但是幸运的是,接受数据的动作很快,别忘了计算机就是靠速度这 7 | 一点,抛开这个,啥都不是。 8 | 很自然的,我们就会进行数据的拼接,将一堆零散的数据拼接成一个个有用的数据帧,哈哈, 9 | 变废为宝。说多了让人很烦,举个例子吧。 10 | 11 | 假如我们定义的数据帧是以'$'开头,以‘#’结尾的。 12 | 13 | 1.下面的程序有一个问题:当同时接收到两个命令的时候就会丢失其中一个,这个后续需要处理 14 | */ 15 | 16 | #include "debugfl.h" 17 | 18 | //串口相关的头文件 19 | #include /*标准输入输出定义*/ 20 | #include /*标准函数库定义*/ 21 | #include /*Unix 标准函数定义*/ 22 | #include 23 | #include 24 | #include /*文件控制定义*/ 25 | #include /*PPSIX 终端控制定义*/ 26 | #include /*错误号定义*/ 27 | #include 28 | 29 | #include "uart1.h" 30 | 31 | 32 | //首先定义了两个字符数组: 33 | //-一个缓冲数组,用来存放每一次读到的数据 34 | char read_data[256]={0}; 35 | //-int read_pt=0; //-指向待处理位置的 36 | //-存放一个完整的数据帧,以便处理 37 | char read_report[256]={0}; 38 | 39 | 40 | 41 | //得到了一个完整的数据帧 42 | void get_complete_frame(int fd) 43 | { 44 | char read_tmp[256]={0}; 45 | int return_flag=0; 46 | int i; 47 | //存放读取到的字节数 48 | while(1) 49 | { 50 | memset(read_tmp,0,sizeof(read_tmp)); 51 | if(read(fd, read_tmp, sizeof(read_tmp))>0) 52 | { 53 | //数据帧的拼接 54 | printf("read_tmp: %s\n",read_tmp); 55 | for( i=0;i