@thi.ng/axidraw 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Change Log
2
+
3
+ - **Last updated**: 2022-12-06T17:16:38Z
4
+ - **Generator**: [thi.ng/monopub](https://thi.ng/monopub)
5
+
6
+ All notable changes to this project will be documented in this file.
7
+ See [Conventional Commits](https://conventionalcommits.org/) for commit guidelines.
8
+
9
+ **Note:** Unlisted _patch_ versions only involve non-code or otherwise excluded changes
10
+ and/or version bumps of transitive dependencies.
11
+
12
+ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/axidraw@0.1.0) (2022-12-06)
13
+
14
+ #### 🚀 Features
15
+
16
+ - import as new pkg ([cc43e84](https://github.com/thi-ng/umbrella/commit/cc43e84))
17
+ - arbitrary unit support, measure draw time ([32e3212](https://github.com/thi-ng/umbrella/commit/32e3212))
18
+ - add AxiDrawOpts.unitsPerInch to support any worldspace units
19
+ - remove paperSize opt
20
+ - add command constants for better mem use
21
+ - update AxiDraw.draw() to measure & return time taken
22
+ - add/update doc strings
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,170 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+
3
+ # ![axidraw](https://media.thi.ng/umbrella/banners-20220914/thing-axidraw.svg?25c834ce)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/axidraw.svg)](https://www.npmjs.com/package/@thi.ng/axidraw)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/axidraw.svg)
7
+ [![Twitter Follow](https://img.shields.io/twitter/follow/thing_umbrella.svg?style=flat-square&label=twitter)](https://twitter.com/thing_umbrella)
8
+
9
+ This project is part of the
10
+ [@thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo.
11
+
12
+ - [About](#about)
13
+ - [Declarative vs. imperative](#declarative-vs-imperative)
14
+ - [No SVG support](#no-svg-support)
15
+ - [Serial port support](#serial-port-support)
16
+ - [Status](#status)
17
+ - [Installation](#installation)
18
+ - [Dependencies](#dependencies)
19
+ - [API](#api)
20
+ - [Authors](#authors)
21
+ - [License](#license)
22
+
23
+ ## About
24
+
25
+ Minimal AxiDraw plotter/drawing machine controller for Node.js.
26
+
27
+ This package provides a super-lightweight alternative to control an [AxiDraw
28
+ plotter](https://axidraw.com/) directly from Node.js, using a small custom set
29
+ of medium/high-level drawing commands. Structurally, these custom commands are
30
+ [thi.ng/hiccup-like](https://github.com/thi-ng/umbrella/blob/develop/packages/hiccup/)
31
+ S-expressions, which can be easily serialized to/from JSON and are translated to
32
+ [EBB commands](https://evil-mad.github.io/EggBot/ebb.html) for the plotter.
33
+
34
+ ### Declarative vs. imperative
35
+
36
+ Due to AxiDraw's lack of G-Code support, most other available AxiDraw support
37
+ libraries are providing only a purely imperative API to control the machine. In
38
+ contrast, this package utilizes a more declarative approach, also very much
39
+ following the pattern of other packages in the
40
+ [thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo, which allows
41
+ (geometry) data to be inspected, augmented, converted/transformed, serialized up
42
+ until the very last moment before being sent to the machine for physical
43
+ output...
44
+
45
+ ### No SVG support
46
+
47
+ This package does **not** provide conversion from SVG or any other geometry
48
+ format conversions. Whilst not containing a full SVG parser (only single paths),
49
+ the family of
50
+ [thi.ng/geom](https://github.com/thi-ng/umbrella/tree/develop/packages/geom)
51
+ packages provides numerous other shape types & operations which can be directly
52
+ utilized to output generated geometry together with this package...
53
+
54
+ The only built-in conversion provided is the [`AxiDraw.polyline()`]() method to
55
+ convert an array of points (representing a polyline) into an array of drawing
56
+ commands. All other conversions are out of scope for this package (& for now).
57
+
58
+ ### Serial port support
59
+
60
+ We're using the [serialport](https://serialport.io/) NPM package to submit data
61
+ directly to the drawing machine. That pacakge includes native bindings for
62
+ Linux, MacOS and Windows.
63
+
64
+ The `AxiDraw.connect()` function (see example below) attempts to find the
65
+ drawing machine by matching a given regexp with available port names. The
66
+ default regexp might only work on Mac, but YMMV!
67
+
68
+ ## Status
69
+
70
+ **ALPHA** - bleeding edge / work-in-progress
71
+
72
+ [Search or submit any issues for this package](https://github.com/thi-ng/umbrella/issues?q=%5Baxidraw%5D+in%3Atitle)
73
+
74
+ ## Installation
75
+
76
+ ```bash
77
+ yarn add @thi.ng/axidraw
78
+ ```
79
+
80
+ ES module import:
81
+
82
+ ```html
83
+ <script type="module" src="https://cdn.skypack.dev/@thi.ng/axidraw"></script>
84
+ ```
85
+
86
+ [Skypack documentation](https://docs.skypack.dev/)
87
+
88
+ For Node.js REPL:
89
+
90
+ ```text
91
+ # with flag only for < v16
92
+ node --experimental-repl-await
93
+
94
+ > const axidraw = await import("@thi.ng/axidraw");
95
+ ```
96
+
97
+ Package sizes (brotli'd, pre-treeshake): ESM: 1.01 KB
98
+
99
+ ## Dependencies
100
+
101
+ - [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
102
+ - [@thi.ng/compose](https://github.com/thi-ng/umbrella/tree/develop/packages/compose)
103
+ - [@thi.ng/errors](https://github.com/thi-ng/umbrella/tree/develop/packages/errors)
104
+ - [@thi.ng/logger](https://github.com/thi-ng/umbrella/tree/develop/packages/logger)
105
+ - [@thi.ng/vectors](https://github.com/thi-ng/umbrella/tree/develop/packages/vectors)
106
+ - [serialport](https://github.com/thi-ng/umbrella/tree/develop/packages/undefined)
107
+
108
+ ## API
109
+
110
+ [Generated API docs](https://docs.thi.ng/umbrella/axidraw/)
111
+
112
+ ```ts tangle:export/readme.js
113
+ import { AxiDraw } from "@thi.ng/axidraw";
114
+ import { circle, vertices } from "@thi.ng/geom";
115
+
116
+ (async () => {
117
+
118
+ // instantiate w/ default options (see docs for info)
119
+ // default paper size is DIN A4
120
+ const axi = new AxiDraw();
121
+
122
+ // connect to 1st serial port matching given regexp
123
+ await axi.connect(/^\/dev\/tty\.usbmodem/);
124
+ // true
125
+
126
+ // compute 60 points on a circle at (100,50) w/ radius 30
127
+ // (all units in mm)
128
+ const verts = vertices(circle([100, 50], 30), { num: 60, last: true });
129
+ // [
130
+ // [ 130, 50 ],
131
+ // [ 129.8356568610482, 53.1358538980296 ],
132
+ // [ 129.34442802201417, 56.23735072453278 ],
133
+ // ...
134
+ // ]
135
+
136
+ // convert to drawing commands (w/ default opts)
137
+ const path = axi.polyline(verts)
138
+ // [
139
+ // [ 'u' ],
140
+ // [ 'm', [ 130, 50 ], 1 ],
141
+ // [ 'd' ],
142
+ // [ 'm', [ 129.8356568610482, 53.1358538980296 ], 1 ],
143
+ // [ 'm', [ 129.34442802201417, 56.23735072453278 ], 1 ],
144
+ // ...
145
+ // ]
146
+
147
+ // draw/send seq of commands (incl. start/end sequence, configurable)
148
+ await axi.draw([["start"], ...path, ["stop"]]);
149
+
150
+ })();
151
+ ```
152
+
153
+ ## Authors
154
+
155
+ Karsten Schmidt
156
+
157
+ If this project contributes to an academic publication, please cite it as:
158
+
159
+ ```bibtex
160
+ @misc{thing-axidraw,
161
+ title = "@thi.ng/axidraw",
162
+ author = "Karsten Schmidt",
163
+ note = "https://thi.ng/axidraw",
164
+ year = 2022
165
+ }
166
+ ```
167
+
168
+ ## License
169
+
170
+ &copy; 2022 Karsten Schmidt // Apache Software License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,101 @@
1
+ import type { ILogger } from "@thi.ng/logger";
2
+ import type { ReadonlyVec } from "@thi.ng/vectors";
3
+ /** Start command sequence (configurable via {@link AxiDrawOpts}) */
4
+ export declare type StartCommand = ["start"];
5
+ /** Stop command sequence (configurable via {@link AxiDrawOpts}) */
6
+ export declare type StopCommand = ["stop"];
7
+ /** Return plotter to initial XY position */
8
+ export declare type HomeCommand = ["home"];
9
+ /** Turn XY motors on/off */
10
+ export declare type MotorCommand = ["on" | "off"];
11
+ /** Pen config, min/down position, max/up position (in %) */
12
+ export declare type PenConfigCommand = ["pen", number?, number?];
13
+ /**
14
+ * Pen up/down, optional delay (in ms), if omitted values used from
15
+ * {@link AxiDrawOpts}.
16
+ */
17
+ export declare type PenUpDownCommand = ["u" | "d", number?];
18
+ /**
19
+ * Move to abs pos (in worldspace coords, default mm), optional speed factor
20
+ * (default: 1)
21
+ */
22
+ export declare type MoveXYCommand = ["m", ReadonlyVec, number?];
23
+ /** Explicit delay (in ms) */
24
+ export declare type WaitCommand = ["w", number];
25
+ export declare type DrawCommand = StartCommand | StopCommand | HomeCommand | MotorCommand | PenConfigCommand | PenUpDownCommand | MoveXYCommand | WaitCommand;
26
+ export interface AxiDrawOpts {
27
+ /**
28
+ * Conversion factor from geometry worldspace units to inches.
29
+ * Default units are millimeters.
30
+ *
31
+ * @defaultValue 25.4
32
+ */
33
+ unitsPerInch: number;
34
+ /**
35
+ * Hardware resolution (steps / inch)
36
+ *
37
+ * @defaultValue 2032
38
+ */
39
+ stepsPerInch: number;
40
+ /**
41
+ * Steps per second
42
+ *
43
+ * @defaultValue 4000
44
+ */
45
+ speed: number;
46
+ /**
47
+ * Up position (%)
48
+ *
49
+ * @defaultValue 60
50
+ */
51
+ up: number;
52
+ /**
53
+ * Up position (%)
54
+ *
55
+ * @defaultValue 30
56
+ */
57
+ down: number;
58
+ /**
59
+ * Delay after pen up
60
+ *
61
+ * @defaultValue 300
62
+ */
63
+ delayUp: number;
64
+ /**
65
+ * Delay after pen down
66
+ *
67
+ * @defaultValue 300
68
+ */
69
+ delayDown: number;
70
+ /**
71
+ * Time in ms to subtract from actual delay time until next command
72
+ *
73
+ * @defaultValue 0
74
+ */
75
+ preDelay: number;
76
+ /**
77
+ * Sequence for `start` {@link DrawCommand}
78
+ *
79
+ * @defaultValue `[ON, PEN, UP]`
80
+ */
81
+ start: DrawCommand[];
82
+ /**
83
+ * Sequence for `end` {@link DrawCommand}
84
+ *
85
+ * @defaultValue `[UP, HOME, OFF]`
86
+ */
87
+ stop: DrawCommand[];
88
+ /**
89
+ * Logger instance
90
+ */
91
+ logger: ILogger;
92
+ }
93
+ export declare const START: StartCommand;
94
+ export declare const STOP: StopCommand;
95
+ export declare const HOME: HomeCommand;
96
+ export declare const PEN: PenConfigCommand;
97
+ export declare const UP: PenUpDownCommand;
98
+ export declare const DOWN: PenUpDownCommand;
99
+ export declare const ON: MotorCommand;
100
+ export declare const OFF: MotorCommand;
101
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
@@ -0,0 +1,8 @@
1
+ export const START = ["start"];
2
+ export const STOP = ["stop"];
3
+ export const HOME = ["home"];
4
+ export const PEN = ["pen"];
5
+ export const UP = ["u"];
6
+ export const DOWN = ["d"];
7
+ export const ON = ["on"];
8
+ export const OFF = ["off"];
package/axidraw.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { Fn0 } from "@thi.ng/api";
2
+ import { ReadonlyVec, Vec } from "@thi.ng/vectors";
3
+ import { SerialPort } from "serialport";
4
+ import { AxiDrawOpts, DrawCommand } from "./api.js";
5
+ export declare const DEFAULT_OPTS: AxiDrawOpts;
6
+ export declare class AxiDraw {
7
+ serial: SerialPort;
8
+ opts: AxiDrawOpts;
9
+ isConnected: boolean;
10
+ pos: Vec;
11
+ constructor(opts?: Partial<AxiDrawOpts>);
12
+ /**
13
+ * Async function. Attempts to connect to the drawing machine via given
14
+ * (partial) serial port path/name, returns true if successful.
15
+ *
16
+ * @param path
17
+ */
18
+ connect(path?: RegExp): Promise<boolean>;
19
+ /**
20
+ * Async function. Converts sequence of {@link DrawCommand}s into actual EBB
21
+ * commands and sends them via configured serial port to the AxiDraw. The
22
+ * optional `cancel` predicate is checked prior to each individual command
23
+ * and processing is stopped if that function returns a truthy result.
24
+ *
25
+ * Returns number of milliseconds taken for drawing.
26
+ *
27
+ * @remarks
28
+ * This function is async and if using `await` will only return once all
29
+ * commands have been processed or cancelled.
30
+ *
31
+ * Reference:
32
+ * - http://evil-mad.github.io/EggBot/ebb.html
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * // execute start sequence, draw a triangle, then exec stop sequence
37
+ * axi.draw([
38
+ * ["start"],
39
+ * ...axi.polyline([[50,50], [100,50], [75, 100], [50,50]]),
40
+ * ["stop"]
41
+ * ]);
42
+ * ```
43
+ *
44
+ * @param commands
45
+ * @param cancel
46
+ */
47
+ draw(commands: Iterable<DrawCommand>, cancel?: Fn0<boolean>): Promise<number>;
48
+ /**
49
+ * Takes an array of 2D points and converts them into an array of
50
+ * {@link DrawCommand}s. The optional `speed` factor can be used to control
51
+ * draw speed (default: 1).
52
+ *
53
+ * @remarks
54
+ * Unless `onlyGeo` is explicitly enabled, the resulting command sequence
55
+ * will also contain necessary pen up/down commands.
56
+ *
57
+ * @param pts
58
+ * @param speed
59
+ * @param onlyGeo
60
+ */
61
+ polyline(pts: ReadonlyVec[], speed?: number, onlyGeo?: boolean): DrawCommand[];
62
+ protected send(msg: string): void;
63
+ }
64
+ //# sourceMappingURL=axidraw.d.ts.map
package/axidraw.js ADDED
@@ -0,0 +1,171 @@
1
+ import { delayed } from "@thi.ng/compose";
2
+ import { assert, unsupported } from "@thi.ng/errors";
3
+ import { ConsoleLogger } from "@thi.ng/logger";
4
+ import { abs2, mulN2, set2, sub2 } from "@thi.ng/vectors";
5
+ import { SerialPort } from "serialport";
6
+ import { DOWN, HOME, OFF, ON, PEN, UP, } from "./api.js";
7
+ export const DEFAULT_OPTS = {
8
+ logger: new ConsoleLogger("axidraw"),
9
+ unitsPerInch: 25.4,
10
+ stepsPerInch: 2032,
11
+ speed: 4000,
12
+ up: 60,
13
+ down: 30,
14
+ delayUp: 300,
15
+ delayDown: 300,
16
+ preDelay: 0,
17
+ start: [ON, PEN, UP],
18
+ stop: [UP, HOME, OFF],
19
+ };
20
+ export class AxiDraw {
21
+ constructor(opts = {}) {
22
+ this.isConnected = false;
23
+ this.pos = [0, 0];
24
+ this.opts = { ...DEFAULT_OPTS, ...opts };
25
+ }
26
+ /**
27
+ * Async function. Attempts to connect to the drawing machine via given
28
+ * (partial) serial port path/name, returns true if successful.
29
+ *
30
+ * @param path
31
+ */
32
+ async connect(path = /^\/dev\/tty\.usbmodem/) {
33
+ for (let port of await SerialPort.list()) {
34
+ if (path.test(port.path)) {
35
+ this.opts.logger.info(`using device: ${port.path}...`);
36
+ this.serial = new SerialPort({
37
+ path: port.path,
38
+ baudRate: 38400,
39
+ });
40
+ this.isConnected = true;
41
+ return true;
42
+ }
43
+ }
44
+ return false;
45
+ }
46
+ /**
47
+ * Async function. Converts sequence of {@link DrawCommand}s into actual EBB
48
+ * commands and sends them via configured serial port to the AxiDraw. The
49
+ * optional `cancel` predicate is checked prior to each individual command
50
+ * and processing is stopped if that function returns a truthy result.
51
+ *
52
+ * Returns number of milliseconds taken for drawing.
53
+ *
54
+ * @remarks
55
+ * This function is async and if using `await` will only return once all
56
+ * commands have been processed or cancelled.
57
+ *
58
+ * Reference:
59
+ * - http://evil-mad.github.io/EggBot/ebb.html
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * // execute start sequence, draw a triangle, then exec stop sequence
64
+ * axi.draw([
65
+ * ["start"],
66
+ * ...axi.polyline([[50,50], [100,50], [75, 100], [50,50]]),
67
+ * ["stop"]
68
+ * ]);
69
+ * ```
70
+ *
71
+ * @param commands
72
+ * @param cancel
73
+ */
74
+ async draw(commands, cancel) {
75
+ assert(this.isConnected, "AxiDraw not yet connected, need to call .connect() first");
76
+ let t0 = Date.now();
77
+ if (!cancel)
78
+ cancel = () => false;
79
+ const { opts: config, pos } = this;
80
+ const { stepsPerInch, unitsPerInch, speed, preDelay } = config;
81
+ // scale factor: worldspace units -> motor steps
82
+ const scale = stepsPerInch / unitsPerInch;
83
+ let targetPos = [0, 0];
84
+ let delta = [0, 0];
85
+ for (let $cmd of commands) {
86
+ if (cancel())
87
+ break;
88
+ const [cmd, a, b] = $cmd;
89
+ let wait = -1;
90
+ switch (cmd) {
91
+ case "start":
92
+ case "stop":
93
+ this.draw(config[cmd], cancel);
94
+ break;
95
+ case "home":
96
+ this.draw([["m", [0, 0]]], cancel);
97
+ break;
98
+ case "on":
99
+ this.send("EM,1,1\r");
100
+ break;
101
+ case "off":
102
+ this.send("EM,0,0\r");
103
+ break;
104
+ case "pen":
105
+ {
106
+ let val = a !== undefined ? a : config.down;
107
+ // unit ref:
108
+ // https://github.com/evil-mad/AxiDraw-Processing/blob/80d81a8c897b8a1872b0555af52a8d1b5b13cec4/AxiGen1/AxiGen1.pde#L213
109
+ this.send(`SC,5,${(7500 + 175 * val) | 0}\r`);
110
+ val = b !== undefined ? b : config.up;
111
+ this.send(`SC,4,${(7500 + 175 * val) | 0}\r`);
112
+ this.send(`SC,10,65535\r`);
113
+ }
114
+ break;
115
+ case "u":
116
+ wait = a !== undefined ? a : config.delayUp;
117
+ this.send(`SP,1,${wait}\r`);
118
+ break;
119
+ case "d":
120
+ wait = a !== undefined ? a : config.delayDown;
121
+ this.send(`SP,0,${wait}\r`);
122
+ break;
123
+ case "w":
124
+ wait = a;
125
+ break;
126
+ case "m":
127
+ {
128
+ mulN2(targetPos, a, scale);
129
+ sub2(delta, targetPos, pos);
130
+ set2(pos, targetPos);
131
+ config.logger.info("target", targetPos, "delta", delta);
132
+ const maxAxis = Math.max(...abs2([], delta));
133
+ wait = (1000 * maxAxis) / (speed * (b || 1));
134
+ this.send(`XM,${wait | 0},${delta[0] | 0},${delta[1] | 0}\r`);
135
+ }
136
+ break;
137
+ default:
138
+ unsupported(`unknown command: ${$cmd}`);
139
+ }
140
+ if (wait > 0) {
141
+ wait = Math.max(0, wait - preDelay);
142
+ config.logger.debug(`waiting ${wait}ms...`);
143
+ await delayed(0, wait);
144
+ }
145
+ }
146
+ return Date.now() - t0;
147
+ }
148
+ /**
149
+ * Takes an array of 2D points and converts them into an array of
150
+ * {@link DrawCommand}s. The optional `speed` factor can be used to control
151
+ * draw speed (default: 1).
152
+ *
153
+ * @remarks
154
+ * Unless `onlyGeo` is explicitly enabled, the resulting command sequence
155
+ * will also contain necessary pen up/down commands.
156
+ *
157
+ * @param pts
158
+ * @param speed
159
+ * @param onlyGeo
160
+ */
161
+ polyline(pts, speed = 1, onlyGeo = false) {
162
+ const commands = pts.map((p) => ["m", p, speed]);
163
+ return onlyGeo
164
+ ? commands
165
+ : [UP, commands[0], DOWN, ...commands.slice(1), UP];
166
+ }
167
+ send(msg) {
168
+ this.opts.logger.debug(msg);
169
+ this.serial.write(msg);
170
+ }
171
+ }
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./api.js";
2
+ export * from "./axidraw.js";
3
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./api.js";
2
+ export * from "./axidraw.js";
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@thi.ng/axidraw",
3
+ "version": "0.1.0",
4
+ "description": "Minimal AxiDraw plotter/drawing machine controller for Node.js",
5
+ "type": "module",
6
+ "module": "./index.js",
7
+ "typings": "./index.d.ts",
8
+ "sideEffects": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/thi-ng/umbrella.git"
12
+ },
13
+ "homepage": "https://github.com/thi-ng/umbrella/tree/master/packages/axidraw#readme",
14
+ "funding": [
15
+ {
16
+ "type": "github",
17
+ "url": "https://github.com/sponsors/postspectacular"
18
+ },
19
+ {
20
+ "type": "patreon",
21
+ "url": "https://patreon.com/thing_umbrella"
22
+ }
23
+ ],
24
+ "author": "Karsten Schmidt <k+npm@thi.ng>",
25
+ "license": "Apache-2.0",
26
+ "scripts": {
27
+ "build": "yarn clean && tsc --declaration",
28
+ "clean": "rimraf '*.js' '*.d.ts' '*.map' doc",
29
+ "doc": "typedoc --excludePrivate --excludeInternal --out doc src/index.ts",
30
+ "doc:ae": "mkdir -p .ae/doc .ae/temp && api-extractor run --local --verbose",
31
+ "doc:readme": "yarn doc:stats && tools:readme",
32
+ "doc:stats": "tools:module-stats",
33
+ "pub": "yarn npm publish --access public",
34
+ "test": "testament test"
35
+ },
36
+ "dependencies": {
37
+ "@thi.ng/api": "^8.5.1",
38
+ "@thi.ng/compose": "^2.1.20",
39
+ "@thi.ng/errors": "^2.2.5",
40
+ "@thi.ng/logger": "^1.4.4",
41
+ "@thi.ng/vectors": "^7.5.26",
42
+ "serialport": "^10.5.0"
43
+ },
44
+ "devDependencies": {
45
+ "@microsoft/api-extractor": "^7.33.5",
46
+ "@thi.ng/testament": "^0.3.6",
47
+ "rimraf": "^3.0.2",
48
+ "tools": "^0.0.1",
49
+ "typedoc": "^0.23.20",
50
+ "typescript": "^4.8.4"
51
+ },
52
+ "keywords": [
53
+ "axidraw",
54
+ "geometry",
55
+ "io",
56
+ "logger",
57
+ "node",
58
+ "plotter",
59
+ "polygon",
60
+ "polyline",
61
+ "serial",
62
+ "typescript"
63
+ ],
64
+ "publishConfig": {
65
+ "access": "public"
66
+ },
67
+ "engines": {
68
+ "node": ">=14"
69
+ },
70
+ "files": [
71
+ "./*.js",
72
+ "./*.d.ts"
73
+ ],
74
+ "exports": {
75
+ ".": {
76
+ "default": "./index.js"
77
+ },
78
+ "./api": {
79
+ "default": "./api.js"
80
+ },
81
+ "./axidraw": {
82
+ "default": "./axidraw.js"
83
+ }
84
+ },
85
+ "thi.ng": {
86
+ "status": "alpha",
87
+ "year": 2022
88
+ },
89
+ "gitHead": "54c5f22520162bac0d58426a3f86ca636e797f71\n"
90
+ }