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