Skip to main content

Local control: Flutter implementation guide

This is the step-by-step build guide for the mobile app's local (BLE) control. The contract it implements — every field, rule and why — is on Local control over BLE; read that first and keep it open. This page gives the order to build things in and Dart code for the parts that must be exact.

:::caution Before you start BLE pass-through on the WFBLE logger is not verified yet. Do step 1 of the bench checklist with nRF Connect before writing BLE code. It also gives you the service and characteristic UUIDs and the notification size, which this guide leaves as placeholders. :::

Build order​

#BuildDone when
1Fetch and cache the profilesOffline restart still has three profiles + rules
2Modbus RTU framingbuildRead(1, 3, 0, 1) is 01 03 00 00 00 01 84 0A
3BLE transportThe Aotai serial reads back over BLE
4DecodingEvery test vector passes
5DetectionBoth bench inverters detected; wrong-profile cases rejected
6Reading, writing, alertsValues match cloud read_registers for the same inverter

Steps 1, 2, 4 and 7 need no hardware.

1. Fetch and cache the profiles​

Send get_modbus_specs on the WebSocket the app already uses, whenever the app starts online. Route the replies by type from your existing message handler into a collector like this one:

import 'dart:async';
import 'dart:convert';

/// Collects one get_modbus_specs reply set: modbus_spec × total, then
/// modbus_detection. Completes with an error on ok:false, a gap, or timeout.
class ModbusSpecFetch {
final _done = Completer<SpecSet>();
final Map<int, Map<String, dynamic>> _specs = {};
int? _total;

Future<SpecSet> get result => _done.future.timeout(const Duration(seconds: 30));

/// Feed every incoming message whose type is modbus_spec or modbus_detection.
void onMessage(Map<String, dynamic> m) {
if (_done.isCompleted) return;
if (m['ok'] != true) {
_done.completeError(SpecFetchError(m['error'] ?? 'unknown error'));
return;
}
if (m['type'] == 'modbus_spec') {
_total = m['total'] as int;
_specs[m['index'] as int] = m;
} else if (m['type'] == 'modbus_detection') {
final total = _total;
if (total == null || _specs.length != total) {
// A message was dropped (the gateway drops rather than blocks when a
// connection is busy). Ask again.
_done.completeError(SpecFetchError('incomplete: ${_specs.length}/$total'));
return;
}
_done.complete(SpecSet(
specs: [for (var i = 1; i <= total; i++) _specs[i]!],
detection: m,
));
}
}
}

class SpecSet {
final List<Map<String, dynamic>> specs; // modbus_spec envelopes, in order
final Map<String, dynamic> detection; // the modbus_detection envelope
SpecSet({required this.specs, required this.detection});
}

class SpecFetchError implements Exception {
final String message;
SpecFetchError(this.message);
@override
String toString() => 'SpecFetchError: $message';
}

The request, with the hashes you already hold:

String specsRequest(Map<String, String> haveByModel) => jsonEncode({
'type': 'get_modbus_specs',
if (haveByModel.isNotEmpty) 'have': haveByModel,
});

Merging into the cache:

  • unchanged: true → keep your cached spec for that model; update the flags (modbusCapable, detectable, requiredFeatures) from the reply.
  • otherwise → store spec and sha256 for that model, replacing the old one.
  • a model you cached that is no longer in the reply → delete it.
  • always replace the detection rules.
  • write the whole set atomically (one file or one DB transaction), so a crash mid-write never leaves half a set.

On SpecFetchError or timeout keep the old cache and retry later (back off; don't loop).

Built-in copy. At build time, save one full reply set into the app's assets (for example with server/cmd/ws-test-client and SEND='{"type":"get_modbus_specs"}'). Load it only when the cache is empty.

Before using a profile, check both:

const supportedAlgorithmVersion = 1;
const supportedFeatures = {
'scale_rule', 'variant_selector', 'batch_within_sheet',
'datetime', 'alert_gate', 'display_variant_selector', 'bit_field',
};

bool usable(Map<String, dynamic> specEnvelope) =>
specEnvelope['modbusCapable'] == true &&
specEnvelope['detectable'] == true &&
(specEnvelope['requiredFeatures'] as List).every(supportedFeatures.contains);

bool rulesUsable(Map<String, dynamic> detection) =>
(detection['detection']['algorithmVersion'] as int) <= supportedAlgorithmVersion;

If the rules or a needed profile are not usable, show "Update the app to control this inverter" — never run with them anyway.

2. Modbus RTU framing​

import 'dart:typed_data';

/// CRC-16/MODBUS: init 0xFFFF, reflected poly 0xA001.
int crc16Modbus(List<int> bytes, [int start = 0, int? end]) {
var crc = 0xFFFF;
for (var i = start; i < (end ?? bytes.length); i++) {
crc ^= bytes[i];
for (var b = 0; b < 8; b++) {
crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xA001 : crc >> 1;
}
}
return crc;
}

Uint8List withCrc(List<int> body) {
final crc = crc16Modbus(body);
return Uint8List.fromList([...body, crc & 0xFF, crc >> 8]); // low byte first
}

/// Read holding (fn 3) or input (fn 4) registers.
Uint8List buildRead(int slave, int fn, int address, int quantity) => withCrc([
slave, fn, address >> 8, address & 0xFF, quantity >> 8, quantity & 0xFF,
]);

/// Write single register (fn 6). [raw] is the already-encoded 16-bit word.
Uint8List buildWriteSingle(int slave, int address, int raw) => withCrc([
slave, 6, address >> 8, address & 0xFF, (raw >> 8) & 0xFF, raw & 0xFF,
]);

/// Write multiple registers (fn 16) — used with quantity 1 for registers
/// whose write_function_code is 16 (IP20 RW settings).
Uint8List buildWriteMultiple(int slave, int address, List<int> rawWords) => withCrc([
slave, 16, address >> 8, address & 0xFF,
rawWords.length >> 8, rawWords.length & 0xFF, rawWords.length * 2,
for (final w in rawWords) ...[(w >> 8) & 0xFF, w & 0xFF],
]);

Unit-test these against known frames before touching BLE:

CallBytes
buildRead(1, 3, 0, 1)01 03 00 00 00 01 84 0A
buildRead(1, 3, 1380, 10)01 03 05 64 00 0A 84 DE
buildRead(1, 3, 0, 10)01 03 00 00 00 0A C5 CD
buildRead(1, 3, 87, 1)01 03 00 57 00 01 35 DA

3. BLE transport​

Wrap whichever BLE package you use (e.g. flutter_blue_plus) behind a small interface, so the Modbus code can be tested with a fake:

abstract class BleLink {
Future<void> write(Uint8List bytes); // to the logger's write characteristic
Stream<List<int>> get incoming; // its notify characteristic, notifications enabled
}

The client below sends one request at a time, puts split notifications back together, drops the logger's AT+… text lines, and classifies every outcome the way detection needs it:

sealed class ReadOutcome {}
class ReadData extends ReadOutcome { final Uint8List data; ReadData(this.data); } // register bytes only
class ReadException extends ReadOutcome { final int code; ReadException(this.code); } // a real answer: "no"
class ReadNoAnswer extends ReadOutcome { final String why; ReadNoAnswer(this.why); } // timeout / bad CRC / desync

class ModbusRtuClient {
final BleLink link;
final Duration timeout;
final int retries;
final String ignorePrefix;
final _buf = <int>[];
Completer<void>? _wake;
Future<void> _queue = Future.value();

ModbusRtuClient(this.link, {required this.timeout, required this.retries, this.ignorePrefix = 'AT+'}) {
link.incoming.listen((chunk) {
_buf.addAll(chunk);
_wake?.complete();
_wake = null;
});
}

/// Build from the detection rules' "read" object.
factory ModbusRtuClient.fromRules(BleLink link, Map<String, dynamic> read) => ModbusRtuClient(
link,
timeout: Duration(milliseconds: read['responseTimeoutMs'] as int),
retries: read['retries'] as int,
ignorePrefix: read['ignoreLinesWithPrefix'] as String,
);

/// Serialised: Modbus RTU has no request ids, so never overlap requests.
Future<ReadOutcome> read(int slave, int fn, int address, int quantity) {
final next = _queue.then((_) => _readWithRetries(slave, fn, address, quantity));
_queue = next.then((_) {}, onError: (_) {});
return next;
}

Future<ReadOutcome> _readWithRetries(int slave, int fn, int address, int quantity) async {
ReadOutcome last = ReadNoAnswer('not sent');
for (var attempt = 0; attempt <= retries; attempt++) {
last = await _once(buildRead(slave, fn, address, quantity), slave, fn, 2 * quantity);
if (last is! ReadNoAnswer) return last; // data or exception: a real answer, don't retry
}
return last;
}

Future<ReadOutcome> _once(Uint8List frame, int slave, int fn, int expectedBytes) async {
// Throw away anything left over: a late reply to an earlier attempt must
// never be read as this one's answer.
_buf.clear();
await link.write(frame);
final deadline = DateTime.now().add(timeout);
while (true) {
final r = _tryParse(slave, fn, expectedBytes);
if (r != null) return r;
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) return ReadNoAnswer('timeout');
_wake = Completer<void>();
await _wake!.future.timeout(left, onTimeout: () {});
}
}

/// Null while more bytes are needed.
ReadOutcome? _tryParse(int slave, int fn, int expectedBytes) {
_dropTextLines();
if (_buf.length < 3) return null;
if (_buf[0] != slave) return ReadNoAnswer('desync: slave ${_buf[0]}');
final int frameLen;
if (_buf[1] == (fn | 0x80)) {
frameLen = 5;
} else if (_buf[1] == fn) {
if (_buf[2] != expectedBytes) return ReadNoAnswer('byte count ${_buf[2]}, expected $expectedBytes');
frameLen = 3 + expectedBytes + 2;
} else {
return ReadNoAnswer('desync: function ${_buf[1]}');
}
if (_buf.length < frameLen) return null;
final crc = crc16Modbus(_buf, 0, frameLen - 2);
if (_buf[frameLen - 2] != (crc & 0xFF) || _buf[frameLen - 1] != (crc >> 8)) {
return ReadNoAnswer('bad CRC');
}
if (frameLen == 5) return ReadException(_buf[2]);
return ReadData(Uint8List.fromList(_buf.sublist(3, 3 + expectedBytes)));
}

/// Removes complete "AT+...\n" lines from the front of the buffer.
void _dropTextLines() {
final p = ignorePrefix.codeUnits;
while (_buf.length >= p.length && _startsWith(_buf, p)) {
final nl = _buf.indexOf(0x0A);
if (nl < 0) return; // wait for the rest of the line
_buf.removeRange(0, nl + 1);
}
}

static bool _startsWith(List<int> b, List<int> p) {
for (var i = 0; i < p.length; i++) {
if (b[i] != p[i]) return false;
}
return true;
}
}

Writes use the same request/response loop: send buildWriteSingle or buildWriteMultiple. A successful fn 6 reply echoes the request. A fn 16 reply is the slave, 16, the address and the quantity, then the CRC (8 bytes). An exception reply is fn | 0x80 + code, as for reads.

4. Decoding​

Every register decodes from its own bytes in the reply. A register at address a in a batch starting at start begins at byte 2 × (a − start).

/// Numbers: big-endian; 32-bit types high word first. Value = raw × scale.
double decodeNumber(String dataType, Uint8List b, double scale) {
final d = ByteData.sublistView(b);
final num raw = switch (dataType) {
'uint16' => d.getUint16(0),
'int16' => d.getInt16(0),
'uint32' => d.getUint32(0),
'int32' => d.getInt32(0),
_ => throw ArgumentError('not a number type: $dataType'),
};
return raw * (scale == 0 ? 1 : scale);
}

/// Text: stop at the first byte outside 0x20–0x7E, trim spaces.
/// Null (an error) when nothing printable is left — never an empty serial.
String? decodeText(Uint8List b) {
final sb = StringBuffer();
for (final c in b) {
if (c < 0x20 || c > 0x7E) break;
sb.writeCharCode(c);
}
final s = sb.toString().trim();
return s.isEmpty ? null : s;
}

/// Date/time: year-2000, month, day, hour, minute, second; no time zone.
/// '' when never set; null when a field is out of range.
String? decodeDateTime(Uint8List b) {
if (b.take(6).every((x) => x == 0)) return '';
final [y, mo, d, h, mi, s] = b.take(6).toList();
if (y > 99 || mo < 1 || mo > 12 || d < 1 || d > 31 || h > 23 || mi > 59 || s > 59) return null;
String two(int v) => v.toString().padLeft(2, '0');
return '${2000 + y}-${two(mo)}-${two(d)}T${two(h)}:${two(mi)}:${two(s)}';
}

/// scale_rule: the selector register's raw value picks the scale.
/// Null when the selector has not been read (refuse writes in that case).
double? resolveScale(Map<String, dynamic> reg, Map<int, int> selectors) {
final rule = reg['scale_rule'];
if (rule == null) return (reg['scale'] as num?)?.toDouble() ?? 1;
final raw = selectors[rule['register'] as int];
if (raw == null) return null;
final bitSet = (raw >> (rule['bit'] as int)) & 1 == 1;
return ((bitSet ? rule['scale_if_set'] : rule['scale_if_clear']) as num).toDouble();
}

Variant filtering, after detection:

/// The rows of [registers] that apply to a device of [variant]; null = unknown.
List<Map<String, dynamic>> rowsForVariant(List<Map<String, dynamic>> registers, String? variant) {
String v(Map r) => (r['variant'] as String?) ?? '';
if (variant != null) {
return registers.where((r) => v(r).isEmpty || v(r) == variant).toList();
}
// Unknown: drop any name that two variants define, keep everything else.
final variantsByName = <String, Set<String>>{};
for (final r in registers) {
if (v(r).isNotEmpty) (variantsByName[r['name']] ??= {}).add(v(r));
}
return registers.where((r) => v(r).isEmpty || variantsByName[r['name']]!.length == 1).toList();
}

5. Detection​

Run the algorithm straight from the rules. Nothing in this code names a model or an address.

enum CheckResult { pass, fail, noAnswer }

sealed class DetectionOutcome {}
class Detected extends DetectionOutcome {
final String model, serial;
final String? variant; // null = unknown variant
Detected(this.model, this.serial, this.variant);
}
class DetectionFailed extends DetectionOutcome {
final String reason; // 'link' | 'ambiguous' | 'unsupported'
final List<String> models;
DetectionFailed(this.reason, this.models);
}

/// [rules] is the `detection` object inside the modbus_detection envelope.
Future<DetectionOutcome> detect(ModbusRtuClient modbus, Map<String, dynamic> rules) async {
final confirmed = <(Map<String, dynamic>, String)>[]; // (model rules, serial)
final unanswered = <String>[];

for (final m in (rules['models'] as List).cast<Map<String, dynamic>>()) {
final slave = m['slaveAddress'] as int;
String? serial;
var result = CheckResult.pass;
for (final c in (m['confirm'] as List).cast<Map<String, dynamic>>()) {
final (r, text) = await _runCheck(modbus, slave, c);
if (text != null) serial = text;
if (r != CheckResult.pass) {
result = r;
break;
}
}
switch (result) {
case CheckResult.pass: confirmed.add((m, serial!));
case CheckResult.noAnswer: unanswered.add(m['model'] as String);
case CheckResult.fail: break; // rejected
}
}

// Order matters: an unheard candidate rules out any decision.
if (unanswered.isNotEmpty) return DetectionFailed('link', unanswered);
if (confirmed.length > 1) return DetectionFailed('ambiguous', [for (final c in confirmed) c.$1['model'] as String]);
if (confirmed.isEmpty) return DetectionFailed('unsupported', const []);

final (m, serial) = confirmed.single;
String? variant;
final vc = m['variant'] as Map<String, dynamic>?;
if (vc != null) {
final out = await modbus.read(m['slaveAddress'] as int, vc['functionCode'] as int, vc['address'] as int, 1);
if (out is ReadData) {
final raw = ByteData.sublistView(out.data).getUint16(0);
final field = (raw >> (vc['bit'] as int)) & ((1 << (vc['width'] as int)) - 1);
variant = (vc['values'] as Map)['$field'] as String?; // undefined value -> unknown
}
}
return Detected(m['model'] as String, serial, variant);
}

/// Returns the check's result, and the decoded text for serial_text.
Future<(CheckResult, String?)> _runCheck(ModbusRtuClient modbus, int slave, Map<String, dynamic> c) async {
final out = await modbus.read(slave, c['functionCode'] as int, c['address'] as int, c['quantity'] as int);
if (out is ReadNoAnswer) return (CheckResult.noAnswer, null);
if (out is ReadException) return (CheckResult.fail, null);
final data = (out as ReadData).data;
switch (c['check']) {
case 'plausible_value':
final v = decodeNumber(c['dataType'] as String, data, (c['scale'] as num?)?.toDouble() ?? 1);
final min = (c['min'] as num?)?.toDouble(), max = (c['max'] as num?)?.toDouble();
final ok = (min == null || v >= min) && (max == null || v <= max);
return (ok ? CheckResult.pass : CheckResult.fail, null);
case 'serial_text':
final s = decodeText(data);
final ok = s != null && s.length >= (c['minLength'] as int);
return (ok ? CheckResult.pass : CheckResult.fail, s?.toUpperCase());
default:
// rulesUsable() must have refused rules with check kinds we don't know.
throw StateError('unknown check ${c['check']}');
}
}

Remember the result (serial → model, spec sha256, variant). On the next connection, run only that model's serial_text check. Use the remembered profile if it passes with the same serial. Otherwise run detect again.

What to show the user:

OutcomeMessageAction
Detected"Connected to model · serial"Continue
Detected, variant nullSame, plus "some readings unavailable until the phase type can be read"Continue; retry the variant read later
link"The inverter did not answer. Move closer and try again."Retry button
ambiguous"Could not identify this inverter reliably."Report it (send the serial and models to support)
unsupported"This inverter model is not supported for local control."—
Rules or profile not usable"Update the app to control this inverter."Store link
No profiles cached and no built-in copy"Connect to the internet once to download inverter profiles."—

6. Reading, writing and alerts​

Using the profile after detection; the rules are on the contract page.

  1. Take rowsForVariant(spec['registers'], variant).

  2. Selectors first. Read every scale_rule.register address (90 and 1061 on Aotai) once per connection, as plain uint16 with function 3. Keep them in a Map<int, int>.

  3. Poll the rows at spec['telemetry_registers'] that survived the variant filter, plus alarm_scan_registers. Group them into reads:

    • sort by address; same read_function_code per read;
    • extend a read while it stays within 125 registers (gaps are fine);
    • if batch_within_sheet is true, start a new read when sheet changes;
    • if a read gets an exception, split it and retry the halves.
  4. Decode each row from its slice with decodeNumber/decodeText/ decodeDateTime, using resolveScale for its scale.

  5. Writes follow the write rules: resolve the scale (refuse if resolveScale returns null), encode round(value / scale), refuse if out of range for uint16/int16 or length > 1, send with write_function_code, then read back. A row with bit/bits is a field of a shared word: read the word, merge, and write the merged word (only claim bit_field support once this is in):

    /// [low] and [width] of a bit-field row, or null for a whole register.
    (int, int)? bitField(Map<String, dynamic> reg) {
    final bit = reg['bit'] as int?;
    final bits = (reg['bits'] as List?)?.cast<int>();
    if (bit != null) return (bit, 1);
    if (bits != null) return (bits[0], bits[1] - bits[0] + 1);
    return null;
    }

    /// The word to write: [current] with only the field replaced by [value].
    int mergeBitField(int current, int low, int width, num value) {
    final max = (1 << width) - 1;
    if (value != value.truncate() || value < 0 || value > max) {
    throw ArgumentError('value $value does not fit a $width-bit field');
    }
    final mask = max << low;
    return (current & ~mask & 0xFFFF) | ((value.toInt() << low) & mask);
    }

    Decode a bit-field row with (raw >> low) & ((1 << width) - 1). The encode_bit_field test vectors check mergeBitField.

  6. Alerts: evaluate alerts[] against each scan, with the hysteresis counts, at about one scan every 30 s.

Show an obvious "Local mode — changes are not synced to the cloud" banner: nothing here reaches the backend.

7. Test vectors​

local-control-vectors.json has 26 cases generated by the server's own decoder. Wire them into flutter test. Every kind must pass:

kindInputsCheck
decodedataType, scale, rawHexexpect.value (number), expect.text (ascii/datetime) or expect.error
resolve_scalethe register, selectors, rawHexexpect.scale and expect.value
variantrawHex of register 87expect.known, and expect.variant when known
encodevalue, dataType, scaleexpect.rawHex, or expect.error (must refuse)
alertalertCode, rawHexexpect.active
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';

Uint8List hexBytes(String h) =>
Uint8List.fromList([for (var i = 0; i < h.length; i += 2) int.parse(h.substring(i, i + 2), radix: 16)]);

void main() {
final file = jsonDecode(File('test/fixtures/local-control-vectors.json').readAsStringSync());
for (final v in (file['vectors'] as List).cast<Map<String, dynamic>>()) {
if (v['kind'] != 'decode') continue; // add the other kinds the same way
test('${v['model']} ${v['register']}: ${v['description']}', () {
final b = hexBytes(v['rawHex']);
final e = v['expect'] as Map<String, dynamic>;
switch (v['dataType']) {
case 'ascii':
final s = decodeText(b);
e['error'] == true ? expect(s, isNull) : expect(s, e['text']);
case 'datetime':
final s = decodeDateTime(b);
e['error'] == true ? expect(s, isNull) : expect(s, e['text']);
default:
final got = decodeNumber(v['dataType'], b, (v['scale'] as num?)?.toDouble() ?? 1);
expect(got, closeTo((e['value'] as num).toDouble(), 1e-9));
}
});
}
}

Copy the file into the app's test fixtures, and refresh it when this page's copy changes. The server's test fails whenever the decoder or a profile changes in a way that changes a vector, so a new file always means a real change.

Checklist before release​

  • Profiles and rules cached on download, written atomically; built-in copy bundled
  • have sent; unchanged merged; gaps in index trigger a retry
  • App refuses newer algorithmVersion and unknown requiredFeatures
  • Framing unit tests pass (table in step 2)
  • All test vectors pass, all five kinds
  • Detection never stops at the first match; link failure never picks a model
  • Both bench inverters detected; each rejects the other's profile
  • BLE reads match cloud read_registers for the same registers
  • Writes: scale resolved, range refused not wrapped, read back
  • Local-mode banner shown; nothing sent to the backend