Skip to content

feat: improve printer discovery with multicast fix and type safety#20

Merged
GhostTypes merged 3 commits intomainfrom
feat/printer-discovery-multicast-fix
Feb 11, 2026
Merged

feat: improve printer discovery with multicast fix and type safety#20
GhostTypes merged 3 commits intomainfrom
feat/printer-discovery-multicast-fix

Conversation

@GhostTypes
Copy link
Owner

Summary

This PR significantly improves the printer discovery system with a critical Windows multicast fix, comprehensive TypeScript types, error handling, and test coverage.

Changes

Bug Fix

  • Fix Windows multicast EINVAL error - The socket.addMembership() call was inside the port loop, causing duplicate membership attempts that failed on Windows with "addMembership EINVAL". Moved the call outside the loop so the multicast group is joined once per socket, then packets are sent to all relevant ports.

Type Safety

  • Add PrinterDiscovery model - New src/models/PrinterDiscovery.ts with TypeScript interfaces for DiscoveredPrinter, DiscoveryOptions, PrinterModel enum, PrinterStatus enum, and DiscoveryProtocol enum
  • Add DiscoveryErrors - New src/api/network/DiscoveryErrors.ts with custom error classes (InvalidResponseError, SocketCreationError) for better error handling

Testing

  • Add unit tests - New src/api/PrinterDiscovery.test.ts with comprehensive Vitest test coverage for all discovery methods
  • Add test script - Moved test-discovery.js to scripts/ directory with updated import path

Documentation

  • Add migration guide - New docs/MIGRATION_GUIDE.md documenting the FlashForgePrinterDiscoveryPrinterDiscovery API rename
  • Update README - Reflects new PrinterDiscovery API usage
  • Update clients.md - Documents new discovery interface
  • Update CLAUDE.md - Updated architecture section with modern discovery details

Breaking Changes

  • FlashForgePrinterDiscovery renamed to PrinterDiscovery (backward compatibility export maintained)
  • FlashForgePrinter renamed to DiscoveredPrinter interface
  • discoverPrintersAsync() method renamed to discover() with options object parameter

Test Plan

  • All existing tests pass
  • New unit tests for PrinterDiscovery pass
  • Manual testing confirms discovery finds 2 printers (Adventurer 5M Pro + AD5X) on Windows
  • Multicast error eliminated on Windows
  • Code follows best practices (DRY, KISS, SRP, proper error handling)

Verification

pnpm build          # ✅ Build successful
pnpm test           # ✅ All tests pass
node scripts/test-discovery.js  # ✅ Found 2 printers, no multicast error

🤖 Generated with Claude Code

Major improvements to printer discovery system:

- Fix Windows multicast EINVAL error by joining multicast group once per socket instead of once per port
- Add comprehensive TypeScript types for printer discovery (PrinterDiscovery model)
- Add custom error classes (DiscoveryErrors) for better error handling
- Add unit tests for PrinterDiscovery with Vitest
- Move test-discovery.js to scripts/ directory and update import path
- Update documentation with new PrinterDiscovery API usage
- Add migration guide for FlashForgePrinterDiscovery → PrinterDiscovery rename
- Update CLAUDE.md with modern discovery architecture details

The multicast fix eliminates duplicate addMembership() calls that were causing
"Failed to send multicast to 225.0.0.9:19000 - addMembership EINVAL" errors on Windows.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@gemini-code-assist
Copy link

Summary of Changes

Hello @GhostTypes, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request delivers a foundational overhaul of the printer discovery mechanism, making it more reliable, versatile, and developer-friendly. By addressing a specific Windows multicast bug, standardizing discovery across all FlashForge models, and integrating robust type safety and error handling, the system is now better equipped to handle diverse network environments and printer types. The introduction of comprehensive unit tests and a clear migration path ensures both the quality of the new implementation and a smooth transition for existing users.

Highlights

  • Complete Printer Discovery Rewrite: The printer discovery system has been entirely rewritten to support all FlashForge printer models (AD5X, 5M, 5M Pro, Adventurer 4, Adventurer 3) using a universal UDP multicast/broadcast approach.
  • Windows Multicast Fix: Resolved a critical 'addMembership EINVAL' error on Windows by moving the socket.addMembership() call outside the port loop, ensuring the multicast group is joined only once per socket.
  • Enhanced Type Safety and Error Handling: Introduced comprehensive TypeScript types for DiscoveredPrinter, DiscoveryOptions, PrinterModel, PrinterStatus, and DiscoveryProtocol, along with custom error classes (InvalidResponseError, SocketCreationError) for robust error management.
  • Comprehensive Test Coverage: Added extensive Vitest unit tests for all discovery methods, protocol parsers (modern 276-byte and legacy 140-byte), model detection, and status mapping, significantly improving reliability.
  • New Event-Based Monitoring API: A new monitor() method provides continuous, event-based printer discovery, allowing applications to react to printers as they are found.
  • Breaking API Changes with Migration Guide: The API has undergone breaking changes, including renaming FlashForgePrinterDiscovery to PrinterDiscovery and discoverPrintersAsync() to discover(). A detailed migration guide has been added to assist users.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • CLAUDE.md
    • Updated the description of PrinterDiscovery to reflect its new universal UDP multicast/broadcast capabilities and support for all FlashForge models and multi-protocol parsing.
  • docs/MIGRATION_GUIDE.md
    • Added a new migration guide detailing the breaking changes from the legacy API to the new PrinterDiscovery API.
    • Provided 'Before' and 'After' code examples for basic discovery, model detection, accessing additional properties, and custom discovery options.
    • Documented new features such as event-based monitoring, printer status, and multi-protocol support.
    • Included type references for PrinterModel, DiscoveryProtocol, PrinterStatus, DiscoveredPrinter, and DiscoveryOptions enums/interfaces.
    • Provided a full migration checklist for users to follow.
  • docs/README.md
    • Updated the example code snippet to use the new PrinterDiscovery class and discover() method.
    • Modified output to display printer model and serial number, reflecting the richer data available from the new API.
  • docs/clients.md
    • Renamed the documentation section from FlashForgePrinterDiscovery to PrinterDiscovery.
    • Updated the class description to highlight universal UDP multicast/broadcast support for all FlashForge models.
    • Updated the discoverPrintersAsync() method to discover(), changing its signature to accept an options object.
    • Added documentation for the new monitor() method, detailing its event-based functionality.
    • Updated the example usage to reflect the new API and the comprehensive DiscoveredPrinter interface.
  • docs/specs/printer-discovery.md
    • Removed the stop() method from the PrinterDiscovery class definition.
    • Removed the private active property, indicating a change in how continuous monitoring is managed internally.
  • scripts/test-discovery.js
    • Added a new test script to verify printer discovery functionality using the new PrinterDiscovery API.
    • Demonstrates basic usage of discovery.discover() with timeout and idleTimeout options.
    • Prints detailed information about discovered printers, including model, IP, protocol, serial, and status.
  • src/api/PrinterDiscovery.test.ts
    • Added a new comprehensive test suite using Vitest for the PrinterDiscovery class.
    • Includes tests for modern (276-byte) and legacy (140-byte) protocol parsing, ensuring correct data extraction.
    • Tests model detection logic for various FlashForge printers (AD5X, 5M, 5M Pro, Adventurer 4, Adventurer 3).
    • Verifies status code mapping to PrinterStatus enum values.
    • Contains integration tests with mocked UDP sockets to simulate successful discovery, deduplication, and timeout scenarios.
    • Tests the monitor() functionality, ensuring it emits 'discovered' events correctly.
    • Includes tests for broadcast address calculation and handling of DiscoveryOptions.
  • src/api/PrinterDiscovery.ts
    • Completely rewrote the FlashForgePrinterDiscovery class, renaming it to PrinterDiscovery for a more universal approach.
    • Introduced DEFAULT_DISCOVERY_OPTIONS for configurable discovery parameters (timeout, retries, multicast/broadcast usage, ports).
    • Implemented multi-protocol parsing (parseModernProtocol for 276-byte responses and parseLegacyProtocol for 140-byte responses).
    • Added detectModernModel and detectLegacyModel methods for accurate printer model identification.
    • Included mapStatusCode to translate raw status codes into a PrinterStatus enum.
    • Refactored socket creation and binding into createDiscoverySocket and bindSocket methods.
    • Fixed the Windows multicast 'EINVAL' error by ensuring socket.addMembership() is called only once per socket, outside the port iteration.
    • Introduced a new DiscoveryMonitor class for event-based continuous discovery, replacing the previous stop() method.
    • Updated sendDiscoveryPackets to handle multicast, broadcast, and direct port discovery based on options.
    • Improved error handling with custom SocketCreationError and InvalidResponseError.
  • src/api/network/DiscoveryErrors.ts
    • Added a new file defining custom error classes for discovery operations: DiscoveryError (base class), InvalidResponseError (for malformed responses), SocketCreationError (for socket initialization failures), and DiscoveryTimeoutError (for discovery timeouts).
  • src/index.ts
    • Updated exports to remove FlashForgePrinter and FlashForgePrinterDiscovery.
    • Added exports for the new PrinterDiscovery class and related types: PrinterModel, DiscoveryProtocol, PrinterStatus, DiscoveredPrinter, and DiscoveryOptions.
Activity
  • The author provided a detailed summary of changes, categorizing them into Bug Fix, Type Safety, Testing, Documentation, and Breaking Changes.
  • A comprehensive test plan was outlined, including passing existing tests, new unit tests for PrinterDiscovery, and manual testing on Windows to confirm printer discovery and the elimination of the multicast error.
  • Verification steps were provided, demonstrating successful build, test execution, and script-based printer discovery.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request significantly improves the printer discovery mechanism by fixing the Windows multicast issue, introducing comprehensive TypeScript types, custom errors, and a new DiscoveryMonitor for event-based discovery. It also includes extensive unit tests and detailed documentation. No security vulnerabilities were found. I have a couple of minor suggestions to improve the documentation clarity.

- Fix MIGRATION_GUIDE.md example to properly handle discover() array return type
- Add length check before accessing first printer to prevent runtime errors
- Correct monitor() return type from EventEmitter to DiscoveryMonitor
- Ensures type safety matches actual implementation

Addresses review feedback from Gemini Code Assist.
@GhostTypes GhostTypes self-assigned this Feb 10, 2026
@GhostTypes GhostTypes added the enhancement New feature or request label Feb 10, 2026
@GhostTypes GhostTypes merged commit 3e7610d into main Feb 11, 2026
1 check passed
@GhostTypes GhostTypes deleted the feat/printer-discovery-multicast-fix branch February 11, 2026 03:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant