From 13b4ee1595eacce6356c84375d6197e1e5d888f2 Mon Sep 17 00:00:00 2001 From: Sebastian Andersson Date: Mon, 18 Mar 2024 15:00:13 +0100 Subject: [PATCH] WIP --- nfc2klipper.py | 58 +++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 12 deletions(-) diff --git a/nfc2klipper.py b/nfc2klipper.py index 794edef..d2563c6 100755 --- a/nfc2klipper.py +++ b/nfc2klipper.py @@ -6,6 +6,9 @@ """Program to set current filament & spool in klipper.""" import argparse +import asyncio +import json +import socket import nfc import requests @@ -13,11 +16,12 @@ SPOOL = "SPOOL" FILAMENT = "FILAMENT" NDEF_TEXT_TYPE = "urn:nfc:wkt:T" +VERSION = "0.0.2" parser = argparse.ArgumentParser() # description="Fetches filaments from Spoolman and creates SuperSlicer filament configs.", -parser.add_argument("--version", action="version", version="%(prog)s 0.0.1") +parser.add_argument("--version", action="version", version="%(prog)s " + VERSION) parser.add_argument( "-c", @@ -36,14 +40,43 @@ + " for format", ) +#parser.add_argument( +# "-u", +# "--url", +# metavar="URL", +# default="http://mainsailos.local", +# help="URL for the moonraker installation", +#) + parser.add_argument( - "-u", - "--url", - metavar="URL", - default="http://mainsailos.local", - help="URL for the moonraker installation", + "-k", + "--klipper-uds", + metavar="PATH", + default="/tmp/klippy_uds", + help="Path to Klipper's API socket.", ) +class KlipperConnection: + def __init__(self): + self.reader = None + self.writer = None + self.msg_id = 1 + + async def connect(self, path): + (self.reader, self.writer) = await self.open_unix_connection(self.path) + + async def send(self, method, params): + cmd = {"id": self.msg_id, + "method": method, + "params": params + } + self.msg_id += 1 + string = json.dumps(cmd, separators=(',', ':')) + self.writer.write(string.encode() + "\003") + await self.writer.drain() + + async def send_gcode(self, gcode): + await send("gcode/script", {"script": gcode}) def set_spool_and_filament(url: str, spool: int, filament: int): """Calls moonraker with the current spool & filament""" @@ -61,12 +94,13 @@ def set_spool_and_filament(url: str, spool: int, filament: int): print(f"Sending spool #{spool}, filament #{filament} to klipper", flush=True) - commands = { - "commands": [ - f"SET_ACTIVE_SPOOL ID={spool}", - f"SET_ACTIVE_FILAMENT ID={filament}", - ] - } +# commands = { +# "commands": [ +# f"SET_ACTIVE_SPOOL ID={spool}", +# f"SET_ACTIVE_FILAMENT ID={filament}", +# ] +# } + # In case the post fails, we might not know if the server has received # it or not, so set them to None: