serial-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,690 @@
1
+ Copyright (C) 2026 danidoble
2
+
3
+ This program is free software: you can redistribute it and/or modify
4
+ it under the terms of the GNU General Public License as published by
5
+ the Free Software Foundation, either version 3 of the License, or
6
+ (at your option) any later version.
7
+
8
+ This program is distributed in the hope that it will be useful,
9
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ GNU General Public License for more details.
12
+
13
+ You should have received a copy of the GNU General Public License
14
+ along with this program. If not, see https://www.gnu.org/licenses/.
15
+
16
+ # GNU GENERAL PUBLIC LICENSE
17
+
18
+ Version 3, 29 June 2007
19
+
20
+ Copyright (C) 2007 Free Software Foundation, Inc.
21
+ <https://fsf.org/>
22
+
23
+ Everyone is permitted to copy and distribute verbatim copies of this
24
+ license document, but changing it is not allowed.
25
+
26
+ ## Preamble
27
+
28
+ The GNU General Public License is a free, copyleft license for
29
+ software and other kinds of works.
30
+
31
+ The licenses for most software and other practical works are designed
32
+ to take away your freedom to share and change the works. By contrast,
33
+ the GNU General Public License is intended to guarantee your freedom
34
+ to share and change all versions of a program--to make sure it remains
35
+ free software for all its users. We, the Free Software Foundation, use
36
+ the GNU General Public License for most of our software; it applies
37
+ also to any other work released this way by its authors. You can apply
38
+ it to your programs, too.
39
+
40
+ When we speak of free software, we are referring to freedom, not
41
+ price. Our General Public Licenses are designed to make sure that you
42
+ have the freedom to distribute copies of free software (and charge for
43
+ them if you wish), that you receive source code or can get it if you
44
+ want it, that you can change the software or use pieces of it in new
45
+ free programs, and that you know you can do these things.
46
+
47
+ To protect your rights, we need to prevent others from denying you
48
+ these rights or asking you to surrender the rights. Therefore, you
49
+ have certain responsibilities if you distribute copies of the
50
+ software, or if you modify it: responsibilities to respect the freedom
51
+ of others.
52
+
53
+ For example, if you distribute copies of such a program, whether
54
+ gratis or for a fee, you must pass on to the recipients the same
55
+ freedoms that you received. You must make sure that they, too, receive
56
+ or can get the source code. And you must show them these terms so they
57
+ know their rights.
58
+
59
+ Developers that use the GNU GPL protect your rights with two steps:
60
+ (1) assert copyright on the software, and (2) offer you this License
61
+ giving you legal permission to copy, distribute and/or modify it.
62
+
63
+ For the developers' and authors' protection, the GPL clearly explains
64
+ that there is no warranty for this free software. For both users' and
65
+ authors' sake, the GPL requires that modified versions be marked as
66
+ changed, so that their problems will not be attributed erroneously to
67
+ authors of previous versions.
68
+
69
+ Some devices are designed to deny users access to install or run
70
+ modified versions of the software inside them, although the
71
+ manufacturer can do so. This is fundamentally incompatible with the
72
+ aim of protecting users' freedom to change the software. The
73
+ systematic pattern of such abuse occurs in the area of products for
74
+ individuals to use, which is precisely where it is most unacceptable.
75
+ Therefore, we have designed this version of the GPL to prohibit the
76
+ practice for those products. If such problems arise substantially in
77
+ other domains, we stand ready to extend this provision to those
78
+ domains in future versions of the GPL, as needed to protect the
79
+ freedom of users.
80
+
81
+ Finally, every program is threatened constantly by software patents.
82
+ States should not allow patents to restrict development and use of
83
+ software on general-purpose computers, but in those that do, we wish
84
+ to avoid the special danger that patents applied to a free program
85
+ could make it effectively proprietary. To prevent this, the GPL
86
+ assures that patents cannot be used to render the program non-free.
87
+
88
+ The precise terms and conditions for copying, distribution and
89
+ modification follow.
90
+
91
+ ## TERMS AND CONDITIONS
92
+
93
+ ### 0. Definitions.
94
+
95
+ "This License" refers to version 3 of the GNU General Public License.
96
+
97
+ "Copyright" also means copyright-like laws that apply to other kinds
98
+ of works, such as semiconductor masks.
99
+
100
+ "The Program" refers to any copyrightable work licensed under this
101
+ License. Each licensee is addressed as "you". "Licensees" and
102
+ "recipients" may be individuals or organizations.
103
+
104
+ To "modify" a work means to copy from or adapt all or part of the work
105
+ in a fashion requiring copyright permission, other than the making of
106
+ an exact copy. The resulting work is called a "modified version" of
107
+ the earlier work or a work "based on" the earlier work.
108
+
109
+ A "covered work" means either the unmodified Program or a work based
110
+ on the Program.
111
+
112
+ To "propagate" a work means to do anything with it that, without
113
+ permission, would make you directly or secondarily liable for
114
+ infringement under applicable copyright law, except executing it on a
115
+ computer or modifying a private copy. Propagation includes copying,
116
+ distribution (with or without modification), making available to the
117
+ public, and in some countries other activities as well.
118
+
119
+ To "convey" a work means any kind of propagation that enables other
120
+ parties to make or receive copies. Mere interaction with a user
121
+ through a computer network, with no transfer of a copy, is not
122
+ conveying.
123
+
124
+ An interactive user interface displays "Appropriate Legal Notices" to
125
+ the extent that it includes a convenient and prominently visible
126
+ feature that (1) displays an appropriate copyright notice, and (2)
127
+ tells the user that there is no warranty for the work (except to the
128
+ extent that warranties are provided), that licensees may convey the
129
+ work under this License, and how to view a copy of this License. If
130
+ the interface presents a list of user commands or options, such as a
131
+ menu, a prominent item in the list meets this criterion.
132
+
133
+ ### 1. Source Code.
134
+
135
+ The "source code" for a work means the preferred form of the work for
136
+ making modifications to it. "Object code" means any non-source form of
137
+ a work.
138
+
139
+ A "Standard Interface" means an interface that either is an official
140
+ standard defined by a recognized standards body, or, in the case of
141
+ interfaces specified for a particular programming language, one that
142
+ is widely used among developers working in that language.
143
+
144
+ The "System Libraries" of an executable work include anything, other
145
+ than the work as a whole, that (a) is included in the normal form of
146
+ packaging a Major Component, but which is not part of that Major
147
+ Component, and (b) serves only to enable use of the work with that
148
+ Major Component, or to implement a Standard Interface for which an
149
+ implementation is available to the public in source code form. A
150
+ "Major Component", in this context, means a major essential component
151
+ (kernel, window system, and so on) of the specific operating system
152
+ (if any) on which the executable work runs, or a compiler used to
153
+ produce the work, or an object code interpreter used to run it.
154
+
155
+ The "Corresponding Source" for a work in object code form means all
156
+ the source code needed to generate, install, and (for an executable
157
+ work) run the object code and to modify the work, including scripts to
158
+ control those activities. However, it does not include the work's
159
+ System Libraries, or general-purpose tools or generally available free
160
+ programs which are used unmodified in performing those activities but
161
+ which are not part of the work. For example, Corresponding Source
162
+ includes interface definition files associated with source files for
163
+ the work, and the source code for shared libraries and dynamically
164
+ linked subprograms that the work is specifically designed to require,
165
+ such as by intimate data communication or control flow between those
166
+ subprograms and other parts of the work.
167
+
168
+ The Corresponding Source need not include anything that users can
169
+ regenerate automatically from other parts of the Corresponding Source.
170
+
171
+ The Corresponding Source for a work in source code form is that same
172
+ work.
173
+
174
+ ### 2. Basic Permissions.
175
+
176
+ All rights granted under this License are granted for the term of
177
+ copyright on the Program, and are irrevocable provided the stated
178
+ conditions are met. This License explicitly affirms your unlimited
179
+ permission to run the unmodified Program. The output from running a
180
+ covered work is covered by this License only if the output, given its
181
+ content, constitutes a covered work. This License acknowledges your
182
+ rights of fair use or other equivalent, as provided by copyright law.
183
+
184
+ You may make, run and propagate covered works that you do not convey,
185
+ without conditions so long as your license otherwise remains in force.
186
+ You may convey covered works to others for the sole purpose of having
187
+ them make modifications exclusively for you, or provide you with
188
+ facilities for running those works, provided that you comply with the
189
+ terms of this License in conveying all material for which you do not
190
+ control copyright. Those thus making or running the covered works for
191
+ you must do so exclusively on your behalf, under your direction and
192
+ control, on terms that prohibit them from making any copies of your
193
+ copyrighted material outside their relationship with you.
194
+
195
+ Conveying under any other circumstances is permitted solely under the
196
+ conditions stated below. Sublicensing is not allowed; section 10 makes
197
+ it unnecessary.
198
+
199
+ ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
200
+
201
+ No covered work shall be deemed part of an effective technological
202
+ measure under any applicable law fulfilling obligations under article
203
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
204
+ similar laws prohibiting or restricting circumvention of such
205
+ measures.
206
+
207
+ When you convey a covered work, you waive any legal power to forbid
208
+ circumvention of technological measures to the extent such
209
+ circumvention is effected by exercising rights under this License with
210
+ respect to the covered work, and you disclaim any intention to limit
211
+ operation or modification of the work as a means of enforcing, against
212
+ the work's users, your or third parties' legal rights to forbid
213
+ circumvention of technological measures.
214
+
215
+ ### 4. Conveying Verbatim Copies.
216
+
217
+ You may convey verbatim copies of the Program's source code as you
218
+ receive it, in any medium, provided that you conspicuously and
219
+ appropriately publish on each copy an appropriate copyright notice;
220
+ keep intact all notices stating that this License and any
221
+ non-permissive terms added in accord with section 7 apply to the code;
222
+ keep intact all notices of the absence of any warranty; and give all
223
+ recipients a copy of this License along with the Program.
224
+
225
+ You may charge any price or no price for each copy that you convey,
226
+ and you may offer support or warranty protection for a fee.
227
+
228
+ ### 5. Conveying Modified Source Versions.
229
+
230
+ You may convey a work based on the Program, or the modifications to
231
+ produce it from the Program, in the form of source code under the
232
+ terms of section 4, provided that you also meet all of these
233
+ conditions:
234
+
235
+ - a) The work must carry prominent notices stating that you modified
236
+ it, and giving a relevant date.
237
+ - b) The work must carry prominent notices stating that it is
238
+ released under this License and any conditions added under
239
+ section 7. This requirement modifies the requirement in section 4
240
+ to "keep intact all notices".
241
+ - c) You must license the entire work, as a whole, under this
242
+ License to anyone who comes into possession of a copy. This
243
+ License will therefore apply, along with any applicable section 7
244
+ additional terms, to the whole of the work, and all its parts,
245
+ regardless of how they are packaged. This License gives no
246
+ permission to license the work in any other way, but it does not
247
+ invalidate such permission if you have separately received it.
248
+ - d) If the work has interactive user interfaces, each must display
249
+ Appropriate Legal Notices; however, if the Program has interactive
250
+ interfaces that do not display Appropriate Legal Notices, your
251
+ work need not make them do so.
252
+
253
+ A compilation of a covered work with other separate and independent
254
+ works, which are not by their nature extensions of the covered work,
255
+ and which are not combined with it such as to form a larger program,
256
+ in or on a volume of a storage or distribution medium, is called an
257
+ "aggregate" if the compilation and its resulting copyright are not
258
+ used to limit the access or legal rights of the compilation's users
259
+ beyond what the individual works permit. Inclusion of a covered work
260
+ in an aggregate does not cause this License to apply to the other
261
+ parts of the aggregate.
262
+
263
+ ### 6. Conveying Non-Source Forms.
264
+
265
+ You may convey a covered work in object code form under the terms of
266
+ sections 4 and 5, provided that you also convey the machine-readable
267
+ Corresponding Source under the terms of this License, in one of these
268
+ ways:
269
+
270
+ - a) Convey the object code in, or embodied in, a physical product
271
+ (including a physical distribution medium), accompanied by the
272
+ Corresponding Source fixed on a durable physical medium
273
+ customarily used for software interchange.
274
+ - b) Convey the object code in, or embodied in, a physical product
275
+ (including a physical distribution medium), accompanied by a
276
+ written offer, valid for at least three years and valid for as
277
+ long as you offer spare parts or customer support for that product
278
+ model, to give anyone who possesses the object code either (1) a
279
+ copy of the Corresponding Source for all the software in the
280
+ product that is covered by this License, on a durable physical
281
+ medium customarily used for software interchange, for a price no
282
+ more than your reasonable cost of physically performing this
283
+ conveying of source, or (2) access to copy the Corresponding
284
+ Source from a network server at no charge.
285
+ - c) Convey individual copies of the object code with a copy of the
286
+ written offer to provide the Corresponding Source. This
287
+ alternative is allowed only occasionally and noncommercially, and
288
+ only if you received the object code with such an offer, in accord
289
+ with subsection 6b.
290
+ - d) Convey the object code by offering access from a designated
291
+ place (gratis or for a charge), and offer equivalent access to the
292
+ Corresponding Source in the same way through the same place at no
293
+ further charge. You need not require recipients to copy the
294
+ Corresponding Source along with the object code. If the place to
295
+ copy the object code is a network server, the Corresponding Source
296
+ may be on a different server (operated by you or a third party)
297
+ that supports equivalent copying facilities, provided you maintain
298
+ clear directions next to the object code saying where to find the
299
+ Corresponding Source. Regardless of what server hosts the
300
+ Corresponding Source, you remain obligated to ensure that it is
301
+ available for as long as needed to satisfy these requirements.
302
+ - e) Convey the object code using peer-to-peer transmission,
303
+ provided you inform other peers where the object code and
304
+ Corresponding Source of the work are being offered to the general
305
+ public at no charge under subsection 6d.
306
+
307
+ A separable portion of the object code, whose source code is excluded
308
+ from the Corresponding Source as a System Library, need not be
309
+ included in conveying the object code work.
310
+
311
+ A "User Product" is either (1) a "consumer product", which means any
312
+ tangible personal property which is normally used for personal,
313
+ family, or household purposes, or (2) anything designed or sold for
314
+ incorporation into a dwelling. In determining whether a product is a
315
+ consumer product, doubtful cases shall be resolved in favor of
316
+ coverage. For a particular product received by a particular user,
317
+ "normally used" refers to a typical or common use of that class of
318
+ product, regardless of the status of the particular user or of the way
319
+ in which the particular user actually uses, or expects or is expected
320
+ to use, the product. A product is a consumer product regardless of
321
+ whether the product has substantial commercial, industrial or
322
+ non-consumer uses, unless such uses represent the only significant
323
+ mode of use of the product.
324
+
325
+ "Installation Information" for a User Product means any methods,
326
+ procedures, authorization keys, or other information required to
327
+ install and execute modified versions of a covered work in that User
328
+ Product from a modified version of its Corresponding Source. The
329
+ information must suffice to ensure that the continued functioning of
330
+ the modified object code is in no case prevented or interfered with
331
+ solely because modification has been made.
332
+
333
+ If you convey an object code work under this section in, or with, or
334
+ specifically for use in, a User Product, and the conveying occurs as
335
+ part of a transaction in which the right of possession and use of the
336
+ User Product is transferred to the recipient in perpetuity or for a
337
+ fixed term (regardless of how the transaction is characterized), the
338
+ Corresponding Source conveyed under this section must be accompanied
339
+ by the Installation Information. But this requirement does not apply
340
+ if neither you nor any third party retains the ability to install
341
+ modified object code on the User Product (for example, the work has
342
+ been installed in ROM).
343
+
344
+ The requirement to provide Installation Information does not include a
345
+ requirement to continue to provide support service, warranty, or
346
+ updates for a work that has been modified or installed by the
347
+ recipient, or for the User Product in which it has been modified or
348
+ installed. Access to a network may be denied when the modification
349
+ itself materially and adversely affects the operation of the network
350
+ or violates the rules and protocols for communication across the
351
+ network.
352
+
353
+ Corresponding Source conveyed, and Installation Information provided,
354
+ in accord with this section must be in a format that is publicly
355
+ documented (and with an implementation available to the public in
356
+ source code form), and must require no special password or key for
357
+ unpacking, reading or copying.
358
+
359
+ ### 7. Additional Terms.
360
+
361
+ "Additional permissions" are terms that supplement the terms of this
362
+ License by making exceptions from one or more of its conditions.
363
+ Additional permissions that are applicable to the entire Program shall
364
+ be treated as though they were included in this License, to the extent
365
+ that they are valid under applicable law. If additional permissions
366
+ apply only to part of the Program, that part may be used separately
367
+ under those permissions, but the entire Program remains governed by
368
+ this License without regard to the additional permissions.
369
+
370
+ When you convey a copy of a covered work, you may at your option
371
+ remove any additional permissions from that copy, or from any part of
372
+ it. (Additional permissions may be written to require their own
373
+ removal in certain cases when you modify the work.) You may place
374
+ additional permissions on material, added by you to a covered work,
375
+ for which you have or can give appropriate copyright permission.
376
+
377
+ Notwithstanding any other provision of this License, for material you
378
+ add to a covered work, you may (if authorized by the copyright holders
379
+ of that material) supplement the terms of this License with terms:
380
+
381
+ - a) Disclaiming warranty or limiting liability differently from the
382
+ terms of sections 15 and 16 of this License; or
383
+ - b) Requiring preservation of specified reasonable legal notices or
384
+ author attributions in that material or in the Appropriate Legal
385
+ Notices displayed by works containing it; or
386
+ - c) Prohibiting misrepresentation of the origin of that material,
387
+ or requiring that modified versions of such material be marked in
388
+ reasonable ways as different from the original version; or
389
+ - d) Limiting the use for publicity purposes of names of licensors
390
+ or authors of the material; or
391
+ - e) Declining to grant rights under trademark law for use of some
392
+ trade names, trademarks, or service marks; or
393
+ - f) Requiring indemnification of licensors and authors of that
394
+ material by anyone who conveys the material (or modified versions
395
+ of it) with contractual assumptions of liability to the recipient,
396
+ for any liability that these contractual assumptions directly
397
+ impose on those licensors and authors.
398
+
399
+ All other non-permissive additional terms are considered "further
400
+ restrictions" within the meaning of section 10. If the Program as you
401
+ received it, or any part of it, contains a notice stating that it is
402
+ governed by this License along with a term that is a further
403
+ restriction, you may remove that term. If a license document contains
404
+ a further restriction but permits relicensing or conveying under this
405
+ License, you may add to a covered work material governed by the terms
406
+ of that license document, provided that the further restriction does
407
+ not survive such relicensing or conveying.
408
+
409
+ If you add terms to a covered work in accord with this section, you
410
+ must place, in the relevant source files, a statement of the
411
+ additional terms that apply to those files, or a notice indicating
412
+ where to find the applicable terms.
413
+
414
+ Additional terms, permissive or non-permissive, may be stated in the
415
+ form of a separately written license, or stated as exceptions; the
416
+ above requirements apply either way.
417
+
418
+ ### 8. Termination.
419
+
420
+ You may not propagate or modify a covered work except as expressly
421
+ provided under this License. Any attempt otherwise to propagate or
422
+ modify it is void, and will automatically terminate your rights under
423
+ this License (including any patent licenses granted under the third
424
+ paragraph of section 11).
425
+
426
+ However, if you cease all violation of this License, then your license
427
+ from a particular copyright holder is reinstated (a) provisionally,
428
+ unless and until the copyright holder explicitly and finally
429
+ terminates your license, and (b) permanently, if the copyright holder
430
+ fails to notify you of the violation by some reasonable means prior to
431
+ 60 days after the cessation.
432
+
433
+ Moreover, your license from a particular copyright holder is
434
+ reinstated permanently if the copyright holder notifies you of the
435
+ violation by some reasonable means, this is the first time you have
436
+ received notice of violation of this License (for any work) from that
437
+ copyright holder, and you cure the violation prior to 30 days after
438
+ your receipt of the notice.
439
+
440
+ Termination of your rights under this section does not terminate the
441
+ licenses of parties who have received copies or rights from you under
442
+ this License. If your rights have been terminated and not permanently
443
+ reinstated, you do not qualify to receive new licenses for the same
444
+ material under section 10.
445
+
446
+ ### 9. Acceptance Not Required for Having Copies.
447
+
448
+ You are not required to accept this License in order to receive or run
449
+ a copy of the Program. Ancillary propagation of a covered work
450
+ occurring solely as a consequence of using peer-to-peer transmission
451
+ to receive a copy likewise does not require acceptance. However,
452
+ nothing other than this License grants you permission to propagate or
453
+ modify any covered work. These actions infringe copyright if you do
454
+ not accept this License. Therefore, by modifying or propagating a
455
+ covered work, you indicate your acceptance of this License to do so.
456
+
457
+ ### 10. Automatic Licensing of Downstream Recipients.
458
+
459
+ Each time you convey a covered work, the recipient automatically
460
+ receives a license from the original licensors, to run, modify and
461
+ propagate that work, subject to this License. You are not responsible
462
+ for enforcing compliance by third parties with this License.
463
+
464
+ An "entity transaction" is a transaction transferring control of an
465
+ organization, or substantially all assets of one, or subdividing an
466
+ organization, or merging organizations. If propagation of a covered
467
+ work results from an entity transaction, each party to that
468
+ transaction who receives a copy of the work also receives whatever
469
+ licenses to the work the party's predecessor in interest had or could
470
+ give under the previous paragraph, plus a right to possession of the
471
+ Corresponding Source of the work from the predecessor in interest, if
472
+ the predecessor has it or can get it with reasonable efforts.
473
+
474
+ You may not impose any further restrictions on the exercise of the
475
+ rights granted or affirmed under this License. For example, you may
476
+ not impose a license fee, royalty, or other charge for exercise of
477
+ rights granted under this License, and you may not initiate litigation
478
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
479
+ any patent claim is infringed by making, using, selling, offering for
480
+ sale, or importing the Program or any portion of it.
481
+
482
+ ### 11. Patents.
483
+
484
+ A "contributor" is a copyright holder who authorizes use under this
485
+ License of the Program or a work on which the Program is based. The
486
+ work thus licensed is called the contributor's "contributor version".
487
+
488
+ A contributor's "essential patent claims" are all patent claims owned
489
+ or controlled by the contributor, whether already acquired or
490
+ hereafter acquired, that would be infringed by some manner, permitted
491
+ by this License, of making, using, or selling its contributor version,
492
+ but do not include claims that would be infringed only as a
493
+ consequence of further modification of the contributor version. For
494
+ purposes of this definition, "control" includes the right to grant
495
+ patent sublicenses in a manner consistent with the requirements of
496
+ this License.
497
+
498
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
499
+ patent license under the contributor's essential patent claims, to
500
+ make, use, sell, offer for sale, import and otherwise run, modify and
501
+ propagate the contents of its contributor version.
502
+
503
+ In the following three paragraphs, a "patent license" is any express
504
+ agreement or commitment, however denominated, not to enforce a patent
505
+ (such as an express permission to practice a patent or covenant not to
506
+ sue for patent infringement). To "grant" such a patent license to a
507
+ party means to make such an agreement or commitment not to enforce a
508
+ patent against the party.
509
+
510
+ If you convey a covered work, knowingly relying on a patent license,
511
+ and the Corresponding Source of the work is not available for anyone
512
+ to copy, free of charge and under the terms of this License, through a
513
+ publicly available network server or other readily accessible means,
514
+ then you must either (1) cause the Corresponding Source to be so
515
+ available, or (2) arrange to deprive yourself of the benefit of the
516
+ patent license for this particular work, or (3) arrange, in a manner
517
+ consistent with the requirements of this License, to extend the patent
518
+ license to downstream recipients. "Knowingly relying" means you have
519
+ actual knowledge that, but for the patent license, your conveying the
520
+ covered work in a country, or your recipient's use of the covered work
521
+ in a country, would infringe one or more identifiable patents in that
522
+ country that you have reason to believe are valid.
523
+
524
+ If, pursuant to or in connection with a single transaction or
525
+ arrangement, you convey, or propagate by procuring conveyance of, a
526
+ covered work, and grant a patent license to some of the parties
527
+ receiving the covered work authorizing them to use, propagate, modify
528
+ or convey a specific copy of the covered work, then the patent license
529
+ you grant is automatically extended to all recipients of the covered
530
+ work and works based on it.
531
+
532
+ A patent license is "discriminatory" if it does not include within the
533
+ scope of its coverage, prohibits the exercise of, or is conditioned on
534
+ the non-exercise of one or more of the rights that are specifically
535
+ granted under this License. You may not convey a covered work if you
536
+ are a party to an arrangement with a third party that is in the
537
+ business of distributing software, under which you make payment to the
538
+ third party based on the extent of your activity of conveying the
539
+ work, and under which the third party grants, to any of the parties
540
+ who would receive the covered work from you, a discriminatory patent
541
+ license (a) in connection with copies of the covered work conveyed by
542
+ you (or copies made from those copies), or (b) primarily for and in
543
+ connection with specific products or compilations that contain the
544
+ covered work, unless you entered into that arrangement, or that patent
545
+ license was granted, prior to 28 March 2007.
546
+
547
+ Nothing in this License shall be construed as excluding or limiting
548
+ any implied license or other defenses to infringement that may
549
+ otherwise be available to you under applicable patent law.
550
+
551
+ ### 12. No Surrender of Others' Freedom.
552
+
553
+ If conditions are imposed on you (whether by court order, agreement or
554
+ otherwise) that contradict the conditions of this License, they do not
555
+ excuse you from the conditions of this License. If you cannot convey a
556
+ covered work so as to satisfy simultaneously your obligations under
557
+ this License and any other pertinent obligations, then as a
558
+ consequence you may not convey it at all. For example, if you agree to
559
+ terms that obligate you to collect a royalty for further conveying
560
+ from those to whom you convey the Program, the only way you could
561
+ satisfy both those terms and this License would be to refrain entirely
562
+ from conveying the Program.
563
+
564
+ ### 13. Use with the GNU Affero General Public License.
565
+
566
+ Notwithstanding any other provision of this License, you have
567
+ permission to link or combine any covered work with a work licensed
568
+ under version 3 of the GNU Affero General Public License into a single
569
+ combined work, and to convey the resulting work. The terms of this
570
+ License will continue to apply to the part which is the covered work,
571
+ but the special requirements of the GNU Affero General Public License,
572
+ section 13, concerning interaction through a network will apply to the
573
+ combination as such.
574
+
575
+ ### 14. Revised Versions of this License.
576
+
577
+ The Free Software Foundation may publish revised and/or new versions
578
+ of the GNU General Public License from time to time. Such new versions
579
+ will be similar in spirit to the present version, but may differ in
580
+ detail to address new problems or concerns.
581
+
582
+ Each version is given a distinguishing version number. If the Program
583
+ specifies that a certain numbered version of the GNU General Public
584
+ License "or any later version" applies to it, you have the option of
585
+ following the terms and conditions either of that numbered version or
586
+ of any later version published by the Free Software Foundation. If the
587
+ Program does not specify a version number of the GNU General Public
588
+ License, you may choose any version ever published by the Free
589
+ Software Foundation.
590
+
591
+ If the Program specifies that a proxy can decide which future versions
592
+ of the GNU General Public License can be used, that proxy's public
593
+ statement of acceptance of a version permanently authorizes you to
594
+ choose that version for the Program.
595
+
596
+ Later license versions may give you additional or different
597
+ permissions. However, no additional obligations are imposed on any
598
+ author or copyright holder as a result of your choosing to follow a
599
+ later version.
600
+
601
+ ### 15. Disclaimer of Warranty.
602
+
603
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
604
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
605
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
606
+ WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
607
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
608
+ A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
609
+ PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
610
+ DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
611
+ CORRECTION.
612
+
613
+ ### 16. Limitation of Liability.
614
+
615
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
616
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
617
+ CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
618
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
619
+ ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
620
+ NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
621
+ LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
622
+ TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
623
+ PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
624
+
625
+ ### 17. Interpretation of Sections 15 and 16.
626
+
627
+ If the disclaimer of warranty and limitation of liability provided
628
+ above cannot be given local legal effect according to their terms,
629
+ reviewing courts shall apply local law that most closely approximates
630
+ an absolute waiver of all civil liability in connection with the
631
+ Program, unless a warranty or assumption of liability accompanies a
632
+ copy of the Program in return for a fee.
633
+
634
+ END OF TERMS AND CONDITIONS
635
+
636
+ ## How to Apply These Terms to Your New Programs
637
+
638
+ If you develop a new program, and you want it to be of the greatest
639
+ possible use to the public, the best way to achieve this is to make it
640
+ free software which everyone can redistribute and change under these
641
+ terms.
642
+
643
+ To do so, attach the following notices to the program. It is safest to
644
+ attach them to the start of each source file to most effectively state
645
+ the exclusion of warranty; and each file should have at least the
646
+ "copyright" line and a pointer to where the full notice is found.
647
+
648
+ <one line to give the program's name and a brief idea of what it does.>
649
+ Copyright (C) <year> <name of author>
650
+
651
+ This program is free software: you can redistribute it and/or modify
652
+ it under the terms of the GNU General Public License as published by
653
+ the Free Software Foundation, either version 3 of the License, or
654
+ (at your option) any later version.
655
+
656
+ This program is distributed in the hope that it will be useful,
657
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
658
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
659
+ GNU General Public License for more details.
660
+
661
+ You should have received a copy of the GNU General Public License
662
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
663
+
664
+ Also add information on how to contact you by electronic and paper
665
+ mail.
666
+
667
+ If the program does terminal interaction, make it output a short
668
+ notice like this when it starts in an interactive mode:
669
+
670
+ <program> Copyright (C) <year> <name of author>
671
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
672
+ This is free software, and you are welcome to redistribute it
673
+ under certain conditions; type `show c' for details.
674
+
675
+ The hypothetical commands \`show w' and \`show c' should show the
676
+ appropriate parts of the General Public License. Of course, your
677
+ program's commands might be different; for a GUI interface, you would
678
+ use an "about box".
679
+
680
+ You should also get your employer (if you work as a programmer) or
681
+ school, if any, to sign a "copyright disclaimer" for the program, if
682
+ necessary. For more information on this, and how to apply and follow
683
+ the GNU GPL, see <https://www.gnu.org/licenses/>.
684
+
685
+ The GNU General Public License does not permit incorporating your
686
+ program into proprietary programs. If your program is a subroutine
687
+ library, you may consider it more useful to permit linking proprietary
688
+ applications with the library. If this is what you want to do, use the
689
+ GNU Lesser General Public License instead of this License. But first,
690
+ please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
package/README.md ADDED
@@ -0,0 +1,154 @@
1
+ # serial-core
2
+
3
+ A easy way to work with serial ports in Node.js
4
+
5
+ ## Development
6
+
7
+ - Install dependencies:
8
+
9
+ ```bash
10
+ npm install
11
+ ```
12
+
13
+ - Run the unit tests:
14
+
15
+ ```bash
16
+ npm run test
17
+ ```
18
+
19
+ - Build the library:
20
+
21
+ ```bash
22
+ npm run build
23
+ ```
24
+
25
+ ## How to use
26
+
27
+ ### Using the Core Abstract Class
28
+
29
+ The `Core` class is an abstract base class that provides the foundation for working with serial ports. To use it, you need to create a class that extends `Core` and implement the abstract methods.
30
+
31
+ #### Basic Setup
32
+
33
+ 1. **Create a class that extends Core:**
34
+
35
+ ```typescript
36
+ import { Core } from './lib/serial/core';
37
+ import { SerialPort } from 'serialport';
38
+
39
+ class MySerialDevice extends Core {
40
+ constructor() {
41
+ super({ port: null });
42
+ }
43
+
44
+ // Implement abstract methods
45
+ protected initParser(): void {
46
+ // Initialize your data parser here
47
+ }
48
+
49
+ protected serialMessage(buffer: Buffer): void {
50
+ // Handle incoming serial data here
51
+ }
52
+ }
53
+ ```
54
+
55
+ #### Configuration
56
+
57
+ Before connecting, configure your serial port:
58
+
59
+ ```typescript
60
+ const device = new MySerialDevice();
61
+
62
+ // Set filters to automatically find your device (optional)
63
+ device.setFilters({
64
+ vendorId: '1234', // Optional: device vendor ID
65
+ productId: '5678' // Optional: device product ID
66
+ });
67
+
68
+ // Set port configuration
69
+ device.setConfig({
70
+ path: '/dev/ttyUSB0', // Port path (optional if using filters)
71
+ baudRate: 9600,
72
+ dataBits: 8,
73
+ stopBits: 1,
74
+ parity: 'none'
75
+ });
76
+ ```
77
+
78
+ #### Available Methods
79
+
80
+ **Connection Management:**
81
+ - `connect()`: Opens the serial port and establishes connection
82
+ - `disconnect()`: Closes the serial port and disconnects
83
+
84
+ **Configuration:**
85
+ - `setConfig(config)`: Set port configuration options
86
+ - `getConfig()`: Get current port configuration
87
+ - `setFilters(filters)`: Set vendor/product ID filters for auto-discovery
88
+ - `getFilters()`: Get current filters
89
+
90
+ **Data Transmission:**
91
+ - `appendToQueue(bytes, action)`: Add data to the send queue
92
+ - `write()`: Send queued data
93
+
94
+ **Utility Methods:**
95
+ - `uint8ArrayToHexArray(array)`: Convert Uint8Array to hex array
96
+ - `stringToArrayHex(string)`: Convert string to hex array
97
+ - `asciiToHex(asciiString, joinWith)`: Convert ASCII to hex
98
+ - `fixHexArray(array, size)`: Normalize hex array values
99
+ - `getConnectionCmd()`: Get the connection command bytes
100
+
101
+ #### Example Usage
102
+
103
+ ```typescript
104
+ class ArduinoDevice extends Core {
105
+ protected initParser(): void {
106
+ // Setup your parser for incoming data
107
+ }
108
+
109
+ protected serialMessage(buffer: Buffer): void {
110
+ console.log('Data received:', buffer);
111
+ }
112
+ }
113
+
114
+ async function main() {
115
+ const arduino = new ArduinoDevice();
116
+
117
+ // Set device filters
118
+ arduino.setFilters({
119
+ vendorId: 'arduino_vendor_id'
120
+ });
121
+
122
+ // Connect to device
123
+ try {
124
+ await arduino.connect();
125
+ console.log('Connected!');
126
+ } catch (error) {
127
+ console.error('Failed to connect:', error);
128
+ }
129
+
130
+ // Listen to events
131
+ arduino.on('serial:connected', () => {
132
+ console.log('Device connected');
133
+ });
134
+
135
+ arduino.on('serial:sent', (data) => {
136
+ console.log('Data sent:', data);
137
+ });
138
+
139
+ arduino.on('serial:timeout', (error) => {
140
+ console.log('Timeout:', error);
141
+ });
142
+
143
+ // Later, disconnect
144
+ await arduino.disconnect();
145
+ }
146
+ ```
147
+
148
+ #### Events
149
+
150
+ The Core class extends `Dispatcher` and emits the following events:
151
+ - `serial:connected` - Emitted when device connects successfully
152
+ - `serial:disconnected` - Emitted when device disconnects
153
+ - `serial:sent` - Emitted after data is sent
154
+ - `serial:timeout` - Emitted when an operation times out
@@ -0,0 +1 @@
1
+ let e=require(`serialport`);var t=class extends CustomEvent{constructor(e,t){super(e,t)}},n=class extends EventTarget{_listeners={debug:!1};_debug=!1;_listenersCallbacks=[];dispatch(e,n={}){let r=new t(e,{detail:n});this.dispatchEvent(r),this._debug&&this.dispatchEvent(new t(`debug`,{detail:{type:e,data:n}}))}dispatchAsync(e,t={},n=100){setTimeout(()=>this.dispatch(e,t),n)}on(e,t){this._listeners[e]!==void 0&&!this._listeners[e]&&(this._listeners[e]=!0),this._listenersCallbacks.push({key:e,callback:t}),this.addEventListener(e,t)}off(e,t){this._listenersCallbacks=this._listenersCallbacks.filter(n=>!(n.key===e&&n.callback===t)),this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this._listeners[e]||(this._listeners[e]=!1)}get availableListeners(){return Object.keys(this._listeners).sort().map(e=>({type:e,listening:this._listeners[e]}))}removeAllListeners(){for(let e of this._listenersCallbacks)[`internal:queue`].includes(e.key)||(this._listenersCallbacks=this._listenersCallbacks.filter(t=>!(t.key===e.key&&t.callback===e.callback)),this.removeEventListener(e.key,e.callback));for(let e of Object.keys(this._listeners))this._listeners[e]=!1}},r=class extends n{config={path:``,baudRate:9600,dataBits:8,lock:!0,stopBits:1,parity:`none`,rtscts:!1,xon:!1,xoff:!1,xany:!1,hupcl:!0};filters={};port=null;queue=[];connectionCmd=null;timeoutAfterWrite=500;timeoutInstance=null;lastAction=null;wasConnected=!1;channelNumber=1;isConnected=!1;constructor({port:e=null}){super(),this.port=e,this.initListeners()}setFilters({vendorId:e,productId:t}){return this.filters={...this.filters,vendorId:e||null},this.filters={...this.filters,productId:t||null},this}getFilters(){return this.filters}setConfig(e){return this.config={...this.config,...e},this}getConfig(){return this.config}async getAvailablePorts(){return(await e.SerialPort.list()).filter(e=>!(!e.path||!e.vendorId||!e.productId||this.filters.vendorId&&e.vendorId.toLowerCase()!==this.filters.vendorId.toLowerCase()||this.filters.productId&&e.productId.toLowerCase()!==this.filters.productId.toLowerCase()))}getConnectionCmd(){return this.connectionCmd}initListeners(){this.on(`internal:queue`,()=>this.runQueue())}async runQueue(){this.port&&this.port.isOpen&&this.queue.length!==0&&(this.timeoutInstance||await this.write())}async onTimeout(e,t){if(!this.wasConnected&&this.lastAction===`connection:start`){this.port?.close(),this.isConnected=!1,this.wasConnected=!1;return}this.timeoutInstance&&=(clearTimeout(this.timeoutInstance),null),this.dispatch(`internal:queue`),this.dispatch(`serial:timeout`,{message:`Operation timed out`,bytes:e,action:t}),console.error(`Timeout after write`,this.lastAction)}startListeningPort(){this.port&&(this.port.open(e=>{if(!this.port)return console.log(`Port is not defined`);if(e)return console.log(`Error opening port: `,e.message);if(!this.connectionCmd)throw Error(`Connection command is not defined`);this.lastAction=`connection:start`,this.timeoutInstance=setTimeout(()=>this.onTimeout(this.connectionCmd,this.lastAction),this.timeoutAfterWrite),this.port.write(this.connectionCmd)}),this.initParser())}onDataReceived(e){this.timeoutInstance&&=(clearTimeout(this.timeoutInstance),null),this.isConnected===!1&&(this.dispatch(`serial:connected`),this.wasConnected=!0,this.isConnected=!0),this.serialMessage(e),this.dispatch(`internal:queue`)}async write(){if(!this.port||this.queue.length===0)return;let e=this.queue[0];this.queue=this.queue.slice(1),this.lastAction=e.action||null,this.timeoutInstance=setTimeout(()=>this.onTimeout(e.bytes,this.lastAction),this.timeoutAfterWrite),this.port.write(e.bytes),this.dispatch(`serial:sent`,e)}async connect(){if(!this.port||!this.port.isOpen)return await this.openPort();if(!this.connectionCmd)throw Error(`Connection command is not defined`);this.appendToQueue(this.connectionCmd,this.port?.isOpen?`connect`:`connection:start`),this.dispatch(`internal:queue`)}async disconnect(){!this.port||!this.port.isOpen||(this.port.close(),this.isConnected=!1,this.wasConnected=!1,this.dispatch(`serial:disconnected`))}async appendToQueue(e,t){if([`connect`,`connection:start`].includes(t)&&(!this.port||!this.port.isOpen))return await this.openPort();this.queue.push({bytes:e,action:t}),this.dispatch(`internal:queue`)}async openPort(){if(this.port&&this.port.isOpen)return;if(this.port&&this.port instanceof e.SerialPortMock&&!this.port.isOpen){this.startListeningPort();return}let t=[],n=this.config;if(!this.config.path){if(t=await this.getAvailablePorts(),t.length===0)throw Error(`Port path is not defined`);t.length>1&&console.warn(`Multiple ports found, using the first one:`,t),n.path=t[0].path}this.port=new e.SerialPort({...n,autoOpen:!1}),this.startListeningPort()}stringToUint8Array(e){return console.warn(`stringToUint8Array is not recommended to use`),Buffer.from(e)}uint8ArrayToHexArray(e){return Array.from(e).map(e=>e.toString(16).toLowerCase().padStart(2,`0`))}stringToArrayHex(e){return Array.from(e).map(e=>e.charCodeAt(0).toString(16))}asciiToHex(e,t=``){let n=[];for(let t=0,r=e.length;t<r;t++){let r=Number(e.charCodeAt(t)).toString(16);n.push(r)}return n.join(t)}fixHexArray(e,t=2){return e.map(e=>typeof e==`string`?e.padStart(t,`0`).toLowerCase():e.toString(16).padStart(t,`0`).toLowerCase())}};exports.Core=r;
@@ -0,0 +1,140 @@
1
+ import { SerialPort, SerialPortMock } from "serialport";
2
+
3
+ //#region lib/types/events.d.ts
4
+
5
+ interface AvailableListener {
6
+ type: string;
7
+ listening: boolean;
8
+ }
9
+ type AvailableListeners = AvailableListener[];
10
+ type DataType = string | number | boolean | object | null;
11
+ // EventListenerOrEventListenerObject is not defined in node so we define it here
12
+ interface EventListener {
13
+ (evt: Event): void;
14
+ }
15
+ interface EventListenerObject {
16
+ handleEvent(object: Event): void;
17
+ }
18
+ type EventListenerOrEventListenerObject = EventListener | EventListenerObject | ((event: SerialEventListener) => void);
19
+ interface Dispatcher$1 {
20
+ dispatch(type: string, data?: DataType): void;
21
+ dispatchAsync(type: string, data?: DataType, ms?: number): void;
22
+ on(type: string, callback: EventListenerOrEventListenerObject): void;
23
+ off(type: string, callback: EventListenerOrEventListenerObject): void;
24
+ serialRegisterAvailableListener(type: string): void;
25
+ availableListeners: AvailableListeners;
26
+ }
27
+ interface Listeners {
28
+ [key: string]: boolean;
29
+ debug: boolean;
30
+ }
31
+ interface ListenersCallbacks {
32
+ key: string;
33
+ callback: EventListenerOrEventListenerObject;
34
+ }
35
+ //#endregion
36
+ //#region lib/events/dispatcher.d.ts
37
+ declare class Dispatcher extends EventTarget implements Dispatcher$1 {
38
+ protected _listeners: Listeners;
39
+ protected _debug: boolean;
40
+ protected _listenersCallbacks: ListenersCallbacks[];
41
+ dispatch(type: string, data?: DataType): void;
42
+ dispatchAsync(type: string, data?: DataType, ms?: number): void;
43
+ on(type: string, callback: EventListenerOrEventListenerObject): void;
44
+ off(type: string, callback: EventListenerOrEventListenerObject): void;
45
+ serialRegisterAvailableListener(type: string): void;
46
+ get availableListeners(): AvailableListeners;
47
+ removeAllListeners(): void;
48
+ }
49
+ //#endregion
50
+ //#region lib/types/core.d.ts
51
+ interface CoreConfig {
52
+ /** The system path of the serial port you want to open. For example, `/dev/tty.XXX` on Mac/Linux, or `COM1` on Windows */
53
+ path: string;
54
+ /**
55
+ * The baud rate of the port to be opened. This should match one of the commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, or 115200. Custom rates are supported best effort per platform. The device connected to the serial port is not guaranteed to support the requested baud rate, even if the port itself supports that baud rate.
56
+ */
57
+ baudRate: number;
58
+ /** Must be one of these: 5, 6, 7, or 8 defaults to 8 */
59
+ dataBits?: 5 | 6 | 7 | 8;
60
+ /** Prevent other processes from opening the port. Windows does not currently support `false`. Defaults to true */
61
+ lock?: boolean;
62
+ /** Must be 1, 1.5 or 2 defaults to 1 */
63
+ stopBits?: 1 | 1.5 | 2;
64
+ parity?: 'none' | 'even' | 'odd' | undefined;
65
+ /** Flow control Setting. Defaults to false */
66
+ rtscts?: boolean;
67
+ /** Flow control Setting. Defaults to false */
68
+ xon?: boolean;
69
+ /** Flow control Setting. Defaults to false */
70
+ xoff?: boolean;
71
+ /** Flow control Setting defaults to false*/
72
+ xany?: boolean;
73
+ /** drop DTR on close. Defaults to true */
74
+ hupcl?: boolean;
75
+ }
76
+ interface PortFilter {
77
+ vendorId?: string | null;
78
+ productId?: string | null;
79
+ }
80
+ interface PortInfo {
81
+ path: string;
82
+ manufacturer?: string;
83
+ serialNumber?: string;
84
+ pnpId?: string;
85
+ locationId?: string;
86
+ vendorId?: string;
87
+ productId?: string;
88
+ }
89
+ interface QueueItem {
90
+ action?: string;
91
+ bytes?: Uint8Array;
92
+ }
93
+ //#endregion
94
+ //#region lib/serial/core.d.ts
95
+ declare abstract class Core extends Dispatcher {
96
+ protected config: CoreConfig;
97
+ protected filters: PortFilter;
98
+ protected port: SerialPort | SerialPortMock | null;
99
+ protected queue: QueueItem[];
100
+ protected connectionCmd: Uint8Array | null;
101
+ protected timeoutAfterWrite: number;
102
+ protected timeoutInstance: ReturnType<typeof setTimeout> | null;
103
+ protected lastAction: null | string;
104
+ protected wasConnected: boolean;
105
+ channelNumber: number;
106
+ protected isConnected: boolean;
107
+ constructor({
108
+ port
109
+ }: {
110
+ port: SerialPort | SerialPortMock | null;
111
+ });
112
+ setFilters({
113
+ vendorId,
114
+ productId
115
+ }: PortFilter): Core;
116
+ getFilters(): PortFilter;
117
+ setConfig(config: CoreConfig): Core;
118
+ getConfig(): CoreConfig;
119
+ protected getAvailablePorts(): Promise<PortInfo[]>;
120
+ getConnectionCmd(): Uint8Array<ArrayBufferLike> | null;
121
+ protected initListeners(): void;
122
+ protected runQueue(): Promise<void>;
123
+ protected onTimeout(bytes: Uint8Array, event: string | null): Promise<void>;
124
+ protected startListeningPort(): void;
125
+ protected abstract initParser(): void;
126
+ protected onDataReceived(buffer: Buffer): void;
127
+ protected abstract serialMessage(buffer: Buffer): void;
128
+ protected write(): Promise<void>;
129
+ connect(): Promise<void>;
130
+ disconnect(): Promise<void>;
131
+ protected appendToQueue(bytes: Uint8Array, action: string): Promise<void>;
132
+ protected openPort(): Promise<void>;
133
+ stringToUint8Array(str: string): Uint8Array;
134
+ uint8ArrayToHexArray(array: Uint8Array): Array<string>;
135
+ stringToArrayHex(string: string): string[];
136
+ asciiToHex(asciiString: string, joinWith?: string): string;
137
+ fixHexArray(array: Array<string | number>, size?: number): string[];
138
+ }
139
+ //#endregion
140
+ export { Core };
@@ -0,0 +1,140 @@
1
+ import { SerialPort, SerialPortMock } from "serialport";
2
+
3
+ //#region lib/types/events.d.ts
4
+
5
+ interface AvailableListener {
6
+ type: string;
7
+ listening: boolean;
8
+ }
9
+ type AvailableListeners = AvailableListener[];
10
+ type DataType = string | number | boolean | object | null;
11
+ // EventListenerOrEventListenerObject is not defined in node so we define it here
12
+ interface EventListener {
13
+ (evt: Event): void;
14
+ }
15
+ interface EventListenerObject {
16
+ handleEvent(object: Event): void;
17
+ }
18
+ type EventListenerOrEventListenerObject = EventListener | EventListenerObject | ((event: SerialEventListener) => void);
19
+ interface Dispatcher$1 {
20
+ dispatch(type: string, data?: DataType): void;
21
+ dispatchAsync(type: string, data?: DataType, ms?: number): void;
22
+ on(type: string, callback: EventListenerOrEventListenerObject): void;
23
+ off(type: string, callback: EventListenerOrEventListenerObject): void;
24
+ serialRegisterAvailableListener(type: string): void;
25
+ availableListeners: AvailableListeners;
26
+ }
27
+ interface Listeners {
28
+ [key: string]: boolean;
29
+ debug: boolean;
30
+ }
31
+ interface ListenersCallbacks {
32
+ key: string;
33
+ callback: EventListenerOrEventListenerObject;
34
+ }
35
+ //#endregion
36
+ //#region lib/events/dispatcher.d.ts
37
+ declare class Dispatcher extends EventTarget implements Dispatcher$1 {
38
+ protected _listeners: Listeners;
39
+ protected _debug: boolean;
40
+ protected _listenersCallbacks: ListenersCallbacks[];
41
+ dispatch(type: string, data?: DataType): void;
42
+ dispatchAsync(type: string, data?: DataType, ms?: number): void;
43
+ on(type: string, callback: EventListenerOrEventListenerObject): void;
44
+ off(type: string, callback: EventListenerOrEventListenerObject): void;
45
+ serialRegisterAvailableListener(type: string): void;
46
+ get availableListeners(): AvailableListeners;
47
+ removeAllListeners(): void;
48
+ }
49
+ //#endregion
50
+ //#region lib/types/core.d.ts
51
+ interface CoreConfig {
52
+ /** The system path of the serial port you want to open. For example, `/dev/tty.XXX` on Mac/Linux, or `COM1` on Windows */
53
+ path: string;
54
+ /**
55
+ * The baud rate of the port to be opened. This should match one of the commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, or 115200. Custom rates are supported best effort per platform. The device connected to the serial port is not guaranteed to support the requested baud rate, even if the port itself supports that baud rate.
56
+ */
57
+ baudRate: number;
58
+ /** Must be one of these: 5, 6, 7, or 8 defaults to 8 */
59
+ dataBits?: 5 | 6 | 7 | 8;
60
+ /** Prevent other processes from opening the port. Windows does not currently support `false`. Defaults to true */
61
+ lock?: boolean;
62
+ /** Must be 1, 1.5 or 2 defaults to 1 */
63
+ stopBits?: 1 | 1.5 | 2;
64
+ parity?: 'none' | 'even' | 'odd' | undefined;
65
+ /** Flow control Setting. Defaults to false */
66
+ rtscts?: boolean;
67
+ /** Flow control Setting. Defaults to false */
68
+ xon?: boolean;
69
+ /** Flow control Setting. Defaults to false */
70
+ xoff?: boolean;
71
+ /** Flow control Setting defaults to false*/
72
+ xany?: boolean;
73
+ /** drop DTR on close. Defaults to true */
74
+ hupcl?: boolean;
75
+ }
76
+ interface PortFilter {
77
+ vendorId?: string | null;
78
+ productId?: string | null;
79
+ }
80
+ interface PortInfo {
81
+ path: string;
82
+ manufacturer?: string;
83
+ serialNumber?: string;
84
+ pnpId?: string;
85
+ locationId?: string;
86
+ vendorId?: string;
87
+ productId?: string;
88
+ }
89
+ interface QueueItem {
90
+ action?: string;
91
+ bytes?: Uint8Array;
92
+ }
93
+ //#endregion
94
+ //#region lib/serial/core.d.ts
95
+ declare abstract class Core extends Dispatcher {
96
+ protected config: CoreConfig;
97
+ protected filters: PortFilter;
98
+ protected port: SerialPort | SerialPortMock | null;
99
+ protected queue: QueueItem[];
100
+ protected connectionCmd: Uint8Array | null;
101
+ protected timeoutAfterWrite: number;
102
+ protected timeoutInstance: ReturnType<typeof setTimeout> | null;
103
+ protected lastAction: null | string;
104
+ protected wasConnected: boolean;
105
+ channelNumber: number;
106
+ protected isConnected: boolean;
107
+ constructor({
108
+ port
109
+ }: {
110
+ port: SerialPort | SerialPortMock | null;
111
+ });
112
+ setFilters({
113
+ vendorId,
114
+ productId
115
+ }: PortFilter): Core;
116
+ getFilters(): PortFilter;
117
+ setConfig(config: CoreConfig): Core;
118
+ getConfig(): CoreConfig;
119
+ protected getAvailablePorts(): Promise<PortInfo[]>;
120
+ getConnectionCmd(): Uint8Array<ArrayBufferLike> | null;
121
+ protected initListeners(): void;
122
+ protected runQueue(): Promise<void>;
123
+ protected onTimeout(bytes: Uint8Array, event: string | null): Promise<void>;
124
+ protected startListeningPort(): void;
125
+ protected abstract initParser(): void;
126
+ protected onDataReceived(buffer: Buffer): void;
127
+ protected abstract serialMessage(buffer: Buffer): void;
128
+ protected write(): Promise<void>;
129
+ connect(): Promise<void>;
130
+ disconnect(): Promise<void>;
131
+ protected appendToQueue(bytes: Uint8Array, action: string): Promise<void>;
132
+ protected openPort(): Promise<void>;
133
+ stringToUint8Array(str: string): Uint8Array;
134
+ uint8ArrayToHexArray(array: Uint8Array): Array<string>;
135
+ stringToArrayHex(string: string): string[];
136
+ asciiToHex(asciiString: string, joinWith?: string): string;
137
+ fixHexArray(array: Array<string | number>, size?: number): string[];
138
+ }
139
+ //#endregion
140
+ export { Core };
@@ -0,0 +1 @@
1
+ import{SerialPort as e,SerialPortMock as t}from"serialport";var n=class extends CustomEvent{constructor(e,t){super(e,t)}},r=class extends EventTarget{_listeners={debug:!1};_debug=!1;_listenersCallbacks=[];dispatch(e,t={}){let r=new n(e,{detail:t});this.dispatchEvent(r),this._debug&&this.dispatchEvent(new n(`debug`,{detail:{type:e,data:t}}))}dispatchAsync(e,t={},n=100){setTimeout(()=>this.dispatch(e,t),n)}on(e,t){this._listeners[e]!==void 0&&!this._listeners[e]&&(this._listeners[e]=!0),this._listenersCallbacks.push({key:e,callback:t}),this.addEventListener(e,t)}off(e,t){this._listenersCallbacks=this._listenersCallbacks.filter(n=>!(n.key===e&&n.callback===t)),this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this._listeners[e]||(this._listeners[e]=!1)}get availableListeners(){return Object.keys(this._listeners).sort().map(e=>({type:e,listening:this._listeners[e]}))}removeAllListeners(){for(let e of this._listenersCallbacks)[`internal:queue`].includes(e.key)||(this._listenersCallbacks=this._listenersCallbacks.filter(t=>!(t.key===e.key&&t.callback===e.callback)),this.removeEventListener(e.key,e.callback));for(let e of Object.keys(this._listeners))this._listeners[e]=!1}},i=class extends r{config={path:``,baudRate:9600,dataBits:8,lock:!0,stopBits:1,parity:`none`,rtscts:!1,xon:!1,xoff:!1,xany:!1,hupcl:!0};filters={};port=null;queue=[];connectionCmd=null;timeoutAfterWrite=500;timeoutInstance=null;lastAction=null;wasConnected=!1;channelNumber=1;isConnected=!1;constructor({port:e=null}){super(),this.port=e,this.initListeners()}setFilters({vendorId:e,productId:t}){return this.filters={...this.filters,vendorId:e||null},this.filters={...this.filters,productId:t||null},this}getFilters(){return this.filters}setConfig(e){return this.config={...this.config,...e},this}getConfig(){return this.config}async getAvailablePorts(){return(await e.list()).filter(e=>!(!e.path||!e.vendorId||!e.productId||this.filters.vendorId&&e.vendorId.toLowerCase()!==this.filters.vendorId.toLowerCase()||this.filters.productId&&e.productId.toLowerCase()!==this.filters.productId.toLowerCase()))}getConnectionCmd(){return this.connectionCmd}initListeners(){this.on(`internal:queue`,()=>this.runQueue())}async runQueue(){this.port&&this.port.isOpen&&this.queue.length!==0&&(this.timeoutInstance||await this.write())}async onTimeout(e,t){if(!this.wasConnected&&this.lastAction===`connection:start`){this.port?.close(),this.isConnected=!1,this.wasConnected=!1;return}this.timeoutInstance&&=(clearTimeout(this.timeoutInstance),null),this.dispatch(`internal:queue`),this.dispatch(`serial:timeout`,{message:`Operation timed out`,bytes:e,action:t}),console.error(`Timeout after write`,this.lastAction)}startListeningPort(){this.port&&(this.port.open(e=>{if(!this.port)return console.log(`Port is not defined`);if(e)return console.log(`Error opening port: `,e.message);if(!this.connectionCmd)throw Error(`Connection command is not defined`);this.lastAction=`connection:start`,this.timeoutInstance=setTimeout(()=>this.onTimeout(this.connectionCmd,this.lastAction),this.timeoutAfterWrite),this.port.write(this.connectionCmd)}),this.initParser())}onDataReceived(e){this.timeoutInstance&&=(clearTimeout(this.timeoutInstance),null),this.isConnected===!1&&(this.dispatch(`serial:connected`),this.wasConnected=!0,this.isConnected=!0),this.serialMessage(e),this.dispatch(`internal:queue`)}async write(){if(!this.port||this.queue.length===0)return;let e=this.queue[0];this.queue=this.queue.slice(1),this.lastAction=e.action||null,this.timeoutInstance=setTimeout(()=>this.onTimeout(e.bytes,this.lastAction),this.timeoutAfterWrite),this.port.write(e.bytes),this.dispatch(`serial:sent`,e)}async connect(){if(!this.port||!this.port.isOpen)return await this.openPort();if(!this.connectionCmd)throw Error(`Connection command is not defined`);this.appendToQueue(this.connectionCmd,this.port?.isOpen?`connect`:`connection:start`),this.dispatch(`internal:queue`)}async disconnect(){!this.port||!this.port.isOpen||(this.port.close(),this.isConnected=!1,this.wasConnected=!1,this.dispatch(`serial:disconnected`))}async appendToQueue(e,t){if([`connect`,`connection:start`].includes(t)&&(!this.port||!this.port.isOpen))return await this.openPort();this.queue.push({bytes:e,action:t}),this.dispatch(`internal:queue`)}async openPort(){if(this.port&&this.port.isOpen)return;if(this.port&&this.port instanceof t&&!this.port.isOpen){this.startListeningPort();return}let n=[],r=this.config;if(!this.config.path){if(n=await this.getAvailablePorts(),n.length===0)throw Error(`Port path is not defined`);n.length>1&&console.warn(`Multiple ports found, using the first one:`,n),r.path=n[0].path}this.port=new e({...r,autoOpen:!1}),this.startListeningPort()}stringToUint8Array(e){return console.warn(`stringToUint8Array is not recommended to use`),Buffer.from(e)}uint8ArrayToHexArray(e){return Array.from(e).map(e=>e.toString(16).toLowerCase().padStart(2,`0`))}stringToArrayHex(e){return Array.from(e).map(e=>e.charCodeAt(0).toString(16))}asciiToHex(e,t=``){let n=[];for(let t=0,r=e.length;t<r;t++){let r=Number(e.charCodeAt(t)).toString(16);n.push(r)}return n.join(t)}fixHexArray(e,t=2){return e.map(e=>typeof e==`string`?e.padStart(t,`0`).toLowerCase():e.toString(16).padStart(t,`0`).toLowerCase())}};export{i as Core};
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "serial-core",
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "A easy way to work with serial ports in Node.js",
6
+ "author": "Danidoble <danidoble@gmail.com>",
7
+ "license": "GPL-3.0-only",
8
+ "homepage": "https://github.com/danidoble/serial-core#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/danidoble/serial-core.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/danidoble/serial-core/issues"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "require": "./dist/serial-core.cjs",
19
+ "import": "./dist/serial-core.mjs"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "main": "./dist/serial-core.cjs",
24
+ "module": "./dist/serial-core.mjs",
25
+ "types": "./dist/serial-core.d.cts",
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "scripts": {
33
+ "build": "prettier --write ./lib/ && tsdown",
34
+ "dev": "tsdown --watch",
35
+ "test": "vitest",
36
+ "typecheck": "tsc --noEmit",
37
+ "prepublishOnly": "npm run build",
38
+ "clean": "rm -rf ./dist/",
39
+ "format": "prettier --write ./lib/"
40
+ },
41
+ "devDependencies": {
42
+ "@danidoble/webserial-vending-commands": "^1.0.3",
43
+ "@serialport/binding-mock": "^10.2.2",
44
+ "@serialport/parser-byte-length": "^13.0.0",
45
+ "@serialport/parser-delimiter": "^13.0.0",
46
+ "@serialport/parser-inter-byte-timeout": "^13.0.0",
47
+ "@types/node": "^25.0.3",
48
+ "bumpp": "^10.3.2",
49
+ "prettier": "3.7.4",
50
+ "serialport": "^13.0.0",
51
+ "tsdown": "^0.18.4",
52
+ "typescript": "^5.9.3",
53
+ "vitest": "^4.0.16"
54
+ },
55
+ "peerDependencies": {
56
+ "serialport": "^13.0.0"
57
+ }
58
+ }