Skip to content

Conversation

@makrsmark
Copy link
Collaborator

@makrsmark makrsmark commented Feb 23, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced message decoding with two new plugins to interpret additional flight-related data, including positional and time-based details.
  • Tests
    • Introduced comprehensive tests for the new plugins to ensure reliable decoding across various message formats, including valid, redacted, and invalid inputs.
  • Bug Fixes
    • Added checks to prevent invalid altitude values from being processed in the decoding results.
  • Documentation
    • Updated export statements to include the new plugins in the official plugin module.

@coderabbitai
Copy link

coderabbitai bot commented Feb 23, 2025

Walkthrough

This update integrates two new plugins into the message decoding process. The MessageDecoder class now registers the plugins Label_16_POSA1 and Label_16_TOD during initialization. Two new plugin classes are introduced—each implementing a decode method along with related qualifiers—and are supported by corresponding test suites. Additionally, the official plugin exports have been updated to include these new modules, ensuring they are available for integration within the overall system.

Changes

File(s) Change Summary
lib/MessageDecoder.ts Added new plugin registrations for Label_16_POSA1 and Label_16_TOD.
lib/plugins/Label_16_POSA1.ts
lib/plugins/Label_16_TOD.ts
Introduced new plugin classes extending DecoderPlugin with decode and qualifiers methods to handle specific message formats.
lib/plugins/Label_16_POSA1.test.ts
lib/plugins/Label_16_TOD.test.ts
Added new test suites validating the behavior of the newly introduced plugins across various scenarios including valid, redacted, and invalid inputs.
lib/plugins/official.ts Updated exports to include the new Label_16_POSA1 and Label_16_TOD plugins.
lib/utils/result_formatter.ts Added a check in the altitude method to prevent NaN values from being assigned to decodeResult.raw.altitude.
lib/plugins/Label_4A.test.ts Modified a test case to adjust the expected length of the formatted.items array from 5 to 4 for a specific input scenario.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant MD as MessageDecoder
    participant P1 as Label_16_POSA1 Plugin
    participant P2 as Label_16_TOD Plugin

    U->>MD: Send message for decoding
    MD->>MD: Initialize and register plugins (P1 and P2)
    alt Message matches POSA1 criteria
        MD->>P1: Call decode(message)
        P1-->>MD: Return decode result
    else Message matches TOD criteria
        MD->>P2: Call decode(message)
        P2-->>MD: Return decode result
    end
    MD-->>U: Return aggregated decode result
Loading

Possibly related PRs

  • Adding label 2P decoding #225: Introduced modifications to the MessageDecoder class by adding new plugin registrations, which aligns closely with the current changes.

Suggested reviewers

  • kevinelliott
  • fredclausen

Poem

In my warren of code, I hop with delight,
Two plugins added, making everything bright.
Label 16 POSA1 and TOD join the race,
Decoding messages with elegant grace.
Bugs nibble away, but joy fills the night! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (7)
lib/plugins/Label_16_POSA1.ts (1)

23-32: Consider adding input validation for empty or malformed messages.

The validation checks for the number of fields and preamble, but it might be worth adding checks for:

  • Empty message text
  • Malformed field values
 decode(message: Message, options: Options = {}) : DecodeResult {
   const decodeResult = this.defaultResult();
   decodeResult.decoder.name = this.name;
   decodeResult.formatted.description = 'Position Report';
   decodeResult.message = message;

+  if (!message.text?.trim()) {
+    if (options.debug) {
+      console.log('Decoder: Empty message text');
+    }
+    decodeResult.remaining.text = message.text || '';
+    decodeResult.decoded = false;
+    decodeResult.decoder.decodeLevel = 'none';
+    return decodeResult;
+  }

   const fields = message.text.split(',');
lib/plugins/Label_16_TOD.ts (1)

22-32: Consider adding input validation for empty or malformed messages.

Similar to the POSA1 decoder, consider adding validation for:

  • Empty message text
  • Malformed field values
 decode(message: Message, options: Options = {}) : DecodeResult {
   const decodeResult = this.defaultResult();
   decodeResult.decoder.name = this.name;
   decodeResult.formatted.description = 'Position Report';
   decodeResult.message = message;

+  if (!message.text?.trim()) {
+    if (options.debug) {
+      console.log('Decoder: Empty message text');
+    }
+    decodeResult.remaining.text = message.text || '';
+    decodeResult.decoded = false;
+    decodeResult.decoder.decodeLevel = 'none';
+    return decodeResult;
+  }

   const fields = message.text.split(',');
lib/plugins/Label_16_POSA1.test.ts (1)

22-39: Consider adding edge case tests.

While the current tests cover valid and redacted cases well, consider adding tests for:

  • Empty message text
  • Malformed coordinates
  • Invalid numeric values
  • Missing fields
test('handles empty message', () => {
  const text = '';
  const decodeResult = plugin.decode({ text });
  expect(decodeResult.decoded).toBe(false);
  expect(decodeResult.decoder.decodeLevel).toBe('none');
});

test('handles malformed coordinates', () => {
  const text = 'POSA1INVALID,GEARS,221626,370,BBOBO,222053,,-61,139,1174,829';
  const decodeResult = plugin.decode({ text });
  expect(decodeResult.decoded).toBe(false);
  expect(decodeResult.decoder.decodeLevel).toBe('none');
});

Also applies to: 41-58

lib/plugins/Label_16_TOD.test.ts (3)

26-26: Remove debug console.log statement.

The console.log statement should be removed as it's not needed for testing and could clutter test output.

-    console.log(decodeResult.formatted.items);

22-43: Add test case for remaining text validation.

The test verifies the decoding of variant 1 but doesn't validate the content of remaining.text. While line 42 checks that it equals ' 97', there's no explanation of what this value represents or why it's important.

Consider adding a comment explaining the significance of the remaining text:

+    // Verify remaining text contains the ground speed value
     expect(decodeResult.remaining.text).toBe('  97');

45-67: Enhance test coverage with edge cases.

The test suite covers basic scenarios but could benefit from additional edge cases:

  1. Messages with invalid timestamps
  2. Messages with out-of-range altitudes
  3. Messages with malformed coordinates

Would you like me to generate additional test cases for these scenarios?

Also applies to: 70-86, 88-97

lib/MessageDecoder.ts (1)

11-75: Consider refactoring plugin registration.

The constructor contains a long list of plugin registrations which could be better organized. Consider grouping plugins by label or functionality and moving the registration logic to a separate method.

Example refactor:

private registerDefaultPlugins(): void {
  const pluginGroups = {
    label10: [
      new Plugins.Label_10_LDR(this),
      new Plugins.Label_10_POS(this),
      new Plugins.Label_10_Slash(this),
    ],
    label16: [
      new Plugins.Label_16_N_Space(this),
      new Plugins.Label_16_POSA1(this),
      new Plugins.Label_16_TOD(this),
    ],
    // ... other groups
  };

  Object.values(pluginGroups).flat().forEach(plugin => this.registerPlugin(plugin));
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c20459 and 528993c.

📒 Files selected for processing (6)
  • lib/MessageDecoder.ts (1 hunks)
  • lib/plugins/Label_16_POSA1.test.ts (1 hunks)
  • lib/plugins/Label_16_POSA1.ts (1 hunks)
  • lib/plugins/Label_16_TOD.test.ts (1 hunks)
  • lib/plugins/Label_16_TOD.ts (1 hunks)
  • lib/plugins/official.ts (1 hunks)
🔇 Additional comments (9)
lib/plugins/official.ts (1)

11-12: LGTM!

The new exports are correctly placed in alphabetical order.

lib/plugins/Label_16_POSA1.ts (3)

7-15: LGTM!

The class declaration and qualifiers are well-defined. The plugin correctly specifies its name and the expected labels and preambles.


17-22: LGTM!

The decode method initialization follows the standard pattern, properly setting up the decode result with default values and message metadata.


46-50: LGTM!

The result finalization is correct, properly setting the decode status and level.

lib/plugins/Label_16_TOD.ts (2)

50-54: LGTM!

The result finalization is correct, properly setting the decode status and level.


7-14:

Details

❓ Verification inconclusive

Consider adding preambles to qualifiers.

The qualifiers only specify labels but not preambles. This might lead to false positives if other Label 16 messages have different preambles.


🏁 Script executed:

#!/bin/bash
# Search for other Label 16 decoders to check their preambles
ast-grep --pattern $'class Label_16_$_ extends DecoderPlugin {
  $$$
  qualifiers() {
    $$$
  }
  $$$
}'

Length of output: 107


Revisit Qualifiers Implementation in Label_16_TOD

The current implementation of the qualifiers in lib/plugins/Label_16_TOD.ts only returns a labels array without including a preamble, which may lead to potential false positives when matching messages. The automated search for similar Label 16 decoders (using the AST pattern) did not return any results, so it’s unclear whether this omission is an isolated case or part of a broader pattern in the codebase.

Please manually verify if other Label 16 decoder plugins are expected to include a preamble—and if they do, consider adding a preamble to the qualifiers in this file to ensure consistency and avoid ambiguity.

lib/plugins/Label_16_POSA1.test.ts (2)

13-21: LGTM!

The qualifiers test is thorough, checking all essential plugin properties.


60-69: LGTM!

The invalid input test case is well-defined and verifies the expected behavior.

lib/MessageDecoder.ts (1)

27-28: LGTM! Plugin registration order is logical.

The new Label 16 plugins are registered after other Label 16 plugins and before Label 1L plugins, maintaining a consistent ordering pattern.

Comment on lines +34 to +45
ResultFormatter.position(decodeResult, CoordinateUtils.decodeStringCoordinates(fields[0].substring(5))); // strip 'POSA1'
const waypoint = fields[1].trim();
const time = DateTimeUtils.convertHHMMSSToTod(fields[2]);
ResultFormatter.altitude(decodeResult, Number(fields[3])*100);
const nextWaypoint = fields[4].trim();
const nextTime = DateTimeUtils.convertHHMMSSToTod(fields[5]);
ResultFormatter.unknownArr(decodeResult, fields.slice(6), ',');
ResultFormatter.route(decodeResult, {waypoints: [
{name: waypoint, time: time, timeFormat: 'tod'},
{name: nextWaypoint, time: nextTime, timeFormat: 'tod'}
]});
decodeResult.decoded = true;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for numeric conversions.

The code assumes that numeric conversions will succeed. Consider adding error handling for:

  • Altitude conversion at line 37
  • Time conversions at lines 36 and 39
-    ResultFormatter.altitude(decodeResult, Number(fields[3])*100);
+    const altitude = Number(fields[3]);
+    if (!Number.isNaN(altitude)) {
+      ResultFormatter.altitude(decodeResult, altitude * 100);
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ResultFormatter.position(decodeResult, CoordinateUtils.decodeStringCoordinates(fields[0].substring(5))); // strip 'POSA1'
const waypoint = fields[1].trim();
const time = DateTimeUtils.convertHHMMSSToTod(fields[2]);
ResultFormatter.altitude(decodeResult, Number(fields[3])*100);
const nextWaypoint = fields[4].trim();
const nextTime = DateTimeUtils.convertHHMMSSToTod(fields[5]);
ResultFormatter.unknownArr(decodeResult, fields.slice(6), ',');
ResultFormatter.route(decodeResult, {waypoints: [
{name: waypoint, time: time, timeFormat: 'tod'},
{name: nextWaypoint, time: nextTime, timeFormat: 'tod'}
]});
decodeResult.decoded = true;
ResultFormatter.position(decodeResult, CoordinateUtils.decodeStringCoordinates(fields[0].substring(5))); // strip 'POSA1'
const waypoint = fields[1].trim();
const time = DateTimeUtils.convertHHMMSSToTod(fields[2]);
const altitude = Number(fields[3]);
if (!Number.isNaN(altitude)) {
ResultFormatter.altitude(decodeResult, altitude * 100);
}
const nextWaypoint = fields[4].trim();
const nextTime = DateTimeUtils.convertHHMMSSToTod(fields[5]);
ResultFormatter.unknownArr(decodeResult, fields.slice(6), ',');
ResultFormatter.route(decodeResult, {waypoints: [
{name: waypoint, time: time, timeFormat: 'tod'},
{name: nextWaypoint, time: nextTime, timeFormat: 'tod'}
]});
decodeResult.decoded = true;

Comment on lines +34 to +49
ResultFormatter.time_of_day(decodeResult, time);
if(fields[1] !== '') {
ResultFormatter.altitude(decodeResult, Number(fields[1]));
}
ResultFormatter.eta(decodeResult, DateTimeUtils.convertHHMMSSToTod(fields[2]));
ResultFormatter.unknown(decodeResult, fields[3]);
const temp = fields[4].split('/');
const posFields = temp[0].split(' ');
ResultFormatter.position(decodeResult, {
latitude: CoordinateUtils.getDirection(posFields[0]) * Number(posFields[1]),
longitude: CoordinateUtils.getDirection(posFields[2]) * Number(posFields[3]),
});

if(temp.length > 1) {
ResultFormatter.flightNumber(decodeResult, temp[1]);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for numeric conversions and array access.

The code makes several assumptions:

  1. Numeric conversions will succeed
  2. Array indices will exist
  3. Split operations will yield expected results

Consider adding error handling:

-    const posFields = temp[0].split(' ');
-    ResultFormatter.position(decodeResult, {
-      latitude: CoordinateUtils.getDirection(posFields[0]) * Number(posFields[1]),
-      longitude: CoordinateUtils.getDirection(posFields[2]) * Number(posFields[3]),
-    });
+    const posFields = temp[0]?.split(' ') || [];
+    if (posFields.length >= 4) {
+      const lat = Number(posFields[1]);
+      const lon = Number(posFields[3]);
+      if (!Number.isNaN(lat) && !Number.isNaN(lon)) {
+        ResultFormatter.position(decodeResult, {
+          latitude: CoordinateUtils.getDirection(posFields[0]) * lat,
+          longitude: CoordinateUtils.getDirection(posFields[2]) * lon,
+        });
+      }
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ResultFormatter.time_of_day(decodeResult, time);
if(fields[1] !== '') {
ResultFormatter.altitude(decodeResult, Number(fields[1]));
}
ResultFormatter.eta(decodeResult, DateTimeUtils.convertHHMMSSToTod(fields[2]));
ResultFormatter.unknown(decodeResult, fields[3]);
const temp = fields[4].split('/');
const posFields = temp[0].split(' ');
ResultFormatter.position(decodeResult, {
latitude: CoordinateUtils.getDirection(posFields[0]) * Number(posFields[1]),
longitude: CoordinateUtils.getDirection(posFields[2]) * Number(posFields[3]),
});
if(temp.length > 1) {
ResultFormatter.flightNumber(decodeResult, temp[1]);
}
ResultFormatter.time_of_day(decodeResult, time);
if(fields[1] !== '') {
ResultFormatter.altitude(decodeResult, Number(fields[1]));
}
ResultFormatter.eta(decodeResult, DateTimeUtils.convertHHMMSSToTod(fields[2]));
ResultFormatter.unknown(decodeResult, fields[3]);
const temp = fields[4].split('/');
const posFields = temp[0]?.split(' ') || [];
if (posFields.length >= 4) {
const lat = Number(posFields[1]);
const lon = Number(posFields[3]);
if (!Number.isNaN(lat) && !Number.isNaN(lon)) {
ResultFormatter.position(decodeResult, {
latitude: CoordinateUtils.getDirection(posFields[0]) * lat,
longitude: CoordinateUtils.getDirection(posFields[2]) * lon,
});
}
}
if(temp.length > 1) {
ResultFormatter.flightNumber(decodeResult, temp[1]);
}

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
lib/plugins/Label_16_TOD.test.ts (4)

22-41: Add assertions for remaining text format.

While the test case is comprehensive in validating the decoded fields, consider adding assertions to verify the format of the remaining text (e.g., length, numeric content).

     expect(decodeResult.formatted.items[3].value).toBe('38.364 N, 75.226 W');
     expect(decodeResult.remaining.text).toBe('  97');
+    expect(decodeResult.remaining.text.trim()).toMatch(/^\d+$/);

43-65: Add assertions for remaining text format.

Similar to variant 1, consider adding assertions to verify the format of the remaining text. Additionally, the test case effectively uses a real-world example, which is good practice.

     expect(decodeResult.formatted.items[4].value).toBe('SXS7SL');
     expect(decodeResult.remaining.text).toBe(' 51');
+    expect(decodeResult.remaining.text.trim()).toMatch(/^\d+$/);

68-84: Add assertions for remaining text format.

Similar to previous variants, consider adding assertions to verify the format of the remaining text. The test case effectively handles missing position data.

     expect(decodeResult.formatted.items[1].value).toBe('12:06:00');
     expect(decodeResult.remaining.text).toBe(' 92');
+    expect(decodeResult.remaining.text.trim()).toMatch(/^\d+$/);

86-95: Add assertion for empty formatted items.

For invalid messages, verify that no formatted items are present to ensure complete validation of the error case.

     expect(decodeResult.decoder.name).toBe('label-16-tod');
     expect(decodeResult.formatted.description).toBe('Position Report');
     expect(decodeResult.message.text).toBe(text);
+    expect(decodeResult.formatted.items.length).toBe(0);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 528993c and 4d3c0ca.

📒 Files selected for processing (2)
  • lib/plugins/Label_16_TOD.test.ts (1 hunks)
  • lib/utils/result_formatter.ts (1 hunks)
🔇 Additional comments (2)
lib/plugins/Label_16_TOD.test.ts (1)

13-20: LGTM! Test case verifies essential plugin properties.

The test case thoroughly validates the plugin's interface by checking the existence of required methods and properties.

lib/utils/result_formatter.ts (1)

77-79: LGTM! Added NaN check for altitude values.

The change prevents invalid altitude values from being processed, which is consistent with similar checks in other methods (e.g., position, temperature).

altitude no longer persisted as it was blank/NaN
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
lib/plugins/Label_4A.ts (1)

41-44: Consider refactoring altitude handling for consistency.

The current implementation has several areas for improvement:

  1. Using hardcoded positions (48, 51) is brittle and differs from the field-based approach used elsewhere
  2. Altitude handling is inconsistent across variants (compare with lines 55 and 69)

Consider refactoring to use the fields array and standardizing altitude handling across all variants:

-        const alt = text.substring(48, 51);
-        if(alt !== '') {
-            ResultFormatter.altitude(decodeResult, Number(alt) * 100);
-        }
+        const alt = fields[6]; // Adjust index based on your field structure
+        if (alt && alt.trim() !== '') {
+            ResultFormatter.altitude(decodeResult, Number(alt) * 100);
+        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 91de92f and 8f83d99.

📒 Files selected for processing (2)
  • lib/plugins/Label_4A.test.ts (2 hunks)
  • lib/plugins/Label_4A.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/plugins/Label_4A.test.ts
🔇 Additional comments (1)
lib/plugins/Label_4A.ts (1)

41-44: LGTM! Good defensive programming.

The addition of the empty string check before processing the altitude value is a good defensive programming practice that prevents potential NaN propagation.

@makrsmark makrsmark merged commit d5f68ca into airframesio:master Mar 8, 2025
4 checks passed
@makrsmark makrsmark deleted the feature/label-16 branch March 8, 2025 13:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant