@cutos/core 3.3.1 → 4.0.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/README.md CHANGED
@@ -1,1531 +1,633 @@
1
1
  # Introduction
2
2
 
3
- The CUTOS (CUT Operating System) Core API is a JavaScript library that provides essential functionalities for LWA (Local Web Application) edge computing and communication in the CUTOS ecosystem. The module is designed to facilitate communication between edge devices, edge gateways, and the cloud. Key features include platform information accessing, edge database operations, IPC (Inter-Process Communication), logging, heartbeat monitoring, and device management, etc. The API is designed to be modular and extensible.
3
+ `@cutos/core` is the TypeScript-friendly Core SDK for CUTOS 4.0. It provides the system-call API used by LWA applications, Node Providers, tools, and services running in the CUTOS ecosystem.
4
4
 
5
- ## Core API Modules Components
5
+ CUTOS 4.0 uses a Capability/Provider model:
6
6
 
7
- ### Platform
8
- - The CoreAPI class is the main entry point for interacting with the CUTOS Core API.
9
- - It provides methods for connecting to the platform, accessing information, and obtaining instances of other classes such as Database, IPC, Logger, etc.
7
+ - **Capability**: a named CUTOS system ability consumed by an LWA, service, or AI agent.
8
+ - **Provider**: a Node.js module or process that implements a Capability.
9
+ - **Contract**: a `capability.contract.json` file that describes methods, events, errors, and permissions.
10
10
 
11
- ### IPC Implementation
12
- - IPC (Inter-Process Communication) is implemented for communication between processes on the same machine or between processes on different machines within the same network segment.
13
- - The IPC class allows sending messages to a specific channel and registering listeners for incoming messages.
11
+ Hardware Device/Driver APIs remain available as the compatibility layer, but new CUTOS 4.0 applications should use Capability/Provider and Promise-first APIs.
14
12
 
15
- ### Database Operations
16
- - The Database class facilitates database operations, including table creation, insertion, updating, querying, and synchronization.
17
- - Provides a structured interface for managing edge databases.
13
+ ## Core API Module Components
18
14
 
19
- ### Device and Driver Management
20
- - The Device and Driver classes represent edge devices and drivers, respectively. The Device can also refer to external devices or modules, such as NFC, fingerprint modules, ID card readers, printers, sensors, GPIO and so on.
21
- - Devices and drivers communicate for data transmission, command reception, and status updates.
22
- - Heartbeat monitoring is implemented for drivers to ensure continuous communication.
15
+ ### Platform
23
16
 
24
- ### Notification
25
- - The Notification class provides functionality for registering, unregistering, and emitting events.
17
+ - `CoreAPI` is the main entry point for connecting to CUTOS runtime.
18
+ - It provides Promise-first methods for reading platform, configuration, box, device, volume, proxy, and shell information.
26
19
 
27
- ### Logging
28
- - The Logger class enables logging of information, warnings, errors, and debug messages.
29
- - Logs are sent and saved to the CUTOS Cloud. In the CUSOS Cloud administration web page, the logs can be queried for a specified device.
20
+ ### Capability And Provider
30
21
 
31
- # Conclusion
22
+ - `cutos.capability(name)` creates a client for calling a CUTOS capability.
23
+ - `cutos.provider(name)` creates a Node-side provider implementation.
24
+ - `Capability.call()` maps to request-response IPC.
25
+ - `Provider.method()` registers a method handler.
26
+ - `Provider.emit()` publishes events to consumers.
32
27
 
33
- The CUTOS Core API provides a comprehensive set of classes for interacting with the CUTOS platform. Developers can use these classes to build applications, manage databases, communicate with devices, and handle various aspects of the CUTOS ecosystem. The modular design allows for flexibility and extensibility, making it suitable for a wide range of use cases within the IoT and smart device domain.
28
+ ### IPC
34
29
 
35
- # Table of Contents
30
+ - IPC is a lower-level channel API for local and cross-device communication.
31
+ - Prefer Capability/Provider for product APIs; use IPC for diagnostics, tools, and experimental services.
36
32
 
37
- 1.[Quick Start](#quick-start)
33
+ ### Database
38
34
 
39
- 2.[PlatformAPI](#platform-api)
35
+ - `CoreClass.Database` provides Promise-first access to the CUTOS local database.
36
+ - `Database.Table` supports table creation, insert, update, delete, query, sync, and mirror-oriented operations.
40
37
 
41
- - Version
42
- - Platform Information
43
- - Configuration
44
- - Box Information
45
- - Device Information
46
- - Http Proxy
47
- - Volume Control
48
- - Shell Command Execution
38
+ ### Notification
49
39
 
50
- 3.[IPC](#ipc-api)
40
+ - `Notification` supports registering, unregistering, and emitting system/application notifications.
51
41
 
52
- 4.[Database](#database-api)
42
+ ### Logging
53
43
 
54
- 5.[Device & Driver](#devicediver-api)
44
+ - `Logger` supports info, warning, error, and debug logs.
55
45
 
56
- 6.[Notification](#notification-api)
46
+ ### Error Model
57
47
 
58
- 7.[Logger](#logger-api)
48
+ - CUTOS 4.0 normalizes errors to `CutosError`.
49
+ - `CutosError` includes `code`, `message`, and optional `detail`.
59
50
 
51
+ # Table Of Contents
52
+
53
+ 1. [Quick Start](#quick-start)
54
+ 2. [Platform API](#platform-api)
55
+ 3. [Capability API](#capability-api)
56
+ 4. [Provider API](#provider-api)
57
+ 5. [IPC API](#ipc-api)
58
+ 6. [Database API](#database-api)
59
+ 7. [Notification API](#notification-api)
60
+ 8. [Logger API](#logger-api)
61
+ 9. [Error Model](#error-model)
62
+ 10. [Capability Contract](#capability-contract)
63
+ 11. [Documentation](#documentation)
60
64
 
61
65
  # Quick Start
62
66
 
63
- ### Install
67
+ ## Install
64
68
 
65
- `
69
+ ```bash
66
70
  npm install @cutos/core
67
- `
68
-
69
- ### Initialize
70
-
71
- ```js
72
- CoreAPI.init(host, callback);
73
71
  ```
74
72
 
75
- * host: CUTOS address. When host is equal to null, it takes the value 'localhost'. During development, it can be changed
76
- to the target address (the device address where CUTOS is installed), such as: '192.168.1.11'
77
- * callback: callback function. The callback function will receive two parameters: result (String) and error (Object).
78
- Among them, error.name is the error name, and error.message is the specific error message.
73
+ ## Import
79
74
 
80
- ##### Example:
81
-
82
- ```js
83
- import { CoreAPI } from '@cutos/core';
84
- CoreAPI.init('192.168.1.11', (result, error) => {
85
- if (!error) {
86
- console.log(result)
87
- } else {
88
- console.error('init failed' + error.message)
89
- }
90
- })
75
+ ```ts
76
+ import {
77
+ CoreAPI,
78
+ CoreClass,
79
+ CoreSimulator,
80
+ CutosError,
81
+ cutos
82
+ } from "@cutos/core"
91
83
  ```
92
84
 
93
- - Return result example:
85
+ ## Initialize
94
86
 
95
- ```json
96
- {
97
- "result": "CUTOS CORE connected."
98
- }
87
+ ```ts
88
+ await CoreAPI.init("localhost")
99
89
  ```
100
90
 
91
+ During development, connect to a target CUTOS device:
101
92
 
102
- # Platform API
103
-
104
- ### CoreAPI.getVersion
105
-
106
- Get platform version information
107
-
108
- ```js
109
- CoreAPI.getVersion();
93
+ ```ts
94
+ await CoreAPI.init("192.168.1.100")
110
95
  ```
111
96
 
112
- - Return result example:
97
+ ## LWA: Consume A Capability
113
98
 
114
- ```
115
- "3.2.8"
116
- ```
99
+ ```ts
100
+ await CoreAPI.init("localhost")
117
101
 
118
- ### CoreAPI.getPlatform
102
+ const hello = cutos.capability("hello-device")
119
103
 
120
- Get platform information
104
+ const result = await hello.call<
105
+ { message: string },
106
+ { message: string }
107
+ >("echo", { message: "hello" })
121
108
 
122
- ```js
123
- CoreAPI.getPlatform(callback);
109
+ console.log(result.message)
124
110
  ```
125
111
 
126
- - callback: callback function
127
-
128
- ##### Example:
112
+ ## Node: Implement A Provider
129
113
 
130
- ```js
131
- CoreAPI.getPlatform(result => {
132
- console.log(result)
133
- });
134
- ```
114
+ ```ts
115
+ await CoreAPI.init("localhost")
135
116
 
136
- - Return result example:
117
+ const provider = cutos.provider("hello-device")
137
118
 
138
- ```json
139
- {
140
- "arch": "x64",
141
- "platform": "win32",
142
- "type": "Windows_NT",
143
- "release": "10.0.19045"
144
- }
145
- ```
146
-
147
- ### CoreAPI.getConfig
148
-
149
- Get configuration information
150
-
151
- ```js
152
- CoreAPI.getConfig(callback);
153
- ```
154
-
155
- - callback: callback function
156
-
157
- ##### Example:
158
-
159
- ```js
160
- CoreAPI.getConfig(result => {
161
- console.log(result)
162
- });
163
- ```
164
-
165
- - Return result example:
166
-
167
- ```json
168
- {
169
- "srvAddress": "www.cut-os.com",
170
- "srvRestProtocol": "https",
171
- "enableTimeSync": true,
172
- "playReport": false,
173
- "language": "Chinese",
174
- "debug": false
175
- }
176
- ```
177
-
178
- ### CoreAPI.getBoxInfo
179
-
180
- Get host information
181
-
182
- ```js
183
- CoreAPI.getBoxInfo(callback);
184
- ```
185
-
186
- - callback: callback function
187
-
188
- ##### Example:
189
-
190
- ```js
191
- CoreAPI.getBoxInfo(result => {
192
- console.log(result)
119
+ provider.method<
120
+ { message: string },
121
+ { message: string }
122
+ >("echo", async params => {
123
+ return { message: params.message }
193
124
  })
194
- ```
195
-
196
- - Return result example:
197
125
 
198
- ```json
199
- {
200
- "id": 1016,
201
- "macAddress": "00-F1-F5-2A-8E-8C",
202
- "ipAddress": "192.168.1.127",
203
- "masterIpAddress": "",
204
- "osVersion": "3.2.0"
205
- }
206
- ````
207
-
208
- - `id`: Host ID
209
- - `macAddress`: Host MAC address
210
- - `ipAddress`: host IP address
211
- - `masterIpAddress`: Master IP address, used when multiple hosts form a host group
212
- - `osVersion`: CUTOS Player Version
213
-
214
- ### CoreAPI.getDeviceInfo
215
-
216
- Get device information
217
-
218
- ```js
219
- CoreAPI.getDeviceInfo(callback);
220
- ```
221
-
222
- - callback: callback function
223
-
224
- ##### Example:
225
-
226
- ```js
227
- CoreAPI.getDeviceInfo(result => {
228
- console.log(result)
126
+ provider.emit("statusChanged", {
127
+ status: "connected",
128
+ message: "hello-device ready"
229
129
  })
230
130
  ```
231
131
 
232
- - Return result example:
233
-
234
- ```json
235
- {
236
- "id": 1234,
237
- "name": "sipTimes office",
238
- "shortName": "",
239
- "groupId": 0,
240
- "groupName": null,
241
- "department": null,
242
- "description": null,
243
- "gwi": "9E1E3B67-...101B",
244
- "gwUrl": "ws://127.0.0.1:61614",
245
- "ext": null,
246
- "token": "D+yIxq1d3...BTgjK....."
247
- }
248
- ```
249
-
250
- - `id`: device ID
251
- - `name`: device name
252
- - `shortName`: device short name
253
- - `groupId`: device group ID
254
- - `groupName`: device group name
255
- - `department`: department
256
- - `description`: description
257
- - `gwi`: gateway ID
258
- - `gwUrl`: gateway address
259
- - `ext`: extended information
260
- - `token`: token
132
+ # Platform API
261
133
 
262
- ### CoreAPI.getVolume
134
+ ## CoreAPI.init
263
135
 
264
- Get the volume
136
+ Connect to CUTOS runtime.
265
137
 
266
- ```js
267
- CoreAPI.getVolume(callback);
138
+ ```ts
139
+ await CoreAPI.init(host?: string | null)
268
140
  ```
269
141
 
270
- - callback: callback function
142
+ - `host`: CUTOS host address. Defaults to `localhost`.
143
+ - Returns: `Promise<string>`.
271
144
 
272
- ##### Example:
145
+ Example:
273
146
 
274
- ```js
275
- CoreAPI.getVolume(result => {
276
- console.log(result)
277
- })
147
+ ```ts
148
+ await CoreAPI.init("localhost")
278
149
  ```
279
150
 
280
- - Return result example:
151
+ ## CoreAPI.connected
281
152
 
282
- ```js
283
- "10"
284
- ```
153
+ Check whether the SDK is connected.
285
154
 
286
- ### CoreAPI.setVolume
287
-
288
- Set the volume
289
-
290
- ```js
291
- CoreAPI.setVolume(value, callback)
155
+ ```ts
156
+ const connected = CoreAPI.connected()
292
157
  ```
293
158
 
294
- - value: volume (0-100)
295
- - callback: callback function
159
+ ## CoreAPI.getVersion
296
160
 
297
- ##### Example:
161
+ Get SDK version.
298
162
 
299
- ```js
300
- CoreAPI.setVolume(70, (result, error) => {
301
- if (!error) {
302
- console.log(result)
303
- }
304
- })
163
+ ```ts
164
+ const version = CoreAPI.getVersion()
305
165
  ```
306
166
 
307
- - Return result example:
167
+ ## CoreAPI.getPlatform
308
168
 
309
- ```json
310
- {
311
- "result": 70
312
- }
313
- ```
314
-
315
- ### CoreAPI.setHttpProxy
316
-
317
- Set proxy to solve LWA cross-domain problem
318
-
319
- ```js
320
- CoreAPI.setHttpProxy(api, target, callback)
321
- ```
322
-
323
- - api: interface name
324
- - target: target address
325
- - callback: callback function. The callback function returns result if successful and error if failed.
326
-
327
- ##### Example:
328
-
329
- ```js
330
- CoreAPI.setHttpProxy('api', 'https://www.cut-os.com', (result, error) => {
331
- if (!error) {
332
- console.log(result)
333
- }
334
- })
335
- ```
336
-
337
- - Return result example:
169
+ Get platform information.
338
170
 
339
- ```json
340
- {
341
- "path": "proxy/api",
342
- "target": "https://www.cut-os.com"
171
+ ```ts
172
+ type PlatformInfo = {
173
+ arch: string
174
+ platform: string
175
+ type: string
176
+ release: string
343
177
  }
344
- ```
345
-
346
- * path: Request address prefix
347
- * target: target address
348
-
349
- ##### Actual interface call example
350
-
351
- ```js
352
- fetch(`http://localhost:3000/proxy/api/rest/sv/system/runtime/ping`)
353
- ```
354
-
355
- ##### The actual request address
356
178
 
357
- ```js
358
- fetch(`https://www.cut-os.com/rest/sv/system/runtime/ping`)
179
+ const platform = await CoreAPI.getPlatform<PlatformInfo>()
359
180
  ```
360
181
 
361
- ### CoreAPI.shell
182
+ ## CoreAPI.getConfig
362
183
 
363
- Shell command execution
184
+ Get CUTOS runtime configuration.
364
185
 
365
- ```js
366
- CoreAPI.shell(command, callback)
186
+ ```ts
187
+ const config = await CoreAPI.getConfig<Record<string, unknown>>()
367
188
  ```
368
189
 
369
- - command: command
370
- - callback: callback function
190
+ ## CoreAPI.getBoxInfo
371
191
 
372
- ##### Example:
192
+ Get host box information.
373
193
 
374
- ```js
375
- CoreAPI.shell('pwd', (result, error) => {
376
- if (!error) {
377
- console.log(result)
378
- }
379
- })
194
+ ```ts
195
+ const box = await CoreAPI.getBoxInfo<Record<string, unknown>>()
380
196
  ```
381
197
 
382
- - Return result example:
198
+ ## CoreAPI.getDeviceInfo
383
199
 
384
- ```
385
- "/home/linaro"
386
- ```
200
+ Get registered CUTOS device identity information.
387
201
 
388
-
389
- # IPC API
390
-
391
- ### CoreAPI.getIPC
392
-
393
- Get IPC instance object
394
-
395
- ```js
396
- let ipc = CoreAPI.getIPC([destAddress]);
202
+ ```ts
203
+ const deviceInfo = await CoreAPI.getDeviceInfo<Record<string, unknown>>()
397
204
  ```
398
205
 
399
- * destAddress: optional parameter, target IP address, used for inter-device process communication
400
-
401
- ![ipc](https://oss.cut-os.com/resources/developer/images/ipc.jpg)
402
-
403
- ### ipc.sendTo
206
+ ## CoreAPI.getSignInfo / CoreAPI.getSignGroupInfo
404
207
 
405
- Send IPC information
208
+ Get sign and sign group metadata.
406
209
 
407
- ```js
408
- ipc.sendTo(channel, args, callback = null);
210
+ ```ts
211
+ const signInfo = await CoreAPI.getSignInfo<Record<string, unknown>>()
212
+ const groupInfo = await CoreAPI.getSignGroupInfo<Record<string, unknown>>()
409
213
  ```
410
214
 
411
- * channel: channel name
412
- * args: information to send
413
- * callback: function callback(result)
215
+ ## CoreAPI.getVolume / CoreAPI.setVolume
414
216
 
415
- ### ipc.on
416
-
417
- Listen IPC
418
-
419
- ```js
420
- ipc.on(channel, listener);
217
+ ```ts
218
+ const volume = await CoreAPI.getVolume<number>()
219
+ await CoreAPI.setVolume(70)
421
220
  ```
422
221
 
423
- * channel: channel name
424
- * listener: function listener(args, respond(result)). args is the data from sender, respond is used to send data(result) back to sender's callback
425
-
426
-
427
- ##### Local device communication example:
428
-
429
- ```js
430
- import {CoreAPI} from '@cutos/core';
431
-
432
- CoreAPI.init();
222
+ ## CoreAPI.setHttpProxy
433
223
 
434
- let ipc = CoreAPI.getIPC();
435
- // listen
436
- ipc.on("channel-1", function (args, respond) {
437
- console.log(args);
438
- respond('received')
439
- });
224
+ Set a runtime HTTP proxy to avoid LWA cross-origin issues during development.
440
225
 
441
- // send
442
- ipc.sendTo("channel-1", {event: "event-1", msg: "msg-1"}, (result) => {
443
- console.log(result)
444
- });
445
- ```
446
-
447
- - Return result example:
448
-
449
- ```json
450
- {
451
- "event": "event-1",
452
- "msg": "msg-1"
226
+ ```ts
227
+ type ProxyResult = {
228
+ path: string
229
+ target: string
453
230
  }
454
- ```
455
-
456
- ##### Example of inter-device process communication:
457
231
 
458
- ##### Sender
459
- IP:192.168.1.136
460
- ```js
461
- import {CoreAPI} from '@cutos/core';
462
-
463
- CoreAPI.init();
464
- // Destination IP:192.168.1.149
465
- let ipc = CoreAPI.getIPC("192.168.1.149");
466
- // Send IPC information
467
- ipc.sendTo("channel-2", {event: "event-2", msg: "msg-2"}, (result) => {
468
- console.log(result)
469
- });
470
- ```
471
- - Return result example:
472
-
473
- ```json
474
- "Received"
232
+ const proxy = await CoreAPI.setHttpProxy<ProxyResult>(
233
+ "api",
234
+ "https://www.cut-os.com"
235
+ )
475
236
  ```
476
237
 
477
- ##### Receiver
478
- IP:192.168.1.149
479
- ```js
480
- import {CoreAPI} from '@cutos/core';
238
+ ## CoreAPI.shell
481
239
 
482
- CoreAPI.init();
240
+ Execute a shell command through CUTOS runtime.
483
241
 
484
- let ipc = CoreAPI.getIPC();
485
- ipc.on("channel-2", (args, respond) => {
486
- console.log(args);
487
- respond('Received')
488
- })
242
+ ```ts
243
+ const pwd = await CoreAPI.shell<string>("pwd")
489
244
  ```
490
245
 
491
- - Return result example:
246
+ Use this API carefully. It should not be exposed to untrusted LWA code without permissions.
492
247
 
493
- ```json
494
- {
495
- "event": "event-2",
496
- "msg": "msg-2"
497
- }
498
- ```
499
-
500
-
501
- # Database API
502
-
503
- The basic table structure of CUTOS database is in Key-Value format, and Value can be any json object. The advantage of
504
- this design is that the database does not need to be upgraded to modify the Value field, but the disadvantage is that it
505
- cannot be accessed as flexibly as traditional databases. If you need more flexible database access functions, you can
506
- use the SQL fully compatible interface provided by CUTOS.
248
+ # Capability API
507
249
 
508
- CUTOS basic table structure (default primary key name is `id`, data type is `INTEGER`):
250
+ ## cutos.capability
509
251
 
510
- | **Field** | **Data type** | **Description** |
511
- |:---------:|:-------------:|:------------------------------------------------------:|
512
- | id | INTEGER | Primary key |
513
- | value | TEXT | Data |
514
- | tid | TEXT | Foreign key, transaction id |
515
- | sync | INTEGER | Synchronization flag: 0-unsynchronized, 1-synchronized |
516
- | timestamp | INTEGER | Last modified timestamp |
252
+ Create a capability client.
517
253
 
518
- ### Database
519
-
520
- Constructor
521
-
522
- ```js
523
- let database = new Database(db);
254
+ ```ts
255
+ const capability = cutos.capability("hello-device")
524
256
  ```
525
257
 
526
- - db: database name, default is lwa.db if name is not passed
258
+ `CoreAPI.capability()` is equivalent.
527
259
 
528
- ### Database.connect
529
-
530
- Connect to database
531
-
532
- ```js
533
- database.connect(callback)
260
+ ```ts
261
+ const capability = CoreAPI.capability("hello-device")
534
262
  ```
535
263
 
536
- - callback: callback function
264
+ ## capability.call
537
265
 
538
- ##### Example:
266
+ Call a Provider method.
539
267
 
540
- ```js
541
- let database = database.connect((result, error) => {
542
- if (!error) {
543
- console.log(result)
544
- }
545
- })
546
- ```
547
-
548
- - Return result example:
549
-
550
- ```json
551
- {
552
- "dbPath": "/home/linaro/.config/dios/data/lwa.db"
553
- }
268
+ ```ts
269
+ const result = await capability.call<
270
+ { message: string },
271
+ { message: string }
272
+ >("echo", { message: "hello" })
554
273
  ```
555
274
 
556
- ### Database.run
557
-
558
- Run sql
275
+ Set a per-call timeout:
559
276
 
560
- ```js
561
- database.run(sql, callback)
277
+ ```ts
278
+ await capability.call(
279
+ "connect",
280
+ { name: "demo" },
281
+ { timeout: 3000 }
282
+ )
562
283
  ```
563
284
 
564
- - sql: execute sql statement
565
- - callback: callback function
285
+ ## capability.on
566
286
 
567
- ##### Example:
287
+ Subscribe to Provider events.
568
288
 
569
- ```js
570
- database.run('select * from device', (result, error) => {
571
- if (!error) {
572
- console.log(result)
573
- }
289
+ ```ts
290
+ const unsubscribe = capability.on<{
291
+ status: "idle" | "connected" | "error"
292
+ message?: string
293
+ }>("statusChanged", data => {
294
+ console.log(data.status)
574
295
  })
575
296
  ```
576
297
 
577
- - Return result example:
298
+ ## capability.off
578
299
 
579
- ```json
580
- [
581
- {
582
- "id": 1,
583
- "value": "{\"type\":\"printer\",\"name\":\"HP-1\"}",
584
- "tid": "tra-001",
585
- "sync": 0,
586
- "timestamp": 1691401911678
587
- },
588
- {
589
- "id": 2,
590
- "value": "{\"type\":\"printer\",\"name\":\"HP-2\"}",
591
- "tid": "tra-002",
592
- "sync": 0,
593
- "timestamp": 1691401911681
594
- }
595
- ]
596
- ```
300
+ Remove one listener or all listeners for an event.
597
301
 
598
- ### Database.Table
599
-
600
- Constructor
601
-
602
- ```js
603
- let table = new Database.Table(name, db);
604
- ```
605
-
606
- - name: table name
607
- - db: database instance
608
-
609
- ##### Example:
610
-
611
- ```js
612
- let table = new Database.Table('device', database);
613
- ```
614
-
615
- ### Table.create
616
-
617
- Create a database table
618
-
619
- ```js
620
- table.create([opts], callback)
621
- ```
622
-
623
- - opts: optional parameters, including 3 attributes:
624
- * retentionTime: retention time, in hours; if not passed, it will be retained forever by default
625
- * keyName: name, if not passed, it will be 'id' by default
626
- * keyType: type, including 2 types 'TEXT' and 'INTEGER', if not passed, it will be 'INTEGER' by default
627
- - callback: callback function
628
-
629
- ##### Example:
630
-
631
- ```js
632
- table.create((result, error) => {
633
- if (!error) {
634
- console.log(result)
635
- }
636
- });
637
- ```
638
-
639
- - Return result example:
640
-
641
- ```json
642
- []
643
- ```
644
-
645
- ### Table.insert
646
-
647
- Insert data
648
-
649
- ```js
650
- table.insert(value, [opts], callback);
651
- ```
652
-
653
- - value: Insert data
654
- - opts: optional parameters
655
- * tid: foreign key id, used to establish relationships between multiple records
656
- - callback: callback function
657
-
658
- ##### Example:
659
-
660
- ```js
661
- let tid = "tra-001";
662
- table.insert({type: "printer", name: "NEC"}, {tid: tid}, (result, error) => {
663
- if (!error) {
664
- console.log(result)
665
- }
666
- });
302
+ ```ts
303
+ capability.off("statusChanged")
667
304
  ```
668
305
 
669
- - Return result example:
306
+ ## capability.dispose
670
307
 
671
- ```json
672
- {
673
- "status": true,
674
- "row": 1
675
- }
676
- ```
308
+ Clear listeners and release the underlying subscription.
677
309
 
678
- ### table.insertById
679
-
680
- Insert data by id
681
-
682
- ```js
683
- table.insertById(id, value, [opts], callback)
310
+ ```ts
311
+ capability.dispose()
684
312
  ```
685
313
 
686
- - id: data id
687
- - value: insert data
688
- - opts: optional parameters
689
- * tid: Foreign key id, used to establish relationships between multiple records
690
- - callback: callback function
691
-
692
- ##### Example:
314
+ # Provider API
693
315
 
694
- ```js
695
- let tid = "tra-001";
696
- table.insertById(1, {type: "printer", name: "NEC"}, {tid: tid}, (result, error) => {
697
- if (!error) {
698
- console.log(result)
699
- }
700
- });
701
- ```
316
+ ## cutos.provider
702
317
 
703
- - Return result example:
318
+ Create a Provider.
704
319
 
705
- ```json
706
- {
707
- "status": true,
708
- "row": 1
709
- }
710
- ```
711
-
712
- ### Table.update
713
-
714
- Update data
715
-
716
- ```js
717
- table.update(id, value, callback);
320
+ ```ts
321
+ const provider = cutos.provider("hello-device")
718
322
  ```
719
323
 
720
- - id: data id
721
- - value: update data
722
- - callback: callback function
324
+ `CoreAPI.provider()` is equivalent.
723
325
 
724
- ##### Example:
725
-
726
- ```js
727
- table.update(row, {type: "printer", name: "HP-2"}, (result, error) => {
728
- if (!error) {
729
- console.log(result)
730
- }
731
- });
326
+ ```ts
327
+ const provider = CoreAPI.provider("hello-device")
732
328
  ```
733
329
 
734
- - Return result example:
330
+ ## provider.method
735
331
 
736
- ```json
737
- {
738
- "status": true,
739
- "msg": 0
740
- }
741
- ```
332
+ Register a method handler.
742
333
 
743
- ### table.delete
744
-
745
- Delete data
746
-
747
- ```js
748
- table.delete(id, callback)
749
- ```
750
-
751
- - id: data id
752
- - callback: callback function
753
-
754
- ### Table.query
755
-
756
- Query data
757
-
758
- ```js
759
- table.query(id, callback);
760
- ```
761
-
762
- - id: data id
763
- - callback: callback function
764
-
765
- ##### Example:
766
-
767
- ```js
768
- deviceTable.query(row, (result, error) => {
769
- if (!error) {
770
- console.log(result)
771
- }
772
- });
773
- ```
774
-
775
- - Return result example:
776
-
777
- ```json
778
- [
779
- {
780
- "id": 2,
781
- "value": "{\"type\":\"printer\",\"name\":\"HP-2\"}",
782
- "tid": "tra-001",
783
- "sync": 0,
784
- "timestamp": 1691401911681
785
- }
786
- ]
787
- ```
788
-
789
- ### Table.sync
790
-
791
- Synchronize data
792
-
793
- ```js
794
- table.sync(id, callback);
334
+ ```ts
335
+ provider.method<
336
+ { message: string },
337
+ { message: string }
338
+ >("echo", async params => {
339
+ return { message: params.message }
340
+ })
795
341
  ```
796
342
 
797
- - id: data id
798
- - callback: callback function
799
-
800
- ##### Example:
343
+ Use `context` when raw command information is needed.
801
344
 
802
- ```js
803
- deviceTable.sync(row, (result, error) => {
804
- if (!error) {
805
- console.log(result)
345
+ ```ts
346
+ provider.method<{ name: string }, { connected: boolean }>(
347
+ "connect",
348
+ async (params, context) => {
349
+ console.log(context.command.cmd)
350
+ return { connected: true }
806
351
  }
807
- });
352
+ )
808
353
  ```
809
354
 
810
- - Return result example:
355
+ Throw `CutosError` for expected business errors.
811
356
 
812
- ```json
813
- {
814
- "status": true,
815
- "msg": 0
816
- }
357
+ ```ts
358
+ throw new CutosError("HELLO_DEVICE_UNAVAILABLE", "The hello device is unavailable.")
817
359
  ```
818
360
 
819
- ### Table.queryUnsynced
361
+ ## provider.emit
820
362
 
821
- Query unsynchronized data
363
+ Emit an event.
822
364
 
823
- ```js
824
- table.queryUnsynced([opts], callback);
365
+ ```ts
366
+ provider.emit("statusChanged", {
367
+ status: "connected",
368
+ message: "hello-device ready"
369
+ })
825
370
  ```
826
371
 
827
- - opts: optional parameters
828
- - callback: callback function
372
+ ## provider.dispose
829
373
 
830
- ##### Example:
374
+ Clear methods and release the underlying command listener.
831
375
 
832
- ```js
833
- deviceTable.queryUnsynced((result, error) => {
834
- if (!error) {
835
- console.log(result)
836
- }
837
- });
376
+ ```ts
377
+ provider.dispose()
838
378
  ```
839
379
 
840
- - Return result example:
841
-
842
- ```json
843
- [
844
- {
845
- "id": 1,
846
- "value": "{\"type\":\"printer\",\"name\":\"NEC\"}",
847
- "tid": "tra-001",
848
- "sync": 0,
849
- "timestamp": 1691402230172
850
- }
851
- ]
852
- ```
380
+ # IPC API
853
381
 
854
- ### Table.queryByTid
382
+ IPC is a lower-level channel API. Prefer Capability/Provider for product APIs.
855
383
 
856
- Query data by foreign key
384
+ ## CoreAPI.getIPC
857
385
 
858
- ```js
859
- table.queryByTid(tid, callback);
386
+ ```ts
387
+ const ipc = CoreAPI.getIPC()
388
+ const remote = CoreAPI.getIPC("192.168.1.149")
860
389
  ```
861
390
 
862
- - tid: foreign key id
863
- - callback: callback function
391
+ ## ipc.call
864
392
 
865
- ##### Example:
866
-
867
- ```js
868
- deviceTable.queryByTid("tra-001", (result, error) => {
869
- if (!error) {
870
- console.log(result)
871
- }
872
- });
393
+ ```ts
394
+ const result = await ipc.call<
395
+ { left: number; right: number },
396
+ { sum: number }
397
+ >("math.add", { left: 2, right: 2 })
873
398
  ```
874
399
 
875
- - Return result example:
400
+ ## ipc.callWithOptions
876
401
 
877
- ```json
878
- [
879
- {
880
- "id": 2,
881
- "value": "{\"type\":\"printer\",\"name\":\"HP-2\"}",
882
- "tid": "tra-001",
883
- "sync": 0,
884
- "timestamp": 1691401911681
885
- }
886
- ]
402
+ ```ts
403
+ await ipc.callWithOptions(
404
+ "math.add",
405
+ { left: 2, right: 2 },
406
+ { timeout: 3000 }
407
+ )
887
408
  ```
888
409
 
889
- ### Table.queryAll
890
-
891
- Query all data
410
+ ## ipc.on
892
411
 
893
- ```js
894
- table.queryAll(callback);
895
- ```
896
-
897
- - callback: callback function
898
-
899
- ##### Example:
900
-
901
- ```js
902
- deviceTable.queryAll((result, error) => {
903
- if (!error) {
904
- console.log(result)
412
+ ```ts
413
+ const off = ipc.on<{ left: number; right: number }, { sum: number }>(
414
+ "math.add",
415
+ (args, respond) => {
416
+ respond({ sum: args.left + args.right })
905
417
  }
906
- });
907
- ```
908
-
909
- - Return result example:
418
+ )
910
419
 
911
- ```json
912
- [
913
- {
914
- "id": 1,
915
- "value": "{\"type\":\"printer\",\"name\":\"HP-1\"}",
916
- "tid": "tra-001",
917
- "sync": 0,
918
- "timestamp": 1691401911678
919
- },
920
- {
921
- "id": 2,
922
- "value": "{\"type\":\"printer\",\"name\":\"HP-2\"}",
923
- "tid": "tra-002",
924
- "sync": 0,
925
- "timestamp": 1691401911681
926
- }
927
- ]
420
+ off?.()
928
421
  ```
929
422
 
423
+ ## ipc.sendTo
930
424
 
931
- # Device&Diver API
932
-
933
- ## Driver
934
-
935
- ### Driver
425
+ Fire-and-forget message.
936
426
 
937
- Constructor
938
-
939
- ```js
940
- const driver = new Driver(name = 'default-driver-name', type = cutosAPI.DEVICE.DEFAULT, counter = 10)
427
+ ```ts
428
+ ipc.sendTo("diagnostic.event", { time: Date.now() })
941
429
  ```
942
430
 
943
- - name: driver name, default is 'default-driver-name'
944
- - type: device type, default is cutosAPI.DEVICE.DEFAULT
945
- - counter: heartbeat interval, default is 10s
946
-
947
- ### Driver.sendData
948
-
949
- Send data to the device
950
-
951
- ```js
952
- driver.sendData(data)
953
- ```
954
-
955
- - data: data
956
-
957
- ### Driver.onCommand
958
-
959
- Receive device commands
960
-
961
- ```js
962
- driver.onCommand(listener)
963
- ```
964
-
965
- - listener: function listener(command, respond), call respond after processing command
966
- - command: command, example: {cmd: "connect", args: ""}
967
- - respond: used to send data back to Device.sendCommand's callback function
968
-
969
- ## SDK
970
-
971
- ### Device
972
-
973
- Constructor
974
-
975
- ```js
976
- const device = new (name = 'default-device-name', type = cutosAPI.DEVICE.DEFAULT)
977
- ```
978
-
979
- * name: device name, default is 'default-device-name'
980
- * type: device type, default is cutosAPI.DEVICE.DEFAULT
981
-
982
- ### Device.init
983
-
984
- Device initialization
985
-
986
- ```js
987
- device.init([opts], callback)
988
- ```
989
-
990
- * opts: optional parameters, passed to the driver loading process, refer
991
- to [Driver Template](#download-project-template)
992
- * callback: function(result, error)
993
-
994
- ##### Example:
995
-
996
- ```js
997
- device.init((result, error) => {
998
- if (error) {
999
- console.log(error)
1000
- return;
1001
- }
1002
- console.log(result)
1003
- });
1004
- ```
1005
-
1006
- ### Device.sendCommand
1007
-
1008
- Send a command to the driver
1009
-
1010
- ```js
1011
- device.sendCommand(command, callback)
1012
- ```
431
+ # Database API
1013
432
 
1014
- - command: command, example: command = {cmd: "connect", args: ""}
1015
- - callback: function callback(result), used to receive the response from driver
433
+ CUTOS database uses a key-value table model. Values can be arbitrary JSON objects.
1016
434
 
1017
- ##### Example:
435
+ ## Database
1018
436
 
1019
- ```js
1020
- device.sendCommand({cmd: "connect", args: ""}, Listener(msg))
437
+ ```ts
438
+ const database = new CoreClass.Database()
439
+ await database.connect()
1021
440
  ```
1022
441
 
1023
- ### Device.onData
1024
-
1025
- Receive data sent by the driver
442
+ ## database.run
1026
443
 
1027
- ```js
1028
- device.onData(listener)
444
+ ```ts
445
+ const rows = await database.run<Array<Record<string, unknown>>>(
446
+ "select * from device"
447
+ )
1029
448
  ```
1030
449
 
1031
- - listener: function listener(data)
1032
-
1033
- ## Device driver relationship
1034
-
1035
- ##### 1. onData and sendData
1036
-
1037
- ![ddr1.png](https://oss.cut-os.com/resources/developer/images/ddr1.png)
1038
-
1039
- ##### 2. sendCommand (without callback function) and onCommand
1040
-
1041
- ![ddr2.png](https://oss.cut-os.com/resources/developer/images/ddr2.png)
1042
-
1043
- ##### 3. sendCommand (with callback function) and onCommand
1044
-
1045
- ![ddr3.png](https://oss.cut-os.com/resources/developer/images/ddr3.png)
1046
-
1047
- ## Device driver management template
1048
-
1049
- ### Download project template
450
+ ## Database.Table
1050
451
 
1051
- | <span style="white-space:nowrap;">Name </span> | Description | Download |
1052
- |:-----------------------------------------------|:----------------------:|:-----------------------------------------------------------------------------------:|
1053
- | driver-template | Device driver template | [Download](https://oss.cut-os.com/resources/developer/template/driver-template.zip) |
1054
-
1055
- ##### Project structure
1056
-
1057
- ```
1058
- ├── driver/ # Driver
1059
- │ ├── src/ # Driver source directory
1060
- │ ├── config.json # Configuration file, configure related parameters
1061
- │ ├── driver-template.js # Driver template
1062
- │ ├── driver-template-def.js # Device driver data definition (same as in SDK)
1063
- │ ├── index.js # Driver loading file
1064
- │ ├── test/ # Test directory
1065
- │ ├── main.js # Test entry file, simulate cutos, create a driver service
1066
- │ ├── package.json # Configuration information for this project
1067
- │ ├── gulpfile.js # Packaging file
1068
- │ ├── readme.txt # Instructions
1069
- ├── sdk/ # Interface SDK
1070
- │ ├── src/ # Source code directory
1071
- │ ├── driver-template.js # Device template
1072
- │ ├── driver-template-def.js # Device driver data definition (same as in driver)
1073
- │ ├── test/     # Test directory
1074
- │ ├── main.js # Test entry file
1075
- │ ├── package.json # Configuration information for this project
1076
- │ ├── gulpfile.mjs # Packaging file
1077
- │ ├── readme.txt # Instructions
452
+ ```ts
453
+ const table = new CoreClass.Database.Table("device", database)
1078
454
  ```
1079
455
 
1080
- ### Installation dependencies
1081
-
1082
- > Note: node version >= 16
1083
-
1084
- ```
1085
- cd driver-template/driver
1086
- npm install
1087
- ```
456
+ ## table.create
1088
457
 
1089
- ```
1090
- cd driver-template/sdk
1091
- npm install
458
+ ```ts
459
+ await table.create({
460
+ keyName: "id",
461
+ keyType: "INTEGER"
462
+ })
1092
463
  ```
1093
464
 
1094
- [//]: # (### Template-based development)
465
+ ## table.insert
1095
466
 
1096
- ### Project startup
1097
-
1098
- You need to start the driver first, then start the SDK.
1099
-
1100
- ```
1101
- npm start
467
+ ```ts
468
+ await table.insert(
469
+ { type: "printer", name: "HP-1" },
470
+ { tid: "tra-001" }
471
+ )
1102
472
  ```
1103
473
 
1104
- If the startup is successful, the console will return the following content
474
+ ## table.insertById / table.insertByKey
1105
475
 
1106
- * driver
1107
-
1108
- ```
1109
- CUTOS CORE connected.
1110
- CUTOS Simulator started and listening on port 1883
1111
- drvDefault onCommand
1112
- {
1113
- "cmd":"init",
1114
- "args":{"name":"driver-template","type":"driver-template","development":true},
1115
- "topicResponse":"device-channel-driver-template-response"
1116
- }
1117
- connect: received.
1118
- cmd: custom-cmd received.
1119
- cmd: unknown is unsupported.
476
+ ```ts
477
+ await table.insertById(1, { type: "printer", name: "HP-1" })
478
+ await table.insertByKey("printer-1", { type: "printer", name: "HP-1" })
1120
479
  ```
1121
480
 
1122
- * SDK
481
+ ## table.update / table.updateByKey
1123
482
 
483
+ ```ts
484
+ await table.update(1, { type: "printer", name: "HP-2" })
485
+ await table.updateByKey("printer-1", { type: "printer", name: "HP-2" })
1124
486
  ```
1125
- CUTOS CORE connected.
1126
- driver template init true
1127
- connect: { msg: 'return success.', status: true }
1128
- ```
1129
-
1130
- ### Packaging and Release
1131
487
 
1132
- ##### Packaging Driver
488
+ ## table.delete
1133
489
 
490
+ ```ts
491
+ await table.delete(1)
1134
492
  ```
1135
- cd driver-template/driver
1136
- npm run build
1137
- ```
1138
-
1139
- ```
1140
- ├── driver/
1141
- │ ├── dist/ # Packaging directory
1142
- │ ├── driver-template-v1.0.1.drv # Packaging file
1143
- ```
1144
-
1145
- ##### Release the driver
1146
-
1147
- Upload the package file to https://www.cut-os.com/ and publish
1148
- Hardware/Driver--Add
1149
-
1150
- ##### Packaged Device SDK
1151
493
 
1152
- ```
1153
- cd driver-template/sdk
1154
- npm run build
1155
- ```
494
+ ## table.query APIs
1156
495
 
496
+ ```ts
497
+ const byId = await table.query<Array<Record<string, unknown>>>(1)
498
+ const byKey = await table.queryByKey<Array<Record<string, unknown>>>("printer-1")
499
+ const byTid = await table.queryByTid<Array<Record<string, unknown>>>("tra-001")
500
+ const all = await table.queryAll<Array<Record<string, unknown>>>()
1157
501
  ```
1158
- ├── sdk/
1159
- │ ├── dist/ # Packaging directory
1160
- │ ├── driver-template-sdk-v1.0.2.zip # Packaging files
1161
- ```
1162
-
1163
- ##### Note:
1164
-
1165
- > 1.The template device-template.js references TYPE, CMD exported in device-template-def.js
1166
- >
1167
- > `import {CMD, TYPE} from './device-template-def.js';`
1168
- > * Device type (TYPE):
1169
- >
1170
- - Type constant: key "TEMPLATE", value "Device template".
1171
- > - Indicates the template type, identifying the category of the device.
1172
- >* Command type (CMD):
1173
- >
1174
- - CMD constant with two pairs:
1175
- >
1176
- - CONNECT: 'connect' represents the connection command.
1177
- > - CUSTOM_CMD: "custom-cmd" represents a custom command for a specific device.
1178
-
1179
- > 2.Configuration requirements: Keep the TYPE parameter 3 in the template consistent so that the driver matches the
1180
- > corresponding SDK.
1181
- >
1182
- > ```let device = new DeviceTemplate('device-template',callback)``` //device-template.js
1183
- >
1184
- > ``` const TYPE = 'device-template';```//device-template-def.js
1185
- >
1186
- > ```{"name": "device-template",...}```//config.json
1187
-
1188
- ## Review
1189
-
1190
- The complete code is as follows:
1191
-
1192
- ### driver
1193
-
1194
- ```js
1195
- // driver/src/driver-template.js
1196
- const {CoreDefine, CoreClass} = require('@cutos/core');
1197
- const {TYPE, CMD} = require('./driver-template-def.js');
1198
- const config = require('./config.json');
1199
-
1200
- class DriverTemplate extends CoreClass.Driver {
1201
- constructor(args) {
1202
- // check
1203
- if (TYPE !== config.type) {
1204
- throw "Error: the 'type' value in config.js and *-def.js MUST be identical.";
1205
- }
1206
- super(args.name, TYPE);
1207
-
1208
- this.startBeat();
1209
- this.updateStatusInfo(CoreDefine.HEARTBEAT_STATUS.ALIVE, "alive");
1210
-
1211
- this.onCommand(({cmd, args}, respond) => {
1212
- // Listen to the messages sent by the device SDK, process the different commands in the message body,
1213
- // and respond back to the device SDK through the callback function.
1214
- switch (cmd) {
1215
- case CMD.CONNECT:
1216
- this.connect(args, respond);
1217
- break;
1218
- case CMD.CUSTOM_CMD:
1219
- this.customCmd(cmd, args);
1220
- break;
1221
- default:
1222
- this.unsupported(cmd, args, respond);
1223
- break;
1224
- }
1225
- });
1226
- }
1227
-
1228
- unsupported(cmd, args, respond) {
1229
- let result = {};
1230
- result.msg = "cmd: " + cmd + " is unsupported.";
1231
- result.status = false;
1232
- console.log(result.msg);
1233
- respond(result);
1234
- }
1235
502
 
1236
- connect(args, respond) {
1237
- console.log("connect: received.");
1238
- let result = {};
1239
- result.msg = "return success.";
1240
- result.status = true;
1241
- respond(result);
1242
- }
1243
-
1244
- // no response
1245
- customCmd(cmd, args) {
1246
- console.log("cmd: " + cmd + args, " received.");
1247
- // process cmd below
1248
- }
1249
-
1250
- sendCustomData() {
1251
- let data = {};
1252
- data.type = "custom-type"; // custom defined data type
1253
- data.values = {}; // values from template driver
1254
- data.values.val = "any value";
1255
- data.values.timeStamp = Date.now();
1256
- this.sendData(data);
1257
- }
1258
- }
503
+ ## table.queryUnsynced
1259
504
 
1260
- module.exports = DriverTemplate;
505
+ ```ts
506
+ const rows = await table.queryUnsynced<Array<Record<string, unknown>>>({ limit: 100 })
1261
507
  ```
1262
508
 
1263
- ### SDK
509
+ ## table.sync
1264
510
 
1265
- ```js
1266
- // sdk/src/driver-template.js
1267
-
1268
- import {CoreClass} from '@cutos/core';
1269
- import {CMD, TYPE} from './driver-template-def.js';
1270
-
1271
- class DriverTemplate extends CoreClass.Device {
1272
- constructor(name, callback, opts = {development: true}) {
1273
- super(name, TYPE, callback, opts);
1274
-
1275
- this.onData((data) => {
1276
- console.log("on data", data)
1277
- });
1278
- }
1279
-
1280
- connect(callback) {
1281
- let cmdMessage = {cmd: CMD.CONNECT};
1282
- this.sendCommand(cmdMessage, callback);
1283
- }
1284
-
1285
- customCmd() {
1286
- let cmdMessage = {cmd: CMD.CUSTOM_CMD, args: ""};
1287
- this.sendCommand(cmdMessage);
1288
- }
1289
- }
1290
-
1291
- export {DriverTemplate};
511
+ ```ts
512
+ await table.sync(1)
1292
513
  ```
1293
514
 
1294
- ```js
1295
- // sdk/test/main.js
1296
- import {CoreAPI} from '@cutos/core';
1297
- import {DriverTemplate} from '../src/driver-template.js';
1298
-
1299
- CoreAPI.init(null, () => {
1300
- //
1301
- let device = new DriverTemplate('driver-template', ({result, msg}) => {
1302
- console.log("driver template init", result, msg ? " error:" + msg : "");
1303
-
1304
- device.onData((data) => {
1305
- console.log("on data", data)
1306
- });
1307
-
1308
- device.connect((result) => {
1309
- console.log("connect: ", result)
1310
- });
1311
- device.customCmd();
1312
- device.sendCommand({cmd: "unknown", args: ""});
1313
- });
1314
- });
1315
- ```
1316
-
1317
-
1318
515
  # Notification API
1319
516
 
1320
- ### CoreAPI.getNotification
517
+ ## CoreAPI.getNotification
1321
518
 
1322
- Get notification information instance object
1323
-
1324
- ```js
1325
- let notification = CoreAPI.getNotification();
1326
- ```
1327
-
1328
- ### notification.register
1329
-
1330
- Register notification listener function
1331
-
1332
- ```js
1333
- notification.register(listener)
519
+ ```ts
520
+ const notification = CoreAPI.getNotification()
1334
521
  ```
1335
522
 
1336
- * listener: listener function
1337
-
1338
- ##### Example:
523
+ ## notification.register
1339
524
 
1340
- ```js
1341
- notification.register((data) => {
1342
- console.log(data);
525
+ ```ts
526
+ notification.register(data => {
527
+ console.log(data)
1343
528
  })
1344
529
  ```
1345
530
 
1346
- - Return result example:
1347
-
1348
- ```json
1349
- {
1350
- "event": "networkConnection",
1351
- "msg": true
1352
- }
1353
- ```
1354
-
1355
- * event: event name
1356
- * msg: event content
531
+ ## notification.unregister
1357
532
 
1358
- ### notification.unregister
1359
-
1360
- Unregister, used to cancel the registration of `notification.register`
1361
-
1362
- ```js
533
+ ```ts
1363
534
  notification.unregister()
1364
535
  ```
1365
536
 
1366
- ### notification.emit
537
+ ## notification.emit
1367
538
 
1368
- Cancel registration, used to cancel the registration of `notification.register`
1369
-
1370
- ```js
1371
- notification.emit(event, msg)
539
+ ```ts
540
+ notification.emit("notification-1", "msg-1")
1372
541
  ```
1373
542
 
1374
- * event: event name
1375
- * msg: event content
1376
-
1377
- ##### Example:
543
+ System notification example:
1378
544
 
1379
- ```js
1380
- import {CoreAPI} from '@cutos/core';
1381
-
1382
- CoreAPI.init();
1383
-
1384
- let notification = CoreAPI.getNotification();
1385
- notification.register((data) => {
1386
- console.log(data);
1387
- })
1388
- notification.emit('notification-1', 'msg-1')
1389
- ```
1390
-
1391
- - Return result example:
1392
-
1393
- ```json
1394
- {
1395
- "event": "notification-1",
1396
- "msg": "msg-1"
545
+ ```ts
546
+ type NetworkNotification = {
547
+ event: "networkConnection"
548
+ msg: boolean
1397
549
  }
1398
550
  ```
1399
551
 
1400
- ### System notification
1401
-
1402
- ##### Network status notification
1403
-
1404
- ```json
1405
- {
1406
- "event": "networkConnection",
1407
- "msg": true
1408
- }
1409
- ```
1410
- * networkConnection: Network status notification
1411
- * true: online; false: offline
1412
-
1413
-
1414
552
  # Logger API
1415
553
 
1416
- ### CoreAPI.getLogger
1417
-
1418
- Get the log instance object
554
+ ## CoreAPI.getLogger
1419
555
 
1420
- ```js
1421
- let logger = CoreAPI.getLogger();
556
+ ```ts
557
+ const logger = CoreAPI.getLogger()
1422
558
  ```
1423
559
 
1424
- ### logger.info
1425
-
1426
- Information
560
+ ## logger.info / warning / error / debug
1427
561
 
1428
- ```js
1429
- logger.info(remark, content, type = "LWA")
562
+ ```ts
563
+ logger.info("hello-device", "provider started")
564
+ logger.warning("hello-device", "slow response")
565
+ logger.error("hello-device", "provider failed")
566
+ logger.debug("hello-device", "debug detail")
1430
567
  ```
1431
568
 
1432
- * remark: remark;
1433
- * content: content;
1434
- * type: type, default is LWA if not passed.
569
+ The third argument is optional and defaults to `LWA`.
1435
570
 
1436
- ##### Example:
1437
-
1438
- ```js
1439
- logger.info('face-api', 'success')
571
+ ```ts
572
+ logger.info("hello-provider", "started", "Provider")
1440
573
  ```
1441
574
 
1442
- * Return result log file example:
575
+ # Error Model
1443
576
 
1444
- ```json
1445
- {
1446
- "dateTime": 1709891709950,
1447
- "status": "The server is alive!"
577
+ CUTOS 4.0 normalizes SDK errors to `CutosError`.
578
+
579
+ ```ts
580
+ try {
581
+ await cutos.capability("hello-device").call("connect", { name: "demo" })
582
+ } catch (error) {
583
+ if (error instanceof CutosError) {
584
+ console.log(error.code)
585
+ console.log(error.message)
586
+ console.log(error.detail)
587
+ }
1448
588
  }
1449
589
  ```
1450
590
 
1451
- ### logger.warning
591
+ Common error codes include:
1452
592
 
1453
- Warning
1454
-
1455
- ```js
1456
- logger.warning(remark, content, type = "LWA")
593
+ ```text
594
+ CUTOS_TIMEOUT
595
+ CUTOS_CORE_ERROR
596
+ DRIVER_INIT_TIMEOUT
597
+ DRIVER_INIT_ERROR
598
+ METHOD_NOT_FOUND
599
+ PROVIDER_ERROR
1457
600
  ```
1458
601
 
1459
- * remark: remark;
1460
- * content: content;
1461
- * type: type, default is LWA if not passed.
602
+ # Capability Contract
1462
603
 
1463
- ##### Example:
1464
-
1465
- ```js
1466
- logger.warning('face-api', 'warning-content')
1467
- ```
1468
-
1469
- * Return result log file example:
604
+ Capabilities should be described by `capability.contract.json`.
1470
605
 
1471
606
  ```json
1472
607
  {
1473
- "type": "LWA",
1474
- "level": "warning",
1475
- "remark": "face-api",
1476
- "content": "warning-content"
608
+ "schemaVersion": "0.1",
609
+ "name": "hello-device",
610
+ "version": "1.0.0",
611
+ "type": "device",
612
+ "methods": {},
613
+ "events": {},
614
+ "errors": {},
615
+ "permissions": []
1477
616
  }
1478
617
  ```
1479
618
 
1480
- ### logger.error
619
+ Contracts are the source of truth for future SDK generation, Provider stubs, documentation, tests, permissions, and AI tool schemas.
1481
620
 
1482
- Error
621
+ # Documentation
1483
622
 
1484
- ```js
1485
- logger.error(remark, content, type = "LWA")
1486
- ```
623
+ Full CUTOS 4.0 SDK API guide:
1487
624
 
1488
- * remark: remark;
1489
- * content: content;
1490
- * type: type, default is LWA if not passed.
1491
-
1492
- ##### Example:
1493
-
1494
- ```js
1495
- logger.error('face-api', 'fatal-content')
1496
- ```
1497
-
1498
- * Example of returned result log file:
1499
-
1500
- ```
1501
- AxiosError: Network Error
625
+ ```text
626
+ docs/CUTOS-4.0-SDK-API.md
1502
627
  ```
1503
628
 
1504
- ### logger.debug
629
+ Capability contract spec:
1505
630
 
1506
- Debug
1507
-
1508
- ```js
1509
- logger.debug(remark, content, type = "LWA")
1510
- ```
1511
-
1512
- * remark: remark;
1513
- * content: content;
1514
- * type: type, default is LWA if not passed.
1515
-
1516
- ##### Example:
1517
-
1518
- ```js
1519
- logger.debug('face-api', 'debug-content')
1520
- ```
1521
-
1522
- * Example of returned result log file:
1523
-
1524
- ```json
1525
- {
1526
- "type": "LWA",
1527
- "level": "debug",
1528
- "remark": "face-api",
1529
- "content": "debug-content"
1530
- }
1531
- ```
631
+ ```text
632
+ docs/CUTOS-Capability-Contract-v0.md
633
+ ```