├── .gitignore
├── LICENSE
├── README.md
├── callback.go
├── go.mod
├── jaylink.go
└── test
└── main.go
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, built with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | # Dependency directories (remove the comment below to include it)
15 | # vendor/
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://goreportcard.com/report/github.com/deadsy/jaylink)
2 | [](https://godoc.org/github.com/deadsy/jaylink)
3 |
4 | # jaylink
5 | Go bindings for the libjaylink library.
6 |
7 | ## What Is It?
8 |
9 | Segger makes J-Link devices. These are USB or network connected JTAG/SWD interfaces.
10 |
11 | Devices: https://www.segger.com/products/debug-probes/j-link/
12 |
13 | libjaylink is a C-based library providing an API for controlling J-Link devices.
14 | This package provides a Go wrapper for the C-library API so the library can be called from Go programs.
15 |
16 | ## Dependencies
17 |
18 | * libjaylink (https://gitlab.zapb.de/zapb/libjaylink/)
19 | * libusb-1.0 (https://libusb.info/)
20 |
21 | ## Notes
22 |
23 | All C-API functions have Go wrappers.
24 | The public interface of this package is a 1-1 mapping from the C-API to a Go style function prototypes.
25 | There are a couple of novel functions added as helper routines, but in general any C usage of the library has a simple mapping to Go.
26 |
27 | ## Status
28 |
29 | * Some testing has been done, mostly using USB based J-Link devices.
30 | * Version 0.2.0 of the libjaylink library has been tested.
31 |
--------------------------------------------------------------------------------
/callback.go:
--------------------------------------------------------------------------------
1 | //-----------------------------------------------------------------------------
2 | /*
3 |
4 | C-Code to support the libjaylink wrapper.
5 |
6 | Note: https://golang.org/cmd/cgo/#hdr-C_references_to_Go
7 |
8 | Using //export in a file places a restriction on the preamble:
9 | since it is copied into two different C output files, it must not contain
10 | any definitions, only declarations. If a file contains both definitions and
11 | declarations, then the two output files will produce duplicate symbols and
12 | the linker will fail. To avoid this, definitions must be placed in preambles
13 | in other files, or in C source files.
14 |
15 | */
16 | //-----------------------------------------------------------------------------
17 |
18 | package jaylink
19 |
20 | /*
21 | #include
22 | #include
23 |
24 | // Go won't allow the "type" field, so this is a C-wrapper.
25 | uint32_t get_hw_type(struct jaylink_hardware_version *h) {
26 | return (uint32_t)h->type;
27 | }
28 |
29 | void goLogCallback(struct jaylink_context *ctx, char *msg);
30 |
31 | int LogCallback(const struct jaylink_context *ctx, enum jaylink_log_level level,
32 | const char *format, va_list args, void *user_data) {
33 | // check the log level
34 | enum jaylink_log_level log_level;
35 | jaylink_log_get_level(ctx, &log_level);
36 | if (level > log_level) {
37 | return 0;
38 | }
39 | // create the message string
40 | char msg[128];
41 | vsnprintf(msg, sizeof(msg), format, args);
42 | // callback to go
43 | goLogCallback((struct jaylink_context *)ctx, msg);
44 | return 0;
45 | }
46 |
47 | */
48 | import "C"
49 |
50 | //-----------------------------------------------------------------------------
51 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/deadsy/jaylink
2 |
3 | go 1.20
4 |
--------------------------------------------------------------------------------
/jaylink.go:
--------------------------------------------------------------------------------
1 | //-----------------------------------------------------------------------------
2 | /*
3 |
4 | Go bindings for the libjaylink library.
5 |
6 | See: https://github.com/deadsy/libjaylink
7 | See: https://gitlab.zapb.de/zapb/libjaylink
8 |
9 | */
10 | //-----------------------------------------------------------------------------
11 |
12 | package jaylink
13 |
14 | /*
15 | #cgo pkg-config: libusb-1.0
16 | #cgo pkg-config: libjaylink
17 | #include
18 | #include
19 |
20 | uint32_t get_hw_type(struct jaylink_hardware_version *h);
21 |
22 | int LogCallback(const struct jaylink_context *ctx, enum jaylink_log_level level,
23 | const char *format, va_list args, void *user_data);
24 |
25 | */
26 | import "C"
27 |
28 | import (
29 | "errors"
30 | "fmt"
31 | "strings"
32 | "sync"
33 | "unsafe"
34 | )
35 |
36 | //-----------------------------------------------------------------------------
37 | // utility functions
38 |
39 | // go2cBuffer creates a C uint8_t buffer from a Go []byte buffer.
40 | // Call freeBuffer on the returned C buffer.
41 | func go2cBuffer(buf []byte) *C.uint8_t {
42 | return (*C.uint8_t)(unsafe.Pointer(C.CString(string(buf))))
43 | }
44 |
45 | // c2goCopy copies a C uint8_t buffer into a Go []byte slice.
46 | func c2goCopy(s []byte, buf *C.uint8_t) []byte {
47 | x := (*[1 << 30]byte)(unsafe.Pointer(buf))
48 | copy(s, x[:])
49 | return s
50 | }
51 |
52 | // c2goSlice creates a Go []byte slice and copies in a C uint8_t buffer.
53 | func c2goSlice(buf *C.uint8_t, n int) []byte {
54 | s := make([]byte, n)
55 | return c2goCopy(s, buf)
56 | }
57 |
58 | // allocBuffer allocates a C uint8_t buffer of length n bytes.
59 | // Call freeBuffer on the returned C buffer.
60 | func allocBuffer(n int) *C.uint8_t {
61 | return (*C.uint8_t)(C.malloc(C.size_t(n)))
62 | }
63 |
64 | // freeBuffer frees a C uint8_t buffer.
65 | func freeBuffer(buf *C.uint8_t) {
66 | C.free(unsafe.Pointer(buf))
67 | }
68 |
69 | // boolToInt converts a boolean to an int.
70 | func boolToInt(x bool) int {
71 | if x {
72 | return 1
73 | }
74 | return 0
75 | }
76 |
77 | // onesCount32 returns the number of 1's in a uint32.
78 | func onesCount32(x uint32) int {
79 | i := 0
80 | for x != 0 {
81 | if x&1 != 0 {
82 | i++
83 | }
84 | x >>= 1
85 | }
86 | return i
87 | }
88 |
89 | //-----------------------------------------------------------------------------
90 | // Errors
91 |
92 | // Error stores error information.
93 | type Error struct {
94 | Name string // function name
95 | Code int // C return code
96 | }
97 |
98 | // apiError returns an C-API error.
99 | func apiError(name string, rc int) *Error {
100 | return &Error{
101 | Name: name,
102 | Code: rc,
103 | }
104 | }
105 |
106 | func (e *Error) Error() string {
107 | return fmt.Sprintf("%s failed, %s", e.Name, StrError(e.Code))
108 | }
109 |
110 | // StrError returns a human-readable description of the error code.
111 | func StrError(code int) string {
112 | cStr := C.jaylink_strerror(C.int(code))
113 | return C.GoString(cStr)
114 | }
115 |
116 | // StrErrorName returns the name of the error code.
117 | func StrErrorName(code int) string {
118 | cStr := C.jaylink_strerror_name(C.int(code))
119 | return C.GoString(cStr)
120 | }
121 |
122 | //-----------------------------------------------------------------------------
123 |
124 | // HostInterface is the host interface bitmap.
125 | // When used for device discovery multiple bits are set.
126 | // When used for specific devices one bit is set for the interface type.
127 | type HostInterface uint32
128 |
129 | // HostInterface bitmap values.
130 | const (
131 | HIF_USB HostInterface = C.JAYLINK_HIF_USB
132 | HIF_TCP HostInterface = C.JAYLINK_HIF_TCP
133 | )
134 |
135 | func (h HostInterface) String() string {
136 | s := []string{}
137 | if h&HIF_USB != 0 {
138 | s = append(s, "usb")
139 | }
140 | if h&HIF_TCP != 0 {
141 | s = append(s, "tcp")
142 | }
143 | if len(s) != 0 {
144 | return strings.Join(s, ",")
145 | }
146 | return "unknown"
147 | }
148 |
149 | // GetHostInterface gets the host interface of a device.
150 | func (dev *Device) GetHostInterface() (HostInterface, error) {
151 | var iface uint32
152 | rc := int(C.jaylink_device_get_host_interface(dev.dev, &iface))
153 | if rc != C.JAYLINK_OK {
154 | return 0, apiError("jaylink_device_get_host_interface", rc)
155 | }
156 | return HostInterface(iface), nil
157 | }
158 |
159 | //-----------------------------------------------------------------------------
160 |
161 | // HardwareType is the device hardware type.
162 | type HardwareType uint32
163 |
164 | // HardwareType values.
165 | const (
166 | // libjaylink values
167 | HW_TYPE_JLINK HardwareType = C.JAYLINK_HW_TYPE_JLINK
168 | HW_TYPE_FLASHER HardwareType = C.JAYLINK_HW_TYPE_FLASHER
169 | HW_TYPE_JLINK_PRO HardwareType = C.JAYLINK_HW_TYPE_JLINK_PRO
170 | // other values
171 | HW_TYPE_JTRACE HardwareType = 1
172 | HW_TYPE_JLINK_LITE_ADI HardwareType = 5
173 | HW_TYPE_JLINK_LITE_XMC4000 HardwareType = 16
174 | HW_TYPE_JLINK_LITE_XMC4200 HardwareType = 17
175 | HW_TYPE_LPCLINK2 HardwareType = 18
176 | )
177 |
178 | func (h HardwareType) String() string {
179 | names := map[HardwareType]string{
180 | HW_TYPE_JLINK: "J-link",
181 | HW_TYPE_FLASHER: "Flasher",
182 | HW_TYPE_JLINK_PRO: "J-Link Pro",
183 | HW_TYPE_JTRACE: "J-Trace",
184 | HW_TYPE_JLINK_LITE_ADI: "J-Link Lite-ADI",
185 | HW_TYPE_JLINK_LITE_XMC4000: "J-Link Lite-XMC4000",
186 | HW_TYPE_JLINK_LITE_XMC4200: "J-Link Lite-XMC4200",
187 | HW_TYPE_LPCLINK2: "J-Link on LPC-Link2",
188 | }
189 | if s, ok := names[h]; ok {
190 | return s
191 | }
192 | return "unknown"
193 | }
194 |
195 | //-----------------------------------------------------------------------------
196 |
197 | // HardwareVersion is the hardware type and version.
198 | type HardwareVersion struct {
199 | Hwtype HardwareType
200 | Major uint8
201 | Minor uint8
202 | Revision uint8
203 | }
204 |
205 | func (h HardwareVersion) String() string {
206 | return fmt.Sprintf("%s %d.%d.%d", h.Hwtype, h.Major, h.Minor, h.Revision)
207 | }
208 |
209 | func c2goHardwareVersion(hw *C.struct_jaylink_hardware_version) *HardwareVersion {
210 | return &HardwareVersion{
211 | Hwtype: HardwareType(C.get_hw_type(hw)),
212 | Major: uint8(hw.major),
213 | Minor: uint8(hw.minor),
214 | Revision: uint8(hw.revision),
215 | }
216 | }
217 |
218 | // GetHardwareVersion gets the hardware version of a device.
219 | func (dev *Device) GetHardwareVersion() (*HardwareVersion, error) {
220 | var hw C.struct_jaylink_hardware_version
221 | rc := int(C.jaylink_device_get_hardware_version(dev.dev, &hw))
222 | if rc != C.JAYLINK_OK {
223 | return nil, apiError("jaylink_device_get_hardware_version", rc)
224 | }
225 | return c2goHardwareVersion(&hw), nil
226 | }
227 |
228 | // GetHardwareVersion gets the hardware version of a device.
229 | func (hdl *DeviceHandle) GetHardwareVersion() (*HardwareVersion, error) {
230 | var hw C.struct_jaylink_hardware_version
231 | rc := int(C.jaylink_get_hardware_version(hdl.hdl, &hw))
232 | if rc != C.JAYLINK_OK {
233 | return nil, apiError("jaylink_get_hardware_version", rc)
234 | }
235 | return c2goHardwareVersion(&hw), nil
236 | }
237 |
238 | //-----------------------------------------------------------------------------
239 |
240 | // UsbAddress stores the USB address number (Product ID).
241 | type UsbAddress uint32
242 |
243 | // UsbAddress values.
244 | const (
245 | USB_ADDRESS_0 UsbAddress = C.JAYLINK_USB_ADDRESS_0 // USB address 0 (Product ID 0x0101)
246 | USB_ADDRESS_1 UsbAddress = C.JAYLINK_USB_ADDRESS_1 // USB address 1 (Product ID 0x0102)
247 | USB_ADDRESS_2 UsbAddress = C.JAYLINK_USB_ADDRESS_2 // USB address 2 (Product ID 0x0103)
248 | USB_ADDRESS_3 UsbAddress = C.JAYLINK_USB_ADDRESS_3 // USB address 3 (Product ID 0x0104)
249 | )
250 |
251 | func (u UsbAddress) String() string {
252 | names := map[UsbAddress]string{
253 | USB_ADDRESS_0: "0x0101",
254 | USB_ADDRESS_1: "0x0102",
255 | USB_ADDRESS_2: "0x0103",
256 | USB_ADDRESS_3: "0x0104",
257 | }
258 | if s, ok := names[u]; ok {
259 | return s
260 | }
261 | return "unknown"
262 | }
263 |
264 | // GetUsbAddress gets the USB address of a device.
265 | func (dev *Device) GetUsbAddress() (UsbAddress, error) {
266 | var usbAddress uint32
267 | rc := int(C.jaylink_device_get_usb_address(dev.dev, &usbAddress))
268 | if rc != C.JAYLINK_OK {
269 | return 0, apiError("jaylink_device_get_usb_address", rc)
270 | }
271 | return UsbAddress(usbAddress), nil
272 | }
273 |
274 | //-----------------------------------------------------------------------------
275 |
276 | // HardwareInfo is a hardware information bitmap.
277 | type HardwareInfo uint32
278 |
279 | // HardwareInfo bitmap values.
280 | const (
281 | HW_INFO_TARGET_POWER HardwareInfo = C.JAYLINK_HW_INFO_TARGET_POWER
282 | HW_INFO_ITARGET HardwareInfo = C.JAYLINK_HW_INFO_ITARGET
283 | HW_INFO_ITARGET_PEAK HardwareInfo = C.JAYLINK_HW_INFO_ITARGET_PEAK
284 | HW_INFO_IPV4_ADDRESS HardwareInfo = C.JAYLINK_HW_INFO_IPV4_ADDRESS
285 | HW_INFO_IPV4_NETMASK HardwareInfo = C.JAYLINK_HW_INFO_IPV4_NETMASK
286 | HW_INFO_IPV4_GATEWAY HardwareInfo = C.JAYLINK_HW_INFO_IPV4_GATEWAY
287 | HW_INFO_IPV4_DNS HardwareInfo = C.JAYLINK_HW_INFO_IPV4_DNS
288 | )
289 |
290 | // GetHardwareInfo retrieves the hardware information of a device.
291 | func (hdl *DeviceHandle) GetHardwareInfo(mask HardwareInfo) ([]uint32, error) {
292 | cInfo := (*C.uint32_t)(C.malloc(32 * C.sizeof_uint32_t))
293 | defer C.free(unsafe.Pointer(cInfo))
294 | rc := int(C.jaylink_get_hardware_info(hdl.hdl, C.uint32_t(mask), cInfo))
295 | if rc != C.JAYLINK_OK {
296 | return nil, apiError("jaylink_get_hardware_info", rc)
297 | }
298 | info := make([]uint32, onesCount32(uint32(mask)))
299 | x := (*[1 << 30]C.uint32_t)(unsafe.Pointer(cInfo))
300 | for i := range info {
301 | info[i] = uint32(x[i])
302 | }
303 | return info, nil
304 | }
305 |
306 | //-----------------------------------------------------------------------------
307 |
308 | // Counter is a device counters bitmap.
309 | type Counter uint32
310 |
311 | // Counter bitmap values.
312 | const (
313 | COUNTER_TARGET_TIME Counter = C.JAYLINK_COUNTER_TARGET_TIME // Time the device is connected to a target in milliseconds.
314 | COUNTER_TARGET_CONNECTIONS Counter = C.JAYLINK_COUNTER_TARGET_CONNECTIONS // Number of times the device was connected or disconnected from a target.
315 | )
316 |
317 | // GetCounters retrieves the counter values of a device.
318 | func (hdl *DeviceHandle) GetCounters(mask Counter) ([]uint32, error) {
319 | cValues := (*C.uint32_t)(C.malloc(32 * C.sizeof_uint32_t))
320 | defer C.free(unsafe.Pointer(cValues))
321 | rc := int(C.jaylink_get_counters(hdl.hdl, C.uint32_t(mask), cValues))
322 | if rc != C.JAYLINK_OK {
323 | return nil, apiError("jaylink_get_counters", rc)
324 | }
325 | values := make([]uint32, onesCount32(uint32(mask)))
326 | x := (*[1 << 30]C.uint32_t)(unsafe.Pointer(cValues))
327 | for i := range values {
328 | values[i] = uint32(x[i])
329 | }
330 | return values, nil
331 | }
332 |
333 | //-----------------------------------------------------------------------------
334 |
335 | // HardwareStatus stores the device hardware status.
336 | type HardwareStatus struct {
337 | TargetVoltage uint16 // Target reference voltage in mV
338 | Tck bool // TCK pin state
339 | Tdi bool // TDI pin state
340 | Tdo bool // TDO pin state
341 | Tms bool // TMS pin state
342 | Tres bool // TRES pin state
343 | Trst bool // TRST pin state
344 | }
345 |
346 | func (hs *HardwareStatus) String() string {
347 | s := []string{}
348 | s = append(s, fmt.Sprintf("target voltage %d mV,", hs.TargetVoltage))
349 | s = append(s, fmt.Sprintf("tck %d", boolToInt(hs.Tck)))
350 | s = append(s, fmt.Sprintf("tdi %d", boolToInt(hs.Tdi)))
351 | s = append(s, fmt.Sprintf("tdo %d", boolToInt(hs.Tdo)))
352 | s = append(s, fmt.Sprintf("tms %d", boolToInt(hs.Tms)))
353 | s = append(s, fmt.Sprintf("tres %d", boolToInt(hs.Tres)))
354 | s = append(s, fmt.Sprintf("trst %d", boolToInt(hs.Trst)))
355 | return strings.Join(s, " ")
356 | }
357 |
358 | // GetHardwareStatus retrieves the hardware status of a device.
359 | func (hdl *DeviceHandle) GetHardwareStatus() (*HardwareStatus, error) {
360 | var cStatus C.struct_jaylink_hardware_status
361 | rc := int(C.jaylink_get_hardware_status(hdl.hdl, &cStatus))
362 | if rc != C.JAYLINK_OK {
363 | return nil, apiError("jaylink_get_hardware_status", rc)
364 | }
365 | status := HardwareStatus{
366 | TargetVoltage: uint16(cStatus.target_voltage),
367 | Tck: bool(cStatus.tck),
368 | Tdi: bool(cStatus.tdi),
369 | Tdo: bool(cStatus.tdo),
370 | Tms: bool(cStatus.tms),
371 | Tres: bool(cStatus.tres),
372 | Trst: bool(cStatus.trst),
373 | }
374 | return &status, nil
375 | }
376 |
377 | //-----------------------------------------------------------------------------
378 | // Capabilities
379 |
380 | // Capabilities is a bitmap of device capabilities.
381 | type Capabilities []byte
382 |
383 | // DeviceCapability is a bit position within the capabilities bitmap.
384 | type DeviceCapability uint
385 |
386 | // DeviceCapability values.
387 | const (
388 | // libjaylink values
389 | DEV_CAP_GET_HW_VERSION DeviceCapability = C.JAYLINK_DEV_CAP_GET_HW_VERSION
390 | DEV_CAP_ADAPTIVE_CLOCKING DeviceCapability = C.JAYLINK_DEV_CAP_ADAPTIVE_CLOCKING
391 | DEV_CAP_READ_CONFIG DeviceCapability = C.JAYLINK_DEV_CAP_READ_CONFIG
392 | DEV_CAP_WRITE_CONFIG DeviceCapability = C.JAYLINK_DEV_CAP_WRITE_CONFIG
393 | DEV_CAP_GET_SPEEDS DeviceCapability = C.JAYLINK_DEV_CAP_GET_SPEEDS
394 | DEV_CAP_GET_FREE_MEMORY DeviceCapability = C.JAYLINK_DEV_CAP_GET_FREE_MEMORY
395 | DEV_CAP_GET_HW_INFO DeviceCapability = C.JAYLINK_DEV_CAP_GET_HW_INFO
396 | DEV_CAP_SET_TARGET_POWER DeviceCapability = C.JAYLINK_DEV_CAP_SET_TARGET_POWER
397 | DEV_CAP_SELECT_TIF DeviceCapability = C.JAYLINK_DEV_CAP_SELECT_TIF
398 | DEV_CAP_GET_COUNTERS DeviceCapability = C.JAYLINK_DEV_CAP_GET_COUNTERS
399 | DEV_CAP_SWO DeviceCapability = C.JAYLINK_DEV_CAP_SWO
400 | DEV_CAP_FILE_IO DeviceCapability = C.JAYLINK_DEV_CAP_FILE_IO
401 | DEV_CAP_REGISTER DeviceCapability = C.JAYLINK_DEV_CAP_REGISTER
402 | DEV_CAP_GET_EXT_CAPS DeviceCapability = C.JAYLINK_DEV_CAP_GET_EXT_CAPS
403 | DEV_CAP_EMUCOM DeviceCapability = C.JAYLINK_DEV_CAP_EMUCOM
404 | DEV_CAP_ETHERNET DeviceCapability = C.JAYLINK_DEV_CAP_ETHERNET
405 | // from Segger J-Link docs
406 | DEV_CAP_RESERVED_1 DeviceCapability = 0
407 | DEV_CAP_WRITE_DCC DeviceCapability = 2
408 | DEV_CAP_TRACE DeviceCapability = 6
409 | DEV_CAP_WRITE_MEM DeviceCapability = 7
410 | DEV_CAP_READ_MEM DeviceCapability = 8
411 | DEV_CAP_EXEC_CODE DeviceCapability = 10
412 | DEV_CAP_RESET_STOP_TIMED DeviceCapability = 14
413 | DEV_CAP_RESERVED_2 DeviceCapability = 15
414 | DEV_CAP_MEASURE_RTCK_REACT DeviceCapability = 16
415 | DEV_CAP_RW_MEM_ARM79 DeviceCapability = 18
416 | DEV_CAP_READ_DCC DeviceCapability = 20
417 | DEV_CAP_GET_CPU_CAPS DeviceCapability = 21
418 | DEV_CAP_EXEC_CPU_CMD DeviceCapability = 22
419 | DEV_CAP_WRITE_DCC_EX DeviceCapability = 24
420 | DEV_CAP_UPDATE_FIRMWARE_EX DeviceCapability = 25
421 | DEV_CAP_INDICATORS DeviceCapability = 28
422 | DEV_CAP_TEST_NET_SPEED DeviceCapability = 29
423 | DEV_CAP_RAWTRACE DeviceCapability = 30
424 | )
425 |
426 | func (dc DeviceCapability) String() string {
427 | dcStr := map[DeviceCapability]string{
428 | // libjaylink values
429 | DEV_CAP_GET_HW_VERSION: "DEV_CAP_GET_HW_VERSION",
430 | DEV_CAP_ADAPTIVE_CLOCKING: "DEV_CAP_ADAPTIVE_CLOCKING",
431 | DEV_CAP_READ_CONFIG: "DEV_CAP_READ_CONFIG",
432 | DEV_CAP_WRITE_CONFIG: "DEV_CAP_WRITE_CONFIG",
433 | DEV_CAP_GET_SPEEDS: "DEV_CAP_GET_SPEEDS",
434 | DEV_CAP_GET_FREE_MEMORY: "DEV_CAP_GET_FREE_MEMORY",
435 | DEV_CAP_GET_HW_INFO: "DEV_CAP_GET_HW_INFO",
436 | DEV_CAP_SET_TARGET_POWER: "DEV_CAP_SET_TARGET_POWER",
437 | DEV_CAP_SELECT_TIF: "DEV_CAP_SELECT_TIF",
438 | DEV_CAP_GET_COUNTERS: "DEV_CAP_GET_COUNTERS",
439 | DEV_CAP_SWO: "DEV_CAP_SWO",
440 | DEV_CAP_FILE_IO: "DEV_CAP_FILE_IO",
441 | DEV_CAP_REGISTER: "DEV_CAP_REGISTER",
442 | DEV_CAP_GET_EXT_CAPS: "DEV_CAP_GET_EXT_CAPS",
443 | DEV_CAP_EMUCOM: "DEV_CAP_EMUCOM",
444 | DEV_CAP_ETHERNET: "DEV_CAP_ETHERNET",
445 | // from jlink docs
446 | DEV_CAP_RESERVED_1: "reserved (always 1)",
447 | DEV_CAP_WRITE_DCC: "DEV_CAP_WRITE_DCC",
448 | DEV_CAP_TRACE: "DEV_CAP_TRACE",
449 | DEV_CAP_WRITE_MEM: "DEV_CAP_WRITE_MEM",
450 | DEV_CAP_READ_MEM: "DEV_CAP_READ_MEM",
451 | DEV_CAP_EXEC_CODE: "DEV_CAP_EXEC_CODE",
452 | DEV_CAP_RESET_STOP_TIMED: "DEV_CAP_RESET_STOP_TIMED",
453 | DEV_CAP_RESERVED_2: "reserved",
454 | DEV_CAP_MEASURE_RTCK_REACT: "DEV_CAP_MEASURE_RTCK_REACT",
455 | DEV_CAP_RW_MEM_ARM79: "DEV_CAP_RW_MEM_ARM79",
456 | DEV_CAP_READ_DCC: "DEV_CAP_READ_DCC",
457 | DEV_CAP_GET_CPU_CAPS: "DEV_CAP_GET_CPU_CAPS",
458 | DEV_CAP_EXEC_CPU_CMD: "DEV_CAP_EXEC_CPU_CMD",
459 | DEV_CAP_WRITE_DCC_EX: "DEV_CAP_WRITE_DCC_EX",
460 | DEV_CAP_UPDATE_FIRMWARE_EX: "DEV_CAP_UPDATE_FIRMWARE_EX",
461 | DEV_CAP_INDICATORS: "DEV_CAP_INDICATORS",
462 | DEV_CAP_TEST_NET_SPEED: "DEV_CAP_TEST_NET_SPEED",
463 | DEV_CAP_RAWTRACE: "DEV_CAP_RAWTRACE",
464 | }
465 | if s, ok := dcStr[dc]; ok {
466 | return s
467 | }
468 | return "unknown"
469 | }
470 |
471 | // HasCap returns true if a capability is present within the capabilities set.
472 | func (caps Capabilities) HasCap(dc DeviceCapability) bool {
473 | if caps == nil {
474 | return false
475 | }
476 | n := int(dc)
477 | if n >= (len(caps) << 3) {
478 | return false
479 | }
480 | return caps[n>>3]&(1<<(n&7)) != 0
481 | }
482 |
483 | func (caps Capabilities) String() string {
484 | s := []string{}
485 | for i := 0; i < (len(caps) << 3); i++ {
486 | dc := DeviceCapability(i)
487 | if caps.HasCap(dc) {
488 | s = append(s, fmt.Sprintf("(%2d) %s", i, dc.String()))
489 | }
490 | }
491 | return strings.Join(s, "\n")
492 | }
493 |
494 | // GetCaps retrieves the capabilities of a device.
495 | func (hdl *DeviceHandle) GetCaps() (Capabilities, error) {
496 | cCaps := (*C.uint8_t)(C.malloc(C.JAYLINK_DEV_CAPS_SIZE))
497 | defer C.free(unsafe.Pointer(cCaps))
498 | rc := int(C.jaylink_get_caps(hdl.hdl, cCaps))
499 | if rc != C.JAYLINK_OK {
500 | return nil, apiError("jaylink_get_caps", rc)
501 | }
502 | x := (*[1 << 30]C.uint8_t)(unsafe.Pointer(cCaps))
503 | caps := make([]byte, C.JAYLINK_DEV_CAPS_SIZE)
504 | for i := range caps {
505 | caps[i] = byte(x[i])
506 | }
507 | return caps, nil
508 | }
509 |
510 | // GetExtendedCaps retrieves the extended capabilities of a device.
511 | // Extended capabilties are a superset of normal capabilities.
512 | func (hdl *DeviceHandle) GetExtendedCaps() (Capabilities, error) {
513 | cCaps := (*C.uint8_t)(C.malloc(C.JAYLINK_DEV_EXT_CAPS_SIZE))
514 | defer C.free(unsafe.Pointer(cCaps))
515 | rc := int(C.jaylink_get_extended_caps(hdl.hdl, cCaps))
516 | if rc != C.JAYLINK_OK {
517 | return nil, apiError("jaylink_get_extended_caps", rc)
518 | }
519 | x := (*[1 << 30]C.uint8_t)(unsafe.Pointer(cCaps))
520 | caps := make([]byte, C.JAYLINK_DEV_EXT_CAPS_SIZE)
521 | for i := range caps {
522 | caps[i] = byte(x[i])
523 | }
524 | return caps, nil
525 | }
526 |
527 | // GetAllCaps returns all device capabilities (normal or extended).
528 | func (hdl *DeviceHandle) GetAllCaps() (Capabilities, error) {
529 | caps, err := hdl.GetCaps()
530 | if err == nil && caps.HasCap(DEV_CAP_GET_EXT_CAPS) {
531 | caps, err = hdl.GetExtendedCaps()
532 | }
533 | return caps, err
534 | }
535 |
536 | //-----------------------------------------------------------------------------
537 |
538 | // Context is a structure representing a libjaylink context.
539 | type Context struct {
540 | ctx *C.struct_jaylink_context
541 | devs **C.struct_jaylink_device
542 | cb LogFunc // logging callback
543 | user interface{} // user data for logging callback
544 | }
545 |
546 | // gContext maps a C context pointer back to the Go context structure.
547 | var gContext = map[*C.struct_jaylink_context]*Context{}
548 |
549 | // lock the gContext map during access.
550 | var gLock = sync.RWMutex{}
551 |
552 | // ctxLookup lookups a Go context using a C context.
553 | func ctxLookup(cCtx *C.struct_jaylink_context) *Context {
554 | gLock.RLock()
555 | ctx := gContext[cCtx]
556 | gLock.RUnlock()
557 | return ctx
558 | }
559 |
560 | // ctxAdd adds a C to Go context lookup.
561 | func ctxAdd(ctx *Context) {
562 | gLock.Lock()
563 | gContext[ctx.ctx] = ctx
564 | gLock.Unlock()
565 | }
566 |
567 | // ctxRemove removes a C to Go context lookup.
568 | func ctxRemove(ctx *Context) {
569 | gLock.Lock()
570 | delete(gContext, ctx.ctx)
571 | gLock.Unlock()
572 | }
573 |
574 | //-----------------------------------------------------------------------------
575 | // Core Operations
576 |
577 | // Init initializes libjaylink.
578 | func Init() (*Context, error) {
579 | ctx := Context{}
580 | rc := int(C.jaylink_init((**C.struct_jaylink_context)(&ctx.ctx)))
581 | if rc != C.JAYLINK_OK {
582 | return nil, apiError("jaylink_init", rc)
583 | }
584 | ctxAdd(&ctx)
585 | return &ctx, nil
586 | }
587 |
588 | // Exit shutdowns libjaylink.
589 | func (ctx *Context) Exit() error {
590 | ctxRemove(ctx)
591 | rc := int(C.jaylink_exit(ctx.ctx))
592 | if rc != C.JAYLINK_OK {
593 | return apiError("jaylink_exit", rc)
594 | }
595 | return nil
596 | }
597 |
598 | // LibraryHasCap checks for a capability of libjaylink.
599 | func LibraryHasCap(capability uint) bool {
600 | return bool(C.jaylink_library_has_cap(uint32(capability)))
601 | }
602 |
603 | //-----------------------------------------------------------------------------
604 | // Device Operations
605 |
606 | // Device is a structure representing a device.
607 | type Device struct {
608 | dev *C.struct_jaylink_device
609 | }
610 |
611 | // DeviceHandle is a structure representing a handle of a device.
612 | type DeviceHandle struct {
613 | hdl *C.struct_jaylink_device_handle
614 | }
615 |
616 | // GetDevices gets available devices.
617 | func (ctx *Context) GetDevices() ([]Device, error) {
618 | var count C.size_t
619 | rc := int(C.jaylink_get_devices(ctx.ctx, &ctx.devs, &count))
620 | if rc != C.JAYLINK_OK {
621 | return nil, apiError("jaylink_get_devices", rc)
622 | }
623 | d := (*[1 << 30]*C.struct_jaylink_device)(unsafe.Pointer(ctx.devs))
624 | dev := make([]Device, int(count))
625 | for i := range dev {
626 | dev[i].dev = d[i]
627 | }
628 | return dev, nil
629 | }
630 |
631 | // FreeDevices frees devices.
632 | func (ctx *Context) FreeDevices(dev []Device, unref bool) {
633 | // sanity check, []Device must be read-only
634 | d := (*[1 << 30]*C.struct_jaylink_device)(unsafe.Pointer(ctx.devs))
635 | for i := range dev {
636 | if d[i] != dev[i].dev {
637 | panic(fmt.Sprintf("dev[%d] pointer has changed", i))
638 | }
639 | }
640 | C.jaylink_free_devices(ctx.devs, C.bool(unref))
641 | }
642 |
643 | // GetSerialNumber gets the serial number of a device.
644 | func (dev *Device) GetSerialNumber() (uint, error) {
645 | var serialNumber C.uint32_t
646 | rc := int(C.jaylink_device_get_serial_number(dev.dev, &serialNumber))
647 | if rc != C.JAYLINK_OK {
648 | return 0, apiError("jaylink_device_get_serial_number", rc)
649 | }
650 | return uint(serialNumber), nil
651 | }
652 |
653 | // GetUsbPorts gets the USB bus and port numbers of a device.
654 | func (dev *Device) GetUsbPorts() (uint8, []uint8, error) {
655 | var cLength C.size_t
656 | var cPorts *C.uint8_t
657 | var cBus C.uint8_t
658 | rc := int(C.jaylink_device_get_usb_bus_ports(dev.dev, &cBus, &cPorts, &cLength))
659 | if rc != C.JAYLINK_OK {
660 | return 0, nil, apiError("jaylink_device_get_usb_bus_ports", rc)
661 | }
662 | ports := make([]uint8, cLength)
663 | p := (*[1 << 30]C.uint8_t)(unsafe.Pointer(cPorts))
664 | for i := range ports {
665 | ports[i] = uint8(p[i])
666 | }
667 | return uint8(cBus), ports, nil
668 | }
669 |
670 | // GetIPv4Address gets the IPv4 address string of a device.
671 | func (dev *Device) GetIPv4Address() (string, error) {
672 | addr := (*C.char)(C.malloc(C.INET_ADDRSTRLEN))
673 | defer C.free(unsafe.Pointer(addr))
674 | rc := int(C.jaylink_device_get_ipv4_address(dev.dev, addr))
675 | if rc != C.JAYLINK_OK {
676 | return "", apiError("jaylink_device_get_ipv4_address", rc)
677 | }
678 | return C.GoString(addr), nil
679 | }
680 |
681 | // GetMacAddress gets the MAC address of a device.
682 | func (dev *Device) GetMacAddress() ([]byte, error) {
683 | mac := allocBuffer(C.JAYLINK_MAC_ADDRESS_LENGTH)
684 | defer freeBuffer(mac)
685 | rc := int(C.jaylink_device_get_mac_address(dev.dev, mac))
686 | if rc != C.JAYLINK_OK {
687 | return nil, apiError("jaylink_device_get_mac_address", rc)
688 | }
689 | return c2goSlice(mac, C.JAYLINK_MAC_ADDRESS_LENGTH), nil
690 | }
691 |
692 | // GetProductName gets the product name of a device.
693 | func (dev *Device) GetProductName() (string, error) {
694 | name := (*C.char)(C.malloc(C.JAYLINK_PRODUCT_NAME_MAX_LENGTH))
695 | defer C.free(unsafe.Pointer(name))
696 | rc := int(C.jaylink_device_get_product_name(dev.dev, name))
697 | if rc != C.JAYLINK_OK {
698 | return "", apiError("jaylink_device_get_product_name", rc)
699 | }
700 | return C.GoString(name), nil
701 | }
702 |
703 | // GetNickName gets the nickname of a device.
704 | func (dev *Device) GetNickName() (string, error) {
705 | name := (*C.char)(C.malloc(C.JAYLINK_NICKNAME_MAX_LENGTH))
706 | defer C.free(unsafe.Pointer(name))
707 | rc := int(C.jaylink_device_get_nickname(dev.dev, name))
708 | if rc != C.JAYLINK_OK {
709 | return "", apiError("jaylink_device_get_nickname", rc)
710 | }
711 | return C.GoString(name), nil
712 | }
713 |
714 | // RefDevice increments the reference count of a device.
715 | func (dev *Device) RefDevice() *Device {
716 | x := C.jaylink_ref_device(dev.dev)
717 | if x == nil {
718 | return nil
719 | }
720 | return dev
721 | }
722 |
723 | // UnrefDevice decrements the reference count of a device.
724 | func (dev *Device) UnrefDevice() {
725 | C.jaylink_unref_device(dev.dev)
726 | }
727 |
728 | // Open opens a device.
729 | func (dev *Device) Open() (*DeviceHandle, error) {
730 | hdl := DeviceHandle{}
731 | rc := int(C.jaylink_open(dev.dev, (**C.struct_jaylink_device_handle)(&hdl.hdl)))
732 | if rc != C.JAYLINK_OK {
733 | return nil, apiError("jaylink_open", rc)
734 | }
735 | return &hdl, nil
736 | }
737 |
738 | // Close closes a device.
739 | func (hdl *DeviceHandle) Close() error {
740 | rc := int(C.jaylink_close(hdl.hdl))
741 | if rc != C.JAYLINK_OK {
742 | return apiError("jaylink_close", rc)
743 | }
744 | return nil
745 | }
746 |
747 | // GetDevice gets the device instance from a device handle.
748 | func (hdl *DeviceHandle) GetDevice() *Device {
749 | x := C.jaylink_get_device(hdl.hdl)
750 | if x == nil {
751 | return nil
752 | }
753 | return &Device{dev: x}
754 | }
755 |
756 | // GetFirmwareVersion retrieves the firmware version of a device.
757 | func (hdl *DeviceHandle) GetFirmwareVersion() (string, error) {
758 | var cVersion *C.char
759 | var cLength C.size_t
760 | rc := int(C.jaylink_get_firmware_version(hdl.hdl, &cVersion, &cLength))
761 | if rc != C.JAYLINK_OK {
762 | return "", apiError("jaylink_get_firmware_version", rc)
763 | }
764 | defer C.free(unsafe.Pointer(cVersion))
765 | return C.GoString(cVersion), nil
766 | }
767 |
768 | // GetFreeMemory retrieves the size of free memory of a device.
769 | func (hdl *DeviceHandle) GetFreeMemory() (uint32, error) {
770 | var cSize C.uint32_t
771 | rc := int(C.jaylink_get_free_memory(hdl.hdl, &cSize))
772 | if rc != C.JAYLINK_OK {
773 | return 0, apiError("jaylink_get_free_memory", rc)
774 | }
775 | return uint32(cSize), nil
776 | }
777 |
778 | // RawConfig is the raw device configuration.
779 | type RawConfig [C.JAYLINK_DEV_CONFIG_SIZE]byte
780 |
781 | // ReadRawConfig reads the raw configuration data of a device.
782 | func (hdl *DeviceHandle) ReadRawConfig() (*RawConfig, error) {
783 | cConfig := allocBuffer(C.JAYLINK_DEV_CONFIG_SIZE)
784 | defer freeBuffer(cConfig)
785 | rc := int(C.jaylink_read_raw_config(hdl.hdl, cConfig))
786 | if rc != C.JAYLINK_OK {
787 | return nil, apiError("jaylink_read_raw_config", rc)
788 | }
789 | var config RawConfig
790 | c2goCopy(config[:], cConfig)
791 | return &config, nil
792 | }
793 |
794 | // WriteRawConfig writes the raw configuration data of a device.
795 | func (hdl *DeviceHandle) WriteRawConfig(config *RawConfig) error {
796 | cConfig := go2cBuffer(config[:])
797 | defer freeBuffer(cConfig)
798 | rc := int(C.jaylink_write_raw_config(hdl.hdl, cConfig))
799 | if rc != C.JAYLINK_OK {
800 | return apiError("jaylink_write_raw_config", rc)
801 | }
802 | return nil
803 | }
804 |
805 | //-----------------------------------------------------------------------------
806 |
807 | // Connection is a device connection.
808 | type Connection struct {
809 | Handle uint16 // handle
810 | Pid uint32 // client process id
811 | Hid [C.INET_ADDRSTRLEN]byte // host id
812 | Iid uint8 // IID
813 | Cid uint8 // CID
814 | Timestamp uint32 // Timestamp of the last registration in milliseconds.
815 | }
816 |
817 | // c2goConnection copies connection data from C to Go.
818 | func c2goConnection(connection *Connection, cConnection *C.struct_jaylink_connection) {
819 | connection.Handle = uint16(cConnection.handle)
820 | connection.Pid = uint32(cConnection.pid)
821 | for i := range connection.Hid {
822 | connection.Hid[i] = byte(cConnection.hid[i])
823 | }
824 | connection.Iid = uint8(cConnection.iid)
825 | connection.Cid = uint8(cConnection.cid)
826 | connection.Timestamp = uint32(cConnection.timestamp)
827 | }
828 |
829 | // go2cConnection copies connection data from Go to C.
830 | func go2cConnection(connection *Connection) *C.struct_jaylink_connection {
831 | cConnection := (*C.struct_jaylink_connection)(C.malloc(C.sizeof_struct_jaylink_connection))
832 | cConnection.handle = C.uint16_t(connection.Handle)
833 | cConnection.pid = C.uint32_t(connection.Pid)
834 | for i := range connection.Hid {
835 | cConnection.hid[i] = C.char(connection.Hid[i])
836 | }
837 | cConnection.iid = C.uint8_t(connection.Iid)
838 | cConnection.cid = C.uint8_t(connection.Cid)
839 | cConnection.timestamp = C.uint32_t(connection.Timestamp)
840 | return cConnection
841 | }
842 |
843 | // Register registers a connection on a device.
844 | func (hdl *DeviceHandle) Register(connection *Connection) ([]Connection, error) {
845 | cConnection := go2cConnection(connection)
846 | defer C.free(unsafe.Pointer(cConnection))
847 | cConnections := (*C.struct_jaylink_connection)(C.malloc(C.JAYLINK_MAX_CONNECTIONS * C.sizeof_struct_jaylink_connection))
848 | defer C.free(unsafe.Pointer(cConnections))
849 | var cCount C.size_t
850 | // register
851 | rc := int(C.jaylink_register(hdl.hdl, cConnection, cConnections, &cCount))
852 | if rc != C.JAYLINK_OK {
853 | return nil, apiError("jaylink_register", rc)
854 | }
855 | // copy the result to go
856 | connections := make([]Connection, int(cCount))
857 | x := (*[1 << 30](C.struct_jaylink_connection))(unsafe.Pointer(cConnections))
858 | for i := range connections {
859 | c2goConnection(&connections[i], &x[i])
860 | }
861 | return connections, nil
862 | }
863 |
864 | // Unregister unregisters a connection from a device.
865 | func (hdl *DeviceHandle) Unregister(connection *Connection) ([]Connection, error) {
866 | cConnection := go2cConnection(connection)
867 | defer C.free(unsafe.Pointer(cConnection))
868 | cConnections := (*C.struct_jaylink_connection)(C.malloc(C.JAYLINK_MAX_CONNECTIONS * C.sizeof_struct_jaylink_connection))
869 | defer C.free(unsafe.Pointer(cConnections))
870 | var cCount C.size_t
871 | // unregister
872 | rc := int(C.jaylink_unregister(hdl.hdl, cConnection, cConnections, &cCount))
873 | if rc != C.JAYLINK_OK {
874 | return nil, apiError("jaylink_unregister", rc)
875 | }
876 | // copy the result to go
877 | connections := make([]Connection, int(cCount))
878 | x := (*[1 << 30](C.struct_jaylink_connection))(unsafe.Pointer(cConnections))
879 | for i := range connections {
880 | c2goConnection(&connections[i], &x[i])
881 | }
882 | return connections, nil
883 | }
884 |
885 | //-----------------------------------------------------------------------------
886 | // Device Discovery
887 |
888 | // DiscoveryScan scans for devices.
889 | func (ctx *Context) DiscoveryScan(ifaces HostInterface) error {
890 | rc := int(C.jaylink_discovery_scan(ctx.ctx, C.uint32_t(ifaces)))
891 | if rc != C.JAYLINK_OK {
892 | return apiError("jaylink_discovery_scan", rc)
893 | }
894 | return nil
895 | }
896 |
897 | //-----------------------------------------------------------------------------
898 | // EMUCOM Operations
899 |
900 | // EmuComRead reads from an EMUCOM channel.
901 | func (hdl *DeviceHandle) EmuComRead(channel uint32, length int) ([]byte, error) {
902 | cBuffer := allocBuffer(length)
903 | defer freeBuffer(cBuffer)
904 | cLength := C.uint32_t(length)
905 | rc := int(C.jaylink_emucom_read(hdl.hdl, C.uint32_t(channel), cBuffer, &cLength))
906 | if rc != C.JAYLINK_OK {
907 | return nil, apiError("jaylink_emucom_read", rc)
908 | }
909 | return c2goSlice(cBuffer, int(cLength)), nil
910 | }
911 |
912 | // EmuComWrite writes to an EMUCOM channel.
913 | func (hdl *DeviceHandle) EmuComWrite(channel uint32, buffer []byte) (int, error) {
914 | cBuffer := go2cBuffer(buffer)
915 | defer freeBuffer(cBuffer)
916 | cLength := C.uint32_t(len(buffer))
917 | rc := int(C.jaylink_emucom_write(hdl.hdl, C.uint32_t(channel), cBuffer, &cLength))
918 | if rc != C.JAYLINK_OK {
919 | return 0, apiError("jaylink_emucom_write", rc)
920 | }
921 | return int(cLength), nil
922 | }
923 |
924 | //-----------------------------------------------------------------------------
925 | // File I/O Operations
926 |
927 | // FileRead reads from a file.
928 | func (hdl *DeviceHandle) FileRead(filename string, offset uint32, length int) ([]byte, error) {
929 | cFilename := C.CString(filename)
930 | defer C.free(unsafe.Pointer(cFilename))
931 | cBuffer := allocBuffer(length)
932 | defer freeBuffer(cBuffer)
933 | cLength := C.uint32_t(length)
934 | rc := int(C.jaylink_file_read(hdl.hdl, cFilename, cBuffer, C.uint32_t(offset), &cLength))
935 | if rc != C.JAYLINK_OK {
936 | return nil, apiError("jaylink_file_read", rc)
937 | }
938 | return c2goSlice(cBuffer, int(cLength)), nil
939 | }
940 |
941 | // FileWrite writes to a file.
942 | func (hdl *DeviceHandle) FileWrite(filename string, buffer []byte, offset uint32) (int, error) {
943 | cFilename := C.CString(filename)
944 | defer C.free(unsafe.Pointer(cFilename))
945 | cBuffer := go2cBuffer(buffer)
946 | defer freeBuffer(cBuffer)
947 | cLength := C.uint32_t(len(buffer))
948 | rc := int(C.jaylink_file_write(hdl.hdl, cFilename, cBuffer, C.uint32_t(offset), &cLength))
949 | if rc != C.JAYLINK_OK {
950 | return 0, apiError("jaylink_file_write", rc)
951 | }
952 | return int(cLength), nil
953 | }
954 |
955 | // FileGetSize retrieves the size of a file.
956 | func (hdl *DeviceHandle) FileGetSize(filename string) (uint32, error) {
957 | cFilename := C.CString(filename)
958 | defer C.free(unsafe.Pointer(cFilename))
959 | var cSize C.uint32_t
960 | rc := int(C.jaylink_file_get_size(hdl.hdl, cFilename, &cSize))
961 | if rc != C.JAYLINK_OK {
962 | return 0, apiError("jaylink_file_get_size", rc)
963 | }
964 | return uint32(cSize), nil
965 | }
966 |
967 | // FileDelete deletes a file.
968 | func (hdl *DeviceHandle) FileDelete(filename string) error {
969 | cFilename := C.CString(filename)
970 | defer C.free(unsafe.Pointer(cFilename))
971 | rc := int(C.jaylink_file_delete(hdl.hdl, cFilename))
972 | if rc != C.JAYLINK_OK {
973 | return apiError("jaylink_file_delete", rc)
974 | }
975 | return nil
976 | }
977 |
978 | //-----------------------------------------------------------------------------
979 | // JTAG Operations
980 |
981 | // JtagVersion is the JTAG command version.
982 | type JtagVersion uint32
983 |
984 | // JtagVersion values.
985 | const (
986 | JTAG_VERSION_2 JtagVersion = C.JAYLINK_JTAG_VERSION_2
987 | JTAG_VERSION_3 JtagVersion = C.JAYLINK_JTAG_VERSION_3
988 | )
989 |
990 | // GetJtagCommandVersion gets the JTAG command version for the device.
991 | func (hdl *DeviceHandle) GetJtagCommandVersion() (JtagVersion, error) {
992 | hw, err := hdl.GetHardwareVersion()
993 | if err != nil {
994 | return 0, err
995 | }
996 | // For major hardware version 5 and above, use Version 3.
997 | if hw.Major >= 5 {
998 | return JTAG_VERSION_3, nil
999 | }
1000 | return JTAG_VERSION_2, nil
1001 | }
1002 |
1003 | // JtagIO performs a JTAG I/O operation.
1004 | func (hdl *DeviceHandle) JtagIO(tms, tdi []byte, n uint16, version JtagVersion) ([]byte, error) {
1005 | nbytes := len(tms)
1006 | if len(tdi) != nbytes {
1007 | panic("len(tms) != len(tdi)")
1008 | }
1009 | cTms := go2cBuffer(tms)
1010 | cTdi := go2cBuffer(tdi)
1011 | cTdo := allocBuffer(nbytes)
1012 | defer freeBuffer(cTms)
1013 | defer freeBuffer(cTdi)
1014 | defer freeBuffer(cTdo)
1015 | rc := int(C.jaylink_jtag_io(hdl.hdl, cTms, cTdi, cTdo, C.uint16_t(n), uint32(version)))
1016 | if rc != C.JAYLINK_OK {
1017 | return nil, apiError("jaylink_jtag_io", rc)
1018 | }
1019 | return c2goSlice(cTdo, nbytes), nil
1020 | }
1021 |
1022 | // JtagClearTrst clears the JTAG test reset (TRST) signal.
1023 | func (hdl *DeviceHandle) JtagClearTrst() error {
1024 | rc := int(C.jaylink_jtag_clear_trst(hdl.hdl))
1025 | if rc != C.JAYLINK_OK {
1026 | return apiError("jaylink_jtag_clear_trst", rc)
1027 | }
1028 | return nil
1029 | }
1030 |
1031 | // JtagSetTrst sets the JTAG test reset (TRST) signal.
1032 | func (hdl *DeviceHandle) JtagSetTrst() error {
1033 | rc := int(C.jaylink_jtag_set_trst(hdl.hdl))
1034 | if rc != C.JAYLINK_OK {
1035 | return apiError("jaylink_jtag_set_trst", rc)
1036 | }
1037 | return nil
1038 | }
1039 |
1040 | //-----------------------------------------------------------------------------
1041 | // Logging
1042 |
1043 | // LogLevel is the log level.
1044 | type LogLevel uint32
1045 |
1046 | // LogLevel values.
1047 | const (
1048 | LOG_LEVEL_NONE LogLevel = C.JAYLINK_LOG_LEVEL_NONE // no messages
1049 | LOG_LEVEL_ERROR LogLevel = C.JAYLINK_LOG_LEVEL_ERROR // error messages
1050 | LOG_LEVEL_WARNING LogLevel = C.JAYLINK_LOG_LEVEL_WARNING // warnings
1051 | LOG_LEVEL_INFO LogLevel = C.JAYLINK_LOG_LEVEL_INFO // informational messages
1052 | LOG_LEVEL_DEBUG LogLevel = C.JAYLINK_LOG_LEVEL_DEBUG // debug messages
1053 | LOG_LEVEL_DEBUG_IO LogLevel = C.JAYLINK_LOG_LEVEL_DEBUG_IO // I/O debug messages
1054 | )
1055 |
1056 | // LogFunc is a logging callback function.
1057 | type LogFunc func(domain, msg string, user interface{})
1058 |
1059 | //export goLogCallback
1060 | func goLogCallback(cCtx *C.struct_jaylink_context, cMsg *C.char) {
1061 | ctx := ctxLookup(cCtx)
1062 | if ctx != nil {
1063 | ctx.cb(ctx.LogGetDomain(), C.GoString(cMsg), ctx.user)
1064 | }
1065 | }
1066 |
1067 | // LogSetLevel sets the log level.
1068 | func (ctx *Context) LogSetLevel(level LogLevel) error {
1069 | rc := int(C.jaylink_log_set_level(ctx.ctx, uint32(level)))
1070 | if rc != C.JAYLINK_OK {
1071 | return apiError("jaylink_log_set_level", rc)
1072 | }
1073 | return nil
1074 | }
1075 |
1076 | // LogGetLevel gets the log level.
1077 | func (ctx *Context) LogGetLevel() (LogLevel, error) {
1078 | var cLevel uint32
1079 | rc := int(C.jaylink_log_get_level(ctx.ctx, &cLevel))
1080 | if rc != C.JAYLINK_OK {
1081 | return 0, apiError("jaylink_log_get_level", rc)
1082 | }
1083 | return LogLevel(cLevel), nil
1084 | }
1085 |
1086 | // LogSetCallback sets the logging callback function.
1087 | func (ctx *Context) LogSetCallback(cb LogFunc, user interface{}) error {
1088 | rc := int(C.jaylink_log_set_callback(ctx.ctx, C.jaylink_log_callback(C.LogCallback), nil))
1089 | if rc != C.JAYLINK_OK {
1090 | return apiError("jaylink_log_set_callback", rc)
1091 | }
1092 | ctx.cb = cb
1093 | ctx.user = user
1094 | return nil
1095 | }
1096 |
1097 | // LogSetDomain sets the log domain.
1098 | func (ctx *Context) LogSetDomain(domain string) error {
1099 | cDomain := C.CString(domain)
1100 | defer C.free(unsafe.Pointer(cDomain))
1101 | rc := int(C.jaylink_log_set_domain(ctx.ctx, cDomain))
1102 | if rc != C.JAYLINK_OK {
1103 | return apiError("jaylink_log_set_domain", rc)
1104 | }
1105 | return nil
1106 | }
1107 |
1108 | // LogGetDomain gets the log domain.
1109 | func (ctx *Context) LogGetDomain() string {
1110 | cDomain := C.jaylink_log_get_domain(ctx.ctx)
1111 | return C.GoString(cDomain)
1112 | }
1113 |
1114 | //-----------------------------------------------------------------------------
1115 | // Serial Wire Debug
1116 |
1117 | // SwdIO performs a SWD I/O operation.
1118 | func (hdl *DeviceHandle) SwdIO(direction, out []byte, n uint16) ([]byte, error) {
1119 | nbytes := len(direction)
1120 | if len(out) != nbytes {
1121 | panic("len(direction) != len(out)")
1122 | }
1123 | cDirection := go2cBuffer(direction)
1124 | cOut := go2cBuffer(out)
1125 | cIn := allocBuffer(nbytes)
1126 | defer freeBuffer(cDirection)
1127 | defer freeBuffer(cOut)
1128 | defer freeBuffer(cIn)
1129 | rc := int(C.jaylink_swd_io(hdl.hdl, cDirection, cOut, cIn, C.uint16_t(n)))
1130 | if rc != C.JAYLINK_OK {
1131 | return nil, apiError("jaylink_swd_io", rc)
1132 | }
1133 | return c2goSlice(cIn, nbytes), nil
1134 | }
1135 |
1136 | //-----------------------------------------------------------------------------
1137 | // Serial Wire Output
1138 |
1139 | // SwoMode is the Serial Wire Output (SWO) capture mode.
1140 | type SwoMode uint32
1141 |
1142 | // SwoMode values.
1143 | const (
1144 | SWO_MODE_UART SwoMode = C.JAYLINK_SWO_MODE_UART // Universal Asynchronous Receiver Transmitter (UART).
1145 | )
1146 |
1147 | // SwoSpeed store Serial Wire Output (SWO) speed information.
1148 | type SwoSpeed struct {
1149 | Freq uint32 // Base frequency in Hz
1150 | MinDiv uint32 // Minimum frequency divider
1151 | MaxDiv uint32 // Maximum frequency divider
1152 | MinPrescaler uint32 // Minimum prescaler
1153 | MaxPrescaler uint32 // Maximum prescaler
1154 | }
1155 |
1156 | // SwoStart starts SWO capture.
1157 | func (hdl *DeviceHandle) SwoStart(mode SwoMode, baudrate, size uint32) error {
1158 | rc := int(C.jaylink_swo_start(hdl.hdl, uint32(mode), C.uint32_t(baudrate), C.uint32_t(size)))
1159 | if rc != C.JAYLINK_OK {
1160 | return apiError("jaylink_swo_start", rc)
1161 | }
1162 | return nil
1163 | }
1164 |
1165 | // SwoStop stops SWO capture.
1166 | func (hdl *DeviceHandle) SwoStop() error {
1167 | rc := int(C.jaylink_swo_stop(hdl.hdl))
1168 | if rc != C.JAYLINK_OK {
1169 | return apiError("jaylink_swo_stop", rc)
1170 | }
1171 | return nil
1172 | }
1173 |
1174 | // SwoRead reads SWO trace data.
1175 | func (hdl *DeviceHandle) SwoRead(length int) ([]byte, error) {
1176 | cLength := C.uint32_t(length)
1177 | cBuffer := allocBuffer(length)
1178 | defer freeBuffer(cBuffer)
1179 | rc := int(C.jaylink_swo_read(hdl.hdl, cBuffer, &cLength))
1180 | if rc != C.JAYLINK_OK {
1181 | return nil, apiError("jaylink_swo_read", rc)
1182 | }
1183 | return c2goSlice(cBuffer, int(cLength)), nil
1184 | }
1185 |
1186 | // SwoGetSpeeds retrieves SWO speeds.
1187 | func (hdl *DeviceHandle) SwoGetSpeeds(mode SwoMode) (*SwoSpeed, error) {
1188 | var cSpeed C.struct_jaylink_swo_speed
1189 | rc := int(C.jaylink_swo_get_speeds(hdl.hdl, uint32(mode), &cSpeed))
1190 | if rc != C.JAYLINK_OK {
1191 | return nil, apiError("jaylink_swo_get_speeds", rc)
1192 | }
1193 | speed := SwoSpeed{
1194 | Freq: uint32(cSpeed.freq),
1195 | MinDiv: uint32(cSpeed.min_div),
1196 | MaxDiv: uint32(cSpeed.max_div),
1197 | MinPrescaler: uint32(cSpeed.min_prescaler),
1198 | MaxPrescaler: uint32(cSpeed.max_prescaler),
1199 | }
1200 | return &speed, nil
1201 | }
1202 |
1203 | //-----------------------------------------------------------------------------
1204 | // Target functions
1205 |
1206 | // TargetInterface is a bitmap of target interfaces.
1207 | type TargetInterface uint32
1208 |
1209 | // TargetInterface bit values
1210 | const (
1211 | TIF_JTAG TargetInterface = C.JAYLINK_TIF_JTAG // Joint Test Action Group, IEEE 1149.1 (JTAG).
1212 | TIF_SWD TargetInterface = C.JAYLINK_TIF_SWD // Serial Wire Debug (SWD).
1213 | TIF_BDM3 TargetInterface = C.JAYLINK_TIF_BDM3 // Background Debug Mode 3 (BDM3).
1214 | TIF_FINE TargetInterface = C.JAYLINK_TIF_FINE // Renesas’ single-wire debug interface (FINE).
1215 | TIF_2W_JTAG_PIC32 TargetInterface = C.JAYLINK_TIF_2W_JTAG_PIC32 // 2-wire JTAG for PIC32 compliant devices.
1216 | )
1217 |
1218 | // Speed stores the target interface speed information.
1219 | type Speed struct {
1220 | Freq uint32 // Base frequency in Hz.
1221 | Div uint16 // Minimum frequency divider.
1222 | }
1223 |
1224 | // SetSpeed sets the target interface speed (in kHz units).
1225 | func (hdl *DeviceHandle) SetSpeed(speed uint16) error {
1226 | rc := int(C.jaylink_set_speed(hdl.hdl, C.uint16_t(speed)))
1227 | if rc != C.JAYLINK_OK {
1228 | return apiError("jaylink_set_speed", rc)
1229 | }
1230 | return nil
1231 | }
1232 |
1233 | // GetSpeeds retrieves target interface speeds.
1234 | func (hdl *DeviceHandle) GetSpeeds() (*Speed, error) {
1235 | var cSpeed C.struct_jaylink_speed
1236 | rc := int(C.jaylink_get_speeds(hdl.hdl, &cSpeed))
1237 | if rc != C.JAYLINK_OK {
1238 | return nil, apiError("jaylink_get_speeds", rc)
1239 | }
1240 | speed := Speed{
1241 | Freq: uint32(cSpeed.freq),
1242 | Div: uint16(cSpeed.div),
1243 | }
1244 | return &speed, nil
1245 | }
1246 |
1247 | // GetMaxSpeed returns the maximum interface speed.
1248 | func (hdl *DeviceHandle) GetMaxSpeed() (uint16, error) {
1249 | speed, err := hdl.GetSpeeds()
1250 | if err != nil {
1251 | return 0, err
1252 | }
1253 | if speed.Div == 0 {
1254 | return 0, errors.New("Speed.Div == 0")
1255 | }
1256 | return uint16(speed.Freq / (1000 * uint32(speed.Div))), nil
1257 | }
1258 |
1259 | // SelectInterface selects the target interface.
1260 | func (hdl *DeviceHandle) SelectInterface(iface TargetInterface) (TargetInterface, error) {
1261 | var prev uint32
1262 | rc := int(C.jaylink_select_interface(hdl.hdl, uint32(iface), &prev))
1263 | if rc != C.JAYLINK_OK {
1264 | return 0, apiError("jaylink_select_interface", rc)
1265 | }
1266 | return TargetInterface(prev), nil
1267 | }
1268 |
1269 | // GetAvailableInterfaces retrieves the available target interfaces.
1270 | func (hdl *DeviceHandle) GetAvailableInterfaces() (uint32, error) {
1271 | var ifaces C.uint32_t
1272 | rc := int(C.jaylink_get_available_interfaces(hdl.hdl, &ifaces))
1273 | if rc != C.JAYLINK_OK {
1274 | return 0, apiError("jaylink_get_available_interfaces", rc)
1275 | }
1276 | return uint32(ifaces), nil
1277 | }
1278 |
1279 | // GetSelectedInterface retrieves the selected target interface.
1280 | func (hdl *DeviceHandle) GetSelectedInterface() (TargetInterface, error) {
1281 | var iface uint32
1282 | rc := int(C.jaylink_get_selected_interface(hdl.hdl, &iface))
1283 | if rc != C.JAYLINK_OK {
1284 | return 0, apiError("jaylink_get_selected_interface", rc)
1285 | }
1286 | return TargetInterface(iface), nil
1287 | }
1288 |
1289 | // ClearReset clears the target reset signal.
1290 | func (hdl *DeviceHandle) ClearReset() error {
1291 | rc := int(C.jaylink_clear_reset(hdl.hdl))
1292 | if rc != C.JAYLINK_OK {
1293 | return apiError("jaylink_clear_reset", rc)
1294 | }
1295 | return nil
1296 | }
1297 |
1298 | // SetReset sets the target reset signal.
1299 | func (hdl *DeviceHandle) SetReset() error {
1300 | rc := int(C.jaylink_set_reset(hdl.hdl))
1301 | if rc != C.JAYLINK_OK {
1302 | return apiError("jaylink_set_reset", rc)
1303 | }
1304 | return nil
1305 | }
1306 |
1307 | // SetTargetPower sets the target power supply.
1308 | func (hdl *DeviceHandle) SetTargetPower(enable bool) error {
1309 | rc := int(C.jaylink_set_target_power(hdl.hdl, C.bool(enable)))
1310 | if rc != C.JAYLINK_OK {
1311 | return apiError("jaylink_set_target_power", rc)
1312 | }
1313 | return nil
1314 | }
1315 |
1316 | //-----------------------------------------------------------------------------
1317 | // Version functions
1318 |
1319 | // VersionPackageGetMajor gets the major version number of the libjaylink package.
1320 | func VersionPackageGetMajor() int {
1321 | return int(C.jaylink_version_package_get_major())
1322 | }
1323 |
1324 | // VersionPackageGetMinor gets the minor version number of the libjaylink package.
1325 | func VersionPackageGetMinor() int {
1326 | return int(C.jaylink_version_package_get_minor())
1327 | }
1328 |
1329 | // VersionPackageGetMicro gets the micro version number of the libjaylink package.
1330 | func VersionPackageGetMicro() int {
1331 | return int(C.jaylink_version_package_get_micro())
1332 | }
1333 |
1334 | // VersionPackageGetString gets the version number string of the libjaylink package.
1335 | func VersionPackageGetString() string {
1336 | return C.GoString(C.jaylink_version_package_get_string())
1337 | }
1338 |
1339 | // VersionLibraryGetCurrent gets the current version number of the libjaylink libtool interface.
1340 | func VersionLibraryGetCurrent() int {
1341 | return int(C.jaylink_version_library_get_current())
1342 | }
1343 |
1344 | // VersionLibraryGetRevision gets the revision version number of the libjaylink libtool interface.
1345 | func VersionLibraryGetRevision() int {
1346 | return int(C.jaylink_version_library_get_revision())
1347 | }
1348 |
1349 | // VersionLibraryGetAge gets the age version number of the libjaylink libtool interface.
1350 | func VersionLibraryGetAge() int {
1351 | return int(C.jaylink_version_library_get_age())
1352 | }
1353 |
1354 | // VersionLibraryGetString gets the version number string of the libjaylink libtool interface.
1355 | func VersionLibraryGetString() string {
1356 | return C.GoString(C.jaylink_version_library_get_string())
1357 | }
1358 |
1359 | //-----------------------------------------------------------------------------
1360 |
--------------------------------------------------------------------------------
/test/main.go:
--------------------------------------------------------------------------------
1 | //-----------------------------------------------------------------------------
2 | /*
3 |
4 | Test program to exercise the libjaylink Go wrapper.
5 |
6 | */
7 | //-----------------------------------------------------------------------------
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 |
16 | "github.com/deadsy/jaylink"
17 | )
18 |
19 | //-----------------------------------------------------------------------------
20 |
21 | const colorGreen = "\033[0;32m"
22 | const colorNone = "\033[0m"
23 |
24 | func logCallback(domain, msg string, user interface{}) {
25 | s := []string{colorGreen, domain, msg, colorNone}
26 | fmt.Printf("%s\n", strings.Join(s, ""))
27 | }
28 |
29 | //-----------------------------------------------------------------------------
30 |
31 | func displayDevice(dev *jaylink.Device) string {
32 | s := []string{}
33 | // hardware version
34 | hw, err := dev.GetHardwareVersion()
35 | if err == nil {
36 | s = append(s, fmt.Sprintf("hardware version: %s", hw))
37 | }
38 | // product name
39 | name, err := dev.GetProductName()
40 | if err == nil {
41 | s = append(s, fmt.Sprintf("product name: %s", name))
42 | }
43 | // nickname
44 | name, err = dev.GetNickName()
45 | if err == nil {
46 | s = append(s, fmt.Sprintf("nickname: %s", name))
47 | }
48 | // serial number
49 | sn, err := dev.GetSerialNumber()
50 | if err == nil {
51 | s = append(s, fmt.Sprintf("serial number: %d", sn))
52 | }
53 | // host interface
54 | hi, err := dev.GetHostInterface()
55 | if err == nil {
56 | s = append(s, fmt.Sprintf("host interface: %s", hi.String()))
57 | }
58 | // usb address
59 | addr, err := dev.GetUsbAddress()
60 | if err == nil {
61 | s = append(s, fmt.Sprintf("usb address: %s", addr))
62 | }
63 | // usb bus and ports
64 | bus, ports, err := dev.GetUsbPorts()
65 | if err == nil {
66 | s = append(s, fmt.Sprintf("usb bus/ports: %d %v", bus, ports))
67 | }
68 | // mac address
69 | mac, err := dev.GetMacAddress()
70 | if err == nil {
71 | s = append(s, fmt.Sprintf("mac address: %v", mac))
72 | }
73 | // ipv4 address
74 | ip, err := dev.GetIPv4Address()
75 | if err == nil {
76 | s = append(s, fmt.Sprintf("ipv4 address: %s", ip))
77 | }
78 | return strings.Join(s, "\n")
79 | }
80 |
81 | //-----------------------------------------------------------------------------
82 |
83 | func displayHandle(hdl *jaylink.DeviceHandle) string {
84 | s := []string{}
85 | // firmware version
86 | ver, err := hdl.GetFirmwareVersion()
87 | if err == nil {
88 | s = append(s, fmt.Sprintf("firmware: %s", ver))
89 | }
90 | // hardware version
91 | hw, err := hdl.GetHardwareVersion()
92 | if err == nil {
93 | s = append(s, fmt.Sprintf("hardware: %s", hw))
94 | }
95 | // capabilities
96 | caps, err := hdl.GetAllCaps()
97 | if err == nil {
98 | s = append(s, fmt.Sprintf("capabilities:\n%s", caps))
99 | }
100 | // hardware info
101 | if caps.HasCap(jaylink.DEV_CAP_GET_HW_INFO) {
102 | mask := jaylink.HW_INFO_TARGET_POWER |
103 | jaylink.HW_INFO_ITARGET |
104 | jaylink.HW_INFO_ITARGET_PEAK
105 | info, err := hdl.GetHardwareInfo(mask)
106 | if err == nil {
107 | s = append(s, fmt.Sprintf("target power: %x", info[0]))
108 | s = append(s, fmt.Sprintf("target current: %x", info[1]))
109 | s = append(s, fmt.Sprintf("peak target current: %x", info[2]))
110 | }
111 | }
112 | // free memory
113 | if caps.HasCap(jaylink.DEV_CAP_GET_FREE_MEMORY) {
114 | free, err := hdl.GetFreeMemory()
115 | if err == nil {
116 | s = append(s, fmt.Sprintf("free memory: %d bytes", free))
117 | }
118 | }
119 | // hardware status
120 | status, err := hdl.GetHardwareStatus()
121 | if err == nil {
122 | s = append(s, fmt.Sprintf("status: %s", status))
123 | }
124 | // maximum interface speed
125 | speed, err := hdl.GetMaxSpeed()
126 | if err == nil {
127 | s = append(s, fmt.Sprintf("max speed: %dkHz", speed))
128 | }
129 | // config
130 | config, err := hdl.ReadRawConfig()
131 | if err == nil {
132 | s = append(s, fmt.Sprintf("config: %v", config))
133 | }
134 |
135 | return strings.Join(s, "\n")
136 | }
137 |
138 | //-----------------------------------------------------------------------------
139 |
140 | func libTest() error {
141 |
142 | fmt.Printf("package: %s\n", jaylink.VersionPackageGetString())
143 | fmt.Printf("library: %s\n", jaylink.VersionLibraryGetString())
144 |
145 | ctx, err := jaylink.Init()
146 | if err != nil {
147 | return err
148 | }
149 | defer ctx.Exit()
150 |
151 | err = ctx.LogSetCallback(logCallback, nil)
152 | if err != nil {
153 | return err
154 | }
155 |
156 | err = ctx.LogSetLevel(jaylink.LOG_LEVEL_DEBUG)
157 | if err != nil {
158 | return err
159 | }
160 |
161 | err = ctx.LogSetDomain("test: ")
162 | if err != nil {
163 | return err
164 | }
165 |
166 | err = ctx.DiscoveryScan(jaylink.HIF_USB)
167 | if err != nil {
168 | return err
169 | }
170 |
171 | dev, err := ctx.GetDevices()
172 | if err != nil {
173 | return err
174 | }
175 | defer ctx.FreeDevices(dev, true)
176 |
177 | fmt.Printf("%d devices found\n", len(dev))
178 | for i := range dev {
179 | fmt.Printf("device %d\n%s\n", i, displayDevice(&dev[i]))
180 |
181 | hdl, err := dev[i].Open()
182 | if err != nil {
183 | fmt.Printf("%s\n", err)
184 | continue
185 | }
186 |
187 | fmt.Printf("%s\n", displayHandle(hdl))
188 |
189 | err = hdl.Close()
190 | if err != nil {
191 | fmt.Printf("%s\n", err)
192 | continue
193 | }
194 | }
195 |
196 | return nil
197 | }
198 |
199 | //-----------------------------------------------------------------------------
200 |
201 | func main() {
202 | err := libTest()
203 | if err != nil {
204 | fmt.Printf("%s\n", err)
205 | os.Exit(1)
206 | }
207 | os.Exit(0)
208 | }
209 |
210 | //-----------------------------------------------------------------------------
211 |
--------------------------------------------------------------------------------