diff --git a/CHANGELOG.md b/CHANGELOG.md index e6cb5e142..65921562a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,24 @@ All notable changes to Bambuddy will be documented in this file. - Bulk edit: printer assignment, print options, queue options - Bulk cancel selected items - Tri-state toggles: unchanged / on / off for each setting +- **Model-Based Queue Assignment** - Queue prints to "any printer of matching model" for load balancing (Issue #162): + - Extract printer model from sliced 3MF files (e.g., "X1C", "P1S") + - Display sliced-for model in archive view + - New queue mode: assign to model instead of specific printer + - Scheduler auto-assigns to first idle printer of matching model + - Filament validation: only assign to printers with required filament types loaded + - Waiting reason display: shows why jobs are waiting (e.g., "Waiting for filament: Printer1 (needs PLA)") + - "Waiting" status badge (purple) distinguishes from regular "Pending" + - Compatibility warnings when file/printer model mismatch +- **Queue Notifications** - Get notified about print queue events: + - Job Added: When a job is added to the queue + - Job Assigned: When a model-based job is assigned to a printer + - Job Started: When a queue job starts printing + - Job Waiting: When a job is waiting for filament (enabled by default) + - Job Skipped: When a job is skipped due to previous failure (enabled by default) + - Job Failed: When a job fails to start (enabled by default) + - Queue Complete: When all queued jobs finish + - New "Print Queue" section in notification provider settings ### Fixes - **Multi-Plate Thumbnail in Queue** - Fixed queue items showing wrong thumbnail for multi-plate files (Issue #166): diff --git a/README.md b/README.md index 999972dbb..18b027125 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,8 @@ ### ⏰ Scheduling & Automation - Print queue with drag-and-drop - Multi-printer selection (send to multiple printers at once) +- Model-based queue assignment (send to "any X1C" for load balancing) +- Filament validation (only assign to printers with required filaments) - Per-printer AMS mapping (individual slot configuration for print farms) - Scheduled prints (date/time) - Queue Only mode (stage without auto-start) @@ -116,6 +118,7 @@ - Print finish photo URL in notifications - HMS error alerts (AMS, nozzle, etc.) - Build plate detection alerts +- Queue events (waiting, skipped, failed) ### 🔧 Integrations - [Spoolman](https://github.com/Donkie/Spoolman) filament sync @@ -506,10 +509,6 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. --- -If you like Bambuddy and want to support it, you can buy Martin a coffee. - ---- - ## 📄 License MIT License — see [LICENSE](LICENSE) for details. @@ -524,6 +523,10 @@ MIT License — see [LICENSE](LICENSE) for details. --- +If you like Bambuddy and want to support it, you can buy Martin a coffee. + +--- +
Made with ❤️ for the 3D printing community
diff --git a/backend/app/api/routes/archives.py b/backend/app/api/routes/archives.py
index 8aff35dcb..85241c422 100644
--- a/backend/app/api/routes/archives.py
+++ b/backend/app/api/routes/archives.py
@@ -78,6 +78,7 @@ def archive_to_response(
"nozzle_diameter": archive.nozzle_diameter,
"bed_temperature": archive.bed_temperature,
"nozzle_temperature": archive.nozzle_temperature,
+ "sliced_for_model": archive.sliced_for_model,
"status": archive.status,
"started_at": archive.started_at,
"completed_at": archive.completed_at,
diff --git a/backend/app/api/routes/notification_templates.py b/backend/app/api/routes/notification_templates.py
index ea5d20819..b47004072 100644
--- a/backend/app/api/routes/notification_templates.py
+++ b/backend/app/api/routes/notification_templates.py
@@ -32,6 +32,14 @@ EVENT_NAMES = {
"filament_low": "Filament Low",
"maintenance_due": "Maintenance Due",
"test": "Test Notification",
+ # Queue notifications
+ "queue_job_added": "Queue Job Added",
+ "queue_job_assigned": "Queue Job Assigned",
+ "queue_job_started": "Queue Job Started",
+ "queue_job_waiting": "Queue Job Waiting",
+ "queue_job_skipped": "Queue Job Skipped",
+ "queue_job_failed": "Queue Job Failed",
+ "queue_completed": "Queue Completed",
}
diff --git a/backend/app/api/routes/notifications.py b/backend/app/api/routes/notifications.py
index a6c925719..f94ce1431 100644
--- a/backend/app/api/routes/notifications.py
+++ b/backend/app/api/routes/notifications.py
@@ -53,6 +53,14 @@ def _provider_to_dict(provider: NotificationProvider) -> dict:
"on_ams_ht_temperature_high": provider.on_ams_ht_temperature_high,
# Build plate detection
"on_plate_not_empty": provider.on_plate_not_empty,
+ # Print queue events
+ "on_queue_job_added": provider.on_queue_job_added,
+ "on_queue_job_assigned": provider.on_queue_job_assigned,
+ "on_queue_job_started": provider.on_queue_job_started,
+ "on_queue_job_waiting": provider.on_queue_job_waiting,
+ "on_queue_job_skipped": provider.on_queue_job_skipped,
+ "on_queue_job_failed": provider.on_queue_job_failed,
+ "on_queue_completed": provider.on_queue_completed,
# Quiet hours
"quiet_hours_enabled": provider.quiet_hours_enabled,
"quiet_hours_start": provider.quiet_hours_start,
diff --git a/backend/app/api/routes/print_queue.py b/backend/app/api/routes/print_queue.py
index a8ed36a0f..4e1ad7b65 100644
--- a/backend/app/api/routes/print_queue.py
+++ b/backend/app/api/routes/print_queue.py
@@ -2,13 +2,17 @@
import json
import logging
+import xml.etree.ElementTree as ET
+import zipfile
from datetime import datetime
+from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
+from backend.app.core.config import settings
from backend.app.core.database import get_db
from backend.app.models.archive import PrintArchive
from backend.app.models.library import LibraryFile
@@ -22,12 +26,75 @@ from backend.app.schemas.print_queue import (
PrintQueueItemUpdate,
PrintQueueReorder,
)
+from backend.app.services.notification_service import notification_service
+from backend.app.utils.printer_models import normalize_printer_model, normalize_printer_model_id
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/queue", tags=["queue"])
+def _extract_filament_types_from_3mf(file_path: Path, plate_id: int | None = None) -> list[str]:
+ """Extract unique filament types from a 3MF file.
+
+ Args:
+ file_path: Path to the 3MF file
+ plate_id: Optional plate index to filter for (for multi-plate files)
+
+ Returns:
+ List of unique filament types (e.g., ["PLA", "PETG"])
+ """
+ types: set[str] = set()
+
+ try:
+ with zipfile.ZipFile(file_path, "r") as zf:
+ if "Metadata/slice_info.config" not in zf.namelist():
+ return []
+
+ content = zf.read("Metadata/slice_info.config").decode()
+ root = ET.fromstring(content)
+
+ if plate_id is not None:
+ # Find the plate element with matching index
+ for plate_elem in root.findall(".//plate"):
+ plate_index = None
+ for meta in plate_elem.findall("metadata"):
+ if meta.get("key") == "index":
+ try:
+ plate_index = int(meta.get("value", "0"))
+ except ValueError:
+ pass
+ break
+
+ if plate_index == plate_id:
+ for filament_elem in plate_elem.findall("filament"):
+ filament_type = filament_elem.get("type", "")
+ used_g = filament_elem.get("used_g", "0")
+ try:
+ used_grams = float(used_g)
+ except (ValueError, TypeError):
+ used_grams = 0
+ if used_grams > 0 and filament_type:
+ types.add(filament_type)
+ break
+ else:
+ # No plate_id specified - extract all filaments with used_g > 0
+ for filament_elem in root.findall(".//filament"):
+ filament_type = filament_elem.get("type", "")
+ used_g = filament_elem.get("used_g", "0")
+ try:
+ used_grams = float(used_g)
+ except (ValueError, TypeError):
+ used_grams = 0
+ if used_grams > 0 and filament_type:
+ types.add(filament_type)
+
+ except Exception as e:
+ logger.warning(f"Failed to extract filament types from {file_path}: {e}")
+
+ return sorted(types)
+
+
def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
"""Add nested archive/printer/library_file info to response."""
# Parse ams_mapping from JSON string BEFORE model_validate
@@ -38,10 +105,21 @@ def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
except json.JSONDecodeError:
ams_mapping_parsed = None
+ # Parse required_filament_types from JSON string
+ required_filament_types_parsed = None
+ if item.required_filament_types:
+ try:
+ required_filament_types_parsed = json.loads(item.required_filament_types)
+ except json.JSONDecodeError:
+ required_filament_types_parsed = None
+
# Create response with parsed ams_mapping
item_dict = {
"id": item.id,
"printer_id": item.printer_id,
+ "target_model": item.target_model,
+ "required_filament_types": required_filament_types_parsed,
+ "waiting_reason": item.waiting_reason,
"archive_id": item.archive_id,
"library_file_id": item.library_file_id,
"position": item.position,
@@ -120,29 +198,71 @@ async def add_to_queue(
db: AsyncSession = Depends(get_db),
):
"""Add an item to the print queue."""
+ # Normalize target_model (e.g., "Bambu Lab X1E" / "C13" -> "X1E")
+ target_model_norm = None
+ if data.target_model:
+ target_model_norm = (
+ normalize_printer_model(data.target_model)
+ or normalize_printer_model_id(data.target_model)
+ or data.target_model
+ )
+
# Validate that either archive_id or library_file_id is provided
if not data.archive_id and not data.library_file_id:
raise HTTPException(400, "Either archive_id or library_file_id must be provided")
+ # Cannot specify both printer_id and target_model
+ if data.printer_id and target_model_norm:
+ raise HTTPException(400, "Cannot specify both printer_id and target_model")
+
# Validate printer exists (if assigned)
if data.printer_id is not None:
result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
if not result.scalar_one_or_none():
raise HTTPException(400, "Printer not found")
- # Validate archive exists (if provided)
+ # Validate target_model has active printers
+ if target_model_norm:
+ result = await db.execute(
+ select(Printer).where(Printer.model == target_model_norm).where(Printer.is_active == True) # noqa: E712
+ )
+ if not result.scalars().first():
+ raise HTTPException(400, f"No active printers for model: {target_model_norm}")
+
+ # Validate archive exists (if provided) and get it for filament extraction
+ archive = None
if data.archive_id:
result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
- if not result.scalar_one_or_none():
+ archive = result.scalar_one_or_none()
+ if not archive:
raise HTTPException(400, "Archive not found")
- # Validate library file exists (if provided)
+ # Validate library file exists (if provided) and get it for filament extraction
+ library_file = None
if data.library_file_id:
result = await db.execute(select(LibraryFile).where(LibraryFile.id == data.library_file_id))
- if not result.scalar_one_or_none():
+ library_file = result.scalar_one_or_none()
+ if not library_file:
raise HTTPException(400, "Library file not found")
- # Get next position for this printer (or for unassigned items)
+ # Extract filament types for model-based assignment (used by scheduler for validation)
+ required_filament_types = None
+ if target_model_norm:
+ # Get file path from archive or library file
+ file_path = None
+ if archive:
+ file_path = settings.base_dir / archive.file_path
+ elif library_file:
+ lib_path = Path(library_file.file_path)
+ file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
+
+ if file_path and file_path.exists():
+ filament_types = _extract_filament_types_from_3mf(file_path, data.plate_id)
+ if filament_types:
+ required_filament_types = json.dumps(filament_types)
+ logger.info(f"Extracted filament types for model-based queue: {filament_types}")
+
+ # Get next position for this printer (or for unassigned/model-based items)
if data.printer_id is not None:
result = await db.execute(
select(func.max(PrintQueueItem.position))
@@ -150,7 +270,7 @@ async def add_to_queue(
.where(PrintQueueItem.status == "pending")
)
else:
- # For unassigned items, get max position across all unassigned
+ # For unassigned/model-based items, get max position across all unassigned
result = await db.execute(
select(func.max(PrintQueueItem.position))
.where(PrintQueueItem.printer_id.is_(None))
@@ -160,6 +280,8 @@ async def add_to_queue(
item = PrintQueueItem(
printer_id=data.printer_id,
+ target_model=target_model_norm,
+ required_filament_types=required_filament_types,
archive_id=data.archive_id,
library_file_id=data.library_file_id,
scheduled_time=data.scheduled_time,
@@ -185,7 +307,8 @@ async def add_to_queue(
await db.refresh(item, ["archive", "printer", "library_file"])
source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
- logger.info(f"Added {source_name} to queue for printer {data.printer_id or 'unassigned'}")
+ target_desc = data.printer_id or (f"model {target_model_norm}" if target_model_norm else "unassigned")
+ logger.info(f"Added {source_name} to queue for {target_desc}")
# MQTT relay - publish queue job added
try:
@@ -200,6 +323,29 @@ async def add_to_queue(
except Exception:
pass # Don't fail queue add if MQTT fails
+ # Send notification for job added
+ try:
+ job_name = (
+ item.archive.filename
+ if item.archive
+ else item.library_file.filename
+ if item.library_file
+ else f"Job #{item.id}"
+ )
+ job_name = job_name.replace(".gcode.3mf", "").replace(".3mf", "")
+ target = (
+ item.printer.name if item.printer else (f"Any {item.target_model}" if target_model_norm else "Unassigned")
+ )
+ await notification_service.on_queue_job_added(
+ job_name=job_name,
+ target=target,
+ db=db,
+ printer_id=item.printer_id,
+ printer_name=item.printer.name if item.printer else None,
+ )
+ except Exception:
+ pass # Don't fail queue add if notification fails
+
return _enrich_response(item)
@@ -287,12 +433,34 @@ async def update_queue_item(
update_data = data.model_dump(exclude_unset=True)
+ # Normalize target_model if being updated
+ if "target_model" in update_data and update_data["target_model"]:
+ update_data["target_model"] = (
+ normalize_printer_model(update_data["target_model"])
+ or normalize_printer_model_id(update_data["target_model"])
+ or update_data["target_model"]
+ )
+
+ # Cannot specify both printer_id and target_model
+ new_printer_id = update_data.get("printer_id", item.printer_id)
+ new_target_model = update_data.get("target_model", item.target_model)
+ if new_printer_id and new_target_model:
+ raise HTTPException(400, "Cannot specify both printer_id and target_model")
+
# Validate new printer_id if being changed (and not None)
if "printer_id" in update_data and update_data["printer_id"] is not None:
result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
if not result.scalar_one_or_none():
raise HTTPException(400, "Printer not found")
+ # Validate target_model has active printers
+ if "target_model" in update_data and update_data["target_model"]:
+ result = await db.execute(
+ select(Printer).where(Printer.model == update_data["target_model"]).where(Printer.is_active == True) # noqa: E712
+ )
+ if not result.scalars().first():
+ raise HTTPException(400, f"No active printers for model: {update_data['target_model']}")
+
# Serialize ams_mapping to JSON for TEXT column storage
if "ams_mapping" in update_data:
update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
diff --git a/backend/app/api/routes/settings.py b/backend/app/api/routes/settings.py
index de1e235e6..b687d3ff9 100644
--- a/backend/app/api/routes/settings.py
+++ b/backend/app/api/routes/settings.py
@@ -311,6 +311,13 @@ async def export_backup(
"on_ams_ht_humidity_high": getattr(p, "on_ams_ht_humidity_high", False),
"on_ams_ht_temperature_high": getattr(p, "on_ams_ht_temperature_high", False),
"on_plate_not_empty": getattr(p, "on_plate_not_empty", True),
+ "on_queue_job_added": getattr(p, "on_queue_job_added", False),
+ "on_queue_job_assigned": getattr(p, "on_queue_job_assigned", False),
+ "on_queue_job_started": getattr(p, "on_queue_job_started", False),
+ "on_queue_job_waiting": getattr(p, "on_queue_job_waiting", True),
+ "on_queue_job_skipped": getattr(p, "on_queue_job_skipped", True),
+ "on_queue_job_failed": getattr(p, "on_queue_job_failed", True),
+ "on_queue_completed": getattr(p, "on_queue_completed", False),
"quiet_hours_enabled": p.quiet_hours_enabled,
"quiet_hours_start": p.quiet_hours_start,
"quiet_hours_end": p.quiet_hours_end,
@@ -1176,6 +1183,13 @@ async def import_backup(
existing.on_ams_ht_humidity_high = provider_data.get("on_ams_ht_humidity_high", False)
existing.on_ams_ht_temperature_high = provider_data.get("on_ams_ht_temperature_high", False)
existing.on_plate_not_empty = provider_data.get("on_plate_not_empty", True)
+ existing.on_queue_job_added = provider_data.get("on_queue_job_added", False)
+ existing.on_queue_job_assigned = provider_data.get("on_queue_job_assigned", False)
+ existing.on_queue_job_started = provider_data.get("on_queue_job_started", False)
+ existing.on_queue_job_waiting = provider_data.get("on_queue_job_waiting", True)
+ existing.on_queue_job_skipped = provider_data.get("on_queue_job_skipped", True)
+ existing.on_queue_job_failed = provider_data.get("on_queue_job_failed", True)
+ existing.on_queue_completed = provider_data.get("on_queue_completed", False)
existing.quiet_hours_enabled = provider_data.get("quiet_hours_enabled", False)
existing.quiet_hours_start = provider_data.get("quiet_hours_start")
existing.quiet_hours_end = provider_data.get("quiet_hours_end")
@@ -1206,6 +1220,13 @@ async def import_backup(
on_ams_ht_humidity_high=provider_data.get("on_ams_ht_humidity_high", False),
on_ams_ht_temperature_high=provider_data.get("on_ams_ht_temperature_high", False),
on_plate_not_empty=provider_data.get("on_plate_not_empty", True),
+ on_queue_job_added=provider_data.get("on_queue_job_added", False),
+ on_queue_job_assigned=provider_data.get("on_queue_job_assigned", False),
+ on_queue_job_started=provider_data.get("on_queue_job_started", False),
+ on_queue_job_waiting=provider_data.get("on_queue_job_waiting", True),
+ on_queue_job_skipped=provider_data.get("on_queue_job_skipped", True),
+ on_queue_job_failed=provider_data.get("on_queue_job_failed", True),
+ on_queue_completed=provider_data.get("on_queue_completed", False),
quiet_hours_enabled=provider_data.get("quiet_hours_enabled", False),
quiet_hours_start=provider_data.get("quiet_hours_start"),
quiet_hours_end=provider_data.get("quiet_hours_end"),
diff --git a/backend/app/core/database.py b/backend/app/core/database.py
index 4b2506d76..5b3175ff4 100644
--- a/backend/app/core/database.py
+++ b/backend/app/core/database.py
@@ -760,6 +760,46 @@ async def run_migrations(conn):
except Exception:
pass
+ # Migration: Add sliced_for_model column to print_archives for printer model from 3MF
+ try:
+ await conn.execute(text("ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)"))
+ except Exception:
+ pass
+
+ # Migration: Add target_model column to print_queue for model-based assignment
+ try:
+ await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
+ except Exception:
+ pass
+
+ # Migration: Add required_filament_types column to print_queue for filament validation
+ try:
+ await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
+ except Exception:
+ pass
+
+ # Migration: Add waiting_reason column to print_queue for status feedback
+ try:
+ await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
+ except Exception:
+ pass
+
+ # Migration: Add queue notification event columns to notification_providers
+ queue_notification_columns = [
+ ("on_queue_job_added", "BOOLEAN DEFAULT 0"),
+ ("on_queue_job_assigned", "BOOLEAN DEFAULT 0"),
+ ("on_queue_job_started", "BOOLEAN DEFAULT 0"),
+ ("on_queue_job_waiting", "BOOLEAN DEFAULT 1"),
+ ("on_queue_job_skipped", "BOOLEAN DEFAULT 1"),
+ ("on_queue_job_failed", "BOOLEAN DEFAULT 1"),
+ ("on_queue_completed", "BOOLEAN DEFAULT 0"),
+ ]
+ for col_name, col_def in queue_notification_columns:
+ try:
+ await conn.execute(text(f"ALTER TABLE notification_providers ADD COLUMN {col_name} {col_def}"))
+ except Exception:
+ pass
+
async def seed_notification_templates():
"""Seed default notification templates if they don't exist."""
diff --git a/backend/app/main.py b/backend/app/main.py
index 40e49a34b..3f124524d 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -1988,6 +1988,34 @@ async def on_print_complete(printer_id: int, data: dict):
except Exception:
pass # Don't fail if MQTT fails
+ # Check if queue is now empty and send notification
+ try:
+ from sqlalchemy import func
+
+ # Count remaining pending items
+ count_result = await db.execute(
+ select(func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
+ )
+ pending_count = count_result.scalar() or 0
+
+ if pending_count == 0:
+ # Count how many completed today (rough approximation)
+ today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
+ completed_result = await db.execute(
+ select(func.count(PrintQueueItem.id)).where(
+ PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
+ PrintQueueItem.completed_at >= today_start,
+ )
+ )
+ completed_count = completed_result.scalar() or 1
+
+ await notification_service.on_queue_completed(
+ completed_count=completed_count,
+ db=db,
+ )
+ except Exception:
+ pass # Don't fail if notification fails
+
# Handle auto_off_after - power off printer if requested (after cooldown)
if queue_item.auto_off_after:
result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
diff --git a/backend/app/models/archive.py b/backend/app/models/archive.py
index 6e99ea491..01e230827 100644
--- a/backend/app/models/archive.py
+++ b/backend/app/models/archive.py
@@ -35,6 +35,9 @@ class PrintArchive(Base):
bed_temperature: Mapped[int | None] = mapped_column(Integer)
nozzle_temperature: Mapped[int | None] = mapped_column(Integer)
+ # Printer model this file was sliced for (extracted from 3MF metadata)
+ sliced_for_model: Mapped[str | None] = mapped_column(String(50), nullable=True)
+
# Print result
status: Mapped[str] = mapped_column(String(20), default="completed")
started_at: Mapped[datetime | None] = mapped_column(DateTime)
diff --git a/backend/app/models/notification.py b/backend/app/models/notification.py
index 4f49ed64b..c04b140d7 100644
--- a/backend/app/models/notification.py
+++ b/backend/app/models/notification.py
@@ -83,6 +83,15 @@ class NotificationProvider(Base):
# Event triggers - Build plate detection
on_plate_not_empty = Column(Boolean, default=True) # Objects detected on plate before print
+ # Event triggers - Print queue
+ on_queue_job_added = Column(Boolean, default=False) # Job added to queue
+ on_queue_job_assigned = Column(Boolean, default=False) # Model-based job assigned to printer
+ on_queue_job_started = Column(Boolean, default=False) # Queue job started printing
+ on_queue_job_waiting = Column(Boolean, default=True) # Job waiting for filament
+ on_queue_job_skipped = Column(Boolean, default=True) # Job skipped (previous print failed)
+ on_queue_job_failed = Column(Boolean, default=True) # Job failed to start
+ on_queue_completed = Column(Boolean, default=False) # All pending jobs finished
+
# Quiet hours (do not disturb)
quiet_hours_enabled = Column(Boolean, default=False)
quiet_hours_start = Column(String(5), nullable=True) # HH:MM format, e.g., "22:00"
diff --git a/backend/app/models/notification_template.py b/backend/app/models/notification_template.py
index 9dcb9ccbc..fb21b9456 100644
--- a/backend/app/models/notification_template.py
+++ b/backend/app/models/notification_template.py
@@ -103,4 +103,47 @@ DEFAULT_TEMPLATES = [
"title_template": "Bambuddy Test",
"body_template": "This is a test notification. If you see this, notifications are working!",
},
+ # Queue notifications
+ {
+ "event_type": "queue_job_added",
+ "name": "Queue Job Added",
+ "title_template": "Job Queued",
+ "body_template": "{job_name} added to queue for {target}",
+ },
+ {
+ "event_type": "queue_job_assigned",
+ "name": "Queue Job Assigned",
+ "title_template": "Job Assigned",
+ "body_template": "{job_name} assigned to {printer} (from Any {target_model} queue)",
+ },
+ {
+ "event_type": "queue_job_started",
+ "name": "Queue Job Started",
+ "title_template": "Queue Job Started",
+ "body_template": "{printer}: {job_name}\nEstimated: {estimated_time}",
+ },
+ {
+ "event_type": "queue_job_waiting",
+ "name": "Queue Job Waiting",
+ "title_template": "Job Waiting for Filament",
+ "body_template": "{job_name} waiting for {target_model}\n{waiting_reason}",
+ },
+ {
+ "event_type": "queue_job_skipped",
+ "name": "Queue Job Skipped",
+ "title_template": "Job Skipped",
+ "body_template": "{printer}: {job_name}\nReason: {reason}",
+ },
+ {
+ "event_type": "queue_job_failed",
+ "name": "Queue Job Failed",
+ "title_template": "Job Failed to Start",
+ "body_template": "{printer}: {job_name}\nReason: {reason}",
+ },
+ {
+ "event_type": "queue_completed",
+ "name": "Queue Completed",
+ "title_template": "Queue Complete",
+ "body_template": "All {completed_count} queued jobs have finished",
+ },
]
diff --git a/backend/app/models/print_queue.py b/backend/app/models/print_queue.py
index 64ccc4980..53c54cb93 100644
--- a/backend/app/models/print_queue.py
+++ b/backend/app/models/print_queue.py
@@ -15,6 +15,15 @@ class PrintQueueItem(Base):
# Links
printer_id: Mapped[int | None] = mapped_column(ForeignKey("printers.id", ondelete="CASCADE"), nullable=True)
+ # Target printer model for model-based assignment (mutually exclusive with printer_id)
+ # When set, scheduler assigns to any idle printer of matching model
+ target_model: Mapped[str | None] = mapped_column(String(50), nullable=True)
+ # Required filament types for model-based assignment (JSON array, e.g., '["PLA", "PETG"]')
+ # Used by scheduler to validate printer has compatible filaments loaded
+ required_filament_types: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # Waiting reason - explains why a model-based job hasn't started yet
+ # Set by scheduler when no matching printer is available
+ waiting_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
# Either archive_id OR library_file_id must be set (archive created at print start from library file)
archive_id: Mapped[int | None] = mapped_column(ForeignKey("print_archives.id", ondelete="CASCADE"), nullable=True)
library_file_id: Mapped[int | None] = mapped_column(
diff --git a/backend/app/schemas/archive.py b/backend/app/schemas/archive.py
index f968fca72..42e005007 100644
--- a/backend/app/schemas/archive.py
+++ b/backend/app/schemas/archive.py
@@ -63,6 +63,8 @@ class ArchiveResponse(BaseModel):
bed_temperature: int | None
nozzle_temperature: int | None
+ sliced_for_model: str | None = None # Printer model this file was sliced for
+
status: str
started_at: datetime | None
completed_at: datetime | None
diff --git a/backend/app/schemas/notification.py b/backend/app/schemas/notification.py
index e0285f464..ca8ff5b41 100644
--- a/backend/app/schemas/notification.py
+++ b/backend/app/schemas/notification.py
@@ -53,6 +53,15 @@ class NotificationProviderBase(BaseModel):
# Event triggers - Build plate detection
on_plate_not_empty: bool = Field(default=True, description="Notify when objects detected on plate before print")
+ # Event triggers - Print queue
+ on_queue_job_added: bool = Field(default=False, description="Notify when job is added to queue")
+ on_queue_job_assigned: bool = Field(default=False, description="Notify when model-based job is assigned to printer")
+ on_queue_job_started: bool = Field(default=False, description="Notify when queue job starts printing")
+ on_queue_job_waiting: bool = Field(default=True, description="Notify when job is waiting for filament")
+ on_queue_job_skipped: bool = Field(default=True, description="Notify when job is skipped")
+ on_queue_job_failed: bool = Field(default=True, description="Notify when job fails to start")
+ on_queue_completed: bool = Field(default=False, description="Notify when all queue jobs finish")
+
# Quiet hours
quiet_hours_enabled: bool = Field(default=False, description="Enable quiet hours")
quiet_hours_start: str | None = Field(default=None, description="Start time in HH:MM format")
@@ -120,6 +129,15 @@ class NotificationProviderUpdate(BaseModel):
# Event triggers - Build plate detection
on_plate_not_empty: bool | None = None
+ # Event triggers - Print queue
+ on_queue_job_added: bool | None = None
+ on_queue_job_assigned: bool | None = None
+ on_queue_job_started: bool | None = None
+ on_queue_job_waiting: bool | None = None
+ on_queue_job_skipped: bool | None = None
+ on_queue_job_failed: bool | None = None
+ on_queue_completed: bool | None = None
+
# Quiet hours
quiet_hours_enabled: bool | None = None
quiet_hours_start: str | None = None
diff --git a/backend/app/schemas/notification_template.py b/backend/app/schemas/notification_template.py
index c484e0586..544a3c57e 100644
--- a/backend/app/schemas/notification_template.py
+++ b/backend/app/schemas/notification_template.py
@@ -45,6 +45,14 @@ EVENT_VARIABLES: dict[str, list[str]] = {
"ams_humidity_high": ["printer", "ams_label", "humidity", "threshold", "timestamp", "app_name"],
"ams_temperature_high": ["printer", "ams_label", "temperature", "threshold", "timestamp", "app_name"],
"test": ["app_name", "timestamp"],
+ # Queue notifications
+ "queue_job_added": ["job_name", "target", "timestamp", "app_name"],
+ "queue_job_assigned": ["job_name", "printer", "target_model", "timestamp", "app_name"],
+ "queue_job_started": ["printer", "job_name", "estimated_time", "timestamp", "app_name"],
+ "queue_job_waiting": ["job_name", "target_model", "waiting_reason", "timestamp", "app_name"],
+ "queue_job_skipped": ["printer", "job_name", "reason", "timestamp", "app_name"],
+ "queue_job_failed": ["printer", "job_name", "reason", "timestamp", "app_name"],
+ "queue_completed": ["completed_count", "timestamp", "app_name"],
}
# Sample data for previewing templates
@@ -136,6 +144,53 @@ SAMPLE_DATA: dict[str, dict[str, str]] = {
"app_name": "Bambuddy",
"timestamp": "2024-01-15 14:30",
},
+ # Queue notifications
+ "queue_job_added": {
+ "job_name": "Benchy.3mf",
+ "target": "Bambu X1C",
+ "timestamp": "2024-01-15 14:30",
+ "app_name": "Bambuddy",
+ },
+ "queue_job_assigned": {
+ "job_name": "Benchy.3mf",
+ "printer": "Bambu X1C #1",
+ "target_model": "X1C",
+ "timestamp": "2024-01-15 14:30",
+ "app_name": "Bambuddy",
+ },
+ "queue_job_started": {
+ "printer": "Bambu X1C",
+ "job_name": "Benchy.3mf",
+ "estimated_time": "1h 23m",
+ "timestamp": "2024-01-15 14:30",
+ "app_name": "Bambuddy",
+ },
+ "queue_job_waiting": {
+ "job_name": "Benchy.3mf",
+ "target_model": "X1C",
+ "waiting_reason": "Printer1 (needs PLA)",
+ "timestamp": "2024-01-15 14:30",
+ "app_name": "Bambuddy",
+ },
+ "queue_job_skipped": {
+ "printer": "Bambu X1C",
+ "job_name": "Benchy.3mf",
+ "reason": "Previous print failed",
+ "timestamp": "2024-01-15 14:30",
+ "app_name": "Bambuddy",
+ },
+ "queue_job_failed": {
+ "printer": "Bambu X1C",
+ "job_name": "Benchy.3mf",
+ "reason": "Upload failed: connection timeout",
+ "timestamp": "2024-01-15 14:30",
+ "app_name": "Bambuddy",
+ },
+ "queue_completed": {
+ "completed_count": "5",
+ "timestamp": "2024-01-15 18:30",
+ "app_name": "Bambuddy",
+ },
}
diff --git a/backend/app/schemas/print_queue.py b/backend/app/schemas/print_queue.py
index d5bdbc780..785145126 100644
--- a/backend/app/schemas/print_queue.py
+++ b/backend/app/schemas/print_queue.py
@@ -17,6 +17,8 @@ UTCDatetime = Annotated[datetime | None, PlainSerializer(serialize_utc_datetime)
class PrintQueueItemCreate(BaseModel):
printer_id: int | None = None # None = unassigned, user assigns later
+ target_model: str | None = None # Target printer model (mutually exclusive with printer_id)
+ required_filament_types: list[str] | None = None # Required filament types for model-based assignment
# Either archive_id OR library_file_id must be provided
archive_id: int | None = None
library_file_id: int | None = None
@@ -40,6 +42,7 @@ class PrintQueueItemCreate(BaseModel):
class PrintQueueItemUpdate(BaseModel):
printer_id: int | None = None
+ target_model: str | None = None # Target printer model (mutually exclusive with printer_id)
position: int | None = None
scheduled_time: datetime | None = None
require_previous_success: bool | None = None
@@ -59,6 +62,9 @@ class PrintQueueItemUpdate(BaseModel):
class PrintQueueItemResponse(BaseModel):
id: int
printer_id: int | None # None = unassigned
+ target_model: str | None = None # Target printer model for model-based assignment
+ required_filament_types: list[str] | None = None # Required filament types for model-based assignment
+ waiting_reason: str | None = None # Why a model-based job hasn't started yet
archive_id: int | None # None if library_file_id is set (archive created at print start)
library_file_id: int | None # For queue items from library files
position: int
diff --git a/backend/app/services/archive.py b/backend/app/services/archive.py
index ba28004ec..d20906f81 100644
--- a/backend/app/services/archive.py
+++ b/backend/app/services/archive.py
@@ -67,6 +67,19 @@ class ThreeMFParser:
content = zf.read("Metadata/slice_info.config").decode()
root = ET.fromstring(content)
+ # Extract printer_model_id from plate metadata
+ # Format:
Print Queue
+ +Job Added
+Job added to queue
+Job Assigned
+Model-based job assigned to printer
+Job Started
+Queue job started printing
+Job Waiting
+Job waiting for filament
+Job Skipped
+Job skipped (previous failed)
+Job Failed
+Job failed to start
+Queue Complete
+All queue jobs finished
++ Scheduler will assign to first available idle {targetModel} printer +
+ )} + + {/* Multi-select header (only in printer mode) */} + {assignmentMode === 'printer' && allowMultiple && displayPrinters.length > 1 && (
+
+ The printer model will be automatically extracted from the 3MF file metadata. +
+
@@ -458,7 +480,7 @@ function SortableQueueItem({
vn?(Fn=qt,qt=null):Fn=qt.sibling;var qn=st(Ze,qt,tt[vn],vt);if(qn===null){qt===null&&(qt=Fn);break}h&&qt&&qn.alternate===null&&g(Ze,qt),Ge=I(qn,Ge,vn),Wn===null?Zt=qn:Wn.sibling=qn,Wn=qn,qt=Fn}if(vn===tt.length)return _(Ze,qt),zn&&ac(Ze,vn),Zt;if(qt===null){for(;vn