Files
MeshPort/bindings/flutter/meshport_flutter/lib/src/client.dart
T

193 lines
5.8 KiB
Dart

import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
String _defaultLibrary() {
if (Platform.isMacOS) {
final bundled =
'${File(Platform.resolvedExecutable).parent.parent.path}/Frameworks/libmeshport_ffi.dylib';
if (File(bundled).existsSync()) return bundled;
}
return Platform.isWindows
? 'meshport_ffi.dll'
: Platform.isMacOS
? 'libmeshport_ffi.dylib'
: 'libmeshport_ffi.so';
}
DynamicLibrary _open(String path) =>
Platform.isIOS ? DynamicLibrary.process() : DynamicLibrary.open(path);
Map<String, dynamic> _call(String path, int handle, String request) {
final library = _open(path);
final call = library
.lookupFunction<
Pointer<Utf8> Function(Uint64, Pointer<Utf8>),
Pointer<Utf8> Function(int, Pointer<Utf8>)
>('meshport_call');
final free = library
.lookupFunction<
Void Function(Pointer<Utf8>),
void Function(Pointer<Utf8>)
>('meshport_string_free');
final input = request.toNativeUtf8();
try {
final result = call(handle, input);
if (result == nullptr) throw StateError('Native response is null');
try {
return jsonDecode(result.toDartString()) as Map<String, dynamic>;
} finally {
free(result);
}
} finally {
calloc.free(input);
}
}
class MeshPortClient {
final String libraryPath;
final int _handle;
final Future<Map<String, dynamic>> Function(Map<String, dynamic>)? _transport;
final Future<void> Function()? _closeTransport;
bool _closed = false;
MeshPortClient._(this.libraryPath, this._handle)
: _transport = null,
_closeTransport = null;
/// A platform-owned control transport. Responses use the same ABI JSON envelope.
MeshPortClient.fromTransport({
required Future<Map<String, dynamic>> Function(Map<String, dynamic>)
request,
required Future<void> Function() close,
}) : libraryPath = '',
_handle = 0,
_transport = request,
_closeTransport = close;
static Future<MeshPortClient> open({String? libraryPath}) async {
final path = libraryPath ?? _defaultLibrary();
final handle = await Isolate.run(() {
final lib = _open(path);
final version = lib.lookupFunction<Uint32 Function(), int Function()>(
'meshport_abi_version',
)();
if (version != 1) throw StateError('Unsupported MeshPort ABI: $version');
return lib.lookupFunction<Uint64 Function(), int Function()>(
'meshport_context_new',
)();
});
if (handle == 0) throw StateError('Could not create MeshPort context');
return MeshPortClient._(path, handle);
}
Future<Map<String, dynamic>> request(Map<String, dynamic> request) async {
if (_closed) throw StateError('MeshPort context is closed');
final path = libraryPath, handle = _handle, text = jsonEncode(request);
final response = _transport != null
? await _transport(request)
: await Isolate.run(() => _call(path, handle, text));
if (response['ok'] != true)
throw StateError(
response['error'] as String? ?? 'Native operation failed',
);
return response['data'] as Map<String, dynamic>;
}
Future<void> validate(String toml) async {
await request({'op': 'validate', 'toml': toml});
}
Future<void> start(String toml) async {
await request({'op': 'start', 'toml': toml});
}
Future<void> stop() async {
await request({'op': 'stop'});
}
/// Opt in to bounded process-wide punch tracing. Does not replace host logging.
Future<Map<String, dynamic>> enableDiagnostics() =>
request({'op': 'diagnostics_enable'});
Future<Map<String, dynamic>> status() => request({'op': 'status'});
Future<Map<String, dynamic>> probe(
String target, {
bool udp = false,
bool echo = false,
int timeoutMs = 5000,
}) => request({
'op': 'probe',
'target': target,
'protocol': udp ? 'UDP' : 'TCP',
'echo': echo,
'timeout_ms': timeoutMs,
});
Future<int> connectTcp(String target) async =>
(await request({'op': 'tcp_connect', 'target': target}))['resource']
as int;
Future<void> writeTcp(int stream, Uint8List data) async {
await request({
'op': 'tcp_write',
'resource': stream,
'bytes': data.toList(),
});
}
Future<Uint8List> readTcp(int stream, {int maxBytes = 16384}) async =>
Uint8List.fromList(
List<int>.from(
(await request({
'op': 'tcp_read',
'resource': stream,
'max_bytes': maxBytes,
}))['bytes'],
),
);
Future<int> bindUdp({int port = 0}) async =>
(await request({'op': 'udp_bind', 'port': port}))['resource'] as int;
Future<void> sendUdp(int socket, String target, Uint8List data) async {
await request({
'op': 'udp_send',
'resource': socket,
'target': target,
'bytes': data.toList(),
});
}
Future<Map<String, dynamic>> sampleUdpQuality(
int socket,
String target,
int sequence, {
int timeoutMs = 1000,
}) => request({
'op': 'quality_sample',
'resource': socket,
'target': target,
'sequence': sequence,
'timeout_ms': timeoutMs,
});
Future<Map<String, dynamic>> receiveUdp(int socket) =>
request({'op': 'udp_receive', 'resource': socket});
Future<void> closeResource(int resource) async {
await request({'op': 'resource_close', 'resource': resource});
}
Future<void> close() async {
if (_closed) return;
_closed = true;
if (_closeTransport != null) {
await _closeTransport();
return;
}
final path = libraryPath, handle = _handle;
await Isolate.run(
() =>
_open(path).lookupFunction<Void Function(Uint64), void Function(int)>(
'meshport_context_free',
)(handle),
);
}
}