Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CONSULT-469] add initial code for field parsing #377

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ members = [
"micro-rdk",
"micro-rdk-installer",
"micro-rdk-macros",
"micro-rdk-nmea",
"micro-rdk-server",
"micro-rdk-ffi",
"examples/modular-drivers",
Expand Down
15 changes: 15 additions & 0 deletions micro-rdk-nmea/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "micro-rdk-nmea"
authors.workspace = true
description.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true
rust-version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
micro-rdk = { workspace = true, features = ["native"] }
thiserror = { workspace = true }
5 changes: 5 additions & 0 deletions micro-rdk-nmea/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# The micro-RDK NMEA 2000 Message Parser (WIP)

This library supplies logic to parse NMEA 2000 messages from byte data into
structs in Rust that can serialize into instances of `GenericReadingsResult` for use in the implementation of
micro-RDK sensors.
1 change: 1 addition & 0 deletions micro-rdk-nmea/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod parse_helpers;
329 changes: 329 additions & 0 deletions micro-rdk-nmea/src/parse_helpers/enums.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,329 @@
pub trait NmeaEnumeratedField: Sized + From<u32> + ToString {}

/// For generating a lookup data type found in an NMEA message. The first argument is the name of the
/// enum type that will be generated. Each successive argument is a tuple with
/// (raw number value, name of enum instance, string representation)
macro_rules! define_nmea_enum {
( $name:ident, $(($value:expr, $var:ident, $label:expr)),*, $default:ident) => {
#[derive(Copy, Clone, Debug)]
pub enum $name {
$($var),*,
$default
}

impl From<u32> for $name {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be TryFrom? Then you wouldn't need the $default:ident or associated enum member and could just return an error.

Copy link
Member Author

@gvaradarajan gvaradarajan Jan 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had this be the behavior because the gonmea library does not fail on an unrecognized lookup value

fn from(value: u32) -> Self {
match value {
$($value => Self::$var),*,
_ => Self::$default
}
}
}

impl ToString for $name {
fn to_string(&self) -> String {
match self {
$(Self::$var => $label),*,
Self::$default => "could not parse"
}.to_string()
}
}

impl NmeaEnumeratedField for $name {}
};

}

// Examples below taken from https://canboat.github.io/canboat/canboat.html

define_nmea_enum!(
WaterReference,
(0, PaddleWheel, "Paddle Wheel"),
(1, PitotTube, "Pitot Tube"),
(2, Doppler, "Doppler"),
(3, Correlation, "Correlation (ultra sound)"),
(4, Electromagnetic, "Electro Magnetic"),
CouldNotParse
);

define_nmea_enum!(
TemperatureSource,
(0, SeaTemperature, "Sea Temperature"),
(1, OutsideTemperature, "Outside Temperature"),
(2, InsideTemperature, "Inside Temperature"),
(3, EngineRoomTemperature, "Engine Room Temperature"),
(4, MainCabinTemperature, "Main Cabin Temeprature"),
(5, LiveWellTemperature, "Live Well Temperature"),
(6, BaitWellTemperature, "Bait Well Temperature"),
(7, RefrigerationTemperature, "Refrigeration Temperature"),
(8, HeatingSystemTemperature, "Heating System Temperature"),
(9, DewPointTemperature, "Dew Point Temperature"),
(
10,
ApparentWindChillTemerature,
"Apparent Wind Chill Temperature"
),
(
11,
TheoreticalWindChillTemperature,
"Theoretical Wind Chill Temperature"
),
(12, HeatIndexTemperature, "Heat Index Temperature"),
(13, FreezerTemperature, "Freezer Temperature"),
(14, ExhaustGasTemperature, "Exhaust Gas Temperature"),
(15, ShaftSealTemeprature, "Shaft Seal Temperature"),
CouldNotParse
);

define_nmea_enum!(
SystemTimeSource,
(0, Gps, "GPS"),
(1, Glonass, "GLONASS"),
(2, RadioStation, "Radio Station"),
(3, LocalCesiumClock, "Local Cesium clock"),
(4, LocalRubidiumClock, "Local Rubidium clock"),
(5, LocalCrystalClock, "Local Crystal clock"),
CouldNotParse
);

define_nmea_enum!(
MagneticVariationSource,
(0, Manual, "Manual"),
(1, AutomaticChart, "Automatic Chart"),
(2, AutomaticTable, "Automatic Table"),
(3, AutomaticCalculation, "Automatic Calculation"),
(4, Wmm2000, "WMM 2000"),
(5, Wmm2005, "WMM 2005"),
(6, Wmm2010, "WMM 2010"),
(7, Wmm2015, "WMM 2015"),
(8, Wmm2020, "WMM 2020"),
CouldNotParse
);

define_nmea_enum!(
RepeatIndicator,
(0, Initial, "Initial"),
(1, FirstRetransmission, "First retransmission"),
(2, SecondRetransmission, "Second retransmission"),
(3, ThirdRetransmission, "Third retransmission"),
(4, FinalRetransmission, "Final retransmission"),
CouldNotParse
);

define_nmea_enum!(
AisMessageId,
(
1,
ScheduledClassAPositionReport,
"Scheduled Class A position report"
),
(
2,
AssignedScheduledClassAPositionReport,
"Assigned scheduled Class A position report"
),
(
3,
InterrogatedClassAPositionReport,
"Interrogated Class A position report"
),
(4, BaseStationReport, "Base station report"),
(5, StaticVoyageRelatedData, "Static and voyage related data"),
(6, BinaryAddressedMessage, "Binary addressed message"),
(7, BinaryAcknowledgement, "Binary acknowledgement"),
(8, BinaryBroadcastMessage, "Binary broadcast message"),
(
9,
StandardSarAircraftPositionReport,
"Standard SAR aircraft position report"
),
(10, UtcDateInquiry, "UTC/date inquiry"),
(11, UtcDateResponse, "UTC/date response"),
(
12,
SafetyRelatedAddressedMessage,
"Safety related addressed message"
),
(
13,
SafetyRelatedAcknowlegdement,
"Safety related acknowledgement"
),
(
14,
SafetyRelatedBroadcastMessage,
"Satety related broadcast message"
),
(15, Interrogation, "Interrogation"),
(16, AssignmentModeCommand, "Assignment mode command"),
(
17,
DgnssBroadcastBinaryMessage,
"DGNSS broadcast binary message"
),
(
18,
StandardClassBPositionReport,
"Standard Class B position report"
),
(
19,
ExtendedClassBPositionReport,
"Extended Class B position report"
),
(
20,
DataLinkManagementMessage,
"Data link management message"
),
(21, AtonReport, "ATON report"),
(22, ChannelManagement, "Channel management"),
(23, GroupAssignmentCommand, "Group assignment command"),
(24, StaticDataReport, "Static data report"),
(25, SingleSlotBinaryMessage, "Single slot binary message"),
(
26,
MultipleSlotBinaryMessage,
"Multiple slot binary message"
),
(
27,
PositionReportForLongRangeApplications,
"Position report for long range applications"
),
CouldNotParse
);

define_nmea_enum!(
PositionAccuracy,
(0, Low, "Low"),
(1, High, "High"),
CouldNotParse
);

define_nmea_enum!(
RaimFlag,
(0, NotInUse, "not in use"),
(1, InUse, "in use"),
CouldNotParse
);

define_nmea_enum!(
TimeStamp,
(60, NotAvailable, "Not available"),
(61, ManualInputMode, "Manual input mode"),
(62, DeadReckoningMode, "Dead reckoning mode"),
(
63,
PositioningSystemIsInoperative,
"Positioning system is inoperative"
),
CouldNotParse
);

define_nmea_enum!(
AisTransceiver,
(0, ChannelAVdlReception, "Channel A VDL reception"),
(1, ChannelBVdlReception, "Channel B VDL reception"),
(2, ChannelAVdlTransmission, "Channel A VDL transmission"),
(3, ChannelBVdlTransmission, "Channel B VDL transmission"),
(
4,
OwnInformationNotBroadcast,
"Own information not broadcast"
),
(5, Reserved, "Reserved"),
CouldNotParse
);

define_nmea_enum!(
NavStatus,
(0, UnderWayUsingEngine, "Under way using engine"),
(1, AtAnchor, "At anchor"),
(2, NotUnderCommand, "Not under command"),
(3, RestrictedManeuverability, "Restricted maneuverability"),
(4, ConstrainedByHerDraught, "Constrained by her draught"),
(5, Moored, "Moored"),
(6, Aground, "Aground"),
(7, EngagedInFishing, "Engaged in Fishing"),
(8, UnderWaySailing, "Under way sailing"),
(
9,
HazardousMaterialHighSpeed,
"Hazardous material - High Speed"
),
(
10,
HazardousMaterialWingInGround,
"Hazardous material - Wing in Ground"
),
(
11,
PowerDrivenVesslTowingAstern,
"Power-driven vessl towing astern"
),
(
12,
PowerDrivenVesslPushingAhead,
"Power-driven vessl pushing ahead or towing alongside"
),
(14, AisSart, "AIS-SART"),
CouldNotParse
);

define_nmea_enum!(
AisSpecialManeuver,
(0, NotAvailable, "Not available"),
(
1,
NotEngagedInSpecialManeuver,
"Not engaged in special maneuver"
),
(2, EngagedInSpecialManeuver, "Engaged in special maneuver"),
(3, Reserved, "Reserved"),
CouldNotParse
);

define_nmea_enum!(
DirectionReference,
(0, True, "True"),
(1, Magnetic, "Magnetic"),
(2, Error, "Error"),
CouldNotParse
);

define_nmea_enum!(
Gns,
(0, Gps, "GPS"),
(1, Glonass, "GLONASS"),
(2, GpsGlonass, "GPS+GLONASS"),
(3, GpsSbasWaas, "GPS+SBAS/WAAS"),
(4, GpsSbasWaasGlonass, "GPS+SBAS/WAAS+GLONASS"),
(5, Chayka, "Chayka"),
(6, Integrated, "integrated"),
(7, Surveyed, "surveyed"),
(8, Galileo, "Galileo"),
CouldNotParse
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CouldNotParse feels like it should be an error vs an actual field. If we want to represent an Unknown LookupField then I would suggest naming it UnknowLookupField or alike

);

define_nmea_enum!(
GnsMethod,
(0, NoGnss, "no GNSS"),
(1, GnssFix, "GNSS fix"),
(2, DgnssFix, "DGNSS fix"),
(3, PreciseGnss, "Precise GNSS"),
(4, RtkFixedInteger, "RTK Fixed Integer"),
(5, RtkFloat, "RTK float"),
(6, EstimatedDrMode, "Estimated (DR) mode"),
(7, ManualInput, "Manual Input"),
(8, SimulateMode, "Simulate mode"),
CouldNotParse
);

define_nmea_enum!(
GnsIntegrity,
(0, NoIntegrityChecking, "No integrity checking"),
(1, Safe, "Safe"),
(2, Caution, "Caution"),
CouldNotParse
);
17 changes: 17 additions & 0 deletions micro-rdk-nmea/src/parse_helpers/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use thiserror::Error;

#[derive(Debug, Error)]
pub enum NumberFieldError {
#[error("field bit size {0} too large for max size {0}")]
ImproperBitSize(usize, usize),
}

#[derive(Debug, Error)]
pub enum NmeaParseError {
#[error(transparent)]
NumberFieldError(#[from] NumberFieldError),
#[error(transparent)]
TryFromSliceError(#[from] std::array::TryFromSliceError),
#[error("found unsupported PGN {0}")]
UnsupportedPgn(u32),
}
3 changes: 3 additions & 0 deletions micro-rdk-nmea/src/parse_helpers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod enums;
pub mod errors;
pub mod parsers;
Loading
Loading