├── .gitignore
├── LICENSE
├── NOTICE
├── README.md
├── examples
└── SimpleMQTT
│ └── SimpleMQTT.ino
├── keywords.txt
├── library.json
├── library.properties
├── platformio.ini
└── src
├── ESP8266AWSIoTMQTTWS.h
├── aws-sdk-arduino
├── DeviceIndependentInterfaces.cpp
├── DeviceIndependentInterfaces.h
├── Utils.cpp
├── Utils.h
├── jsmn.c
├── jsmn.h
├── sha256.cpp
└── sha256.h
├── aws
├── AwsIotSigv4.cpp
├── AwsIotSigv4.h
├── ESP8266DateTimeProvider.cpp
└── ESP8266DateTimeProvider.h
├── aws_iot_config.h
├── config
├── AWSConnectionParams.cpp
└── AWSConnectionParams.h
├── mqtt
├── MqttClient.cpp
└── MqttClient.h
└── ws
├── CircularByteBuffer.h
├── WebSocketClientAdapter.cpp
└── WebSocketClientAdapter.h
/.gitignore:
--------------------------------------------------------------------------------
1 | .pioenvs
2 | .piolibdeps
3 | .clang_complete
4 | .gcc-flags.json
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/NOTICE:
--------------------------------------------------------------------------------
1 | aws-mqtt-websockets code subject to the LGPL-3.0 license:
2 |
3 | GNU LESSER GENERAL PUBLIC LICENSE
4 | Version 3, 29 June 2007
5 |
6 | Copyright (C) 2007 Free Software Foundation, Inc.
7 | Everyone is permitted to copy and distribute verbatim copies
8 | of this license document, but changing it is not allowed.
9 |
10 |
11 | This version of the GNU Lesser General Public License incorporates
12 | the terms and conditions of version 3 of the GNU General Public
13 | License, supplemented by the additional permissions listed below.
14 |
15 | 0. Additional Definitions.
16 |
17 | As used herein, "this License" refers to version 3 of the GNU Lesser
18 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
19 | General Public License.
20 |
21 | "The Library" refers to a covered work governed by this License,
22 | other than an Application or a Combined Work as defined below.
23 |
24 | An "Application" is any work that makes use of an interface provided
25 | by the Library, but which is not otherwise based on the Library.
26 | Defining a subclass of a class defined by the Library is deemed a mode
27 | of using an interface provided by the Library.
28 |
29 | A "Combined Work" is a work produced by combining or linking an
30 | Application with the Library. The particular version of the Library
31 | with which the Combined Work was made is also called the "Linked
32 | Version".
33 |
34 | The "Minimal Corresponding Source" for a Combined Work means the
35 | Corresponding Source for the Combined Work, excluding any source code
36 | for portions of the Combined Work that, considered in isolation, are
37 | based on the Application, and not on the Linked Version.
38 |
39 | The "Corresponding Application Code" for a Combined Work means the
40 | object code and/or source code for the Application, including any data
41 | and utility programs needed for reproducing the Combined Work from the
42 | Application, but excluding the System Libraries of the Combined Work.
43 |
44 | 1. Exception to Section 3 of the GNU GPL.
45 |
46 | You may convey a covered work under sections 3 and 4 of this License
47 | without being bound by section 3 of the GNU GPL.
48 |
49 | 2. Conveying Modified Versions.
50 |
51 | If you modify a copy of the Library, and, in your modifications, a
52 | facility refers to a function or data to be supplied by an Application
53 | that uses the facility (other than as an argument passed when the
54 | facility is invoked), then you may convey a copy of the modified
55 | version:
56 |
57 | a) under this License, provided that you make a good faith effort to
58 | ensure that, in the event an Application does not supply the
59 | function or data, the facility still operates, and performs
60 | whatever part of its purpose remains meaningful, or
61 |
62 | b) under the GNU GPL, with none of the additional permissions of
63 | this License applicable to that copy.
64 |
65 | 3. Object Code Incorporating Material from Library Header Files.
66 |
67 | The object code form of an Application may incorporate material from
68 | a header file that is part of the Library. You may convey such object
69 | code under terms of your choice, provided that, if the incorporated
70 | material is not limited to numerical parameters, data structure
71 | layouts and accessors, or small macros, inline functions and templates
72 | (ten or fewer lines in length), you do both of the following:
73 |
74 | a) Give prominent notice with each copy of the object code that the
75 | Library is used in it and that the Library and its use are
76 | covered by this License.
77 |
78 | b) Accompany the object code with a copy of the GNU GPL and this license
79 | document.
80 |
81 | 4. Combined Works.
82 |
83 | You may convey a Combined Work under terms of your choice that,
84 | taken together, effectively do not restrict modification of the
85 | portions of the Library contained in the Combined Work and reverse
86 | engineering for debugging such modifications, if you also do each of
87 | the following:
88 |
89 | a) Give prominent notice with each copy of the Combined Work that
90 | the Library is used in it and that the Library and its use are
91 | covered by this License.
92 |
93 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
94 | document.
95 |
96 | c) For a Combined Work that displays copyright notices during
97 | execution, include the copyright notice for the Library among
98 | these notices, as well as a reference directing the user to the
99 | copies of the GNU GPL and this license document.
100 |
101 | d) Do one of the following:
102 |
103 | 0) Convey the Minimal Corresponding Source under the terms of this
104 | License, and the Corresponding Application Code in a form
105 | suitable for, and under terms that permit, the user to
106 | recombine or relink the Application with a modified version of
107 | the Linked Version to produce a modified Combined Work, in the
108 | manner specified by section 6 of the GNU GPL for conveying
109 | Corresponding Source.
110 |
111 | 1) Use a suitable shared library mechanism for linking with the
112 | Library. A suitable mechanism is one that (a) uses at run time
113 | a copy of the Library already present on the user's computer
114 | system, and (b) will operate properly with a modified version
115 | of the Library that is interface-compatible with the Linked
116 | Version.
117 |
118 | e) Provide Installation Information, but only if you would otherwise
119 | be required to provide such information under section 6 of the
120 | GNU GPL, and only to the extent that such information is
121 | necessary to install and execute a modified version of the
122 | Combined Work produced by recombining or relinking the
123 | Application with a modified version of the Linked Version. (If
124 | you use option 4d0, the Installation Information must accompany
125 | the Minimal Corresponding Source and Corresponding Application
126 | Code. If you use option 4d1, you must provide the Installation
127 | Information in the manner specified by section 6 of the GNU GPL
128 | for conveying Corresponding Source.)
129 |
130 | 5. Combined Libraries.
131 |
132 | You may place library facilities that are a work based on the
133 | Library side by side in a single library together with other library
134 | facilities that are not Applications and are not covered by this
135 | License, and convey such a combined library under terms of your
136 | choice, if you do both of the following:
137 |
138 | a) Accompany the combined library with a copy of the same work based
139 | on the Library, uncombined with any other library facilities,
140 | conveyed under the terms of this License.
141 |
142 | b) Give prominent notice with the combined library that part of it
143 | is a work based on the Library, and explaining where to find the
144 | accompanying uncombined form of the same work.
145 |
146 | 6. Revised Versions of the GNU Lesser General Public License.
147 |
148 | The Free Software Foundation may publish revised and/or new versions
149 | of the GNU Lesser General Public License from time to time. Such new
150 | versions will be similar in spirit to the present version, but may
151 | differ in detail to address new problems or concerns.
152 |
153 | Each version is given a distinguishing version number. If the
154 | Library as you received it specifies that a certain numbered version
155 | of the GNU Lesser General Public License "or any later version"
156 | applies to it, you have the option of following the terms and
157 | conditions either of that published version or of any later version
158 | published by the Free Software Foundation. If the Library as you
159 | received it does not specify a version number of the GNU Lesser
160 | General Public License, you may choose any version of the GNU Lesser
161 | General Public License ever published by the Free Software Foundation.
162 |
163 | If the Library as you received it specifies that a proxy can decide
164 | whether future versions of the GNU Lesser General Public License shall
165 | apply, that proxy's public statement of acceptance of any version is
166 | permanent authorization for you to choose that version for the
167 | Library.
168 |
169 |
170 | ################################################################################
171 |
172 | WebSockets code subject to the LGPL-3.0 license:
173 |
174 | Copyright (c) 2015 Markus Sattler. All rights reserved.
175 |
176 | This library is free software; you can redistribute it and/or
177 | modify it under the terms of the GNU Lesser General Public
178 | License as published by the Free Software Foundation; either
179 | version 2.1 of the License, or (at your option) any later version.
180 |
181 | This library is distributed in the hope that it will be useful,
182 | but WITHOUT ANY WARRANTY; without even the implied warranty of
183 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
184 | Lesser General Public License for more details.
185 |
186 | You should have received a copy of the GNU Lesser General Public
187 | License along with this library; if not, write to the Free Software
188 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
189 |
190 |
191 | ################################################################################
192 |
193 | Paho code subject to the Eclipse Public License Version 1.0:
194 |
195 | Copyright (c) 2014, 2015 IBM Corp.
196 |
197 | All rights reserved. This program and the accompanying materials
198 | are made available under the terms of the Eclipse Public License v1.0
199 | and Eclipse Distribution License v1.0 which accompany this distribution.
200 |
201 | The Eclipse Public License is available at
202 | http://www.eclipse.org/legal/epl-v10.html
203 | and the Eclipse Distribution License is available at
204 | http://www.eclipse.org/org/documents/edl-v10.php.
205 |
206 |
207 | ################################################################################
208 |
209 | AWS Labs experimental SDK code subject to the Apache License Version 2.0
210 |
211 | Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
212 |
213 | Apache License
214 | Version 2.0, January 2004
215 |
216 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
217 |
218 | 1. Definitions.
219 |
220 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
221 |
222 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
223 |
224 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
225 |
226 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
227 |
228 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
229 |
230 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
231 |
232 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
233 |
234 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
235 |
236 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
237 |
238 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
239 |
240 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
241 |
242 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
243 |
244 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
245 |
246 | 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
247 | 2. You must cause any modified files to carry prominent notices stating that You changed the files; and
248 | 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
249 | 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
250 |
251 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
252 |
253 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
254 |
255 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
256 |
257 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
258 |
259 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
260 |
261 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
262 |
263 | END OF TERMS AND CONDITIONS
264 |
265 |
266 | ################################################################################
267 |
268 | JSMN code subject to the MIT License:
269 |
270 | Copyright (c) 2010 Serge A. Zaitsev
271 |
272 | Permission is hereby granted, free of charge, to any person obtaining a copy
273 | of this software and associated documentation files (the "Software"), to deal
274 | in the Software without restriction, including without limitation the rights
275 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
276 | copies of the Software, and to permit persons to whom the Software is
277 | furnished to do so, subject to the following conditions:
278 |
279 | The above copyright notice and this permission notice shall be included in
280 | all copies or substantial portions of the Software.
281 |
282 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
283 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
284 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
285 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
286 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
287 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
288 | THE SOFTWARE.
289 |
290 |
291 | ################################################################################
292 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AWS IoT Websockets
2 |
3 | ---------------------------------------------
4 | :warning: :warning: :warning: **This is no longer maintained and obsolete, there is better way to do this: [follow instructions from here](https://github.com/debsahu/ESP-MQTT-AWS-IoT-Core) Still want to use this, follow instructions below** :warning: :warning: :warning:
5 | ---------------------------------------------
6 | Arduino Library derived from [joekickass/esp8266-arduino-aws-iot-ws](https://github.com/joekickass/esp8266-arduino-aws-iot-ws) to work with Arduino
7 |
8 | [](https://www.youtube.com/watch?v=AiCa6E_DBL8)
9 |
10 | ## Dependencies
11 |
12 | | Library | Link | Use |
13 | |---------------------------|-----------------------------------------------------------------|---------------------|
14 | |arduinoWebSockets |https://github.com/Links2004/arduinoWebSockets |websocket comm impl |
15 | |PahoMQTT |https://projects.eclipse.org/projects/technology.paho/downloads |mqtt comm impl |
16 | |ArduinoJSON 6.5.0-beta |https://github.com/bblanchon/ArduinoJson/releases |data |
17 |
18 |
19 | ## Headers from [joekickass/esp8266-arduino-aws-iot-ws](https://github.com/joekickass/esp8266-arduino-aws-iot-ws)
20 |
21 | Library for connecting to the AWS IoT service from an ESP8266 using websockets. Authenticates using AWS IAM credentials and sigV4.
22 |
23 | Based on the work of [AWS labs](https://github.com/awslabs/aws-sdk-arduino), basically using its SigV4 implementation and a fork by [Sander van de Graaf](https://github.com/svdgraaf/aws-sdk-arduino). The fork is reflected in [the License](LICENSE).
24 |
25 | Inspired by [Fábio Toledo](https://github.com/odelot/aws-mqtt-websockets)s work on [aws-mqtt-websockets](https://github.com/odelot/aws-mqtt-websockets), but using libraries accessible through the PlatformIO library manager. **This is actually the main reason for creating the library**.
26 |
27 | Adds MQTT functionality using the [Paho](https://projects.eclipse.org/projects/technology.paho) library. It is fairly easy to replace with another MQTT client, e.g. [PubSubClient](https://github.com/knolleary/pubsubclient).
28 |
29 | ## Attributions
30 |
31 | Big thanks to [Fábio Toledo](https://github.com/odelot) for his work on [aws-mqtt-websockets](https://github.com/odelot/aws-mqtt-websockets). Any credit should be directed to him and the authors of the libraries used in this project.
32 |
33 | The library uses code from the following projects. License information can be found in the [NOTICE](NOTICE) file:
34 | - [AWS labs - aws-sdk-arduino](https://github.com/awslabs/aws-sdk-arduino)
35 | - [Sander van de Graaf - aws-sdk-arduino](https://github.com/svdgraaf/aws-sdk-arduino)
36 | - [Fábio Toledo - aws-mqtt-websockets](https://github.com/odelot/aws-mqtt-websockets)
37 | - [Serge Zaitsev - JSMN](https://github.com/zserge/jsmn)
38 | - [Paho MQTT client](https://www.eclipse.org)
39 | - [Stephan Brumme - SHA256](http://create.stephan-brumme.com/)
40 |
41 | In the case of missing license information, I took the liberty of adding it.
42 |
43 | ## Architecture
44 |
45 | 
46 |
--------------------------------------------------------------------------------
/examples/SimpleMQTT/SimpleMQTT.ino:
--------------------------------------------------------------------------------
1 | #include
2 | #include //https://github.com/bblanchon/ArduinoJson (use v6.xx)
3 | #include //https://github.com/debsahu/esp8266-arduino-aws-iot-ws
4 | //https://github.com/Links2004/arduinoWebSockets
5 | //https://projects.eclipse.org/projects/technology.paho/downloads (download Arduino version)
6 |
7 | const char *ssid = "WIFI_SSID";
8 | const char *password = "WIFI_PASSWORD";
9 |
10 | // See `src/aws_iot_config.h` for formatting
11 | char *region = (char *) "us-east-1";
12 | char *endpoint = (char *) "xxxxxxxxxxxx";
13 | char *mqttHost = (char *) "xxxxxxxxxxxx.iot.us-east-1.amazonaws.com";
14 | int mqttPort = 443;
15 | char *iamKeyId = (char *) "yyyyyyyyyyyyyyyyyy";
16 | char *iamSecretKey = (char *) "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";
17 | const char* aws_topic = "$aws/things/ZZZZZZZZZZZZ/shadow/update";
18 |
19 | #if !(ARDUINOJSON_VERSION_MAJOR == 6 and ARDUINOJSON_VERSION_MINOR == 5)
20 | #error "Install ArduinoJson v6.5.0-beta"
21 | #endif
22 |
23 | ESP8266DateTimeProvider dtp;
24 | AwsIotSigv4 sigv4(&dtp, region, endpoint, mqttHost, mqttPort, iamKeyId, iamSecretKey);
25 | AWSConnectionParams cp(sigv4);
26 | AWSWebSocketClientAdapter adapter(cp);
27 | AWSMqttClient client(adapter, cp);
28 |
29 | void setup() {
30 |
31 | Serial.begin(115200);
32 | while(!Serial) {
33 | yield();
34 | }
35 |
36 | WiFi.begin(ssid, password);
37 | while (WiFi.status() != WL_CONNECTED) {
38 | delay(500);
39 | Serial.print(".");
40 | }
41 |
42 | int res = client.connect();
43 | Serial.printf("mqtt connect=%d\n", res);
44 |
45 | if (res == 0) {
46 | client.subscribe(aws_topic, 1,
47 | [](const char* topic, const char* msg)
48 | { Serial.printf("Got msg '%s' on topic %s\n", msg, topic); }
49 | );
50 | }
51 | }
52 |
53 | void loop() {
54 | if (client.isConnected()) {
55 | DynamicJsonDocument jsonBuffer;
56 | JsonObject root = jsonBuffer.to();
57 | JsonObject state = root.createNestedObject("state");
58 | JsonObject state_reported = state.createNestedObject("reported");
59 | state_reported["value"] = random(100);
60 | serializeJson(root, Serial);
61 | Serial.println();
62 | char shadow[measureJson(root) + 1];
63 | serializeJson(root, shadow, sizeof(shadow));
64 |
65 | client.publish(aws_topic, shadow, 0, false);
66 | client.yield();
67 |
68 | } else {
69 | Serial.println("Not connected...");
70 | delay(2000);
71 | }
72 |
73 | delay(30000);
74 | }
--------------------------------------------------------------------------------
/keywords.txt:
--------------------------------------------------------------------------------
1 | ESP8266AWSIoTMQTTWS KEYWORD1
2 | ESP8266DateTimeProvider KEYWORD2
3 | AwsIotSigv4 KEYWORD2
4 | AWSConnectionParams KEYWORD2
5 | AWSWebSocketClientAdapter KEYWORD2
6 | AWSMqttClient KEYWORD2
--------------------------------------------------------------------------------
/library.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "AWS IoT ESP8266 Arduino Websockets",
3 | "keywords": "AWS, IoT, SDK, ESP8266, Websockets, sigv4, Arduino",
4 | "description": "AWS IoT Device SDK for ESP8266/Arduino using Websockets and sigv4 authentication.",
5 | "repository":
6 | {
7 | "type": "git",
8 | "url": "https://github.com/debsahu/esp8266-arduino-aws-iot-ws"
9 | },
10 | "version": "0.1.4",
11 | "frameworks": "arduino",
12 | "platforms": "espressif8266",
13 | "dependencies": [
14 | {
15 | "name": "Paho",
16 | "authors": "Eclipse",
17 | "frameworks": "arduino",
18 | "platforms": "*"
19 | },
20 | {
21 | "name": "WebSockets",
22 | "authors": "Markus Sattler",
23 | "frameworks": "arduino",
24 | "platforms": "*"
25 | },
26 | {
27 | "name": "jsmn",
28 | "authors": "Serge Zaitsev",
29 | "frameworks": "*",
30 | "platforms": "*"
31 | }
32 | ]
33 | }
34 |
--------------------------------------------------------------------------------
/library.properties:
--------------------------------------------------------------------------------
1 | name=AWS IoT ESP8266 Arduino Websockets
2 | version=0.1.5
3 | author=Tomas Nilsson
4 | maintainer=Debashish Sahu
5 | sentence=AWS IoT Device SDK for ESP8266/Arduino using Websockets and sigv4 authentication
6 | paragraph=AWS IoT Device SDK for ESP8266/Arduino using Websockets and sigv4 authentication
7 | category=Communication
8 | url=https://github.com/debsahu/esp8266-arduino-aws-iot-ws
9 | architectures=esp8266
--------------------------------------------------------------------------------
/platformio.ini:
--------------------------------------------------------------------------------
1 | ; PlatformIO Project Configuration File
2 | ;
3 | ; Build options: build flags, source filter
4 | ; Upload options: custom upload port, speed and extra flags
5 | ; Library options: dependencies, extra library storages
6 | ; Advanced options: extra scripting
7 | ;
8 | ; Please visit documentation for the other options and examples
9 | ; http://docs.platformio.org/page/projectconf.html
10 | [platformio]
11 | env_default = d1_mini
12 |
13 | [env:d1_mini]
14 | platform = espressif8266
15 | board = d1_mini
16 | framework = arduino
17 | lib_deps = Paho
18 | WebSockets
19 | jsmn
20 |
--------------------------------------------------------------------------------
/src/ESP8266AWSIoTMQTTWS.h:
--------------------------------------------------------------------------------
1 | #ifndef ESP8266AWSIOTMQTTWS_H_
2 | #define ESP8266AWSIOTMQTTWS_H_
3 |
4 | #include "config/AWSConnectionParams.h"
5 | #include "mqtt/MqttClient.h"
6 | #include "aws/AwsIotSigv4.h"
7 | #include "aws/ESP8266DateTimeProvider.h"
8 | #include "aws-sdk-arduino/DeviceIndependentInterfaces.h"
9 | #include "ws/CircularByteBuffer.h"
10 | #include "ws/WebSocketClientAdapter.h"
11 |
12 | #endif
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/DeviceIndependentInterfaces.cpp:
--------------------------------------------------------------------------------
1 | #include "DeviceIndependentInterfaces.h"
2 |
3 | IHttpClient::~IHttpClient() {
4 | }
5 | IDateTimeProvider::~IDateTimeProvider() {
6 | }
7 |
8 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/DeviceIndependentInterfaces.h:
--------------------------------------------------------------------------------
1 | #ifndef DEVICEINDEPENDENTINTERFACES_H_
2 | #define DEVICEINDEPENDENTINTERFACES_H_
3 |
4 | #pragma once
5 |
6 | /* HTTPClient Interface. Wraps the functionality of the existing TCPClient, and
7 | * EthernetClient for Spark Core and Intel Galileo Respectively. */
8 | class IHttpClient {
9 | public:
10 | virtual ~IHttpClient();
11 | /* Send http request and return the response. */
12 | virtual char* send(const char *request, const char* serverUrl,
13 | int port) = 0;
14 | /* Returns true if the client uses a curl command, false if the client uses
15 | * raw http/https. */
16 | virtual bool usesCurl(void) = 0;
17 | };
18 |
19 | /* Interface for setting and retrieving the current time. Required for sigv4
20 | * signing. */
21 | class IDateTimeProvider {
22 | public:
23 | virtual ~IDateTimeProvider();
24 | /* Retrieve the current GMT date and time in yyyyMMddHHmmss format. */
25 | virtual const char* getDateTime(void) = 0;
26 | /* Return true if the sync function requires the current time as in
27 | * argument. */
28 | virtual bool syncTakesArg(void) = 0;
29 | /* Called if AWS Service reports in accurate time. Sets the provider to
30 | * current time. If syncTakesArg() returns true, this argument takes the
31 | * current GMT date and time in yyyyMMddHHmmss format. Else, the nput value
32 | * is ignored and may be null. */
33 | virtual void sync(const char* dateTime) = 0;
34 | };
35 |
36 | #endif /* AWSDEVICEINDEPENDENTINTERFACES_H_ */
37 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/Utils.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Utils.cpp
3 | *
4 | * See Utils.h for description.
5 | *
6 | * Created on: Jun 30, 2014
7 | * Author: hoffmaj
8 | */
9 |
10 | #include "Utils.h"
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include "jsmn.h"
16 | #include "sha256.h"
17 |
18 | /* Constants for base64Encode. */
19 | static const char ENCODE_CHARS[] =
20 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
21 | static const char PAD_CHAR = '=';
22 |
23 | /* Constants for findHttpStatusCode. */
24 | static const char HTTP_STATUS_CODE_PREFIX[] = "HTTP/1.1 ";
25 | static const int HTTP_STATUS_CODE_LEN = 3;
26 |
27 | /* Constants for hmacSha256. */
28 | static const int BLOCK_SIZE = 64;
29 | static const char OPAD = 0x5c;
30 | static const char IPAD = 0x36;
31 | const int SHA256_DEC_HASH_LEN = 32;
32 |
33 | char *base64Encode(const char *toEncode) {
34 | int inLen = strlen(toEncode);
35 | /* For every three input chars there are 4 output chars, plus an extra 4
36 | * output chars for the possible 1 or 2 remaining input chars, plus an
37 | * extra byte for null termination. */
38 | size_t encodedLen = (((inLen / 3) + (inLen % 3 > 0)) * 4) + 1;
39 |
40 | char *encoded = new char[encodedLen]();
41 | int chunkIdx;
42 | char inChar1;
43 | char inChar2;
44 | char inChar3;
45 | int outIdx1;
46 | int outIdx2;
47 | int outIdx3;
48 | int outIdx4;
49 |
50 | for (chunkIdx = 0; chunkIdx < inLen / 3; chunkIdx++) {
51 | /* This approach of treating each character individually instead of
52 | * containing all bits in a long type allows the encoding to work on 8,
53 | * 16, 32, and 64 bit systems. */
54 | inChar1 = *toEncode++;
55 | inChar2 = *toEncode++;
56 | inChar3 = *toEncode++;
57 |
58 | outIdx1 = (inChar1 & 0xFC) >> 2;
59 | outIdx2 = ((inChar1 & 0x03) << 4) + ((inChar2 & 0xF0) >> 4);
60 | outIdx3 = ((inChar2 & 0x0F) << 2) + ((inChar3 & 0xC0) >> 6);
61 | outIdx4 = inChar3 & 0x3F;
62 |
63 | encoded[chunkIdx * 4] = ENCODE_CHARS[outIdx1];
64 | encoded[chunkIdx * 4 + 1] = ENCODE_CHARS[outIdx2];
65 | encoded[chunkIdx * 4 + 2] = ENCODE_CHARS[outIdx3];
66 | encoded[chunkIdx * 4 + 3] = ENCODE_CHARS[outIdx4];
67 | }
68 |
69 | switch (inLen % 3) {
70 | case 1:
71 | /* 1 extra input char -> 2 output chars and 2 padding chars. */
72 |
73 | inChar1 = *toEncode++;
74 |
75 | outIdx1 = (inChar1 & 0xFC) >> 2;
76 | outIdx2 = (inChar1 & 0x03) << 4;
77 |
78 | encoded[chunkIdx * 4] = ENCODE_CHARS[outIdx1];
79 | encoded[chunkIdx * 4 + 1] = ENCODE_CHARS[outIdx2];
80 | encoded[chunkIdx * 4 + 2] = PAD_CHAR;
81 | encoded[chunkIdx * 4 + 3] = PAD_CHAR;
82 | chunkIdx++;
83 | break;
84 | case 2:
85 | /* 2 extra input chars -> 3 output chars and 1 padding char. */
86 |
87 | inChar1 = *toEncode++;
88 | inChar2 = *toEncode++;
89 | outIdx1 = (inChar1 & 0xFC) >> 2;
90 | outIdx2 = ((inChar1 & 0x03) << 4) + ((inChar2 & 0xF0) >> 4);
91 | outIdx3 = ((inChar2 & 0x0F) << 2);
92 | encoded[chunkIdx * 4] = ENCODE_CHARS[outIdx1];
93 | encoded[chunkIdx * 4 + 1] = ENCODE_CHARS[outIdx2];
94 | encoded[chunkIdx * 4 + 2] = ENCODE_CHARS[outIdx3];
95 | encoded[chunkIdx * 4 + 3] = PAD_CHAR;
96 | chunkIdx++;
97 | break;
98 | }
99 | /* Ensure null termination. */
100 | encoded[chunkIdx * 4] = 0;
101 |
102 | return encoded;
103 | }
104 |
105 | int digitCount(int i) {
106 | int digits;
107 | for (digits = 0; i != 0; digits++)
108 | i /= 10;
109 | return digits;
110 | }
111 |
112 | char* escapeQuotes(const char* unescaped) {
113 | int unescapedLen = strlen(unescaped);
114 |
115 | /* Count quotes so that the amount of memory to be allocated can be
116 | * determined */
117 | int quoteCount = 0;
118 | for (int i = 0; i < unescapedLen; i++) {
119 | if (unescaped[i] == '\"') {
120 | quoteCount++;
121 | }
122 | }
123 |
124 | /* Copy ever character over, including a backslash before every quote. */
125 | char* escaped = new char[unescapedLen + quoteCount + 1]();
126 | int escapedWritten = 0;
127 | for (int i = 0; i < unescapedLen; i++) {
128 | if (unescaped[i] == '\"') {
129 | escaped[escapedWritten] = '\\';
130 | escapedWritten++;
131 | }
132 | escaped[escapedWritten] = unescaped[i];
133 | escapedWritten++;
134 | }
135 | return escaped;
136 | }
137 |
138 | bool findJsonStartEnd(const char* str, int* start, int* end) {
139 | /* Ignore everything before the first unquoted bracket and after the
140 | * unquoted bracket matching the first unquoted bracket, eg. headers and
141 | * newlines. */
142 | int strLen = strlen(str);
143 | /* Incrememented for every unquoted '{' and decremented for every
144 | * unquoted '}' */
145 | int braceBalance = 0;
146 | /* -1 is invalid start and end indices. */
147 | int s = -1;
148 | int e = -1;
149 | bool inQuotes = false;
150 | for (int i = 0; i < strLen; i++) {
151 | /* Toggle inQuotes. */
152 | if (str[i] == '\"') {
153 | inQuotes = !inQuotes;
154 | }
155 | /* Only consider brackets outside of quotes. */
156 | if (!inQuotes) {
157 | if (str[i] == '{') {
158 | if (s == -1) {
159 | s = i;
160 | }
161 | braceBalance++;
162 | } else if (str[i] == '}') {
163 | braceBalance--;
164 | if (braceBalance == 0) {
165 | e = i;
166 | break;
167 | }
168 | }
169 | }
170 | }
171 | *start = s;
172 | *end = e;
173 | /* If not a full json string no success. */
174 | if ((s == -1) || (e == -1)) {
175 | return false;
176 | }
177 | return true;
178 | }
179 |
180 | int findHttpStatusCode(const char* str) {
181 | /* If the input is null OR the input is not long enough to contain the
182 | * error code OR the first characters of the input are not
183 | * HTTP_STATUS_CODE_PREFIX, return 0; */
184 | if (str == NULL
185 | || strlen(str)
186 | < strlen(HTTP_STATUS_CODE_PREFIX) + HTTP_STATUS_CODE_LEN
187 | || strncmp(HTTP_STATUS_CODE_PREFIX, str,
188 | strlen(HTTP_STATUS_CODE_PREFIX))) {
189 | return 0;
190 | }
191 | /* copy the error code string and convert it to an int. */
192 | char errorCodeStr[HTTP_STATUS_CODE_LEN + 1];
193 | strncpy(errorCodeStr, str + strlen(HTTP_STATUS_CODE_PREFIX),
194 | HTTP_STATUS_CODE_LEN);
195 | return atoi(errorCodeStr);
196 | }
197 |
198 | int jsonArraySize(const char* jsonArrayStr, int jsonArrayStrLen) {
199 | int elementCount = 0;
200 | bool inQuotes = false;
201 | if (jsonArrayStr[0] != '[' || jsonArrayStr[jsonArrayStrLen - 1] != ']') {
202 | /* Invalid syntax. */
203 | return -1;
204 | }
205 | for (int i = 1; i < jsonArrayStrLen - 1; i++) {
206 | if (jsonArrayStr[i] == '"' && jsonArrayStr[i - 1] != '\\') {
207 | if (inQuotes) {
208 | elementCount++;
209 | }
210 | inQuotes = !inQuotes;
211 | }
212 | }
213 | return elementCount;
214 | }
215 |
216 | char** jsonArrayToStringArray(int numOfElements, const char* jsonArrayStr,
217 | int jsonArrayStrLen) {
218 | char** strArray = new char*[numOfElements]();
219 | int start = -1;
220 | int elementCount = 0;
221 | bool inQuotes = false;
222 | if (jsonArrayStr[0] != '[' || jsonArrayStr[jsonArrayStrLen - 1] != ']') {
223 | /* Invalid syntax. */
224 | return 0;
225 | }
226 | for (int i = 1; i < jsonArrayStrLen - 1; i++) {
227 | if (jsonArrayStr[i] == '"' && jsonArrayStr[i - 1] != '\\') {
228 | if (inQuotes) {
229 | /* Delete values and return null if we find more elements than
230 | * expected. */
231 | if (elementCount == numOfElements) {
232 | for (int j = 0; j < numOfElements; j++) {
233 | delete[] strArray[j];
234 | }
235 | delete[] strArray;
236 | return 0;
237 | }
238 |
239 | char* str = new char[(i - start) + 1]();
240 | strncpy(str, jsonArrayStr + start, i - start);
241 | strArray[elementCount] = str;
242 | elementCount++;
243 | } else {
244 | start = i + 1;
245 | }
246 | inQuotes = !inQuotes;
247 | }
248 | }
249 | return strArray;
250 | }
251 |
252 | bool isKey(const char * json, int thisEnd, int nextStart) {
253 | /* Check the characters in between the two tokens. */
254 | for (int i = thisEnd; i < nextStart; i++) {
255 | if (json[i] == ':') {
256 | /* A ':' means the token on the left is a key. */
257 | return true;
258 | } else if (json[i] == ',') {
259 | /* A ',' means the token on the left is a value. */
260 | return false;
261 | }
262 | }
263 | return false;
264 | }
265 |
266 | bool isOuterKey(const char * json, int thisEnd, int nextStart) {
267 | /* Check if token is a key at all before checking if it is an inner key. */
268 | if (!isKey(json, thisEnd, nextStart)) {
269 | return false;
270 | }
271 | /* True when we are in a quoted section of a string. Ignore braces in a
272 | * quoted section. */
273 | bool inQuote = false;
274 | /* The number of opening braces encountered minus the number of closing
275 | * braces encountered. braceLevel greater than 1 means we are looking at
276 | * inner keys. */
277 | int braceLevel = 0;
278 | for (int i = 0; i < thisEnd; i++) {
279 | switch (json[i]) {
280 | case '"':
281 | /* Toggle inQuote. */
282 | inQuote = !inQuote;
283 | break;
284 | case '{':
285 | /* If not in quotes, increase braceLevel. */
286 | if (!inQuote) {
287 | braceLevel++;
288 | }
289 | break;
290 | case '}':
291 | /* If not in quotes, decrease braceLevel. */
292 | if (!inQuote) {
293 | braceLevel--;
294 | }
295 | break;
296 | }
297 | }
298 | /* if we are at brace level 1 upon reaching, the key is in the outermost
299 | * json object */
300 | return (braceLevel == 1);
301 |
302 | }
303 |
304 | char* jsmnGetVal(const char* key, const char* json, jsmntok_t* tokens,
305 | int tokenCount) {
306 | /* Look at all json tokens. */
307 | for (int i = 0; i < tokenCount - 1; i++) {
308 | /* Check if token is an outer key. */
309 | if (isOuterKey(json, tokens[i].end, tokens[i + 1].start)) {
310 | int currentKeyLen = tokens[i].end - tokens[i].start;
311 | int valueLen = tokens[i + 1].end - tokens[i + 1].start;
312 | /* Check if the key we are looking at is the key we are looking
313 | * for. */
314 | if (((int) strlen(key) == currentKeyLen)
315 | && (strncmp(json + tokens[i].start, key, currentKeyLen) == 0)) {
316 | /* Copy and return the value */
317 | char* value = new char[valueLen + 1]();
318 | strncpy(value, json + tokens[i + 1].start, valueLen);
319 | return value;
320 | }
321 | }
322 | }
323 | /* Key was not found. */
324 | return NULL;
325 | }
326 |
327 | char* getTimeFromInvalidSignatureMessage(const char* message) {
328 | int messageLen = strlen(message);
329 | /* Iterate through each character in the string. */
330 | for (int i = 0; i < messageLen; i++) {
331 | /* If an opening parenthesis is found, copy the following 15
332 | * characters, excluding the 9th character which is a 'T'.*/
333 | if (message[i] == '(') {
334 | char* time = new char[15]();
335 | sprintf(time, "%.8s%.6s", message + i + 1, message + i + 10);
336 | return time;
337 | }
338 | }
339 | return 0;
340 | }
341 |
342 | char* hmacSha256(const char* key, int keyLen, const char* message,
343 | int messageLen) {
344 | SHA256* sha256 = new SHA256();
345 | /* The corrected key should be BLOCK_SIZE long. */
346 | char* correctedKey = new char[BLOCK_SIZE + 1]();
347 | /* If the key is greater than BLOCK_SIZE long, copy over its sha256 hash of
348 | * SHA256_DEC_HASH_LEN, leaving 0-padding to fill the entire BLOCK_SIZE. */
349 | if ((int) keyLen > BLOCK_SIZE) {
350 | sha256->reset();
351 | sha256->add(key, keyLen);
352 | char* hashedKey = sha256->getHashDec();
353 | memcpy(correctedKey, hashedKey, SHA256_DEC_HASH_LEN);
354 | delete[] hashedKey;
355 | }
356 | /* if the key is less than BLOCK_SIZE long, simply copy it over, leaving
357 | * 0-padding to fill the entire BLOCK_SIZE. */
358 | else {
359 | memcpy(correctedKey, key, keyLen);
360 | }
361 |
362 | /* Using an exclusive or with these OPAD and IPAD values to create the
363 | * iPadded and oPadded values specified by the HMAC algorithm. */
364 | char* oPadded = new char[BLOCK_SIZE + 1]();
365 | char* iPadded = new char[BLOCK_SIZE + 1]();
366 | for (int i = 0; i < BLOCK_SIZE; i++) {
367 | oPadded[i] = correctedKey[i] ^ OPAD;
368 | iPadded[i] = correctedKey[i] ^ IPAD;
369 | }
370 |
371 | delete[] correctedKey;
372 |
373 | /* Create the inner hash with the concatenation of iPadded and message. */
374 | sha256->reset();
375 | sha256->add(iPadded, BLOCK_SIZE);
376 | delete[] iPadded;
377 | sha256->add(message, messageLen);
378 | char* innerHash = sha256->getHashDec();
379 |
380 | /* Create the outer hash with the concatenation of oPadded and
381 | * innerhash. */
382 | sha256->reset();
383 | sha256->add(oPadded, BLOCK_SIZE);
384 | delete[] oPadded;
385 | sha256->add(innerHash, SHA256_DEC_HASH_LEN);
386 | delete[] innerHash;
387 | char* final = sha256->getHashDec();
388 | delete sha256;
389 | return final;
390 | }
391 |
392 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/Utils.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Utils.h
3 | *
4 | * Utility functions for the Arduino AWS SDK.
5 | *
6 | * Created on: Jun 30, 2014
7 | * Author: hoffmaj
8 | */
9 |
10 | #ifndef UTILS_H_
11 | #define UTILS_H_
12 |
13 | #pragma once
14 |
15 | #include
16 | #include "jsmn.h"
17 |
18 | extern const int SHA256_DEC_HASH_LEN;
19 |
20 | /* Base encode 64 an array of characters. Returned array must be deleted by
21 | * caller. */
22 | char *base64Encode(const char *inputBuffer);
23 |
24 | /* Determine the number of digits in the base 10 representation a given
25 | * number. */
26 | int digitCount(int i);
27 |
28 | /* Create a string identical to the given string except with backslashes before
29 | * quotes. Caller must delete the returned string. */
30 | char* escapeQuotes(const char* unescaped);
31 |
32 | /* Determines the index of the opening and closing of a json string that is
33 | * surrounded by non-json, eg. http headers and newlines. Returns true if json
34 | * was found, false otherwise. */
35 | bool findJsonStartEnd(const char* str, int* start, int* end);
36 |
37 | /* Find and return the status code of an http response. */
38 | int findHttpStatusCode(const char* str);
39 |
40 | /* Given a char* of json array syntax ( e.g. ["a", "b", "c"]), count the number
41 | * of elements. */
42 | int jsonArraySize(const char* jsonArrayStr, int jsonArrayStrLen);
43 |
44 | /* Given a char* of json array syntax ( e.g. ["a", "b", "c"]) and the number of
45 | * elements, create a matching array of char*'s. Caller must delete the created
46 | * array AND each element. */
47 | char** jsonArrayToStringArray(int numOfElements, const char* jsonArrayStr,
48 | int jsonArrayStrLen);
49 |
50 | /* Determines whether a token is a json key, given the json string, the token's
51 | * end index, and the next token's start index. This includes keys of inner
52 | * json objects, i.e. both 'a' and 'b' would be a key in '{"a":{"b":1}}'. */
53 | bool isKey(const char * json, int thisEnd, int nextStart);
54 |
55 | /* Determines whether a token is a json key, given the json string, the token's
56 | * end index, and the next token's start index. This does not include keys of
57 | * inner json objects, i.e. 'a' would be a key in '{"a":{"b":1}}', but 'b'
58 | * would not. */
59 | bool isOuterKey(const char * json, int thisEnd, int nextStart);
60 |
61 | /* Given a json key, get a corresponding key. Takes the key, the json object
62 | * string, and the jsmn tokens. Returns 0 if key does not exist. If key does
63 | * exist, user must free the memory allocated to store the value. */
64 | char* jsmnGetVal(const char* key, const char* json, jsmntok_t* tokens,
65 | int tokenCount);
66 |
67 | /* Very minimal implementation for finding the current time from the message
68 | * returned by a signature failure. This works with at least Kinesis and
69 | * DynamoDB, in which the time is located within the 15 characters following
70 | * the first opening parenthesis. (e.g. "...(20140721T184435Z ..." )*/
71 | char* getTimeFromInvalidSignatureMessage(const char* message);
72 |
73 | /* Apply hmac to the key and message. */
74 | char* hmacSha256(const char* key, int keyLen, const char* message,
75 | int messageLen);
76 |
77 | #endif /* UTILS_H_ */
78 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/jsmn.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2010 Serge A. Zaitsev
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in
12 | * all copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | * THE SOFTWARE.
21 | */
22 |
23 | #include
24 |
25 | #include "jsmn.h"
26 |
27 | /**
28 | * Allocates a fresh unused token from the token pull.
29 | */
30 | static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens,
31 | size_t num_tokens) {
32 | jsmntok_t *tok;
33 | if (parser->toknext >= num_tokens) {
34 | return NULL;
35 | }
36 | tok = &tokens[parser->toknext++];
37 | tok->start = tok->end = -1;
38 | tok->size = 0;
39 | #ifdef JSMN_PARENT_LINKS
40 | tok->parent = -1;
41 | #endif
42 | return tok;
43 | }
44 |
45 | /**
46 | * Fills token type and boundaries.
47 | */
48 | static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, int start,
49 | int end) {
50 | token->type = type;
51 | token->start = start;
52 | token->end = end;
53 | token->size = 0;
54 | }
55 |
56 | /**
57 | * Fills next available token with JSON primitive.
58 | */
59 | static jsmnerr_t jsmn_parse_primitive(jsmn_parser *parser, const char *js,
60 | size_t len, jsmntok_t *tokens, size_t num_tokens) {
61 | jsmntok_t *token;
62 | int start;
63 |
64 | start = parser->pos;
65 |
66 | for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
67 | switch (js[parser->pos]) {
68 | #ifndef JSMN_STRICT
69 | /* In strict mode primitive must be followed by "," or "}" or "]" */
70 | case ':':
71 | #endif
72 | case '\t':
73 | case '\r':
74 | case '\n':
75 | case ' ':
76 | case ',':
77 | case ']':
78 | case '}':
79 | goto found;
80 | }
81 | if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
82 | parser->pos = start;
83 | return JSMN_ERROR_INVAL;
84 | }
85 | }
86 | #ifdef JSMN_STRICT
87 | /* In strict mode primitive must be followed by a comma/object/array */
88 | parser->pos = start;
89 | return JSMN_ERROR_PART;
90 | #endif
91 |
92 | found: if (tokens == NULL) {
93 | parser->pos--;
94 | return (jsmnerr_t) 0;
95 | }
96 | token = jsmn_alloc_token(parser, tokens, num_tokens);
97 | if (token == NULL) {
98 | parser->pos = start;
99 | return JSMN_ERROR_NOMEM;
100 | }
101 | jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
102 | #ifdef JSMN_PARENT_LINKS
103 | token->parent = parser->toksuper;
104 | #endif
105 | parser->pos--;
106 | return (jsmnerr_t) 0;
107 | }
108 |
109 | /**
110 | * Filsl next token with JSON string.
111 | */
112 | static jsmnerr_t jsmn_parse_string(jsmn_parser *parser, const char *js,
113 | size_t len, jsmntok_t *tokens, size_t num_tokens) {
114 | jsmntok_t *token;
115 |
116 | int start = parser->pos;
117 |
118 | parser->pos++;
119 |
120 | /* Skip starting quote */
121 | for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
122 | char c = js[parser->pos];
123 |
124 | /* Quote: end of string */
125 | if (c == '\"') {
126 | if (tokens == NULL) {
127 | return (jsmnerr_t) 0;
128 | }
129 | token = jsmn_alloc_token(parser, tokens, num_tokens);
130 | if (token == NULL) {
131 | parser->pos = start;
132 | return JSMN_ERROR_NOMEM;
133 | }
134 | jsmn_fill_token(token, JSMN_STRING, start + 1, parser->pos);
135 | #ifdef JSMN_PARENT_LINKS
136 | token->parent = parser->toksuper;
137 | #endif
138 | return (jsmnerr_t) 0;
139 | }
140 |
141 | /* Backslash: Quoted symbol expected */
142 | if (c == '\\') {
143 | parser->pos++;
144 | switch (js[parser->pos]) {
145 | /* Allowed escaped symbols */
146 | case '\"':
147 | case '/':
148 | case '\\':
149 | case 'b':
150 | case 'f':
151 | case 'r':
152 | case 'n':
153 | case 't':
154 | break;
155 | /* Allows escaped symbol \uXXXX */
156 | case 'u':
157 | parser->pos++;
158 | int i;
159 | for (i = 0; i < 4 && js[parser->pos] != '\0'; i++) {
160 | /* If it isn't a hex character we have an error */
161 | if (!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
162 | (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
163 | (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
164 | parser->pos = start;
165 | return JSMN_ERROR_INVAL;
166 | }
167 | parser->pos++;
168 | }
169 | parser->pos--;
170 | break;
171 | /* Unexpected symbol */
172 | default:
173 | parser->pos = start;
174 | return JSMN_ERROR_INVAL;
175 | }
176 | }
177 | }
178 | parser->pos = start;
179 | return JSMN_ERROR_PART;
180 | }
181 |
182 | /**
183 | * Parse JSON string and fill tokens.
184 | */
185 | jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
186 | jsmntok_t *tokens, unsigned int num_tokens) {
187 | jsmnerr_t r;
188 | int i;
189 | jsmntok_t *token;
190 | int count = 0;
191 |
192 | for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
193 | char c;
194 | jsmntype_t type;
195 |
196 | c = js[parser->pos];
197 | switch (c) {
198 | case '{':
199 | case '[':
200 | count++;
201 | if (tokens == NULL) {
202 | break;
203 | }
204 | token = jsmn_alloc_token(parser, tokens, num_tokens);
205 | if (token == NULL)
206 | return JSMN_ERROR_NOMEM;
207 | if (parser->toksuper != -1) {
208 | tokens[parser->toksuper].size++;
209 | #ifdef JSMN_PARENT_LINKS
210 | token->parent = parser->toksuper;
211 | #endif
212 | }
213 | token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
214 | token->start = parser->pos;
215 | parser->toksuper = parser->toknext - 1;
216 | break;
217 | case '}':
218 | case ']':
219 | if (tokens == NULL)
220 | break;
221 | type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
222 | #ifdef JSMN_PARENT_LINKS
223 | if (parser->toknext < 1) {
224 | return JSMN_ERROR_INVAL;
225 | }
226 | token = &tokens[parser->toknext - 1];
227 | for (;;) {
228 | if (token->start != -1 && token->end == -1) {
229 | if (token->type != type) {
230 | return JSMN_ERROR_INVAL;
231 | }
232 | token->end = parser->pos + 1;
233 | parser->toksuper = token->parent;
234 | break;
235 | }
236 | if (token->parent == -1) {
237 | break;
238 | }
239 | token = &tokens[token->parent];
240 | }
241 | #else
242 | for (i = parser->toknext - 1; i >= 0; i--) {
243 | token = &tokens[i];
244 | if (token->start != -1 && token->end == -1) {
245 | if (token->type != type) {
246 | return JSMN_ERROR_INVAL;
247 | }
248 | parser->toksuper = -1;
249 | token->end = parser->pos + 1;
250 | break;
251 | }
252 | }
253 | /* Error if unmatched closing bracket */
254 | if (i == -1)
255 | return JSMN_ERROR_INVAL;
256 | for (; i >= 0; i--) {
257 | token = &tokens[i];
258 | if (token->start != -1 && token->end == -1) {
259 | parser->toksuper = i;
260 | break;
261 | }
262 | }
263 | #endif
264 | break;
265 | case '\"':
266 | r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
267 | if (r < 0)
268 | return r;
269 | count++;
270 | if (parser->toksuper != -1 && tokens != NULL)
271 | tokens[parser->toksuper].size++;
272 | break;
273 | case '\t':
274 | case '\r':
275 | case '\n':
276 | case ':':
277 | case ',':
278 | case ' ':
279 | break;
280 | #ifdef JSMN_STRICT
281 | /* In strict mode primitives are: numbers and booleans */
282 | case '-':
283 | case '0':
284 | case '1':
285 | case '2':
286 | case '3':
287 | case '4':
288 | case '5':
289 | case '6':
290 | case '7':
291 | case '8':
292 | case '9':
293 | case 't':
294 | case 'f':
295 | case 'n':
296 | #else
297 | /* In non-strict mode every unquoted value is a primitive */
298 | default:
299 | #endif
300 | r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
301 | if (r < 0)
302 | return r;
303 | count++;
304 | if (parser->toksuper != -1 && tokens != NULL)
305 | tokens[parser->toksuper].size++;
306 | break;
307 |
308 | #ifdef JSMN_STRICT
309 | /* Unexpected char in strict mode */
310 | default:
311 | return JSMN_ERROR_INVAL;
312 | #endif
313 | }
314 | }
315 |
316 | for (i = parser->toknext - 1; i >= 0; i--) {
317 | /* Unmatched opened object or array */
318 | if (tokens[i].start != -1 && tokens[i].end == -1) {
319 | return JSMN_ERROR_PART;
320 | }
321 | }
322 |
323 | return (jsmnerr_t) count;
324 | }
325 |
326 | /**
327 | * Creates a new parser based over a given buffer with an array of tokens
328 | * available.
329 | */
330 | void jsmn_init(jsmn_parser *parser) {
331 | parser->pos = 0;
332 | parser->toknext = 0;
333 | parser->toksuper = -1;
334 | }
335 |
336 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/jsmn.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2010 Serge A. Zaitsev
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in
12 | * all copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | * THE SOFTWARE.
21 | */
22 |
23 | #ifndef __JSMN_H_
24 | #define __JSMN_H_
25 | #include
26 | #define JSMN_STRICT
27 | #ifdef __cplusplus
28 | extern "C" {
29 | #endif
30 |
31 | /**
32 | * JSON type identifier. Basic types are:
33 | * o Object
34 | * o Array
35 | * o String
36 | * o Other primitive: number, boolean (true/false) or null
37 | */
38 | typedef enum {
39 | JSMN_PRIMITIVE = 0, JSMN_OBJECT = 1, JSMN_ARRAY = 2, JSMN_STRING = 3
40 | } jsmntype_t;
41 |
42 | typedef enum {
43 | /* Not enough tokens were provided */
44 | JSMN_ERROR_NOMEM = -1,
45 | /* Invalid character inside JSON string */
46 | JSMN_ERROR_INVAL = -2,
47 | /* The string is not a full JSON packet, more bytes expected */
48 | JSMN_ERROR_PART = -3,
49 | } jsmnerr_t;
50 |
51 | /**
52 | * JSON token description.
53 | * @param type type (object, array, string etc.)
54 | * @param start start position in JSON data string
55 | * @param end end position in JSON data string
56 | */
57 | typedef struct {
58 | jsmntype_t type;
59 | int start;
60 | int end;
61 | int size;
62 | #ifdef JSMN_PARENT_LINKS
63 | int parent;
64 | #endif
65 | } jsmntok_t;
66 |
67 | /**
68 | * JSON parser. Contains an array of token blocks available. Also stores
69 | * the string being parsed now and current position in that string
70 | */
71 | typedef struct {
72 | unsigned int pos; /* offset in the JSON string */
73 | unsigned int toknext; /* next token to allocate */
74 | int toksuper; /* superior token node, e.g parent object or array */
75 | } jsmn_parser;
76 |
77 | /**
78 | * Create JSON parser over an array of tokens
79 | */
80 | void jsmn_init(jsmn_parser *parser);
81 |
82 | /**
83 | * Run JSON parser. It parses a JSON data string into and array of tokens, each describing
84 | * a single JSON object.
85 | */
86 | jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
87 | jsmntok_t *tokens, unsigned int num_tokens);
88 |
89 | #ifdef __cplusplus
90 | }
91 | #endif
92 |
93 | #endif /* __JSMN_H_ */
94 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/sha256.cpp:
--------------------------------------------------------------------------------
1 | // //////////////////////////////////////////////////////////
2 | // sha256.cpp
3 | // Copyright (c) 2014 Stephan Brumme. All rights reserved.
4 | // see http://create.stephan-brumme.com/disclaimer.html
5 | //
6 |
7 | #include "sha256.h"
8 |
9 | /* These lines have been discarded from the original source code. endian.h is
10 | * not necessarilly included on the devices that will use this SDK. Little
11 | * Endian is assumed instead. */
12 | // // big endian architectures need #define __BYTE_ORDER __BIG_ENDIAN
13 | // #ifndef _MSC_VER
14 | // #include
15 | // #endif
16 | /// same as reset()
17 | SHA256::SHA256() {
18 | reset();
19 | }
20 |
21 | /// restart
22 | void SHA256::reset() {
23 | m_numBytes = 0;
24 | m_bufferSize = 0;
25 |
26 | // according to RFC 1321
27 | m_hash[0] = 0x6a09e667;
28 | m_hash[1] = 0xbb67ae85;
29 | m_hash[2] = 0x3c6ef372;
30 | m_hash[3] = 0xa54ff53a;
31 | m_hash[4] = 0x510e527f;
32 | m_hash[5] = 0x9b05688c;
33 | m_hash[6] = 0x1f83d9ab;
34 | m_hash[7] = 0x5be0cd19;
35 | }
36 |
37 | namespace {
38 | inline uint32_t rotate(uint32_t a, uint32_t c) {
39 | return (a >> c) | (a << (32 - c));
40 | }
41 |
42 | inline uint32_t swap(uint32_t x) {
43 | #if defined(__GNUC__) || defined(__clang__)
44 | return __builtin_bswap32(x);
45 | #endif
46 | #ifdef MSC_VER
47 | return _byteswap_ulong(x);
48 | #endif
49 |
50 | return (x >> 24) | ((x >> 8) & 0x0000FF00) | ((x << 8) & 0x00FF0000)
51 | | (x << 24);
52 | }
53 |
54 | // mix functions for processBlock()
55 | inline uint32_t f1(uint32_t e, uint32_t f, uint32_t g) {
56 | uint32_t term1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25);
57 | uint32_t term2 = (e & f) ^ (~e & g); //(g ^ (e & (f ^ g)))
58 | return term1 + term2;
59 | }
60 |
61 | inline uint32_t f2(uint32_t a, uint32_t b, uint32_t c) {
62 | uint32_t term1 = rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22);
63 | uint32_t term2 = ((a | b) & c) | (a & b); //(a & (b ^ c)) ^ (b & c);
64 | return term1 + term2;
65 | }
66 | }
67 |
68 | /// process 64 bytes
69 | void SHA256::processBlock(const void* data) {
70 | // get last hash
71 | uint32_t a = m_hash[0];
72 | uint32_t b = m_hash[1];
73 | uint32_t c = m_hash[2];
74 | uint32_t d = m_hash[3];
75 | uint32_t e = m_hash[4];
76 | uint32_t f = m_hash[5];
77 | uint32_t g = m_hash[6];
78 | uint32_t h = m_hash[7];
79 |
80 | // data represented as 16x 32-bit words
81 | const uint32_t* input = (uint32_t*) data;
82 | // convert to big endian
83 | uint32_t words[64];
84 | int i;
85 | for (i = 0; i < 16; i++)
86 | #if defined(__BYTE_ORDER) && (__BYTE_ORDER != 0) && (__BYTE_ORDER == __BIG_ENDIAN)
87 | words[i] = input[i];
88 | #else
89 | words[i] = swap(input[i]);
90 | #endif
91 |
92 | uint32_t x, y; // temporaries
93 |
94 | // first round
95 | x = h + f1(e, f, g) + 0x428a2f98 + words[0];
96 | y = f2(a, b, c);
97 | d += x;
98 | h = x + y;
99 | x = g + f1(d, e, f) + 0x71374491 + words[1];
100 | y = f2(h, a, b);
101 | c += x;
102 | g = x + y;
103 | x = f + f1(c, d, e) + 0xb5c0fbcf + words[2];
104 | y = f2(g, h, a);
105 | b += x;
106 | f = x + y;
107 | x = e + f1(b, c, d) + 0xe9b5dba5 + words[3];
108 | y = f2(f, g, h);
109 | a += x;
110 | e = x + y;
111 | x = d + f1(a, b, c) + 0x3956c25b + words[4];
112 | y = f2(e, f, g);
113 | h += x;
114 | d = x + y;
115 | x = c + f1(h, a, b) + 0x59f111f1 + words[5];
116 | y = f2(d, e, f);
117 | g += x;
118 | c = x + y;
119 | x = b + f1(g, h, a) + 0x923f82a4 + words[6];
120 | y = f2(c, d, e);
121 | f += x;
122 | b = x + y;
123 | x = a + f1(f, g, h) + 0xab1c5ed5 + words[7];
124 | y = f2(b, c, d);
125 | e += x;
126 | a = x + y;
127 |
128 | // secound round
129 | x = h + f1(e, f, g) + 0xd807aa98 + words[8];
130 | y = f2(a, b, c);
131 | d += x;
132 | h = x + y;
133 | x = g + f1(d, e, f) + 0x12835b01 + words[9];
134 | y = f2(h, a, b);
135 | c += x;
136 | g = x + y;
137 | x = f + f1(c, d, e) + 0x243185be + words[10];
138 | y = f2(g, h, a);
139 | b += x;
140 | f = x + y;
141 | x = e + f1(b, c, d) + 0x550c7dc3 + words[11];
142 | y = f2(f, g, h);
143 | a += x;
144 | e = x + y;
145 | x = d + f1(a, b, c) + 0x72be5d74 + words[12];
146 | y = f2(e, f, g);
147 | h += x;
148 | d = x + y;
149 | x = c + f1(h, a, b) + 0x80deb1fe + words[13];
150 | y = f2(d, e, f);
151 | g += x;
152 | c = x + y;
153 | x = b + f1(g, h, a) + 0x9bdc06a7 + words[14];
154 | y = f2(c, d, e);
155 | f += x;
156 | b = x + y;
157 | x = a + f1(f, g, h) + 0xc19bf174 + words[15];
158 | y = f2(b, c, d);
159 | e += x;
160 | a = x + y;
161 |
162 | // extend to 24 words
163 | for (; i < 24; i++)
164 | words[i] = words[i - 16]
165 | + (rotate(words[i - 15], 7) ^ rotate(words[i - 15], 18)
166 | ^ (words[i - 15] >> 3)) + words[i - 7]
167 | + (rotate(words[i - 2], 17) ^ rotate(words[i - 2], 19)
168 | ^ (words[i - 2] >> 10));
169 |
170 | // third round
171 | x = h + f1(e, f, g) + 0xe49b69c1 + words[16];
172 | y = f2(a, b, c);
173 | d += x;
174 | h = x + y;
175 | x = g + f1(d, e, f) + 0xefbe4786 + words[17];
176 | y = f2(h, a, b);
177 | c += x;
178 | g = x + y;
179 | x = f + f1(c, d, e) + 0x0fc19dc6 + words[18];
180 | y = f2(g, h, a);
181 | b += x;
182 | f = x + y;
183 | x = e + f1(b, c, d) + 0x240ca1cc + words[19];
184 | y = f2(f, g, h);
185 | a += x;
186 | e = x + y;
187 | x = d + f1(a, b, c) + 0x2de92c6f + words[20];
188 | y = f2(e, f, g);
189 | h += x;
190 | d = x + y;
191 | x = c + f1(h, a, b) + 0x4a7484aa + words[21];
192 | y = f2(d, e, f);
193 | g += x;
194 | c = x + y;
195 | x = b + f1(g, h, a) + 0x5cb0a9dc + words[22];
196 | y = f2(c, d, e);
197 | f += x;
198 | b = x + y;
199 | x = a + f1(f, g, h) + 0x76f988da + words[23];
200 | y = f2(b, c, d);
201 | e += x;
202 | a = x + y;
203 |
204 | // extend to 32 words
205 | for (; i < 32; i++)
206 | words[i] = words[i - 16]
207 | + (rotate(words[i - 15], 7) ^ rotate(words[i - 15], 18)
208 | ^ (words[i - 15] >> 3)) + words[i - 7]
209 | + (rotate(words[i - 2], 17) ^ rotate(words[i - 2], 19)
210 | ^ (words[i - 2] >> 10));
211 |
212 | // fourth round
213 | x = h + f1(e, f, g) + 0x983e5152 + words[24];
214 | y = f2(a, b, c);
215 | d += x;
216 | h = x + y;
217 | x = g + f1(d, e, f) + 0xa831c66d + words[25];
218 | y = f2(h, a, b);
219 | c += x;
220 | g = x + y;
221 | x = f + f1(c, d, e) + 0xb00327c8 + words[26];
222 | y = f2(g, h, a);
223 | b += x;
224 | f = x + y;
225 | x = e + f1(b, c, d) + 0xbf597fc7 + words[27];
226 | y = f2(f, g, h);
227 | a += x;
228 | e = x + y;
229 | x = d + f1(a, b, c) + 0xc6e00bf3 + words[28];
230 | y = f2(e, f, g);
231 | h += x;
232 | d = x + y;
233 | x = c + f1(h, a, b) + 0xd5a79147 + words[29];
234 | y = f2(d, e, f);
235 | g += x;
236 | c = x + y;
237 | x = b + f1(g, h, a) + 0x06ca6351 + words[30];
238 | y = f2(c, d, e);
239 | f += x;
240 | b = x + y;
241 | x = a + f1(f, g, h) + 0x14292967 + words[31];
242 | y = f2(b, c, d);
243 | e += x;
244 | a = x + y;
245 |
246 | // extend to 40 words
247 | for (; i < 40; i++)
248 | words[i] = words[i - 16]
249 | + (rotate(words[i - 15], 7) ^ rotate(words[i - 15], 18)
250 | ^ (words[i - 15] >> 3)) + words[i - 7]
251 | + (rotate(words[i - 2], 17) ^ rotate(words[i - 2], 19)
252 | ^ (words[i - 2] >> 10));
253 |
254 | // fifth round
255 | x = h + f1(e, f, g) + 0x27b70a85 + words[32];
256 | y = f2(a, b, c);
257 | d += x;
258 | h = x + y;
259 | x = g + f1(d, e, f) + 0x2e1b2138 + words[33];
260 | y = f2(h, a, b);
261 | c += x;
262 | g = x + y;
263 | x = f + f1(c, d, e) + 0x4d2c6dfc + words[34];
264 | y = f2(g, h, a);
265 | b += x;
266 | f = x + y;
267 | x = e + f1(b, c, d) + 0x53380d13 + words[35];
268 | y = f2(f, g, h);
269 | a += x;
270 | e = x + y;
271 | x = d + f1(a, b, c) + 0x650a7354 + words[36];
272 | y = f2(e, f, g);
273 | h += x;
274 | d = x + y;
275 | x = c + f1(h, a, b) + 0x766a0abb + words[37];
276 | y = f2(d, e, f);
277 | g += x;
278 | c = x + y;
279 | x = b + f1(g, h, a) + 0x81c2c92e + words[38];
280 | y = f2(c, d, e);
281 | f += x;
282 | b = x + y;
283 | x = a + f1(f, g, h) + 0x92722c85 + words[39];
284 | y = f2(b, c, d);
285 | e += x;
286 | a = x + y;
287 |
288 | // extend to 48 words
289 | for (; i < 48; i++)
290 | words[i] = words[i - 16]
291 | + (rotate(words[i - 15], 7) ^ rotate(words[i - 15], 18)
292 | ^ (words[i - 15] >> 3)) + words[i - 7]
293 | + (rotate(words[i - 2], 17) ^ rotate(words[i - 2], 19)
294 | ^ (words[i - 2] >> 10));
295 |
296 | // sixth round
297 | x = h + f1(e, f, g) + 0xa2bfe8a1 + words[40];
298 | y = f2(a, b, c);
299 | d += x;
300 | h = x + y;
301 | x = g + f1(d, e, f) + 0xa81a664b + words[41];
302 | y = f2(h, a, b);
303 | c += x;
304 | g = x + y;
305 | x = f + f1(c, d, e) + 0xc24b8b70 + words[42];
306 | y = f2(g, h, a);
307 | b += x;
308 | f = x + y;
309 | x = e + f1(b, c, d) + 0xc76c51a3 + words[43];
310 | y = f2(f, g, h);
311 | a += x;
312 | e = x + y;
313 | x = d + f1(a, b, c) + 0xd192e819 + words[44];
314 | y = f2(e, f, g);
315 | h += x;
316 | d = x + y;
317 | x = c + f1(h, a, b) + 0xd6990624 + words[45];
318 | y = f2(d, e, f);
319 | g += x;
320 | c = x + y;
321 | x = b + f1(g, h, a) + 0xf40e3585 + words[46];
322 | y = f2(c, d, e);
323 | f += x;
324 | b = x + y;
325 | x = a + f1(f, g, h) + 0x106aa070 + words[47];
326 | y = f2(b, c, d);
327 | e += x;
328 | a = x + y;
329 |
330 | // extend to 56 words
331 | for (; i < 56; i++)
332 | words[i] = words[i - 16]
333 | + (rotate(words[i - 15], 7) ^ rotate(words[i - 15], 18)
334 | ^ (words[i - 15] >> 3)) + words[i - 7]
335 | + (rotate(words[i - 2], 17) ^ rotate(words[i - 2], 19)
336 | ^ (words[i - 2] >> 10));
337 |
338 | // seventh round
339 | x = h + f1(e, f, g) + 0x19a4c116 + words[48];
340 | y = f2(a, b, c);
341 | d += x;
342 | h = x + y;
343 | x = g + f1(d, e, f) + 0x1e376c08 + words[49];
344 | y = f2(h, a, b);
345 | c += x;
346 | g = x + y;
347 | x = f + f1(c, d, e) + 0x2748774c + words[50];
348 | y = f2(g, h, a);
349 | b += x;
350 | f = x + y;
351 | x = e + f1(b, c, d) + 0x34b0bcb5 + words[51];
352 | y = f2(f, g, h);
353 | a += x;
354 | e = x + y;
355 | x = d + f1(a, b, c) + 0x391c0cb3 + words[52];
356 | y = f2(e, f, g);
357 | h += x;
358 | d = x + y;
359 | x = c + f1(h, a, b) + 0x4ed8aa4a + words[53];
360 | y = f2(d, e, f);
361 | g += x;
362 | c = x + y;
363 | x = b + f1(g, h, a) + 0x5b9cca4f + words[54];
364 | y = f2(c, d, e);
365 | f += x;
366 | b = x + y;
367 | x = a + f1(f, g, h) + 0x682e6ff3 + words[55];
368 | y = f2(b, c, d);
369 | e += x;
370 | a = x + y;
371 |
372 | // extend to 64 words
373 | for (; i < 64; i++)
374 | words[i] = words[i - 16]
375 | + (rotate(words[i - 15], 7) ^ rotate(words[i - 15], 18)
376 | ^ (words[i - 15] >> 3)) + words[i - 7]
377 | + (rotate(words[i - 2], 17) ^ rotate(words[i - 2], 19)
378 | ^ (words[i - 2] >> 10));
379 |
380 | // eigth round
381 | x = h + f1(e, f, g) + 0x748f82ee + words[56];
382 | y = f2(a, b, c);
383 | d += x;
384 | h = x + y;
385 | x = g + f1(d, e, f) + 0x78a5636f + words[57];
386 | y = f2(h, a, b);
387 | c += x;
388 | g = x + y;
389 | x = f + f1(c, d, e) + 0x84c87814 + words[58];
390 | y = f2(g, h, a);
391 | b += x;
392 | f = x + y;
393 | x = e + f1(b, c, d) + 0x8cc70208 + words[59];
394 | y = f2(f, g, h);
395 | a += x;
396 | e = x + y;
397 | x = d + f1(a, b, c) + 0x90befffa + words[60];
398 | y = f2(e, f, g);
399 | h += x;
400 | d = x + y;
401 | x = c + f1(h, a, b) + 0xa4506ceb + words[61];
402 | y = f2(d, e, f);
403 | g += x;
404 | c = x + y;
405 | x = b + f1(g, h, a) + 0xbef9a3f7 + words[62];
406 | y = f2(c, d, e);
407 | f += x;
408 | b = x + y;
409 | x = a + f1(f, g, h) + 0xc67178f2 + words[63];
410 | y = f2(b, c, d);
411 | e += x;
412 | a = x + y;
413 |
414 | // update hash
415 | m_hash[0] += a;
416 | m_hash[1] += b;
417 | m_hash[2] += c;
418 | m_hash[3] += d;
419 | m_hash[4] += e;
420 | m_hash[5] += f;
421 | m_hash[6] += g;
422 | m_hash[7] += h;
423 | }
424 |
425 | /// add arbitrary number of bytes
426 | void SHA256::add(const void* data, size_t numBytes) {
427 | const uint8_t* current = (const uint8_t*) data;
428 |
429 | if (m_bufferSize > 0) {
430 | while (numBytes > 0 && m_bufferSize < BlockSize) {
431 | m_buffer[m_bufferSize++] = *current++;
432 | numBytes--;
433 | }
434 | }
435 |
436 | // full buffer
437 | if (m_bufferSize == BlockSize) {
438 | processBlock(m_buffer);
439 | m_numBytes += BlockSize;
440 | m_bufferSize = 0;
441 | }
442 |
443 | // no more data ?
444 | if (numBytes == 0)
445 | return;
446 |
447 | // process full blocks
448 | while (numBytes >= BlockSize) {
449 | processBlock(current);
450 | current += BlockSize;
451 | m_numBytes += BlockSize;
452 | numBytes -= BlockSize;
453 | }
454 |
455 | // keep remaining bytes in buffer
456 | while (numBytes > 0) {
457 | m_buffer[m_bufferSize++] = *current++;
458 | numBytes--;
459 | }
460 | }
461 |
462 | /// process final block, less than 64 bytes
463 | void SHA256::processBuffer() {
464 | // the input bytes are considered as bits strings, where the first bit is the most significant bit of the byte
465 |
466 | // - append "1" bit to message
467 | // - append "0" bits until message length in bit mod 512 is 448
468 | // - append length as 64 bit integer
469 |
470 | // number of bits
471 | size_t paddedLength = m_bufferSize * 8;
472 |
473 | // plus one bit set to 1 (always appended)
474 | paddedLength++;
475 |
476 | // number of bits must be (numBits % 512) = 448
477 | size_t lower11Bits = paddedLength & 511;
478 | if (lower11Bits <= 448)
479 | paddedLength += 448 - lower11Bits;
480 | else
481 | paddedLength += 512 + 448 - lower11Bits;
482 | // convert from bits to bytes
483 | paddedLength /= 8;
484 |
485 | // only needed if additional data flows over into a second block
486 | unsigned char extra[BlockSize];
487 |
488 | // append a "1" bit, 128 => binary 10000000
489 | if (m_bufferSize < BlockSize)
490 | m_buffer[m_bufferSize] = 128;
491 | else
492 | extra[0] = 128;
493 |
494 | size_t i;
495 | for (i = m_bufferSize + 1; i < BlockSize; i++)
496 | m_buffer[i] = 0;
497 | for (; i < paddedLength; i++)
498 | extra[i - BlockSize] = 0;
499 |
500 | // add message length in bits as 64 bit number
501 | uint64_t msgBits = 8 * (m_numBytes + m_bufferSize);
502 | // find right position
503 | unsigned char* addLength;
504 | if (paddedLength < BlockSize)
505 | addLength = m_buffer + paddedLength;
506 | else
507 | addLength = extra + paddedLength - BlockSize;
508 |
509 | // must be big endian
510 | *addLength++ = (msgBits >> 56) & 0xFF;
511 | *addLength++ = (msgBits >> 48) & 0xFF;
512 | *addLength++ = (msgBits >> 40) & 0xFF;
513 | *addLength++ = (msgBits >> 32) & 0xFF;
514 | *addLength++ = (msgBits >> 24) & 0xFF;
515 | *addLength++ = (msgBits >> 16) & 0xFF;
516 | *addLength++ = (msgBits >> 8) & 0xFF;
517 | *addLength = msgBits & 0xFF;
518 |
519 | // process blocks
520 | processBlock(m_buffer);
521 | // flowed over into a second block ?
522 | if (paddedLength > BlockSize)
523 | processBlock(extra);
524 | }
525 |
526 | /// return latest hash as 16 hex characters
527 | /* Modified from original source code. Using char* instead of string. */
528 | char* SHA256::getHash() {
529 | // convert hash to string
530 | static const char dec2hex[16 + 1] = "0123456789abcdef";
531 |
532 | // save old hash if buffer is partially filled
533 | uint32_t oldHash[HashValues];
534 | for (int i = 0; i < HashValues; i++)
535 | oldHash[i] = m_hash[i];
536 |
537 | // process remaining bytes
538 | processBuffer();
539 |
540 | // create hash string
541 | /* Modified from original source code. Creating char* instead of string. */
542 | char* hashBuffer = new char[HashValues * 8 + 1]();
543 | size_t offset = 0;
544 | for (int i = 0; i < HashValues; i++) {
545 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 28) & 15];
546 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 24) & 15];
547 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 20) & 15];
548 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 16) & 15];
549 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 12) & 15];
550 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 8) & 15];
551 | hashBuffer[offset++] = dec2hex[(m_hash[i] >> 4) & 15];
552 | hashBuffer[offset++] = dec2hex[m_hash[i] & 15];
553 |
554 | // restore old hash
555 | m_hash[i] = oldHash[i];
556 | }
557 | // zero-terminated string
558 | hashBuffer[offset] = 0;
559 |
560 | return hashBuffer;
561 | }
562 |
563 | /* This function added to original source. It is a modified version of
564 | * getHash() from above. */
565 | /// return latest hash raw (not as hex)
566 | char* SHA256::getHashDec() {
567 | // save old hash if buffer is partially filled
568 | uint32_t oldHash[HashValues];
569 | for (int i = 0; i < HashValues; i++)
570 | oldHash[i] = m_hash[i];
571 |
572 | // process remaining bytes
573 | processBuffer();
574 |
575 | // create hash string
576 | /* Modified from original source code. Creating char* instead of string. */
577 | char* hashBuffer = new char[HashValues * 4 + 1]();
578 | size_t offset = 0;
579 | for (int i = 0; i < HashValues; i++) {
580 | hashBuffer[offset++] = (m_hash[i] >> 24) & 0xff;
581 | hashBuffer[offset++] = (m_hash[i] >> 16) & 0xff;
582 | hashBuffer[offset++] = (m_hash[i] >> 8) & 0xff;
583 | hashBuffer[offset++] = m_hash[i] & 0xff;
584 | // restore old hash
585 | m_hash[i] = oldHash[i];
586 | }
587 | // zero-terminated string
588 | hashBuffer[offset] = 0;
589 |
590 | return hashBuffer;
591 | }
592 |
593 | /// compute SHA256 of a memory block
594 | /* Modified from original source code. Using char* instead of string. */
595 | char* SHA256::operator()(const void* data, size_t numBytes) {
596 | reset();
597 | add(data, numBytes);
598 | return getHash();
599 | }
600 |
601 | /* These lines have been discarded from the original source code. std::string object
602 | * is not necessarilly included on the devices that will use this SDK.*/
603 | ///// compute SHA256 of a string, excluding final zero
604 | //std::string SHA256::operator()(const std::string& text)
605 | //{
606 | // reset();
607 | // add(text.c_str(), text.size());
608 | // return getHash();
609 | //}
610 |
--------------------------------------------------------------------------------
/src/aws-sdk-arduino/sha256.h:
--------------------------------------------------------------------------------
1 | // //////////////////////////////////////////////////////////
2 | // sha256.h
3 | // Copyright (c) 2014 Stephan Brumme. All rights reserved.
4 | // see http://create.stephan-brumme.com/disclaimer.html
5 | //
6 | #ifndef SHA256_H_
7 | #define SHA256_H_
8 |
9 | #pragma once
10 |
11 | //#include "hash.h"
12 |
13 | /* This include statement has been discarded from the original source code. Not
14 | * using string object as it is not necessarilly included on the devices that
15 | * will use this SDK. */
16 | //#include
17 | // define fixed size integer types
18 | #ifdef _MSC_VER
19 | // Windows
20 | typedef unsigned __int8 uint8_t;
21 | typedef unsigned __int32 uint32_t;
22 | typedef unsigned __int64 uint64_t;
23 | #else
24 | // GCC
25 | #include
26 | #endif
27 | // This line added to original source code. defines size_t.
28 | #include "stddef.h"
29 |
30 | /// compute SHA256 hash
31 | /** Usage:
32 | SHA256 sha256;
33 | std::string myHash = sha256("Hello World"); // std::string
34 | std::string myHash2 = sha256("How are you", 11); // arbitrary data, 11 bytes
35 |
36 | // or in a streaming fashion:
37 |
38 | SHA256 sha256;
39 | while (more data available)
40 | sha256.add(pointer to fresh data, number of new bytes);
41 | std::string myHash3 = sha256.getHash();
42 | */
43 | class SHA256 //: public Hash
44 | {
45 | public:
46 | /// same as reset()
47 | SHA256();
48 |
49 | /// compute SHA256 of a memory block
50 | /* Modified from original source code. Using char* instead of string. */
51 | char* operator()(const void* data, size_t numBytes);
52 | /// compute SHA256 of a string, excluding final zero
53 | /* Modified from original source code. Using char* instead of string. */
54 | char* operator()(const char* text);
55 |
56 | /// add arbitrary number of bytes
57 | void add(const void* data, size_t numBytes);
58 |
59 | /// return latest hash as 16 hex characters
60 | /* Modified from original source code. Using char* instead of string. */
61 | char* getHash();
62 |
63 | /* This function added to original source. */
64 | /// return latest hash raw (not as hex)
65 | char* getHashDec();
66 |
67 | /// restart
68 | void reset();
69 |
70 | private:
71 | /// process 64 bytes
72 | void processBlock(const void* data);
73 | /// process everything left in the internal buffer
74 | void processBuffer();
75 |
76 | /// split into 64 byte blocks (=> 512 bits)
77 | enum {
78 | BlockSize = 512 / 8, HashValues = 8
79 | };
80 |
81 | /// size of processed data in bytes
82 | uint64_t m_numBytes;
83 | /// valid bytes in m_buffer
84 | size_t m_bufferSize;
85 | /// bytes not processed yet
86 | uint8_t m_buffer[BlockSize];
87 | /// hash, stored as integers
88 | uint32_t m_hash[8];
89 | };
90 | #endif
--------------------------------------------------------------------------------
/src/aws/AwsIotSigv4.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * Modified 2017 joekickass
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License").
6 | * You may not use this file except in compliance with the License.
7 | * A copy of the License is located at
8 | *
9 | * http://aws.amazon.com/apache2.0
10 | *
11 | * or in the "license" file accompanying this file. This file is distributed
12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13 | * express or implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | /* Modified version of AwsClient2
18 | * https://github.com/awslabs/aws-sdk-arduino/blob/master/src/common/AWSClient2.h
19 | */
20 | #include "aws-sdk-arduino/sha256.h"
21 | #include "aws-sdk-arduino/Utils.h"
22 |
23 | #include "AwsIotSigv4.h"
24 | #include "aws_iot_config.h"
25 |
26 | AwsIotSigv4::AwsIotSigv4(IDateTimeProvider *dtp,
27 | char *region,
28 | char *endpoint,
29 | char *mqttHost,
30 | int mqttPort,
31 | char *iamKeyId,
32 | char *iamSecretKey) :
33 | awsRegion(region),
34 | awsEndpoint(endpoint),
35 | awsHost(mqttHost),
36 | awsPort(mqttPort),
37 | awsKeyId(iamKeyId),
38 | awsSecretKey(iamSecretKey),
39 | dateTimeProvider(dtp)
40 | {
41 | }
42 |
43 | AwsIotSigv4::~AwsIotSigv4()
44 | {
45 | }
46 |
47 | size_t AwsIotSigv4::createRequest(char** out)
48 | {
49 | char* path;
50 | size_t pathLen = createPath(&path);
51 | size_t reqLen = strlen(awsHost) + pathLen + 7;
52 | *out = new char[reqLen];
53 | sprintf(*out, "wss://%s%s", awsHost, path);
54 | delete[] path;
55 | return reqLen;
56 | }
57 |
58 | size_t AwsIotSigv4::createPath(char** out)
59 | {
60 | if (dateTimeProvider == 0) {
61 | return 0;
62 | }
63 |
64 | // step 1
65 | char date[DATE_LEN + 1];
66 | char time[TIME_LEN + 1];
67 | getDateTime(date, time);
68 |
69 | int csLen = getCredentialStringLength();
70 | char credentialString[csLen + 1];
71 | getCredentialString(credentialString, date);
72 |
73 | char queryString[QS_LEN + 1];
74 | getQueryString(queryString, credentialString, date, time);
75 |
76 | char payloadHash[HASH_HEX_LEN + 1];
77 | getPayloadHash(payloadHash);
78 |
79 | char canonicalRequest[CR_LEN];
80 | createCanonicalRequest(canonicalRequest, queryString, payloadHash);
81 |
82 | char canonicalRequestHash[HASH_HEX_LEN + 1];
83 | getCanonicalRequestHash(canonicalRequestHash, canonicalRequest);
84 |
85 | // step 2
86 | csLen = getCredentialScopeLength();
87 | char credentialScope[csLen + 1];
88 | getCredentialScope(credentialScope, date);
89 | char stringToSign[ALG_LEN + DATE_LEN + TIME_LEN + csLen + HASH_HEX_LEN + 6];
90 | createStringToSign(stringToSign, date, time, credentialScope, canonicalRequestHash);
91 |
92 | // step 3
93 | char signature[HASH_HEX_LEN];
94 | createSignature(signature, stringToSign, date);
95 |
96 | // step 4
97 | addSignatureToQueryString(queryString, signature);
98 |
99 | int requestLen = getRequestLength(queryString);
100 | (*out) = new char[requestLen]();
101 | addSignatureQSToRequest(*out, queryString);
102 |
103 | return requestLen;
104 | }
105 |
106 | /* CanonicalRequest =
107 | * HTTPRequestMethod + '\n' +
108 | * CanonicalURI + '\n' +
109 | * CanonicalQueryString + '\n' +
110 | * CanonicalHeaders + '\n' +
111 | * SignedHeaders + '\n' +
112 | * HexEncode(Hash(RequestPayload))
113 | */
114 | void AwsIotSigv4::createCanonicalRequest(char* out, char* qs, char* payloadHash)
115 | {
116 | // Method, URI
117 | sprintf(out, "%s\n", METHOD);
118 | sprintf(out, "%s%s\n", out, PATH);
119 |
120 | // Query String
121 | sprintf(out, "%s%s\n", out, qs);
122 |
123 | // Canonical headers. Only host is used.
124 | sprintf(out, "%shost:%s:%d\n\n", out, awsHost, awsPort);
125 |
126 | // Signed headers
127 | sprintf(out, "%shost\n", out);
128 |
129 | // Payload hash
130 | sprintf(out, "%s%s", out, payloadHash);
131 | }
132 |
133 | void AwsIotSigv4::createStringToSign(char *out, char* date, char* time, char* cs, char* canonicalRequestHash)
134 | {
135 | sprintf(out, "%s\n%sT%sZ\n%s\n%s", ALGORITHM, date, time, cs, canonicalRequestHash);
136 | }
137 |
138 | void AwsIotSigv4::createSignature(char* out, char* sts, char* date)
139 | {
140 | int keyLen = SECRET_KEY_LEN + 4;
141 | char* key = new char[keyLen + 1];
142 | sprintf(key, "AWS4%s", awsSecretKey);
143 |
144 | char* k1 = hmacSha256(key, keyLen, date, DATE_LEN);
145 | delete[] key;
146 |
147 | char* k2 = hmacSha256(k1, SHA256_DEC_HASH_LEN, awsRegion, strlen(awsRegion));
148 | delete[] k1;
149 |
150 | char* k3 = hmacSha256(k2, SHA256_DEC_HASH_LEN, SERVICE, strlen(SERVICE));
151 | delete[] k2;
152 |
153 | char* k4 = hmacSha256(k3, SHA256_DEC_HASH_LEN, "aws4_request", 12);
154 | delete[] k3;
155 |
156 | char* k5 = hmacSha256(k4, SHA256_DEC_HASH_LEN, sts, strlen(sts));
157 | delete[] k4;
158 |
159 | /* Convert the chars in hash to hex for signature. */
160 | for (int i = 0; i < SHA256_DEC_HASH_LEN; ++i) {
161 | sprintf(out + 2 * i, "%02lx", 0xff & (unsigned long) k5[i]);
162 | }
163 | delete[] k5;
164 | }
165 |
166 | void AwsIotSigv4::addSignatureToQueryString(char* out, char* signature)
167 | {
168 | sprintf(out, "%s&X-Amz-Signature=%s", out, signature);
169 | }
170 |
171 | void AwsIotSigv4::addSignatureQSToRequest(char* out, char* qs)
172 | {
173 | sprintf(out, "%s%s?%s", out, PATH, qs);
174 | }
175 |
176 | int AwsIotSigv4::getRequestLength(char* queryString) {
177 | return strlen(PATH) + strlen(queryString)+2;
178 | }
179 |
180 | // Size of credential scope (not including terminating null char) */
181 | int AwsIotSigv4::getCredentialScopeLength() {
182 | return DATE_LEN + strlen(awsRegion) + strlen(SERVICE) + 16;
183 | }
184 |
185 | // Create credential scope, e.g. "////aws4_request"
186 | void AwsIotSigv4::getCredentialScope(char *out, char* date)
187 | {
188 | sprintf(out, "%s/%s/%s/aws4_request", date, awsRegion, SERVICE);
189 | }
190 |
191 | // Size of credential scope (not including terminating null char) */
192 | int AwsIotSigv4::getCredentialStringLength() {
193 | return ACCESS_KEY_ID_LEN + DATE_LEN + strlen(awsRegion) + strlen(SERVICE) + 24;
194 | }
195 |
196 | // Create credential string, e.g. "////aws4_request"
197 | // Must be URI encoded (i.e. '/' -> %2F and ' ' -> %20)
198 | void AwsIotSigv4::getCredentialString(char *out, char* date)
199 | {
200 | sprintf(out, "%s%%2F%s%%2F%s%%2F%s%%2Faws4_request", awsKeyId, date, awsRegion, SERVICE);
201 | }
202 |
203 | void AwsIotSigv4::getQueryString(char* out, char* cs, char* date, char* time)
204 | {
205 | sprintf(out, "X-Amz-Algorithm=%s", ALGORITHM);
206 | sprintf(out, "%s&X-Amz-Credential=%s", out, cs);
207 | sprintf(out, "%s&X-Amz-Date=%sT%sZ", out, date, time);
208 | sprintf(out, "%s&X-Amz-Expires=86400", out);
209 | sprintf(out, "%s&X-Amz-SignedHeaders=host", out);
210 | }
211 |
212 | // Payload is always empty. Generate hash anyway.
213 | void AwsIotSigv4::getPayloadHash(char* out)
214 | {
215 | SHA256* sha256 = new SHA256();
216 | char* payloadHash = (*sha256)("", 0);
217 | snprintf(out, HASH_HEX_LEN + 1, "%s", payloadHash);
218 | delete[] payloadHash;
219 | delete sha256;
220 | }
221 |
222 | void AwsIotSigv4::getCanonicalRequestHash(char* out, char* canonicalRequest)
223 | {
224 | SHA256* sha256 = new SHA256();
225 | char* canonicalRequestHash = (*sha256)(canonicalRequest, strlen (canonicalRequest));
226 | snprintf(out, HASH_HEX_LEN + 1, "%s", canonicalRequestHash);
227 | delete[] canonicalRequestHash;
228 | delete sha256;
229 | }
230 |
231 | void AwsIotSigv4::getDateTime(char* date, char* time)
232 | {
233 | const char* dateTime = dateTimeProvider->getDateTime();
234 | snprintf(date, DATE_LEN + 1, "%s", dateTime);
235 | snprintf(time, TIME_LEN + 1, "%s", dateTime + DATE_LEN);
236 | }
237 |
--------------------------------------------------------------------------------
/src/aws/AwsIotSigv4.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * Modified 2017 joekickass
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License").
6 | * You may not use this file except in compliance with the License.
7 | * A copy of the License is located at
8 | *
9 | * http://aws.amazon.com/apache2.0
10 | *
11 | * or in the "license" file accompanying this file. This file is distributed
12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13 | * express or implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | /* Modified version of AwsClient2
18 | * https://github.com/awslabs/aws-sdk-arduino/blob/master/src/common/AWSClient2.h
19 | *
20 | * Using simplified algorithm for mqtt/websockets
21 | * http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt-ws
22 | */
23 |
24 | #ifndef AWSIOTSIGV4_H_
25 | #define AWSIOTSIGV4_H_
26 |
27 | #include
28 | #include
29 |
30 | #include "aws-sdk-arduino/DeviceIndependentInterfaces.h"
31 |
32 | /* HTTP VERB */
33 | static const char* METHOD = "GET";
34 | /* URI scheme */
35 | static const char* PROTOCOL = "wss";
36 | /* URI path */
37 | static const char* PATH = "/mqtt";
38 | /* AWS service */
39 | static const char* SERVICE = "iotdevicegateway";
40 | /* Hash algorithm */
41 | static const char* ALGORITHM = "AWS4-HMAC-SHA256";
42 |
43 | /* GMT date in yyyyMMdd format (not including terminating null char) */
44 | static const int DATE_LEN = 8;
45 | /* GMT time in HHmmss format (not including terminating null char) */
46 | static const int TIME_LEN = 6;
47 | /* Size of sha hashes and signatures in hexidecimal */
48 | static const int HASH_HEX_LEN = 64;
49 | /* Size of algorithm (not including terminating null char) */
50 | static const int ALG_LEN = strlen(ALGORITHM);
51 | /* Size of access key id (not including terminating null char) */
52 | static const int ACCESS_KEY_ID_LEN = 20;
53 | /* Size of secret key (not including terminating null char) */
54 | static const int SECRET_KEY_LEN = 40;
55 | /* Size of query string (not including terminating null char) */
56 | // TODO: Tweak size?
57 | static const int QS_LEN = ALG_LEN + SECRET_KEY_LEN + DATE_LEN + TIME_LEN + 200;
58 | /* Size of canonical request (not including terminating null char) */
59 | // TODO: Tweak size?
60 | static const int CR_LEN = 400;
61 |
62 | /*
63 | * AwsIotSigv4
64 | *
65 | * A ws connection is initiated by sending a HTTP GET request using the URL:
66 | * wss://.iot..amazonaws.com/mqtt
67 | */
68 | class AwsIotSigv4
69 | {
70 | public:
71 | AwsIotSigv4(IDateTimeProvider* dtp,
72 | char *region,
73 | char *endpoint,
74 | char *mqttHost,
75 | int mqttPort,
76 | char *iamKeyId,
77 | char *iamSecretKey);
78 | ~AwsIotSigv4();
79 |
80 | /*
81 | * Create a Sigv4 signed HTTP upgrade request (aka websocket handshake) to
82 | * the AWS IoT service.
83 | *
84 | * Example:
85 | * wss://A2MBBEONHC9LUG.iot.us-east-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20170508%2Feu-west-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20170508T123058Z&X-Amz-SignedHeaders=host&X-Amz-Signature=5d945eab451da3756ef5ad9bf1b1741dae26f5416d5e754d2ad260497df42d23
86 | * Caller must free memory
87 | */
88 | size_t createRequest(char** out);
89 |
90 | /*
91 | * Create the path part of a Sigv4 signed HTTP upgrade request (aka
92 | * websocket handshake) to the AWS IoT service.
93 | *
94 | * Example:
95 | * /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20170508%2Feu-west-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20170508T123058Z&X-Amz-SignedHeaders=host&X-Amz-Signature=5d945eab451da3756ef5ad9bf1b1741dae26f5416d5e754d2ad260497df42d23
96 | *
97 | * Caller must free memory
98 | */
99 | size_t createPath(char** out);
100 |
101 | /* Region, e.g. "us-east-1" in "A2MBBEONHC9LUG.iot.us-east-1.amazonaws.com" */
102 | char* awsRegion;
103 |
104 | /* Endpoint, e.g. "A2MBBEONHC9LUG" in "A2MBBEONHC9LUG.iot.us-east-1.amazonaws.com" */
105 | char* awsEndpoint;
106 |
107 | /* Host, e.g. "A2MBBEONHC9LUG.iot.us-east-1.amazonaws.com" */
108 | char* awsHost;
109 |
110 | /* Port, e.g. 443 */
111 | int awsPort;
112 |
113 | /* The user's AWS Access Key ID for accessing the AWS Resource. */
114 | char* awsKeyId;
115 |
116 | /* The user's AWS Secret Key for accessing the AWS Resource. */
117 | char* awsSecretKey;
118 |
119 | private:
120 | /* Used to keep track of time. */
121 | IDateTimeProvider* dateTimeProvider;
122 |
123 | /* First step of sigv4 signing */
124 | void createCanonicalRequest(char* out, char* qs, char* payloadHash);
125 |
126 | /* Second step of sigv4 signing */
127 | void createStringToSign(char *out, char* date, char* time, char* cs, char* canonicalRequestHash);
128 |
129 | /* Third step of sigv4 signing.
130 | * Given the string to sign, create the signature (a 64-char cstring) */
131 | void createSignature(char* out, char* sts, char* date);
132 |
133 | /* Fourth and last step of sigv4 signing, divided up in 2 methods
134 | * Add signature to request */
135 | void addSignatureToQueryString(char* out, char* signature);
136 | void addSignatureQSToRequest(char* out, char* qs);
137 |
138 | /* Calculate the size of the final request string based on queryString */
139 | int getRequestLength(char* queryString);
140 |
141 | /* Calculate the size of the credential scope string */
142 | int getCredentialScopeLength();
143 |
144 | /* Get the credential scope */
145 | void getCredentialScope(char* out, char* date);
146 |
147 | /* Calculate the size of the credential string */
148 | int getCredentialStringLength();
149 |
150 | /* Get the credential string (which is access key id + credential scope) */
151 | void getCredentialString(char* out, char* date);
152 |
153 | /* Get the canonical query string */
154 | void getQueryString(char* out, char* cs, char* date, char* time);
155 |
156 | /* Get the current date and time */
157 | void getDateTime(char* outDate, char* outTime);
158 |
159 | /* Create payloadHash from empty payload */
160 | void getPayloadHash(char* out);
161 |
162 | /* Create canonical request hash */
163 | void getCanonicalRequestHash(char* out, char* canonicalRequest);
164 | };
165 |
166 | #endif
167 |
--------------------------------------------------------------------------------
/src/aws/ESP8266DateTimeProvider.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright Sander van de Graaf (svdgraaf)
3 | * Modified 2017 joekickass
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License").
6 | * You may not use this file except in compliance with the License.
7 | * A copy of the License is located at
8 | *
9 | * http://aws.amazon.com/apache2.0
10 | *
11 | * or in the "license" file accompanying this file. This file is distributed
12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13 | * express or implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | #include
18 |
19 | ESP8266DateTimeProvider::ESP8266DateTimeProvider() : timeClient()
20 | {
21 | strcpy(dateTime,"20120101000000");
22 | }
23 |
24 | const char* ESP8266DateTimeProvider::getDateTime()
25 | {
26 | sync(0);
27 | return dateTime;
28 | }
29 |
30 | bool ESP8266DateTimeProvider::syncTakesArg(void)
31 | {
32 | return false;
33 | }
34 |
35 | void ESP8266DateTimeProvider::sync(const char* dt)
36 | {
37 | if (!timeClient.connect("aws.amazon.com", 80)) {
38 | Serial.println("Could not connect to timeserver. Using old timestamp");
39 | return;
40 | }
41 |
42 | // send a bad header on purpose, so we get a 400 with a DATE: timestamp
43 | timeClient.println("GET example.com/ HTTP/1.1");
44 | timeClient.println("Connection: close");
45 | timeClient.println();
46 |
47 | int timeout_busy = 0;
48 | while( ( !timeClient.available() ) && ( timeout_busy++ < 5000 ) ) {
49 | // Wait until the client sends some data
50 | delay(1);
51 | }
52 |
53 | // kill client if timeout
54 | if(timeout_busy >= 5000) {
55 | timeClient.flush();
56 | timeClient.stop();
57 | Serial.println("Timeout receiving timeserver data. Using old timestamp");
58 | return;
59 | }
60 |
61 | // read the http GET Response
62 | String req2 = timeClient.readString();
63 |
64 | // close connection
65 | delay(1);
66 | timeClient.flush();
67 | timeClient.stop();
68 |
69 | int ipos = req2.indexOf("Date:");
70 | if(ipos > 0) {
71 | String gmtDate = req2.substring(ipos, ipos + 35);
72 | String utctime = gmtDate.substring(18,22) + getMonth(gmtDate.substring(14,17)) + gmtDate.substring(11,13) + gmtDate.substring(23,25) + gmtDate.substring(26,28) + gmtDate.substring(29,31);
73 | utctime.substring(0, 14).toCharArray(dateTime, 15);
74 | }
75 | }
76 |
77 | String ESP8266DateTimeProvider::getMonth(String sM) {
78 | if(sM=="Jan") return "01";
79 | if(sM=="Feb") return "02";
80 | if(sM=="Mar") return "03";
81 | if(sM=="Apr") return "04";
82 | if(sM=="May") return "05";
83 | if(sM=="Jun") return "06";
84 | if(sM=="Jul") return "07";
85 | if(sM=="Aug") return "08";
86 | if(sM=="Sep") return "09";
87 | if(sM=="Oct") return "10";
88 | if(sM=="Nov") return "11";
89 | if(sM=="Dec") return "12";
90 | return "01";
91 | }
92 |
--------------------------------------------------------------------------------
/src/aws/ESP8266DateTimeProvider.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * Modified 2017 joekickass
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License").
6 | * You may not use this file except in compliance with the License.
7 | * A copy of the License is located at
8 | *
9 | * http://aws.amazon.com/apache2.0
10 | *
11 | * or in the "license" file accompanying this file. This file is distributed
12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13 | * express or implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | /* Modified version of ESP8266AWSImplementations.h
18 | * https://github.com/heskew/aws-sdk-arduino/blob/master/src/esp8266/ESP8266AWSImplementations.h
19 | */
20 |
21 | #ifndef ESP8266DATETIMEPROVIDER_H_
22 | #define ESP8266DATETIMEPROVIDER_H_
23 |
24 | #include
25 |
26 | #include "aws-sdk-arduino/DeviceIndependentInterfaces.h"
27 |
28 | class ESP8266DateTimeProvider : public IDateTimeProvider
29 | {
30 | public:
31 | ESP8266DateTimeProvider();
32 |
33 | /* Retrieve the current GMT date and time in yyyyMMddHHmmss format. */
34 | virtual const char* getDateTime(void);
35 |
36 | /* Return true if the sync function requires the current time as in
37 | * argument. */
38 | virtual bool syncTakesArg(void);
39 |
40 | /* Called if AWS Service reports in accurate time. Sets the provider to
41 | * current time. If syncTakesArg() returns true, this argument takes the
42 | * current GMT date and time in yyyyMMddHHmmss format. Else, the nput value
43 | * is ignored and may be null. */
44 | virtual void sync(const char* dt);
45 |
46 | private:
47 |
48 | /* DateTime in yyyyMMddHHmmss format */
49 | char dateTime[15];
50 |
51 | WiFiClient timeClient;
52 |
53 | String getMonth(String sM);
54 | };
55 |
56 | #endif
57 |
--------------------------------------------------------------------------------
/src/aws_iot_config.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * Modified 2017 joekickass
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License").
6 | * You may not use this file except in compliance with the License.
7 | * A copy of the License is located at
8 | *
9 | * http://aws.amazon.com/apache2.0
10 | *
11 | * or in the "license" file accompanying this file. This file is distributed
12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13 | * express or implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | #ifndef SRC_SHADOW_IOT_SHADOW_CONFIG_H_
18 | #define SRC_SHADOW_IOT_SHADOW_CONFIG_H_
19 |
20 | #define AWS_REGION "eu-central-1"
21 |
22 | #define AWS_IAM_KEY_ID "AKIAIOSFODNN7EXAMPLE"
23 | #define AWS_IAM_SECRET_KEY "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
24 |
25 | #define AWS_IOT_ENDPOINT "A2MBBEONHC9LUG"
26 | #define AWS_IOT_MQTT_HOST "A2MBBEONHC9LUG.iot.eu-west-1.amazonaws.com" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow
27 | #define AWS_IOT_MQTT_PORT 443 ///< default port for MQTT/S
28 | #define AWS_IOT_MQTT_CLIENT_ID "esp8266-id" ///< MQTT client ID should be unique for every device
29 | #define AWS_IOT_MY_THING_NAME "esp8266-name" ///< Thing Name of the Shadow this device is associated with
30 |
31 | // MQTT config
32 | #define AWS_IOT_MQTT_TX_BUF_LEN 512 ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow
33 | #define AWS_IOT_MQTT_RX_BUF_LEN 512 ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped.
34 | #define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow
35 |
36 | // Thing Shadow specific config
37 | #define SHADOW_MAX_SIZE_OF_RX_BUFFER AWS_IOT_MQTT_RX_BUF_LEN+1 ///< Maximum size of the SHADOW buffer to store the received Shadow message
38 | #define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments"
39 | #define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10 ///< This is size of the extra sequence number that will be appended to the Unique client Id
40 | #define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20 ///< This is size of the the total clientToken key and value pair in the JSON
41 | #define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested
42 | #define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time
43 | #define MAX_JSON_TOKEN_EXPECTED 120 ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published
44 | #define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 ///< All shadow actions have to be published or subscribed to a topic which is of the format $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name
45 | #define MAX_SIZE_OF_THING_NAME 20 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger
46 | #define MAX_SHADOW_TOPIC_LENGTH_BYTES MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME ///< This size includes the length of topic with Thing Name
47 |
48 | // Auto Reconnect specific config
49 | #define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm
50 | #define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect.
51 |
52 | #endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */
53 |
--------------------------------------------------------------------------------
/src/config/AWSConnectionParams.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Tomas Nilsson (joekickass)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 |
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #include "config/AWSConnectionParams.h"
18 | #include "aws_iot_config.h"
19 |
20 | AWSConnectionParams::AWSConnectionParams(AwsIotSigv4& sigv4) :
21 | sigv4(sigv4)
22 | {
23 | }
24 |
25 | AWSConnectionParams::~AWSConnectionParams()
26 | {
27 | if (path != 0) {
28 | delete[] path;
29 | }
30 | }
31 |
32 | char* AWSConnectionParams::getHost()
33 | {
34 | return sigv4.awsHost;
35 | }
36 |
37 | unsigned int AWSConnectionParams::getPort()
38 | {
39 | return sigv4.awsPort;
40 | }
41 |
42 | char* AWSConnectionParams::getPath()
43 | {
44 | if (path == 0) {
45 | sigv4.createPath(&path);
46 | }
47 | return path;
48 | }
49 |
50 | char* AWSConnectionParams::getFingerprint()
51 | {
52 | return "";
53 | }
54 |
55 | char* AWSConnectionParams::getProtocol()
56 | {
57 | return "mqtt";
58 | }
59 |
60 | bool AWSConnectionParams::useSsl()
61 | {
62 | return true;
63 | }
64 |
65 | unsigned int AWSConnectionParams::getVersion()
66 | {
67 | return 4;
68 | }
69 | char* AWSConnectionParams::getClientId()
70 | {
71 | return AWS_IOT_MQTT_CLIENT_ID;
72 | }
73 |
--------------------------------------------------------------------------------
/src/config/AWSConnectionParams.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Tomas Nilsson (joekickass)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 |
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #ifndef AWSCONNECTIONPARAMS_H_
18 | #define AWSCONNECTIONPARAMS_H_
19 |
20 | #include "ws/WebSocketClientAdapter.h"
21 | #include "mqtt/MqttClient.h"
22 | #include "aws/AwsIotSigv4.h"
23 |
24 | class AWSConnectionParams : public WebSocketParams, public MqttParams
25 | {
26 | public:
27 | AWSConnectionParams(AwsIotSigv4& sigv4);
28 | ~AWSConnectionParams();
29 |
30 | // TCP params
31 | char* getHost();
32 | unsigned int getPort();
33 |
34 | // WS params
35 | char* getPath();
36 | char* getFingerprint();
37 | char* getProtocol();
38 | bool useSsl();
39 |
40 | // MQTT params
41 | unsigned int getVersion();
42 | char* getClientId();
43 |
44 | private:
45 |
46 | AwsIotSigv4 sigv4;
47 |
48 | char* path;
49 | };
50 |
51 | #endif
52 |
--------------------------------------------------------------------------------
/src/mqtt/MqttClient.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Tomas Nilsson (joekickass)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 |
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #include "mqtt/MqttClient.h"
18 |
19 | // Keep a global reference of the instance to use in FPT callback
20 | AWSMqttClient* AWSMqttClient::instance = NULL;
21 |
22 | MqttParams::~MqttParams() {}
23 |
24 | AWSMqttClient::AWSMqttClient(AWSWebSocketClientAdapter& wsAdapter, MqttParams& p) :
25 | adapter(wsAdapter),
26 | ipstack(adapter),
27 | client(ipstack),
28 | params(p)
29 | {
30 | AWSMqttClient::instance = this;
31 | for(int i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) {
32 | SubscriptionCallbacks[i].topic = 0;
33 | SubscriptionCallbacks[i].cb = NULL;
34 | }
35 | }
36 |
37 | AWSMqttClient::~AWSMqttClient()
38 | {
39 | }
40 |
41 | int AWSMqttClient::connect()
42 | {
43 | // make sure we're stopped
44 | adapter.stop();
45 |
46 | char* host = params.getHost();
47 | int port = params.getPort();
48 | int success = ipstack.connect(host, port);
49 | if (!success) {
50 | return -1;
51 | }
52 |
53 | MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
54 | data.MQTTVersion = params.getVersion();
55 | data.clientID.cstring = params.getClientId();
56 |
57 | return client.connect(data);
58 | }
59 |
60 | bool AWSMqttClient::isConnected()
61 | {
62 | return adapter.connected() && client.isConnected();
63 | }
64 |
65 | void AWSMqttClient::yield()
66 | {
67 | client.yield();
68 | }
69 |
70 | void AWSMqttClient::disconnect()
71 | {
72 | client.disconnect();
73 | }
74 |
75 | int AWSMqttClient::publish(const char* topic, const char* payload, unsigned int qos, bool retained)
76 | {
77 | // Need a non-const, null terminated string
78 | char pl[strlen(payload) + 1];
79 | snprintf(pl, strlen(payload) + 1, "%s", payload);
80 | MQTT::QoS qs = static_cast(qos); // Assuming default enum values
81 | return client.publish(topic, pl, strlen(payload) + 1, qs, retained);
82 | }
83 |
84 | int AWSMqttClient::subscribe(const char* topic, unsigned int qos, subscriptionCallback cb)
85 | {
86 | MQTT::QoS qs = static_cast(qos); // Assuming default enum values
87 | addCallback(topic, cb);
88 | return client.subscribe(topic, qs,
89 | // Need to use a lamda w.o. capture list since MQTT::Client.messageHandler is PTF
90 | [](MQTT::MessageData& md) {
91 | // c strings from underlying implementation are not null terminated. Create new.
92 | char topic[md.topicName.lenstring.len + 1];
93 | snprintf(topic, md.topicName.lenstring.len + 1, "%s", md.topicName.lenstring.data);
94 | char msg[md.message.payloadlen + 1];
95 | snprintf(msg, md.message.payloadlen + 1, "%s", (char*)md.message.payload);
96 | instance->handleCallback(topic, msg);
97 | }
98 | );
99 | }
100 |
101 | void AWSMqttClient::unsubscribe(const char *topic)
102 | {
103 | removeCallback(topic);
104 | client.unsubscribe(topic);
105 | }
106 |
107 | void AWSMqttClient::addCallback(const char* topic, subscriptionCallback cb)
108 | {
109 | if (topic == NULL || cb == NULL) {
110 | return;
111 | }
112 |
113 | for(int i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) {
114 | if (SubscriptionCallbacks[i].topic == 0) {
115 | SubscriptionCallbacks[i].topic = topic;
116 | SubscriptionCallbacks[i].cb = cb;
117 | break;
118 | }
119 | }
120 | }
121 |
122 | void AWSMqttClient::removeCallback(const char* topic)
123 | {
124 | if (topic == NULL) {
125 | return;
126 | }
127 |
128 | for(int i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) {
129 | if (strcmp(SubscriptionCallbacks[i].topic, topic) == 0) {
130 | SubscriptionCallbacks[i].topic = 0;
131 | SubscriptionCallbacks[i].cb = NULL;
132 | break;
133 | }
134 | }
135 | }
136 |
137 | subscriptionCallback AWSMqttClient::getCallback(const char* topic)
138 | {
139 | if (topic == NULL) {
140 | return NULL;
141 | }
142 |
143 | for(int i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) {
144 | if (strcmp(SubscriptionCallbacks[i].topic, topic) == 0) {
145 | return SubscriptionCallbacks[i].cb;
146 | }
147 | }
148 | return NULL;
149 | }
150 |
151 | void AWSMqttClient::handleCallback(const char* topic, const char* msg)
152 | {
153 | subscriptionCallback cb = getCallback(topic);
154 | if (topic != NULL && cb != NULL) {
155 | cb(topic, msg);
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/src/mqtt/MqttClient.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Tomas Nilsson (joekickass)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 |
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #ifndef MQTTCLIENT_H_
18 | #define MQTTCLIENT_H_
19 |
20 | #include
21 | #include
22 | #include
23 |
24 | #include "ws/WebSocketClientAdapter.h"
25 |
26 | // TODO Refactor away config here
27 | #include "aws_iot_config.h"
28 |
29 | // (const char* topic, const char* payload)
30 | typedef void (*subscriptionCallback) (const char*, const char*);
31 |
32 | struct {
33 | const char* topic;
34 | subscriptionCallback cb;
35 | } SubscriptionCallbacks[AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS];
36 |
37 | /*
38 | * MqttParams provides connection parameters for the MqttClient
39 | *
40 | * Using an abstract class instead of a plain data struct allows parameters that
41 | * are more dynamic in nature, such as signatures based on current date/time.
42 | * An example of this is AWS sigv4 signature authentication
43 | */
44 | class MqttParams
45 | {
46 | public:
47 | virtual char* getHost() =0;
48 | virtual unsigned int getPort() =0;
49 | virtual unsigned int getVersion() =0;
50 | virtual char* getClientId() =0;
51 | virtual ~MqttParams() =0;
52 | };
53 |
54 | /**
55 | * MQTT client running MQTT over WebSockets.
56 | *
57 | * Assumes WebSockets handles security using TLS.
58 | *
59 | * TODO: Also assumes null terminated c strings as payload (i.e. json data)
60 | * Some information on the AWS IoT Websocket+MQTT protocols
61 | * http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html
62 | */
63 | class AWSMqttClient {
64 |
65 | public:
66 |
67 | AWSMqttClient(AWSWebSocketClientAdapter& a, MqttParams& p);
68 | ~AWSMqttClient();
69 |
70 | //Establish a Websocket connection and connect to the MQTT host.
71 | //Returns 0 if successful, or non-zero otherwise
72 | int connect();
73 |
74 | bool isConnected();
75 |
76 | void yield();
77 |
78 | void disconnect();
79 |
80 | // Publish to topic
81 | // Returns 0 if successful, or non-zero otherwise.
82 | // TODO: Remove retained?
83 | int publish(const char* topic, const char* payload, unsigned int qos, bool retained);
84 |
85 | // Subscribe to topic
86 | // Returns 0 if successful, or non-zero otherwise.
87 | int subscribe(const char* topic, unsigned int qos, subscriptionCallback cb);
88 |
89 | void unsubscribe(const char* topic);
90 |
91 | private:
92 |
93 | // Paho MQTT client callbacks are PTFs. Using a global variable to hold object reference
94 | // Note that this will break if more than one instance of AWSMqttClient is created
95 | static AWSMqttClient* instance;
96 |
97 | AWSWebSocketClientAdapter& adapter;
98 | IPStack ipstack;
99 | // TODO Remove config params
100 | MQTT::Client client;
101 | MqttParams& params;
102 |
103 | void addCallback(const char* topic, subscriptionCallback cb);
104 | void removeCallback(const char* topic);
105 |
106 | subscriptionCallback getCallback(const char* topic);
107 | void handleCallback(const char* topic, const char* msg);
108 | };
109 |
110 | #endif
111 |
--------------------------------------------------------------------------------
/src/ws/CircularByteBuffer.h:
--------------------------------------------------------------------------------
1 | /*
2 | This file is part of aws-mqtt-websockets.
3 |
4 | aws-mqtt-websockets is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | aws-mqtt-websockets is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with aws-mqtt-websockets. If not, see
16 | */
17 |
18 | #ifndef __CIRCULARBYTEBUFFER_H_
19 | #define __CIRCULARBYTEBUFFER_H_
20 |
21 | //#define DEBUG_CBB(...) os_printf( __VA_ARGS__ )
22 |
23 | #ifndef DEBUG_CBB
24 | #define DEBUG_CBB(...)
25 | #define NODEBUG_CBB
26 | #endif
27 |
28 | class CircularByteBuffer {
29 | public:
30 |
31 | CircularByteBuffer () {
32 | data = NULL;
33 | size = 0;
34 | capacity = 0;
35 | }
36 | ~CircularByteBuffer(){
37 | if (data!=NULL)
38 | free (data);
39 | }
40 |
41 | void clear ()
42 | {
43 | size = 0;
44 | begin = 0;
45 | end = 0;
46 | }
47 |
48 | void deallocate () {
49 | if (data!=NULL) {
50 | free (data);
51 | data = NULL;
52 | }
53 | }
54 |
55 | void init (long capacity) {
56 | if (data!=NULL)
57 | free (data);
58 | data = (byte*) malloc (capacity);
59 | size = 0;
60 | begin = 0;
61 | end = 0;
62 | this->capacity = capacity;
63 | }
64 |
65 | long getSize () {
66 | return size;
67 | }
68 |
69 | byte peek () {
70 | return data[begin];
71 | }
72 | void push (byte b) {
73 | if (size+1 == capacity) {
74 | DEBUG_CBB ("buffer full");
75 | return;
76 | }
77 | data[end] = b;
78 | end = (end+1) % capacity;
79 | size += 1;
80 |
81 | }
82 |
83 | byte pop () {
84 | if (size == 0){
85 | DEBUG_CBB ("buffer empty");
86 | return 0;
87 | }
88 | byte ret = data[begin];
89 | begin = (begin+1) % capacity;
90 | size -= 1;
91 | return ret;
92 |
93 | }
94 |
95 | void push (byte* b, long len){
96 | if (size+len >= capacity) {
97 | DEBUG_CBB ("buffer full");
98 | return;
99 | }
100 | if ( (end + len) <= capacity ) {
101 | memcpy ((void*)&data[end],b,len);
102 | end += len;
103 | } else {
104 | long endSide = capacity - end;
105 | memcpy ((void*)&data[end],b,endSide);
106 | end = 0;
107 | memcpy ((void*)&data[end],b+endSide,len-endSide);
108 | end += len-endSide;
109 | }
110 | size += len;
111 |
112 | }
113 |
114 | byte* pop (byte* b, long len){
115 | if ( (size - len) < 0 ) {
116 | DEBUG_CBB ("buffer empty");
117 | return NULL;
118 | }
119 | if ( (begin + len) <= capacity ) {
120 | memcpy (b,(void*)&data[begin],len);
121 | begin += len;
122 | } else {
123 | long endSide = capacity - begin;
124 | memcpy (b,(void*)&data[begin],endSide);
125 | begin = 0;
126 | memcpy (b+endSide,(void*)&data[begin],len-endSide);
127 | begin += len-endSide;
128 | }
129 | size -= len;
130 | }
131 |
132 | private:
133 | byte* data;
134 | long capacity;
135 | long size;
136 | long begin;
137 | long end;
138 | };
139 |
140 |
141 |
142 | #endif
143 |
--------------------------------------------------------------------------------
/src/ws/WebSocketClientAdapter.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Tomas Nilsson (joekickass)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 |
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #include "ws/WebSocketClientAdapter.h"
18 |
19 | WebSocketParams::~WebSocketParams() {}
20 |
21 | AWSWebSocketClientAdapter::AWSWebSocketClientAdapter(WebSocketParams& p, size_t bufferSize) :
22 | ws(),
23 | params(p),
24 | isConnected(false)
25 | {
26 | fifo.init(bufferSize);
27 | ws.onEvent([=] (WStype_t type, uint8_t * payload, size_t length) {
28 | webSocketEvent(type, payload, length);
29 | });
30 | }
31 |
32 | AWSWebSocketClientAdapter::~AWSWebSocketClientAdapter()
33 | {
34 | }
35 |
36 | void AWSWebSocketClientAdapter::webSocketEvent(WStype_t type, uint8_t * payload, size_t length)
37 | {
38 | switch(type) {
39 | case WStype_DISCONNECTED:
40 | isConnected = false;
41 | break;
42 | case WStype_CONNECTED:
43 | isConnected = true;
44 | break;
45 | case WStype_TEXT:
46 | fifo.push(payload, length);
47 | break;
48 | case WStype_BIN:
49 | fifo.push(payload, length);
50 | break;
51 | }
52 | }
53 |
54 | /*
55 | * Completely disregards arguments. Uses config values instead.
56 | *
57 | * Returns true if successful, false otherwise
58 | */
59 | int AWSWebSocketClientAdapter::connect(IPAddress ip, uint16_t p)
60 | {
61 | return connect(0, 0);
62 | }
63 |
64 | /*
65 | * Completely disregards arguments. Uses config values instead.
66 | *
67 | * Returns true if successful, false otherwise
68 | */
69 | int AWSWebSocketClientAdapter::connect(const char *h, uint16_t p)
70 | {
71 | const char* host = params.getHost();
72 | const int port = params.getPort();
73 | const char* path = params.getPath();
74 | const char* fingerprint = params.getFingerprint();
75 | const char* protocol = params.getProtocol();
76 | const bool useSsl = params.useSsl();
77 |
78 | if (useSsl) {
79 | ws.beginSSL(host, port, path, fingerprint, protocol);
80 | } else {
81 | ws.begin(host, port, path, fingerprint);
82 | }
83 |
84 | // Wait until connected
85 | long connectionTimeout = 5000;
86 | long now = millis();
87 | while((millis() - now) < connectionTimeout) {
88 | ws.loop();
89 | if(connected()) return true;
90 | delay (10);
91 | }
92 | return false;
93 | }
94 |
95 | size_t AWSWebSocketClientAdapter::write(uint8_t b)
96 | {
97 | if (!connected())
98 | return 0;
99 |
100 | return write (&b,1);;
101 | }
102 |
103 | size_t AWSWebSocketClientAdapter::write(const uint8_t *buf, size_t size)
104 | {
105 | if (!connected())
106 | return 0;
107 |
108 | if (ws.sendBIN(buf,size))
109 | return size;
110 |
111 | return 0;
112 | }
113 |
114 | int AWSWebSocketClientAdapter::available()
115 | {
116 | if (!connected())
117 | return false;
118 |
119 | ws.loop();
120 |
121 | return fifo.getSize();
122 | }
123 |
124 | int AWSWebSocketClientAdapter::read()
125 | {
126 | if (!connected())
127 | return EXIT_FAILURE;
128 |
129 | return fifo.pop();
130 | }
131 |
132 | int AWSWebSocketClientAdapter::read(uint8_t *buf, size_t size)
133 | {
134 | if (!connected())
135 | return EXIT_FAILURE;
136 |
137 | int s = (fifo.getSize() < size) ? fifo.getSize() : size;
138 | fifo.pop(buf, s);
139 |
140 | return s;
141 | }
142 |
143 | int AWSWebSocketClientAdapter::peek()
144 | {
145 | if (!connected())
146 | return EXIT_FAILURE;
147 |
148 | return fifo.peek();
149 | }
150 |
151 | void AWSWebSocketClientAdapter::flush()
152 | {
153 | // do nothing
154 | }
155 |
156 | void AWSWebSocketClientAdapter::stop()
157 | {
158 | if(connected()) {
159 | isConnected = false;
160 | fifo.clear();
161 | }
162 | ws.disconnect();
163 | }
164 |
165 | uint8_t AWSWebSocketClientAdapter::connected()
166 | {
167 | return isConnected;
168 | }
169 |
170 | AWSWebSocketClientAdapter::operator bool()
171 | {
172 | return isConnected;
173 | }
174 |
--------------------------------------------------------------------------------
/src/ws/WebSocketClientAdapter.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Tomas Nilsson (joekickass)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 |
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | #ifndef WEBSOCKETCLIENTADAPTER_H_
18 | #define WEBSOCKETCLIENTADAPTER_H_
19 |
20 | #include
21 | #include
22 | #include
23 |
24 | #include "ws/CircularByteBuffer.h"
25 |
26 | /*
27 | * WebSocketParams provides connection parameters for the AWSWebSocketClientAdapter
28 | *
29 | * Using an abstract class instead of a plain data struct allows parameters that
30 | * are more dynamic in nature, such as signatures based on current date/time.
31 | * An example of this is AWS sigv4 signature authentication
32 | */
33 | class WebSocketParams
34 | {
35 | public:
36 | virtual char* getHost() =0;
37 | virtual unsigned int getPort() =0;
38 | virtual char* getPath() =0;
39 | virtual char* getFingerprint() =0;
40 | virtual char* getProtocol() =0;
41 | virtual bool useSsl() =0;
42 | virtual ~WebSocketParams() =0;
43 | };
44 |
45 | /**
46 | * Implements the Arduino Client interface used by mqtt client and IpStack,
47 | * see https://github.com/esp8266/Arduino/blob/master/cores/esp8266/Client.h
48 | *
49 | * Delegates to WebSockets for Arduino.
50 | *
51 | * Note that adapting the Client.h interface to a websocket implementation can
52 | * not really be done in a good way. Client.h is a TCP/IP layer interface and
53 | * uses only hosts and ports for addressing. Websockets, on the other hand, is a
54 | * higher layer protocol. It's an independent TCP-based protocol with a
55 | * handshake that mimics a HTTP upgrade request, after which it establishes an
56 | * open, two-way connection. Websockets thus uses port 80 (or 443 for TLS) and
57 | * URL addressing (most notably path and protocol arguments), which is not
58 | * really possible to squeeze into a TCP/IP interface. This is instead passed
59 | * to the adapter at creation time.
60 | */
61 | class AWSWebSocketClientAdapter : public Client
62 | {
63 | public:
64 |
65 | AWSWebSocketClientAdapter(WebSocketParams& p, size_t bufferSize = 1000);
66 | ~AWSWebSocketClientAdapter();
67 |
68 | // Arduino Client.h interface
69 | virtual int connect(IPAddress ip, uint16_t port);
70 | virtual int connect(const char *host, uint16_t port);
71 | virtual size_t write(uint8_t b);
72 | virtual size_t write(const uint8_t *buf, size_t size);
73 | virtual int available();
74 | virtual int read();
75 | virtual int read(uint8_t *buf, size_t size);
76 | virtual int peek();
77 | virtual void flush();
78 | virtual void stop();
79 | virtual uint8_t connected();
80 | virtual operator bool();
81 |
82 | private:
83 |
84 | // Websocket implementation
85 | WebSocketsClient ws;
86 |
87 | // Used for buffering data when reading/writing
88 | CircularByteBuffer fifo;
89 |
90 | // Connection params used instead of connect() arguments
91 | WebSocketParams& params;
92 |
93 | // Tracks connection state
94 | bool isConnected;
95 |
96 | // Callback handling websocket events
97 | void webSocketEvent(WStype_t type, uint8_t * payload, size_t length);
98 | };
99 |
100 | #endif
101 |
--------------------------------------------------------------------------------