Skip to content

Conversation

@MarioIvancik
Copy link
Member

@MarioIvancik MarioIvancik commented Aug 14, 2024

Fixes:
https://youtrack.bringauto.com/issue/BAF-874/Virtual-Vehicle-cannot-parse-command

Depends on:
bringauto/mission-module#19

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced JSON parsing for command data in the fleet protocol, improving data handling.
    • Enhanced error reporting during initialization with clearer feedback on exceptions.
    • Updated the structure of scenario JSON files for better argument handling.
  • Bug Fixes

    • Removed outdated dependencies on the Protobuf library, streamlining the project.
  • Documentation

    • Updated README to clarify the dual role of the system and expanded functionality details.
    • Revised command-line argument descriptions for improved clarity, including updates to the prerequisites.
  • Chores

    • Cleaned up project configuration by removing unnecessary submodule references.

@MarioIvancik MarioIvancik self-assigned this Aug 14, 2024
@coderabbitai
Copy link

coderabbitai bot commented Aug 14, 2024

Walkthrough

The changes primarily involve the removal of the Protobuf library and associated dependencies from the project, simplifying the build configuration. This includes updates to various CMake and source files, where references to Protobuf are eliminated. Additionally, the submodule declaration for lib/mission-module has been removed from .gitmodules, indicating a shift in project dependencies. The overall effect is a transition towards using JSON for command processing in certain components, reflecting a potential refocus of the project's communication strategy.

Changes

File Change Summary
.gitmodules Removed submodule declaration for lib/mission-module.
CMakeLists.txt Removed Protobuf-related configurations and updated library dependencies.
README.md Updated protobuf version requirement from = 3.17.3 to >= 3.17.3.
cmake/Dependencies.cmake Removed inclusion of protobuf library as a dependency.
source/bringauto/communication/fleet_protocol/FleetProtocol.cpp Shifted from Protobuf to nlohmann::json for command processing.
source/bringauto/settings/SettingsParser.cpp Updated command argument options related to fleet communication from "protobuf" to "INTERNAL-PROTOCOL".
test/smurf/duplicitStopScenario/scenarios.json Changed structure of "arguments" field to array format and renamed "timeout" to "timeout_s".
test/smurf/etnaDefaultScenario/scenarios.json Changed structure of "arguments" field to array format and renamed "timeout" to "timeout_s".
test/smurf/routeChangeScenario/scenarios.json Changed structure of "arguments" field to array format and renamed "timeout" to "timeout_s".
include/bringauto/communication/Status.hpp Updated variable initialization syntax for nextStop_.
include/bringauto/osm/Route.hpp Updated member variable initializations in Station struct.
main.cpp Added include directive for <iostream> and enhanced error reporting.
test/CMakeLists.txt Removed protobuff_lib from linked libraries for test target.

Possibly related PRs

  • Command handling logic from mission module docs #14: The changes in CMakeLists.txt regarding the removal of the FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) line and the associated library setup are directly related to the main PR's removal of Protobuf dependencies.
  • BAF-948 update dependencies, fix gps vehicle #15: The updates in the .gitmodules file and CMakeLists.txt regarding dependency management align with the main PR's focus on simplifying project dependencies by removing the lib/mission-module submodule and the protobuff_lib.

Suggested reviewers

  • Melky-Phoe

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e013f09 and d4be853.

📒 Files selected for processing (1)
  • source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/bringauto/communication/fleet_protocol/FleetProtocol.cpp

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 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: 1

Outside diff range, codebase verification and nitpick comments (3)
CMakeLists.txt (1)

6-6: Document the version update.

The project version has been updated to 3.2.0. Ensure this change is documented in the project's changelog or release notes.

source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (2)

136-142: Ensure comprehensive JSON error handling.

The current JSON parsing implementation catches json::parse_error, which is good. However, consider logging the exception message to provide more context on the failure.

-  } catch (json::parse_error &) {
-    logging::Logger::logWarning("Cannot parse car command!");
+  } catch (json::parse_error &e) {
+    logging::Logger::logWarning("Cannot parse car command! Error: {}", e.what());

149-162: Improve JSON field access error handling.

The current implementation catches json::exception for field access errors. Consider logging the specific exception message to aid debugging.

-  } catch (json::exception &) {
-    logging::Logger::logWarning("Cannot parse car command!");
+  } catch (json::exception &e) {
+    logging::Logger::logWarning("Cannot parse car command! Error: {}", e.what());
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between eecaf64 and c6f1965.

Files selected for processing (9)
  • .gitmodules (1 hunks)
  • CMakeLists.txt (3 hunks)
  • README.md (1 hunks)
  • cmake/Dependencies.cmake (1 hunks)
  • include/bringauto/communication/fleet_protocol/FleetProtocol.hpp (1 hunks)
  • source/bringauto/common_utils/EnumUtils.cpp (1 hunks)
  • source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (3 hunks)
  • source/bringauto/settings/SettingsParser.cpp (1 hunks)
  • test/CMakeLists.txt (1 hunks)
Files skipped from review due to trivial changes (4)
  • .gitmodules
  • README.md
  • include/bringauto/communication/fleet_protocol/FleetProtocol.hpp
  • test/CMakeLists.txt
Additional comments not posted (5)
cmake/Dependencies.cmake (1)

Line range hint 1-24:
Verify removal of all protobuf dependencies.

The protobuf library has been removed from the dependencies. Ensure that all parts of the codebase that previously relied on protobuf are updated to use JSON or are otherwise handled.

Verification successful

Protobuf dependencies appear to be removed. The search for protobuf references in the entire codebase did not return any results, indicating that all dependencies on protobuf have likely been removed. If you have specific concerns or need further verification, consider manually checking or running additional checks.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that no parts of the codebase still rely on `protobuf`.

# Test: Search for any remaining references to `protobuf`. Expect: No occurrences.
rg --type cpp 'protobuf'

Length of output: 24


Script:

#!/bin/bash
# Description: Comprehensive search for any remaining references to `protobuf` in the codebase.

# Search for `protobuf` in all file types to ensure it's completely removed.
rg 'protobuf'

Length of output: 13

source/bringauto/common_utils/EnumUtils.cpp (1)

10-18: Verify usage of the new string-based valueToEnum function.

Ensure that all calls to EnumUtils::valueToEnum with a string argument are updated and validated properly.

CMakeLists.txt (1)

6-6: Verify the build process after protobuf removal.

The protobuf related configurations have been removed. Ensure that the build process is unaffected and the project compiles successfully.

source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (1)

174-186: Confirm the completeness of JSON status logging.

The function logs the generated JSON status string. Ensure that all relevant status fields are included in the JSON object to provide a complete status report.

Verification successful

Confirm the completeness of JSON status logging.

The generateCarStatusString function appears to include all relevant fields for the car's status in the JSON object. The fields logged are:

  • Telemetry: altitude, latitude, longitude, speed, and fuel.
  • Next Stop: name, altitude, latitude, and longitude.
  • State.

These fields seem comprehensive for generating a car status report. Ensure that these fields align with the expected data structure and requirements.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all relevant status fields are included in the JSON object.

# Test: Search for the `generateCarStatusString` function and ensure all fields are logged.
ast-grep --lang cpp --pattern $'std::string FleetProtocol::generateCarStatusString(const Status &status) {
  $$$
  statusJson[$_] = $_;
  $$$
}'

Length of output: 145


Script:

#!/bin/bash
# Description: Extract the JSON field assignments within the `generateCarStatusString` function to verify completeness.

# Use `rg` to search for the function definition and capture the relevant lines.
rg -A 20 'std::string FleetProtocol::generateCarStatusString' --glob '*.cpp'

Length of output: 2378

source/bringauto/settings/SettingsParser.cpp (1)

91-97: Update command-line options for clarity.

The fleet provider option has been updated to "INTERNAL-PROTOCOL." Ensure that this reflects the intended protocol and that users are informed of the change through documentation or release notes.

Verification successful

Documentation reflects updated fleet provider option.

The README.md file includes information about the fleet-provider option and mentions internal-protocol, indicating that the documentation has been updated to reflect the changes in the codebase. No further action is needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the documentation reflects the updated fleet provider option.

# Test: Search for occurrences of "fleet-provider" in documentation files.
rg --type markdown --type rst --type txt 'fleet-provider'

Length of output: 454

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

Outside diff range, codebase verification and nitpick comments (1)
source/bringauto/settings/StateSmurfDefinition.cpp (1)

Implications of Removing changeToState Function

The changeToState function is actively used in the codebase, specifically in SimVehicle.cpp. Its removal will affect the application's ability to manage state transitions, as it is a critical part of the logic for transitioning between autonomy states.

  • File and Location of Usage:
    • source/bringauto/virtual_vehicle/vehicle_provider/SimVehicle.cpp

Please ensure that any changes to this function are carefully considered to maintain the application's state management capabilities.

Analysis chain

Line range hint 28-48: Consider the implications of removing changeToState.

The removal of the changeToState function indicates a change in how state transitions are managed. Ensure that this does not affect the application's ability to transition between states based on autonomy actions.

Run the following script to verify the usage of the changeToState function in the codebase:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `changeToState` function.

# Test: Search for the function usage. Expect: No occurrences.
rg --type cpp --type h $'changeToState'

Length of output: 562

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c6f1965 and 0e1f2e6.

Files ignored due to path filters (3)
  • test/smurf/duplicitStopScenario/etalons/fewNodes.log is excluded by !**/*.log
  • test/smurf/etnaDefaultScenario/etalons/default.log is excluded by !**/*.log
  • test/smurf/routeChangeScenario/etalons/delayedChange.log is excluded by !**/*.log
Files selected for processing (10)
  • README.md (1 hunks)
  • include/bringauto/settings/StateSmurfDefinition.hpp (1 hunks)
  • source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (4 hunks)
  • source/bringauto/communication/terminal/TerminalOutput.cpp (1 hunks)
  • source/bringauto/settings/SettingsParser.cpp (2 hunks)
  • source/bringauto/settings/StateSmurfDefinition.cpp (2 hunks)
  • source/bringauto/virtual_vehicle/vehicle_provider/SimVehicle.cpp (2 hunks)
  • test/smurf/duplicitStopScenario/scenarios.json (1 hunks)
  • test/smurf/etnaDefaultScenario/scenarios.json (1 hunks)
  • test/smurf/routeChangeScenario/scenarios.json (1 hunks)
Files skipped from review due to trivial changes (2)
  • README.md
  • source/bringauto/communication/terminal/TerminalOutput.cpp
Additional comments not posted (16)
test/smurf/etnaDefaultScenario/scenarios.json (2)

9-9: Clarify the unit in timeout_s.

Renaming timeout to timeout_s is a good practice as it clarifies the unit of measurement (seconds). Ensure that this change is consistently applied throughout the codebase.


10-15: Review the arguments array format.

The change from an object to an array format for arguments is beneficial for standardizing command-line argument parsing. Ensure that any code parsing these arguments is updated to handle the new format.

test/smurf/routeChangeScenario/scenarios.json (2)

9-9: Clarify the unit in timeout_s.

Renaming timeout to timeout_s ensures clarity regarding the unit of measurement. Verify consistent application across the codebase.


10-15: Review the arguments array format.

Switching arguments to an array format aligns with best practices for command-line argument parsing. Ensure that all related parsing logic is updated accordingly.

test/smurf/duplicitStopScenario/scenarios.json (2)

9-9: Clarify the unit in timeout_s.

The change from timeout to timeout_s is consistent with the goal of clear unit representation. Ensure uniformity across the project.


10-16: Review the arguments array format.

The conversion of arguments to an array format is a positive change for command-line argument handling. Ensure that all relevant parsing logic is updated to accommodate this format.

include/bringauto/settings/StateSmurfDefinition.hpp (1)

Line range hint 9-13: Verify the impact of removing state constants.

The removal of state constants such as statusSentState, commandReceivedState, startReceivedState, stopReceivedState, and noActionReceivedState suggests a shift in state management logic. Ensure that these changes do not break existing functionality or state transitions elsewhere in the codebase.

Run the following script to verify the usage of these removed state constants in the codebase:

source/bringauto/settings/StateSmurfDefinition.cpp (1)

17-26: Review the new state transitions.

The state transitions have been simplified. Ensure that the new transitions between connected, drive, idle, and inStop states meet the application's requirements and do not introduce any unintended behavior.

Run the following script to verify the usage of the createStateDiagram function in the codebase:

Verification successful

State Transitions Verification Completed

The new state transitions in StateSmurfDefinition appear to be properly integrated into the application's context. The createStateDiagram function is used within a conditional compilation block to set up state transitions for a vehicle system, and no unintended behavior is evident from the context provided. Ensure that these transitions align with the application's requirements and are tested under the STATE_SMURF configuration.

  • File: main.cpp
  • Context: Conditional compilation with STATE_SMURF feature toggle.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `createStateDiagram` function.

# Test: Search for the function usage. Expect: Occurrences that align with the new state transitions.
rg --type cpp --type h $'createStateDiagram'

Length of output: 387


Script:

#!/bin/bash
# Extract context around the usage of createStateDiagram in main.cpp
rg --type cpp -A 10 -B 10 'createStateDiagram' main.cpp

Length of output: 898

source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (4)

130-136: Review JSON parsing error handling.

The JSON parsing includes error handling with logging. Ensure that the logging provides sufficient information for debugging and that the application can recover gracefully from parsing errors.


168-180: Review JSON status generation.

The generation of car status as a JSON object is a significant change. Ensure that the JSON structure accurately represents the car's status and that all necessary fields are included.


7-12: Ensure JSON library compatibility.

The inclusion of the nlohmann::json library is a key change. Ensure that the library is compatible with the project's requirements and that all necessary dependencies are included in the build configuration.

Run the following script to verify the inclusion of the JSON library in the build configuration:

Verification successful

JSON Library is Properly Included in Build Configuration

The nlohmann_json library is correctly included in the build configuration files. It is specified in CMakeLists.txt with the FIND_PACKAGE command and linked appropriately in the project. No further action is needed regarding this concern.

  • CMakeLists.txt: FIND_PACKAGE(nlohmann_json 3.2.0 REQUIRED)
  • CMakeLists.txt: nlohmann_json::nlohmann_json
  • test/CMakeLists.txt: nlohmann_json::nlohmann_json
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the inclusion of the JSON library in the build configuration.

# Test: Search for the JSON library in the build configuration files. Expect: Proper inclusion.
rg --type cmake $'nlohmann::json'

Length of output: 32


Script:

#!/bin/bash
# Description: Search for alternative references to the JSON library in CMake files.

# Look for common CMake commands that might include the JSON library.
rg --type cmake 'nlohmann_json|nlohmann|find_package|target_link_libraries' -A 2

Length of output: 2583


143-156: Verify mission data extraction from JSON.

The extraction of mission data from JSON fields is a critical operation. Ensure that the JSON structure matches the expected format and that all necessary fields are present.

Run the following script to verify the usage of the processBufferData function in the codebase:

Verification successful

Mission data extraction from JSON is consistent with the expected structure.

The code correctly accesses the JSON fields "stops", "name", "position", "latitude", and "longitude" as expected. No issues were found with the extraction logic.

  • The JSON structure used in the code snippet aligns with the expected format.
  • All necessary fields are present and accessed correctly.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `processBufferData` function.

# Test: Search for the function usage. Expect: Occurrences that align with the new JSON structure.
rg --type cpp --type h $'processBufferData'

Length of output: 388


Script:

#!/bin/bash
# Search for any JSON schema or documentation that defines the expected structure of the JSON object.
rg --type cpp --type h --type md --type json 'stops|name|position|latitude|longitude'

Length of output: 25001

source/bringauto/virtual_vehicle/vehicle_provider/SimVehicle.cpp (2)

Line range hint 114-197: Separation of concerns in evaluateCommand.

The removal of StateSmurfDefinition::changeToState enhances the separation of concerns by focusing this method solely on command evaluation.


225-227: Conditional compilation for state transitions.

The use of conditional compilation for StateSmurfDefinition::changeToState maintains flexibility in state management.

source/bringauto/settings/SettingsParser.cpp (2)

91-97: Update to fleet provider settings.

The changes from "protobuf" to "INTERNAL-PROTOCOL" and renaming to "JSON fleet provider" align with the transition to JSON.


351-351: Typo correction in getFormattedSettings.

The correction from "fleet-providerr" to "fleet-provider" improves clarity and accuracy.

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: 6

🧹 Outside diff range and nitpick comments (5)
main.cpp (1)

Line range hint 63-66: LGTM: Improved error handling during initialization

The addition of the try-catch block for initialization improves error handling and aligns with the enhanced error reporting mentioned in the summary. Using std::cerr for error output is a good practice.

Consider adding more context to the error message:

- std::cerr << "[ERROR] Error occurred during initialization: " << e.what() << std::endl;
+ std::cerr << "[ERROR] Error occurred during Virtual Vehicle initialization: " << e.what() << std::endl;

This change provides more specific information about where the error occurred.

source/bringauto/settings/SettingsParser.cpp (1)

97-103: LGTM! Consider adding a comment for clarity.

The changes from "protobuf" to "INTERNAL-PROTOCOL" and the recategorization of options under "JSON fleet provider" align well with the PR objective of replacing protobuf with JSON.

Consider adding a brief comment explaining the transition from protobuf to JSON for future maintainers:

// Note: INTERNAL-PROTOCOL refers to the JSON-based communication protocol that replaced the previous protobuf implementation
source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (3)

12-12: Consider using nlohmann::json instead of ordered_json

Unless the order of JSON object keys is crucial for your application, you might consider using nlohmann::json instead of nlohmann::ordered_json for potential performance benefits.


146-152: Simplify loop using range-based for loop

You can simplify the loop by using a range-based for loop, which improves readability.

Apply this diff to refactor the loop:

-        for(int i = 0; i < commandJson.at("stops").size(); i++) {
-            osm::Route::Station station;
-            station.name = commandJson.at("stops").at(i).at("name");
-            station.latitude = commandJson.at("stops").at(i).at("position").at("latitude");
-            station.longitude = commandJson.at("stops").at(i).at("position").at("longitude");
-            missions.push_back(station);
+        for (const auto& stopJson : commandJson["stops"]) {
+            osm::Route::Station station;
+            station.name = stopJson.at("name");
+            station.latitude = stopJson.at("position").at("latitude");
+            station.longitude = stopJson.at("position").at("longitude");
+            missions.push_back(station);
         }

181-181: Avoid logging potentially large JSON strings

Logging statusJson.dump() may output large strings and impact performance or clutter logs. Consider logging a summary or specific fields instead.

Apply this diff to modify the log statement:

-    settings::Logger::logInfo("Generating car status: {}", statusJson.dump());
+    settings::Logger::logInfo("Generated car status with state: {}", statusJson["state"]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0e1f2e6 and a865137.

📒 Files selected for processing (7)
  • CMakeLists.txt (0 hunks)
  • README.md (0 hunks)
  • cmake/Dependencies.cmake (0 hunks)
  • main.cpp (1 hunks)
  • source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (3 hunks)
  • source/bringauto/settings/SettingsParser.cpp (1 hunks)
  • test/CMakeLists.txt (0 hunks)
💤 Files with no reviewable changes (4)
  • CMakeLists.txt
  • README.md
  • cmake/Dependencies.cmake
  • test/CMakeLists.txt
🧰 Additional context used
🔇 Additional comments (5)
main.cpp (1)

15-15: LGTM: Addition of header

The inclusion of is appropriate for the new error handling mechanism using std::cerr. This change aligns with the enhanced error reporting mentioned in the summary.

source/bringauto/settings/SettingsParser.cpp (3)

Line range hint 1-424: Summary of changes and recommendations

The changes in this file successfully update the command-line options and their descriptions to reflect the transition from protobuf to JSON, which aligns with the PR objective. However, there are a few areas that require attention:

  1. Consider adding a comment explaining the transition from protobuf to JSON for clarity.
  2. Verify if any updates are needed in the areCmdArgumentsCorrect method to ensure it correctly validates all command-line arguments after the transition.
  3. Review the implementation of fillFleetSettings and fillInternalProtocolSettings to confirm they properly handle the new JSON-based fleet provider settings.

These verifications will ensure that the SettingsParser class fully supports the new JSON-based approach and maintains consistency throughout the codebase.


Line range hint 321-346: Verify implementation of fillFleetSettings and fillInternalProtocolSettings

While no changes are visible in the provided diff for these methods, it's crucial to ensure they correctly handle the new JSON-based fleet provider settings.

Please review the implementation of fillFleetSettings and fillInternalProtocolSettings to confirm they properly handle the transition from protobuf to JSON. Specifically, check if:

  1. The FLEET_PROVIDER enum values are up-to-date.
  2. The INTERNAL_PROTOCOL_SETTINGS are correctly parsed and set.
#!/bin/bash
# Description: Verify the implementation of fillFleetSettings and fillInternalProtocolSettings

# Test: Check the FleetProvider enum definition
rg --type cpp 'enum class FleetProvider'

# Test: Examine the fillFleetSettings and fillInternalProtocolSettings methods
rg --type cpp -A 20 'void SettingsParser::fillFleetSettings'
rg --type cpp -A 20 'void SettingsParser::fillInternalProtocolSettings'

Line range hint 107-160: Verify if updates are needed in areCmdArgumentsCorrect

While no changes were made to this method, it's important to ensure that it still correctly validates all command-line arguments after the transition from protobuf to JSON.

Please review if any updates are needed in the areCmdArgumentsCorrect method, particularly in the allParameters vector, to reflect any changes in the available command-line options.

source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (1)

7-7: Including the JSON header file

The inclusion of <nlohmann/json.hpp> is necessary for JSON parsing functionality.

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: 1

🧹 Outside diff range and nitpick comments (5)
include/bringauto/osm/Route.hpp (1)

28-30: Approve changes with suggestions for improvement

The initialization of Station struct members is a good practice that prevents undefined behavior. However, consider the following suggestions:

  1. For latitude and longitude, consider using named constants or a special value to indicate an uninitialized state, as 0.0 might be a valid coordinate in some contexts.
  2. Add validation in the constructor or setter methods to ensure latitude is between -90 and 90, and longitude is between -180 and 180.
  3. Consider using a more descriptive default value for name, such as "Unnamed Station", if appropriate for your use case.

Here's a potential improvement:

struct Station {
    static constexpr double INVALID_COORDINATE = std::numeric_limits<double>::quiet_NaN();
    
    std::string name {"Unnamed Station"};
    double latitude { INVALID_COORDINATE };
    double longitude { INVALID_COORDINATE };

    void setCoordinates(double lat, double lon) {
        if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
            throw std::invalid_argument("Invalid coordinates");
        }
        latitude = lat;
        longitude = lon;
    }
};

This approach uses NaN as an invalid state and adds validation when setting coordinates.

CMakeLists.txt (1)

6-6: Version update looks good, consider updating documentation.

The version bump from 3.2.0 to 3.3.0 is appropriate for the changes described in the PR objectives. This minor version increase correctly reflects the transition from Protobuf to JSON, which is a significant change but doesn't break backwards compatibility.

Don't forget to update any relevant documentation, changelogs, or release notes to reflect this version change and the switch from Protobuf to JSON.

source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (3)

12-12: Consider using nlohmann::json instead of nlohmann::ordered_json

If the insertion order of the JSON elements is not required, you can use nlohmann::json instead of nlohmann::ordered_json for better performance.


175-175: Add a comment to explain the hardcoded fuel value

Even though the hardcoded fuel value is used for testing purposes, consider adding a comment to clarify its intent for future maintainers.

Apply this diff to add a comment:

  statusJson["telemetry"]["speed"] = status.getSpeed();
+ // Hardcoded fuel value for testing purposes
  statusJson["telemetry"]["fuel"] = 0.42;

176-179: Document the behavior of status.getNextStop()

Since status.getNextStop() always returns an object with default-initialized members, adding documentation or a comment can inform future developers that it's safe to access its members without null checks.

Would you like assistance in adding appropriate documentation or comments to clarify this behavior?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a865137 and e013f09.

📒 Files selected for processing (4)
  • CMakeLists.txt (1 hunks)
  • include/bringauto/communication/Status.hpp (1 hunks)
  • include/bringauto/osm/Route.hpp (1 hunks)
  • source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • include/bringauto/communication/Status.hpp
🧰 Additional context used
📓 Learnings (1)
source/bringauto/communication/fleet_protocol/FleetProtocol.cpp (6)
Learnt from: MarioIvancik
PR: bringauto/virtual-vehicle#11
File: source/bringauto/communication/fleet_protocol/FleetProtocol.cpp:171-179
Timestamp: 2024-10-17T07:39:59.450Z
Learning: In the virtual vehicle, there is no telemetry for fuel, and the value is used purely for testing purposes.
Learnt from: MarioIvancik
PR: bringauto/virtual-vehicle#11
File: source/bringauto/communication/fleet_protocol/FleetProtocol.cpp:177-177
Timestamp: 2024-10-17T08:35:13.267Z
Learning: In the C++ file `source/bringauto/communication/fleet_protocol/FleetProtocol.cpp`, the method `status.getNextStop()` always returns an object with default-initialized members, so accessing its members without null checks is safe.
Learnt from: MarioIvancik
PR: bringauto/virtual-vehicle#11
File: source/bringauto/communication/fleet_protocol/FleetProtocol.cpp:133-133
Timestamp: 2024-10-17T08:03:08.175Z
Learning: In the `FleetProtocol::processBufferData` method in `FleetProtocol.cpp`, null `bufferData.data` is acceptable because `json::parse` handles it appropriately, so an explicit null check is unnecessary.
Learnt from: MarioIvancik
PR: bringauto/virtual-vehicle#11
File: source/bringauto/communication/fleet_protocol/FleetProtocol.cpp:146-156
Timestamp: 2024-10-17T08:16:09.783Z
Learning: In the `FleetProtocol::processBufferData` method in `FleetProtocol.cpp`, it's acceptable to use `at()` for accessing JSON fields without prior checks, as commands are validated before being sent to the virtual vehicle, and `at()` throws an exception if a key is missing.
Learnt from: MarioIvancik
PR: bringauto/virtual-vehicle#11
File: source/bringauto/communication/fleet_protocol/FleetProtocol.cpp:155-155
Timestamp: 2024-10-17T07:23:23.169Z
Learning: Commands are validated before being sent to the virtual vehicle.
Learnt from: MarioIvancik
PR: bringauto/virtual-vehicle#11
File: source/bringauto/communication/fleet_protocol/FleetProtocol.cpp:155-155
Timestamp: 2024-10-17T07:23:23.169Z
Learning: The `valueToEnum` function sets the action to "invalid" if the received string is not recognized.
🔇 Additional comments (2)
include/bringauto/osm/Route.hpp (1)

28-30: Verify JSON serialization/deserialization for Station struct

Given that this PR is part of replacing protobuf with JSON, it's important to ensure that the Station struct can be properly serialized to and deserialized from JSON format.

Please confirm that:

  1. There is JSON serialization/deserialization logic implemented for the Station struct.
  2. The default values (empty string for name, 0.0 for coordinates) are handled appropriately in the JSON conversion process.
  3. Any JSON parsing code correctly handles missing fields by using these default values.

Consider running the following script to check for JSON-related code:

This will help ensure that the changes to the Station struct are properly integrated with the new JSON-based system.

CMakeLists.txt (1)

Line range hint 1-143: Verify Protobuf removal and its impact on CMakeLists.txt

The PR objectives mention replacing Protobuf with JSON, but the visible changes in this file don't reflect any Protobuf-related removals. To ensure consistency and completeness of the changes:

  1. Confirm that all Protobuf-related configurations have been removed from this file if they existed previously.
  2. Verify that any dependencies or libraries related to Protobuf (e.g., protobuff_lib) have been removed from the TARGET_LINK_LIBRARIES section.
  3. Check if any Protobuf-related FIND_PACKAGE commands have been removed.

To help verify these changes, you can run the following script:

This script will help identify any remaining Protobuf references, show any uncommitted changes, and display recent commit history for this file.

✅ Verification successful

Protobuf removal in CMakeLists.txt verified successfully. No Protobuf-related configurations or dependencies remain.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining Protobuf-related configurations in CMakeLists.txt

# Test: Search for Protobuf-related keywords
echo "Searching for Protobuf-related keywords in CMakeLists.txt:"
rg -i 'protobuf|protobuff' CMakeLists.txt

# Test: Check if there are any uncommitted changes in CMakeLists.txt
echo "Checking for uncommitted changes in CMakeLists.txt:"
git diff -- CMakeLists.txt

# Test: Show the git history for CMakeLists.txt to see recent changes
echo "Recent changes to CMakeLists.txt:"
git log -n 5 --pretty=format:"%h - %s" -- CMakeLists.txt

Length of output: 744

@sonarqubecloud
Copy link

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.

2 participants