-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathllms-full.txt
More file actions
391 lines (291 loc) · 18.4 KB
/
Copy pathllms-full.txt
File metadata and controls
391 lines (291 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# OPC UA Laravel Client — Full Reference
> Laravel integration for OPC UA built on opcua-client and opcua-session-manager.
## Package Metadata
- Repository: https://github.com/php-opcua/laravel-opcua
- Packagist: https://packagist.org/packages/php-opcua/laravel-opcua
- Documentation: https://github.com/php-opcua/laravel-opcua/tree/master/docs (also at https://php-opcua.com)
- License: MIT
- PHP: >= 8.2
- Laravel: 11.x, 12.x, 13.x
- Dependencies: php-opcua/opcua-client ^4.4.0, php-opcua/opcua-session-manager ^4.4.0, psr/event-dispatcher ^1.0, illuminate/support, illuminate/console, illuminate/contracts (all ^11.0|^12.0|^13.0)
## Architecture
OpcuaManager checks for the session manager daemon's IPC endpoint at connection time. If present, ManagedClient (daemon-proxied) is created. Otherwise, a direct Client via ClientBuilder::create()->...->connect() is used. The switch is transparent. The IPC endpoint is auto-selected per platform: Unix-domain socket on Linux/macOS, TCP loopback on Windows.
```
HTTP Request → Opcua::connect()
├── session manager reachable? → ManagedClient (IPC to daemon → TCP to OPC UA server)
│ └── TransportFactory::create($endpoint) picks UnixSocketTransport or TcpLoopbackTransport
└── session manager missing? → ClientBuilder::create()->...->connect() (direct TCP to OPC UA server)
```
## Installation
```bash
composer require php-opcua/laravel-opcua
php artisan vendor:publish --tag=opcua-config
```
## Configuration (config/opcua.php)
Three sections: default connection name, session_manager, connections.
### Session Manager Config
| Key | Env | Default | Description |
|-----|-----|---------|-------------|
| enabled | OPCUA_SESSION_MANAGER_ENABLED | true | Enable daemon auto-detection |
| socket_path | OPCUA_SOCKET_PATH | per-OS (unix://<storage_path('app/opcua-session-manager.sock')> on Linux/macOS, tcp://127.0.0.1:9990 on Windows) | IPC endpoint URI: unix://<path>, tcp://127.0.0.1:<port> (loopback-only), or scheme-less path (= unix://<path>, BC with pre-v4.2.0 configs) |
| timeout | OPCUA_SESSION_TIMEOUT | 600 | Session inactivity timeout (seconds) |
| cleanup_interval | OPCUA_CLEANUP_INTERVAL | 30 | Cleanup check interval |
| auth_token | OPCUA_AUTH_TOKEN | null | Shared secret for IPC |
| max_sessions | OPCUA_MAX_SESSIONS | 100 | Max concurrent sessions |
| socket_mode | — | 0600 | Socket permissions |
| allowed_cert_dirs | — | null | Certificate directory whitelist |
| log_channel | OPCUA_LOG_CHANNEL | Laravel default | Daemon log channel |
| cache_store | OPCUA_CACHE_STORE | Laravel default | Daemon cache store |
| auto_publish | OPCUA_AUTO_PUBLISH | false | Auto-publish for sessions with subscriptions (dispatches PSR-14 events) |
### Connection Config
New in v4.0.1 (per-connection):
| auto_connect | false | Auto-connect on daemon startup (requires auto_publish) |
| subscriptions | — | Array of subscription definitions with monitored_items and event_monitored_items |
| Key | Default | Description |
|-----|---------|-------------|
| endpoint | opc.tcp://localhost:4840 | Server URL |
| security_policy | None | None, Basic128Rsa15, Basic256, Basic256Sha256, Aes128Sha256RsaOaep, Aes256Sha256RsaPss, ECC_nistP256, ECC_nistP384, ECC_brainpoolP256r1, ECC_brainpoolP384r1 |
| security_mode | None | None, Sign, SignAndEncrypt |
| username / password | null | User authentication |
| client_certificate / client_key | null | Client cert (auto-generated if omitted) |
| ca_certificate | null | CA for server validation |
| user_certificate / user_key | null | X.509 auth |
| timeout | 5.0 | Network timeout (seconds) |
| auto_retry | null | Max reconnection retries |
| batch_size | null | Max items per batch |
| browse_max_depth | 10 | Default browseRecursive depth |
| trust_store_path | storage/app/opcua-trust-store | Directory for trusted/rejected server certificates |
| trust_policy | TrustPolicy::Strict | Trust policy: Strict, AcceptOnce, AcceptAll |
| auto_accept | false | Auto-accept unknown server certificates on first connection |
| auto_accept_force | false | Force-accept even previously rejected certificates |
| auto_detect_write_type | true | Enable auto-detection of write value types |
| read_metadata_cache | true | Cache node metadata for read operations |
## OpcuaManager API
### Connection Management
- connection(?string $name = null): OpcUaClientInterface — get/cache client by name
- connect(?string $name = null): OpcUaClientInterface — connect named connection
- connectTo(string $endpointUrl, array $config = [], ?string $as = null): OpcUaClientInterface — ad-hoc
- disconnect(?string $name = null): void — disconnect and remove from cache
- disconnectAll(): void — disconnect all tracked connections
- getDefaultConnection(): string — default connection name
- isSessionManagerRunning(): bool — check if daemon socket exists
### Proxied Methods (via __call to default connection)
All OpcUaClientInterface methods are proxied: read, readMulti, write, writeMulti, browse, browseAll, browseRecursive, browseWithContinuation, browseNext, resolveNodeId, translateBrowsePaths, call, createSubscription, createMonitoredItems, createEventMonitoredItem, modifyMonitoredItems, setTriggering, deleteMonitoredItems, deleteSubscription, publish, transferSubscriptions, republish, historyReadRaw, historyReadProcessed, historyReadAtTime, getEndpoints, discoverDataTypes, trustCertificate, untrustCertificate, connect, disconnect, reconnect, isConnected, getConnectionState, getTimeout, getAutoRetry, getBatchSize, getServerMaxNodesPerRead, getServerMaxNodesPerWrite, getDefaultBrowseMaxDepth, getLogger, getCache, invalidateCache, flushCache, getExtensionObjectRepository.
Note: In v4, OpcUaClientInterface no longer exposes setter methods (setTimeout, setAutoRetry, setBatchSize, setDefaultBrowseMaxDepth, setLogger, setCache). These are configured at build time via ClientBuilder or through the Laravel config.
## Facade (Opcua)
Static access to OpcuaManager with full PHPDoc for IDE autocompletion. Resolves to OpcuaManager::class.
v4.4.0 added 21 new `@method static` annotations covering the new client surface (no application-side changes required, just type hints / autocomplete):
- **HistoryUpdate (9, Part 11 §6.9)** — `historyInsertData`, `historyReplaceData`, `historyUpdateData`, `historyDeleteRawModified`, `historyDeleteAtTime`, `historyInsertEvent`, `historyReplaceEvent`, `historyUpdateEvent`, `historyDeleteEvent`
- **File transfer (10, Part 5 §C.2 + §C.3)** — `openFile`, `closeFile`, `readFile`, `writeFile`, `getFilePosition`, `setFilePosition`, `createDirectory`, `createFileInDirectory`, `deleteFileSystemObject`, `moveOrCopyFileSystemObject`
- **Aggregates (2, Part 13)** — `aggregate(DataValue[] $raw, …, AggregateFunction, ?AggregateOptions)`, `historyAggregate(NodeId|string, …, AggregateFunction, ?AggregateOptions)`
Mixed-version deployments (Laravel `^4.4` against daemon still on `^4.3`) will throw `BadMethodCallException` if any new method is called — upgrade order: daemon first, then the Laravel application.
## OpcuaServiceProvider
- Merges config/opcua.php
- Registers OpcuaManager singleton with Laravel's logger and cache injected
- Creates 'opcua' alias
- Registers SessionCommand in console mode
- Publishes config with tag 'opcua-config'
## SessionCommand (php artisan opcua:session)
Options: --timeout, --cleanup-interval, --max-sessions, --socket-mode, --log-channel, --cache-store
Resolves logger via app('log')->channel($channel) and cache via app('cache')->store($store). Creates SessionManagerDaemon and runs it.
When `auto_publish` is enabled, resolves `EventDispatcherInterface` from the container and passes it to the daemon. Reads connections with `auto_connect: true` and calls `$daemon->autoConnect()` before `$daemon->run()`.
## Auto-Publish & Auto-Connect (v4.0.1)
When `auto_publish: true` in session_manager config, the daemon automatically calls `publish()` for sessions with active subscriptions. The client's PSR-14 events (`DataChangeReceived`, `EventNotificationReceived`, `AlarmActivated`, etc.) are dispatched through Laravel's event system.
Per-connection `auto_connect: true` with `subscriptions` config makes the daemon connect and register monitoring on startup:
```php
// config/opcua.php
'session_manager' => ['auto_publish' => true],
'connections' => [
'plc-1' => [
'endpoint' => 'opc.tcp://192.168.1.10:4840',
'auto_connect' => true,
'subscriptions' => [
[
'publishing_interval' => 500.0,
'max_keep_alive_count' => 5,
'monitored_items' => [
['node_id' => 'ns=2;s=Temperature', 'client_handle' => 1],
],
'event_monitored_items' => [
['node_id' => 'i=2253', 'client_handle' => 10],
],
],
],
],
],
```
```php
// EventServiceProvider
Event::listen(DataChangeReceived::class, function (DataChangeReceived $e) {
DB::table('sensor_readings')->insert([
'client_handle' => $e->clientHandle,
'value' => $e->dataValue->getValue(),
]);
});
```
Runtime subscriptions via Facade are also auto-published. Manual `publish()` is blocked while auto-publish is active (returns `auto_publish_active` error).
## Reading Values
```php
$dv = $client->read('i=2259');
echo $dv->getValue(); // scalar value
echo $dv->statusCode; // int (0 = Good)
echo $dv->sourceTimestamp; // ?DateTimeImmutable
// Force metadata refresh (bypasses read metadata cache)
$dv = $client->read('i=2259', refresh: true);
```
Signature: `read(string|NodeId $nodeId, bool $refresh = false): DataValue`
All methods accept string NodeIds: 'i=2259', 'ns=2;i=1001', 'ns=2;s=MyNode'.
### readMulti — array or builder
```php
// Array
$results = $client->readMulti([['nodeId' => 'i=2259']]);
// Builder
$results = $client->readMulti()->node('i=2259')->value()->execute();
```
## Writing Values
```php
$status = $client->write('ns=2;i=1001', 42, BuiltinType::Int32);
// With auto-detection (type is nullable in v4)
$status = $client->write('ns=2;i=1001', 42);
```
Signature: `write(string|NodeId $nodeId, mixed $value, ?BuiltinType $type = null): int`
When `$type` is null and `auto_detect_write_type` is enabled (default), the client reads the node's data type metadata and selects the correct BuiltinType. Throws WriteTypeDetectionException on failure, WriteTypeMismatchException on mismatch.
### writeMulti — array or builder
```php
$results = $client->writeMulti()->node('ns=2;i=1001')->int32(42)->execute();
```
## Browsing
```php
$refs = $client->browse('i=85'); // ReferenceDescription[]
$refs = $client->browse('i=85', nodeClasses: [NodeClass::Variable]); // filter
$refs = $client->browse('i=85', useCache: false); // skip cache
$allRefs = $client->browseAll('i=85');
$tree = $client->browseRecursive('i=85', maxDepth: 3); // BrowseNode[]
$nodeId = $client->resolveNodeId('/Objects/Server/ServerStatus');
```
ReferenceDescription properties: nodeId, browseName, displayName, nodeClass, isForward, referenceTypeId, typeDefinition.
BrowseNode properties: reference (ReferenceDescription), children (BrowseNode[]).
## Method Calls
```php
$result = $client->call('i=85', 'ns=2;i=5000', [new Variant(BuiltinType::Double, 3.0)]);
// CallResult: statusCode, inputArgumentResults, outputArguments
```
## Subscriptions
```php
$sub = $client->createSubscription(500.0);
// SubscriptionResult: subscriptionId, revisedPublishingInterval, revisedLifetimeCount, revisedMaxKeepAliveCount
$monitored = $client->createMonitoredItems($sub->subscriptionId, [...]);
// MonitoredItemResult[]: statusCode, monitoredItemId, revisedSamplingInterval, revisedQueueSize
$pub = $client->publish();
// PublishResult: subscriptionId, sequenceNumber, moreNotifications, notifications, availableSequenceNumbers
$client->deleteSubscription($sub->subscriptionId);
// Modify monitored items
$modifyResults = $client->modifyMonitoredItems($sub->subscriptionId, [
['monitoredItemId' => $itemId, 'requestedParameters' => ['samplingInterval' => 200.0]],
]);
// MonitoredItemModifyResult[]: statusCode, revisedSamplingInterval, revisedQueueSize
// Set triggering links between monitored items
$triggerResult = $client->setTriggering($sub->subscriptionId, $triggeringItemId, linksToAdd: [$linkedItemId]);
// SetTriggeringResult: addResults, removeResults
// Session recovery
$results = $client->transferSubscriptions([$subId]); // TransferResult[]
$result = $client->republish($subId, $seqNum); // array
```
## History Read
```php
$values = $client->historyReadRaw('ns=2;i=1001', $start, $end); // DataValue[]
$values = $client->historyReadProcessed('ns=2;i=1001', $start, $end, 60000.0, $aggregateType);
$values = $client->historyReadAtTime('ns=2;i=1001', [$t1, $t2, $t3]);
```
## Trust Store
FileTrustStore manages trusted and rejected server certificates on disk.
```php
// Configured via config/opcua.php:
// 'trust_store_path' => storage_path('app/opcua-trust-store'),
// 'trust_policy' => TrustPolicy::Strict,
// 'auto_accept' => false,
// 'auto_accept_force' => false,
// Manually trust/untrust a certificate
$client->trustCertificate($derEncodedCert);
$client->untrustCertificate($derEncodedCert);
```
TrustPolicy enum values: Strict (only explicitly trusted certs), AcceptOnce (trust on first contact, reject if changed), AcceptAll (trust everything).
Throws UntrustedCertificateException when a server presents a certificate not in the trust store under Strict policy.
## PSR-14 Events
56 events dispatched via Laravel's event dispatcher. All events are immutable `final readonly` DTOs in `PhpOpcua\Client\Event\*`. Register listeners via Laravel's EventServiceProvider or Event facade.
Coverage:
- Connection lifecycle: ClientConnecting, ClientConnected, ClientDisconnecting, ClientDisconnected, ClientReconnecting, ConnectionFailed
- Secure channel / session: SecureChannelOpened, SecureChannelClosed, SessionCreated, SessionActivated, SessionClosed
- Read/write: NodeValueRead, NodeValueWritten, NodeValueWriteFailed, WriteTypeDetecting, WriteTypeDetected
- Browse: NodeBrowsed
- Subscriptions: SubscriptionCreated, SubscriptionDeleted, SubscriptionKeepAlive, SubscriptionTransferred, PublishResponseReceived
- Monitored items: MonitoredItemCreated, MonitoredItemModified, MonitoredItemDeleted, TriggeringConfigured
- Notifications: DataChangeReceived, EventNotificationReceived
- Alarms (Part 9): AlarmEventReceived, AlarmActivated, AlarmDeactivated, AlarmAcknowledged, AlarmConfirmed, AlarmShelved, AlarmSeverityChanged, LimitAlarmExceeded, OffNormalAlarmTriggered
- History: HistoryDataDeleted, HistoryDataUpdated, HistoryEventDeleted, HistoryEventUpdated
- File transfer: FileOpened, FileClosed, FileBytesRead, FileBytesWritten
- Aggregates (Part 13): AggregateComputed
- Discovery: DataTypesDiscovered
- Cache: CacheHit, CacheMiss
- Retry: RetryAttempt, RetryExhausted
- Trust store: ServerCertificateAutoAccepted, ServerCertificateManuallyTrusted, ServerCertificateRejected, ServerCertificateRemoved, ServerCertificateTrusted
## New Exceptions (v4)
- UntrustedCertificateException — server certificate is not trusted by the trust store
- WriteTypeDetectionException — auto-detection of the write value type failed (node metadata unreadable)
- WriteTypeMismatchException — the detected data type does not match the provided PHP value
## Cache
```php
$client->invalidateCache('i=85'); // clear one node
$client->flushCache(); // clear all
$client->browse('i=85', useCache: false); // skip per-call
```
Cache is configured at build time via ClientBuilder. Laravel's cache store is injected automatically by the service provider. The `read_metadata_cache` config key controls whether node metadata is cached for read operations.
## Logging
```php
$client->getLogger(); // current logger (PSR-3)
```
Laravel's default logger is injected automatically by the service provider. In v4, the logger is configured at build time via ClientBuilder (no runtime setLogger on the interface).
## Type Discovery
```php
$count = $client->discoverDataTypes(); // int
$count = $client->discoverDataTypes(namespaceIndex: 2);
$repo = $client->getExtensionObjectRepository();
```
## Security
10 policies: None, Basic128Rsa15, Basic256, Basic256Sha256, Aes128Sha256RsaOaep, Aes256Sha256RsaPss, ECC_nistP256, ECC_nistP384, ECC_brainpoolP256r1, ECC_brainpoolP384r1.
3 modes: None, Sign, SignAndEncrypt.
3 auth methods: Anonymous, Username/Password, X.509 Certificate.
Auto-generated client certificates when policy/mode set but no cert provided (RSA 2048 for RSA policies, EC matching curve for ECC policies).
Certificate trust management via FileTrustStore with configurable TrustPolicy.
## MockClient (Testing)
```php
$mock = MockClient::create()
->onRead('i=2259', fn() => DataValue::ofInt32(0));
$mock->read('i=2259');
echo $mock->callCount('read'); // 1
```
DataValue factories: ofBoolean, ofInt32, ofUInt32, ofInt16, ofUInt16, ofDouble, ofFloat, ofString, of, bad.
## Result DTOs
- SubscriptionResult: subscriptionId, revisedPublishingInterval, revisedLifetimeCount, revisedMaxKeepAliveCount
- MonitoredItemResult: statusCode, monitoredItemId, revisedSamplingInterval, revisedQueueSize
- MonitoredItemModifyResult: statusCode, revisedSamplingInterval, revisedQueueSize
- SetTriggeringResult: addResults, removeResults
- CallResult: statusCode, inputArgumentResults, outputArguments
- BrowseResultSet: references, continuationPoint
- PublishResult: subscriptionId, sequenceNumber, moreNotifications, notifications, availableSequenceNumbers
- BrowsePathResult: statusCode, targets
- BrowsePathTarget: targetId, remainingPathIndex
- TransferResult: statusCode, availableSequenceNumbers
- ExtensionObject: typeId, body (for server-defined structured types)
## Related Packages
- php-opcua/opcua-client — Pure PHP OPC UA client (core protocol)
- php-opcua/opcua-session-manager — Daemon-based session persistence
- php-opcua/opcua-cli — CLI tool for OPC UA operations
- php-opcua/opcua-client-nodeset — Pre-generated PHP types from OPC Foundation companion specifications
- php-opcua/uanetstandard-test-suite — Docker-based OPC UA test servers (UA-.NETStandard)
## Testing
7 unit test files (~161 it() blocks) + 22 integration test files (~119 it() blocks), Pest PHP. Integration tests require uanetstandard-test-suite Docker containers (`v1.5.0`, exposes the historizing server on `:24842`, ECC NIST/Brainpool servers on `:4848`/`:4849`, HTTPS Binary on `:4852`, Security Key Service on `:4851`).
```bash
./vendor/bin/pest tests/Unit/
./vendor/bin/pest tests/Integration/ --group=integration
```