@iotflows/mtconnect 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +75 -2
- package/package.json +23 -4
- package/src/agent.js +138 -0
- package/src/index.d.ts +45 -0
- package/src/index.js +5 -0
- package/src/machine.js +81 -0
- package/src/xml.js +59 -0
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
CHANGED
|
@@ -1,3 +1,76 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @iotflows/mtconnect
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Watch an MTConnect agent for each machine's execution state and the parts it makes. No dependencies.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @iotflows/mtconnect
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Requires Node.js 20+.
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
const { MTConnectAgent } = require('@iotflows/mtconnect');
|
|
13
|
+
|
|
14
|
+
const agent = new MTConnectAgent('https://demo.mtconnect.org');
|
|
15
|
+
|
|
16
|
+
agent.on('execution', (e) => console.log(e.device, e.state)); // OKUMA RUNNING
|
|
17
|
+
agent.on('parts', (e) => console.log(e.device, e.count, e.program)); // OKUMA 1 IMTS-2022-1E-MM.MIN
|
|
18
|
+
|
|
19
|
+
agent.start();
|
|
20
|
+
// agent.stop();
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Events
|
|
24
|
+
|
|
25
|
+
| Event | Payload | When |
|
|
26
|
+
|--------------|---------|------|
|
|
27
|
+
| `execution` | `{ device, state, execution, mode, timestamp }` | A machine's state changes. On start, one event per machine with its current state. |
|
|
28
|
+
| `parts` | `{ device, count, program, timestamp }` | A machine made `count` parts. `program` is "program - comment". |
|
|
29
|
+
| `connect` | | The agent is reachable (on start, and again after an outage). |
|
|
30
|
+
| `disconnect` | `error` | The agent is unreachable. Every machine then gets an `execution` event with `UNKNOWN`. |
|
|
31
|
+
|
|
32
|
+
`device` is the MTConnect device name. `timestamp` is the agent's time for the change. It's undefined for the initial state, because that may be hours old.
|
|
33
|
+
|
|
34
|
+
## How it decides
|
|
35
|
+
|
|
36
|
+
**State**
|
|
37
|
+
- `Execution` `ACTIVE` → `RUNNING`.
|
|
38
|
+
- `UNAVAILABLE`, or the agent can't be reached → `UNKNOWN`.
|
|
39
|
+
- Anything else (`READY`, `INTERRUPTED`, `FEED_HOLD`, …) → `STOPPED`.
|
|
40
|
+
- With `automaticOnly: true`, `ACTIVE` only counts as `RUNNING` when `ControllerMode` is `AUTOMATIC`.
|
|
41
|
+
|
|
42
|
+
**Parts**
|
|
43
|
+
- Every increase of `PartCount` is counted. `TARGET`, `REMAINING`, `BAD`, `ABORTED` and `FAILED` counters are ignored.
|
|
44
|
+
- If the counter goes down, it was reset, so its new value is counted as new parts.
|
|
45
|
+
- After an outage, parts made in the meantime are counted.
|
|
46
|
+
- Machines without a `PartCount` count one part each time `Execution` becomes `PROGRAM_COMPLETED`.
|
|
47
|
+
|
|
48
|
+
It reads `/current` once, then every change through `/sample`, so brief states between polls (like a 0.25 s `PROGRAM_COMPLETED`) aren't missed. Only the five data items it uses are requested.
|
|
49
|
+
|
|
50
|
+
## Send to IoTFlows
|
|
51
|
+
|
|
52
|
+
With [`@iotflows/device`](https://www.npmjs.com/package/@iotflows/device):
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
const { IoTFlowsDevice } = require('@iotflows/device');
|
|
56
|
+
const { MTConnectAgent } = require('@iotflows/mtconnect');
|
|
57
|
+
|
|
58
|
+
const iotflows = new IoTFlowsDevice({ username: 'dev_xxxxxxxx', password: 'xxxxxxxx' });
|
|
59
|
+
await iotflows.connect();
|
|
60
|
+
|
|
61
|
+
const agent = new MTConnectAgent('http://192.168.1.50:5000');
|
|
62
|
+
agent.on('execution', (e) => iotflows.asset(e.device).execution(e.state));
|
|
63
|
+
agent.on('parts', (e) => iotflows.asset(e.device).count(e.count, e.program ? { part_name: e.program } : {}));
|
|
64
|
+
agent.start();
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
This assumes each IoTFlows asset has the same name as its MTConnect device. For a ready-to-run version with a config file, name mapping and logging, see [iotflows-mtconnect-gateway](https://github.com/iotflows/iotflows-mtconnect-gateway).
|
|
68
|
+
|
|
69
|
+
## Options
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
new MTConnectAgent(url, {
|
|
73
|
+
interval: 2000, // poll every 2 s
|
|
74
|
+
automaticOnly: false,
|
|
75
|
+
});
|
|
76
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iotflows/mtconnect",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Simple MTConnect client: watch an agent for machine execution state and parts made.",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "src/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"src"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "node --test test/unit.test.js"
|
|
12
|
+
},
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"mtconnect",
|
|
18
|
+
"cnc",
|
|
19
|
+
"machine-monitoring",
|
|
20
|
+
"oee",
|
|
21
|
+
"iotflows"
|
|
22
|
+
],
|
|
23
|
+
"homepage": "https://iotflows.com",
|
|
24
|
+
"license": "Apache-2.0"
|
|
25
|
+
}
|
package/src/agent.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { EventEmitter } = require('events');
|
|
4
|
+
const { setTimeout: sleep } = require('timers/promises');
|
|
5
|
+
const { PATH, parseHeader, parseObservations } = require('./xml');
|
|
6
|
+
const { Machine } = require('./machine');
|
|
7
|
+
|
|
8
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Watches an MTConnect agent and emits:
|
|
12
|
+
* 'execution' { device, state, execution, mode, timestamp } state is RUNNING | STOPPED | UNKNOWN
|
|
13
|
+
* 'parts' { device, count, program, timestamp } parts made since the last event
|
|
14
|
+
* 'connect' agent reachable (again)
|
|
15
|
+
* 'disconnect' (error) agent unreachable; every machine goes UNKNOWN
|
|
16
|
+
*
|
|
17
|
+
* It reads /current once, then every change through /sample, so short states between polls aren't missed.
|
|
18
|
+
*/
|
|
19
|
+
class MTConnectAgent extends EventEmitter {
|
|
20
|
+
constructor(url, { interval = 2000, automaticOnly = false } = {}) {
|
|
21
|
+
super();
|
|
22
|
+
if (!url) throw new Error('MTConnectAgent needs the agent URL, e.g. http://192.168.1.50:5000');
|
|
23
|
+
this.url = url.replace(/\/$/, '');
|
|
24
|
+
this.interval = interval;
|
|
25
|
+
this.automaticOnly = automaticOnly;
|
|
26
|
+
this.machines = new Map(); // MTConnect device name -> Machine
|
|
27
|
+
this.connected = false;
|
|
28
|
+
this._emitted = new Map(); // device name -> last emitted state
|
|
29
|
+
this._next = null; // where to continue reading: { instanceId, nextSequence }
|
|
30
|
+
this._stopper = null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Start polling. */
|
|
34
|
+
start() {
|
|
35
|
+
if (this._stopper) return;
|
|
36
|
+
this._stopper = new AbortController();
|
|
37
|
+
this._loop(this._stopper.signal);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Stop polling, including any request in progress. */
|
|
41
|
+
stop() {
|
|
42
|
+
this._stopper?.abort();
|
|
43
|
+
this._stopper = null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async _loop(signal) {
|
|
47
|
+
let down = false;
|
|
48
|
+
while (!signal.aborted) {
|
|
49
|
+
try {
|
|
50
|
+
await this._poll(signal);
|
|
51
|
+
if (!this.connected) {
|
|
52
|
+
this.connected = true;
|
|
53
|
+
down = false;
|
|
54
|
+
this.emit('connect');
|
|
55
|
+
}
|
|
56
|
+
} catch (err) {
|
|
57
|
+
if (signal.aborted) break;
|
|
58
|
+
this._next = null;
|
|
59
|
+
this.connected = false;
|
|
60
|
+
if (!down) this.emit('disconnect', err);
|
|
61
|
+
down = true;
|
|
62
|
+
for (const machine of this.machines.values()) {
|
|
63
|
+
machine.execution = undefined; // nothing is known while the agent is unreachable
|
|
64
|
+
this._emitState(machine);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
await sleep(this.interval, undefined, { signal }).catch(() => {});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Read everything new since the last poll. */
|
|
72
|
+
async _poll(signal) {
|
|
73
|
+
while (!signal.aborted) {
|
|
74
|
+
if (!this._next) return this._readCurrent(signal);
|
|
75
|
+
|
|
76
|
+
const xml = await this._fetch('sample', { from: this._next.nextSequence, count: 1000 }, signal);
|
|
77
|
+
const header = parseHeader(xml);
|
|
78
|
+
if (!header || header.instanceId !== this._next.instanceId) {
|
|
79
|
+
// Agent restarted, or we fell behind its buffer: start over
|
|
80
|
+
this._next = null;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
this._apply(parseObservations(xml), true);
|
|
84
|
+
this._next = header;
|
|
85
|
+
if (header.nextSequence > header.lastSequence) return; // caught up
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async _readCurrent(signal) {
|
|
90
|
+
const xml = await this._fetch('current', {}, signal);
|
|
91
|
+
const header = parseHeader(xml);
|
|
92
|
+
if (!header) throw new Error('Unexpected response from /current');
|
|
93
|
+
|
|
94
|
+
const observations = parseObservations(xml);
|
|
95
|
+
for (const name of new Set(observations.map((o) => o.device))) {
|
|
96
|
+
const machine = this.machines.get(name) || new Machine(name, { automaticOnly: this.automaticOnly });
|
|
97
|
+
machine.selectDataItems(observations);
|
|
98
|
+
if (machine.dataItems.Execution) this.machines.set(name, machine); // skips e.g. the "Agent" device
|
|
99
|
+
}
|
|
100
|
+
// Part counts already on the machine are the baseline; after an outage, parts made meanwhile are counted
|
|
101
|
+
this._apply(observations, false);
|
|
102
|
+
this._next = header;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
_apply(observations, live) {
|
|
106
|
+
for (const o of observations) {
|
|
107
|
+
const machine = this.machines.get(o.device);
|
|
108
|
+
if (!machine) continue;
|
|
109
|
+
const parts = machine.apply(o, live);
|
|
110
|
+
if (parts > 0) {
|
|
111
|
+
this.emit('parts', { device: machine.name, count: parts, program: machine.program, timestamp: o.timestamp });
|
|
112
|
+
}
|
|
113
|
+
// Live changes are emitted as they happen; a snapshot only once it's fully applied
|
|
114
|
+
if (live) this._emitState(machine, o.timestamp);
|
|
115
|
+
}
|
|
116
|
+
if (!live) for (const machine of this.machines.values()) this._emitState(machine);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
_emitState(machine, timestamp) {
|
|
120
|
+
const { state } = machine;
|
|
121
|
+
if (this._emitted.get(machine.name) === state) return;
|
|
122
|
+
this._emitted.set(machine.name, state);
|
|
123
|
+
this.emit('execution', { device: machine.name, state, execution: machine.execution, mode: machine.mode, timestamp });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async _fetch(request, params, signal) {
|
|
127
|
+
const query = new URLSearchParams({ path: PATH, ...params });
|
|
128
|
+
const response = await fetch(`${this.url}/${request}?${query}`, {
|
|
129
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]),
|
|
130
|
+
});
|
|
131
|
+
const xml = await response.text();
|
|
132
|
+
// An MTConnectError (e.g. OUT_OF_RANGE) has no nextSequence; callers handle it through parseHeader()
|
|
133
|
+
if (!response.ok && !xml.includes('<MTConnectError')) throw new Error(`HTTP ${response.status}`);
|
|
134
|
+
return xml;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = { MTConnectAgent };
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
|
|
3
|
+
export type MachineState = 'RUNNING' | 'STOPPED' | 'UNKNOWN';
|
|
4
|
+
|
|
5
|
+
export interface MTConnectAgentOptions {
|
|
6
|
+
/** How often to poll the agent, in ms. Defaults to 2000. */
|
|
7
|
+
interval?: number;
|
|
8
|
+
/** Count as RUNNING only when ControllerMode is AUTOMATIC. Defaults to false. */
|
|
9
|
+
automaticOnly?: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ExecutionEvent {
|
|
13
|
+
/** MTConnect device name, e.g. "OKUMA". */
|
|
14
|
+
device: string;
|
|
15
|
+
state: MachineState;
|
|
16
|
+
/** Raw MTConnect Execution value, e.g. "ACTIVE", "READY". Undefined while the agent is unreachable. */
|
|
17
|
+
execution?: string;
|
|
18
|
+
/** Raw ControllerMode value, e.g. "AUTOMATIC". */
|
|
19
|
+
mode?: string;
|
|
20
|
+
/** Agent timestamp of the change. Undefined for the initial snapshot and when the agent is unreachable. */
|
|
21
|
+
timestamp?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface PartsEvent {
|
|
25
|
+
device: string;
|
|
26
|
+
/** Parts made since the last event. */
|
|
27
|
+
count: number;
|
|
28
|
+
/** "program - comment", or undefined if neither is known. */
|
|
29
|
+
program?: string;
|
|
30
|
+
timestamp?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export declare class MTConnectAgent extends EventEmitter {
|
|
34
|
+
constructor(url: string, options?: MTConnectAgentOptions);
|
|
35
|
+
readonly url: string;
|
|
36
|
+
/** Whether the last poll succeeded. */
|
|
37
|
+
readonly connected: boolean;
|
|
38
|
+
start(): void;
|
|
39
|
+
stop(): void;
|
|
40
|
+
|
|
41
|
+
on(event: 'execution', listener: (e: ExecutionEvent) => void): this;
|
|
42
|
+
on(event: 'parts', listener: (e: PartsEvent) => void): this;
|
|
43
|
+
on(event: 'connect', listener: () => void): this;
|
|
44
|
+
on(event: 'disconnect', listener: (err: Error) => void): this;
|
|
45
|
+
}
|
package/src/index.js
ADDED
package/src/machine.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Tracks one MTConnect device: its execution state and the parts it makes.
|
|
4
|
+
|
|
5
|
+
const IGNORED_SUBTYPES = {
|
|
6
|
+
PartCount: ['TARGET', 'REMAINING', 'BAD', 'ABORTED', 'FAILED'],
|
|
7
|
+
Program: ['ACTIVE', 'SCHEDULE'], // prefer MAIN / no subType
|
|
8
|
+
ProgramComment: ['ACTIVE'],
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
class Machine {
|
|
12
|
+
constructor(name, { automaticOnly = false } = {}) {
|
|
13
|
+
this.name = name;
|
|
14
|
+
this.automaticOnly = automaticOnly;
|
|
15
|
+
this.dataItems = {}; // type -> the dataItemId we follow
|
|
16
|
+
this.execution = undefined; // raw MTConnect value, e.g. ACTIVE, READY
|
|
17
|
+
this.mode = undefined;
|
|
18
|
+
this.partCount = undefined;
|
|
19
|
+
this.programName = undefined;
|
|
20
|
+
this.programComment = undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Follow the first data item of each type in a /current snapshot, skipping unwanted subTypes. */
|
|
24
|
+
selectDataItems(observations) {
|
|
25
|
+
this.dataItems = {};
|
|
26
|
+
for (const o of observations) {
|
|
27
|
+
if (o.device !== this.name || this.dataItems[o.type]) continue;
|
|
28
|
+
if (!(IGNORED_SUBTYPES[o.type] || []).includes(o.subType)) this.dataItems[o.type] = o.dataItemId;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** RUNNING, STOPPED or UNKNOWN. */
|
|
33
|
+
get state() {
|
|
34
|
+
if (this.execution === undefined || this.execution === 'UNAVAILABLE') return 'UNKNOWN';
|
|
35
|
+
const running = this.execution === 'ACTIVE' && (!this.automaticOnly || this.mode === 'AUTOMATIC');
|
|
36
|
+
return running ? 'RUNNING' : 'STOPPED';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** "program - comment", or undefined if neither is known. */
|
|
40
|
+
get program() {
|
|
41
|
+
return [this.programName, this.programComment].filter(Boolean).join(' - ') || undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Apply one observation and return how many parts it completed.
|
|
46
|
+
* `live` is false for /current snapshots, where a PROGRAM_COMPLETED may be old news.
|
|
47
|
+
*/
|
|
48
|
+
apply(o, live) {
|
|
49
|
+
if (this.dataItems[o.type] !== o.dataItemId) return 0;
|
|
50
|
+
|
|
51
|
+
switch (o.type) {
|
|
52
|
+
case 'Program':
|
|
53
|
+
this.programName = o.value;
|
|
54
|
+
return 0;
|
|
55
|
+
case 'ProgramComment':
|
|
56
|
+
this.programComment = o.value;
|
|
57
|
+
return 0;
|
|
58
|
+
case 'ControllerMode':
|
|
59
|
+
this.mode = o.value;
|
|
60
|
+
return 0;
|
|
61
|
+
case 'Execution': {
|
|
62
|
+
// No part counter: a completed program counts as one part
|
|
63
|
+
const completed = live && !this.dataItems.PartCount && o.value === 'PROGRAM_COMPLETED' && this.execution !== 'PROGRAM_COMPLETED';
|
|
64
|
+
this.execution = o.value;
|
|
65
|
+
return completed ? 1 : 0;
|
|
66
|
+
}
|
|
67
|
+
case 'PartCount': {
|
|
68
|
+
const count = Number(o.value);
|
|
69
|
+
if (o.value === '' || !Number.isInteger(count)) return 0; // UNAVAILABLE
|
|
70
|
+
const previous = this.partCount;
|
|
71
|
+
this.partCount = count;
|
|
72
|
+
if (previous === undefined || count === previous) return 0;
|
|
73
|
+
// Counter went down: it was reset, so everything since the reset is new
|
|
74
|
+
return count > previous ? count - previous : count;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { Machine };
|
package/src/xml.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Minimal MTConnect XML reading with regular expressions, for the few observation types we use.
|
|
4
|
+
|
|
5
|
+
const TYPES = ['Execution', 'ControllerMode', 'PartCount', 'Program', 'ProgramComment'];
|
|
6
|
+
|
|
7
|
+
/** Agent query that returns only the data items above. */
|
|
8
|
+
const PATH =
|
|
9
|
+
'//DataItem[@type="EXECUTION" or @type="CONTROLLER_MODE" or @type="PART_COUNT" or @type="PROGRAM" or @type="PROGRAM_COMMENT"]';
|
|
10
|
+
|
|
11
|
+
/** The response header, or null if the response is an MTConnectError (e.g. OUT_OF_RANGE). */
|
|
12
|
+
function parseHeader(xml) {
|
|
13
|
+
const header = xml.match(/<Header\b([^>]*)>/)?.[1];
|
|
14
|
+
const nextSequence = Number(attribute(header, 'nextSequence'));
|
|
15
|
+
if (!nextSequence) return null;
|
|
16
|
+
return {
|
|
17
|
+
instanceId: attribute(header, 'instanceId'),
|
|
18
|
+
nextSequence,
|
|
19
|
+
lastSequence: Number(attribute(header, 'lastSequence')),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** All observations of TYPES, across devices, in the order they happened. */
|
|
24
|
+
function parseObservations(xml) {
|
|
25
|
+
const observations = [];
|
|
26
|
+
const deviceStreams = /<DeviceStream\b([^>]*)>([\s\S]*?)<\/DeviceStream>/g;
|
|
27
|
+
const elements = new RegExp(`<(${TYPES.join('|')})\\b([^>]*?)(?:/>|>([^<]*)</\\1>)`, 'g');
|
|
28
|
+
|
|
29
|
+
for (const [, deviceAttributes, deviceXml] of xml.matchAll(deviceStreams)) {
|
|
30
|
+
const device = attribute(deviceAttributes, 'name');
|
|
31
|
+
for (const [, type, attributes, text = ''] of deviceXml.matchAll(elements)) {
|
|
32
|
+
observations.push({
|
|
33
|
+
device,
|
|
34
|
+
type,
|
|
35
|
+
dataItemId: attribute(attributes, 'dataItemId'),
|
|
36
|
+
subType: attribute(attributes, 'subType'),
|
|
37
|
+
sequence: Number(attribute(attributes, 'sequence')),
|
|
38
|
+
timestamp: attribute(attributes, 'timestamp'),
|
|
39
|
+
value: decode(text.trim()),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return observations.sort((a, b) => a.sequence - b.sequence);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function attribute(attributes, name) {
|
|
47
|
+
return attributes?.match(new RegExp(`\\b${name}="([^"]*)"`))?.[1];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function decode(text) {
|
|
51
|
+
return text
|
|
52
|
+
.replace(/</g, '<')
|
|
53
|
+
.replace(/>/g, '>')
|
|
54
|
+
.replace(/"/g, '"')
|
|
55
|
+
.replace(/'/g, "'")
|
|
56
|
+
.replace(/&/g, '&');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
module.exports = { PATH, parseHeader, parseObservations };
|