Created
August 24, 2023 02:18
-
-
Save jstm88/5cfc5726785e0a94554ddf19ce02293b to your computer and use it in GitHub Desktop.
Prusa Upload Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
import json | |
import time | |
import hashlib | |
import requests | |
import urllib.parse | |
PRINTER_URL="http://..." | |
API_KEY="..." | |
def sizeof_fmt(num, suffix="B"): | |
for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"): | |
if abs(num) < 1024.0: | |
return f"{num:3.1f}{unit}{suffix}" | |
num /= 1024.0 | |
return f"{num:.1f}Yi{suffix}" | |
if not len(sys.argv) > 1: | |
sys.stderr.write("No file given\n") | |
sys.exit(1) | |
src_path = os.path.expanduser(sys.argv[1]) | |
src_filename = os.path.basename(src_path) | |
upload_filename = "{}_{}".format(int(time.time()), src_filename) | |
with open(src_path, 'rb') as f: | |
src_rawdata = f.read() | |
src_hash = hashlib.sha256() | |
src_hash.update(src_rawdata) | |
print("Uploading {} file...".format(sizeof_fmt(len(src_rawdata)))) | |
start_time = time.time() | |
try: | |
put_response = requests.put( | |
url="{}/api/v1/files/usb/{}".format(PRINTER_URL, urllib.parse.quote(upload_filename)), | |
headers={"X-Api-Key": API_KEY, "Content-Type": "text/x.gcode", "Overwrite": "0"}, | |
data=src_rawdata) | |
except requests.exceptions.RequestException: | |
sys.stderr.write("HTTP Request failed\n") | |
sys.exit(1) | |
if (put_response.status_code != 201): | |
sys.stderr.write("Upload error\n") | |
sys.exit(1) | |
end_time = time.time() | |
bytes = len(src_rawdata) | |
seconds = end_time - start_time | |
bps = ((8 * len(src_rawdata)) / ((end_time - start_time))) | |
print("Uploaded in {} seconds ({})".format(int(seconds), sizeof_fmt(bps, suffix="bps"))) | |
print("Verifying...") | |
put_rdict = json.loads(put_response.text) | |
dl_path = put_rdict.get('refs').get('download') | |
try: | |
dl_response = requests.get( | |
url="{}{}".format(PRINTER_URL, dl_path), | |
headers={"X-Api-Key": API_KEY}) | |
except requests.exceptions.RequestException: | |
sys.stderr.write("HTTP Request failed\n") | |
print("File could not be validated") | |
sys.exit(1) | |
if (dl_response.status_code != 200): | |
print("File could not be validated") | |
sys.exit(1) | |
dl_hash = hashlib.sha256() | |
dl_hash.update(dl_response.content) | |
if (len(src_hash.digest()) > 0) and (src_hash.digest() == dl_hash.digest()): | |
print("Valid! Ready to print.") | |
sys.exit(0) | |
else: | |
print("SRC: {}".format(src_hash.hexdigest())) | |
print("DST: {}".format(dl_hash.hexdigest())) | |
print("UPLOADED FILE CORRUPTED!!!") | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment