Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…into add-rtk-support
  • Loading branch information
Gold872 committed Dec 26, 2024
2 parents 98b5293 + 0ab7f8e commit 159ebb5
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 59 deletions.
7 changes: 7 additions & 0 deletions .github/pubspec_overrides.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
resolution:

dependency_overrides:
burt_network:
git:
url: https://github.com/BinghamtonRover/Networking
ref: 2.3.1
12 changes: 10 additions & 2 deletions .github/workflows/analyzer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,18 @@ jobs:
# https://github.com/dart-lang/setup-dart/blob/main/README.md
- uses: dart-lang/setup-dart@v1
with:
sdk: 3.5.2
sdk: 3.6.0

# This package is part of a Pub Workspace. However, CI still needs to
# run on this repo by itself, so we want to override burt_network to use
# a Git dependency ONLY on GitHub Actions.
#
# To get around this, we commit the overrides to the .github folder where
# Dart can't find them, then copy them as part of the CI workflow.
- name: Install dependencies
run: dart pub get
run: |
mv .github/pubspec_overrides.yaml .
dart pub get
- name: Analyze project source
run: dart analyze --fatal-infos
Expand Down
16 changes: 12 additions & 4 deletions .github/workflows/dartdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:

steps:
- uses: actions/checkout@v3
with:
with:
fetch-depth: 0

- name: Git Setup
Expand All @@ -24,12 +24,20 @@ jobs:
- name: Install Dart
uses: dart-lang/setup-dart@v1

# This package is part of a Pub Workspace. However, CI still needs to
# run on this repo by itself, so we want to override burt_network to use
# a Git dependency ONLY on GitHub Actions.
#
# To get around this, we commit the overrides to the .github folder where
# Dart can't find them, then copy them as part of the CI workflow.
- name: Install dependencies
run: dart pub get
run: |
mv .github/pubspec_overrides.yaml .
dart pub get
- name: Analyze Dart code
run: dart analyze --fatal-infos

- name: Output error
if: failure()
run: echo "::error The code or is missing documentation. Run flutter analyze --dartdocs"
Expand All @@ -44,4 +52,4 @@ jobs:
git status
git stage --force docs
git commit -a -m "Generated documentation"
git push --force
git push --force
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ build/

# This file tells the rover to get its dependencies from local files instead of Git/Pub.
# GitHub's CI needs to use the Pub versions, so we don't check in this file.
pubspec_overrides.yaml
./pubspec_overrides.yaml
8 changes: 4 additions & 4 deletions bin/data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ Future<void> main() async {
);
server.sendMessage(data);
final data2 = ArmData(
base: MotorData(angle: motor2.current),
shoulder: MotorData(angle: motor.current),
elbow: MotorData(angle: motor.current),
base: MotorData(currentAngle: motor2.current),
shoulder: MotorData(currentAngle: motor.current),
elbow: MotorData(currentAngle: motor.current),
version: Version(major: 1),
);
server.sendMessage(data2);
final data3 = GripperData(lift: MotorData(angle: pi + -1 * 2 * motor.current), version: Version(major: 1));
final data3 = GripperData(lift: MotorData(currentAngle: pi + -1 * 2 * motor.current), version: Version(major: 1));
server.sendMessage(data3);
final data4 = RoverPosition(
orientation: Orientation(
Expand Down
144 changes: 100 additions & 44 deletions bin/serial.dart
Original file line number Diff line number Diff line change
@@ -1,92 +1,148 @@
import "dart:io";
import "dart:typed_data";
import "package:args/args.dart";
import "package:collection/collection.dart";

import "package:burt_network/burt_network.dart";
import "package:libserialport/libserialport.dart";

typedef ProtoConstructor = Message Function(List<int> data);

const constructors = <Device, ProtoConstructor>{
Device.DRIVE: DriveData.fromBuffer,
Device.ARM: ArmData.fromBuffer,
Device.GRIPPER: GripperData.fromBuffer,
Device.SCIENCE: GripperData.fromBuffer,
Device.ANTENNA: AntennaFirmwareData.fromBuffer,
};

final deviceNames = {
for (final device in constructors.keys)
device.name.toLowerCase(): device,
};

final logger = BurtLogger();

bool ascii = false;
late bool ascii;
late bool rawMode;
ProtoConstructor? constructor;
String? messageName;

void handlePacket(Uint8List buffer) {
try {
if (rawMode) {
logger.debug("Got packet: $buffer");
} else if (constructor == null) {
final string = String.fromCharCodes(buffer).trim();
logger.debug("Got string: $string");
} else {
final message = constructor!(buffer);
logger.debug("Got $messageName message: ${message.toProto3Json()}");
}
} catch (error) {
logger.error("Could not decode packet: $error\n Buffer: $buffer");
}
}

Future<void> listenToDevice(String port) async {
Future<void> listenToDevice(String port, int baudRate) async {
logger.info("Connecting to $port...");
final device = SerialDevice(
portName: port,
readInterval: const Duration(milliseconds: 100),
logger: logger,
baudRate: baudRate,
);
if (!await device.init()) {
logger.critical("Could not connect to $port");
return;
}
logger.info("Connected. Listening...");
device.stream.listen(processAscii);
device.stream.listen(handlePacket);
device.startListening();
}

Future<void> listenToFirmware(String port) async {
Future<void> listenToFirmware(String port, int baudRate) async {
logger.info("Connecting to $port...");
final device = BurtFirmwareSerial(
port: port,
logger: logger,
baudRate: baudRate,
);
if (!await device.init()) {
logger.critical("Could not connect to $port");
await device.dispose();
return;
}
logger.info("Connected? ${device.isReady}. Listening...");
constructor = getDataConstructor(device.device);
constructor = constructors[device.device];
if (constructor == null) {
logger.error("Unsupported serial device: ${device.device.name}");
await device.dispose();
return;
}
device.rawStream.listen(processFirmware);
device.rawStream.listen(handlePacket);
}

typedef ProtoConstructor = Message Function(List<int> data);

ProtoConstructor? getDataConstructor(Device device) => switch (device) {
Device.DRIVE => DriveData.fromBuffer,
Device.ARM => ArmData.fromBuffer,
Device.GRIPPER => GripperData.fromBuffer,
Device.SCIENCE => GripperData.fromBuffer,
_ => null,
};
void printUsage(ArgParser parser) =>
// ignore: avoid_print
print("\nUsage: dart run :serial [-h] [-f] [-r | -d <device>] [-b <baud>] <port>\n${parser.usage}");

ProtoConstructor? constructor;
ArgParser buildParser() => ArgParser()
..addFlag("help", abbr: "h", negatable: false, help: "Show this help message")
..addFlag("firmware", abbr: "f", negatable: false, help: "Whether to perform the standard firmware handshake")
..addFlag("raw", abbr: "r", negatable: false, help: "Whether to print incoming packets as raw bytes")
..addOption("baud", abbr: "b", defaultsTo: "9600", help: "The baud rate to listen with")
..addOption(
"device", abbr: "d",
allowed: deviceNames.keys,
help: "The device being read. This will attempt to parse data as messages from that device\n"
" Note: If -f is passed, this will be ignored and the firmware will identify itself",
);

void main(List<String> args) async {
if (args.isEmpty) {
logger.info("Ports: ${SerialPort.availablePorts}");
return;
} else if (args.contains("-h") || args.contains("--help")) {
logger.info("Usage: dart run -r :serial [-a | --ascii] [port]");
Future<void> main(List<String> args) async {
// Basic arg parsing
final parser = buildParser();
final ArgResults results;
try {
results = buildParser().parse(args);
} on FormatException catch (error) {
logger.error(error.message);
printUsage(parser);
return;
}
var port = args.first;
if (!Platform.isWindows && !port.startsWith("/dev")) port = "/dev/$port";
if (args.contains("-a") || args.contains("--ascii")) {
logger.info("Running in ASCII mode");
ascii = true;
}
if (args.contains("-f") || args.contains("--firmware")) {
await listenToFirmware(port);
} else {
await listenToDevice(port);
final isFirmware = results.flag("firmware");
final showHelp = results.flag("help");
final deviceName = results.option("device");
final baudRateString = results.option("baud")!;
final baudRate = int.tryParse(baudRateString);
rawMode = results.flag("raw");
var port = results.rest.firstOrNull;
if (showHelp) {
printUsage(parser);
return;
} else if (port == null) {
logger.info("Ports: ${SerialDevice.allPorts}");
return;
} else if (baudRate == null) {
logger.critical("Could not parse baud rate as an integer: $baudRateString");
exit(1);
} else if (rawMode && deviceName != null) {
logger.critical("Cannot specify both --raw and --device");
exit(2);
}
}

void processFirmware(Uint8List buffer) {
try {
final data = constructor!(buffer);
logger.debug("Got data: ${data.toProto3Json()}");
} catch (error) {
logger.error("Could not decode DriveData: $error\n Buffer: $buffer");
// Try to identify a device, if passed.
final device = deviceNames[deviceName];
constructor = constructors[device];
if (constructor != null) {
final buffer = Uint8List(0);
messageName = constructor!(buffer).messageName;
logger.info("Parsing all data as $messageName messages");
}
}

void processAscii(Uint8List buffer) {
final s = String.fromCharCodes(buffer).trim();
logger.debug("Got string: $s");
if (!Platform.isWindows && !port.startsWith("/dev")) port = "/dev/$port";
if (isFirmware) {
await listenToFirmware(port, baudRate);
} else {
await listenToDevice(port, baudRate);
}
}
3 changes: 1 addition & 2 deletions lib/src/devices/firmware.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ class FirmwareManager extends Service {
logger.debug("Initializing device: ${device.port}");
result &= await device.init();
if (!device.isReady) continue;
final subscription = device.messages?.listen(collection.server.sendWrapper);
if (subscription == null) continue;
final subscription = device.messages.listen(collection.server.sendWrapper);
_subscriptions.add(subscription);
}
return result;
Expand Down
6 changes: 4 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ description: A sample command-line application.
version: 1.0.0
publish_to: none

resolution: workspace
environment:
sdk: ^3.5.0
sdk: ^3.6.0

# Add regular dependencies here.
dependencies:
args: ^2.6.0
burt_network:
git: https://github.com/BinghamtonRover/Networking.git
collection: ^1.19.0
Expand All @@ -19,6 +21,6 @@ dependencies:
protobuf: ^3.1.0

dev_dependencies:
ffigen: ^14.0.0
ffigen: ^16.0.0
test: ^1.25.8
very_good_analysis: ^6.0.0

0 comments on commit 159ebb5

Please sign in to comment.