dougbrion / octorest Goto Github PK
View Code? Open in Web Editor NEWThis project forked from hroncok/octoclient
Python client library for OctoPrint REST API
Home Page: http://docs.octoprint.org/en/master/api/
License: Other
This project forked from hroncok/octoclient
Python client library for OctoPrint REST API
Home Page: http://docs.octoprint.org/en/master/api/
License: Other
Test whether prints start automatically after being uploaded when the "print" flag is set to "true".
Reported to not be working here: https://www.rs-online.com/designspark/building-a-3d-print-queue-automation-system-part-2
Many of the methods need improved, (or some...) testing.
This works:
hets.upload("test.gcode")
hets.select("test.gcode", print=True)
This does not:
hets.upload("test.gcode", select=True, print=True)
The file is uploaded, but not selected (and does not start printing, obviously).
I suspect it has to do with how the arguments are formatted. Here is a function that works properly that I wrote before finding this library:
def upload_and_run(path: str | os.PathLike) -> None:
url: str = f"{URL}/api/files/local"
headers: dict[str, str] = {
"X-Api-Key": API_KEY,
}
with open(path, "rb") as file:
files: dict[str, tuple] = {
"file": (os.path.basename(path), file),
}
data: dict[str] = {
"select": True,
"print": True,
}
response = requests.post(url, headers=headers, files=files, data=data)
if response.status_code != 201:
error: str = json.loads(response.content)["error"]
raise IOError(f"Failed to upload: {error}")
The first thing anyone who wants to use this client will need to do is get an API key.
Currently, the best practice regarding getting an API key is to programmatically request one.
I think it would be very appropriate for this project to include support for this process.
BTW, thank you for this wonderful project!
I seem to be having some trouble getting the printer to respond to the .gcode() command. I can see the command show up in the terminal and the printer responds with 'OK' but the command doesn't seem to be executed. Oddly enough, if I copy/paste the text from the terminal window into the input line and send it, the printer responds appropriately. Any idea what might be going on here?
Fully implement methods for the whole OctoPrint API (http://docs.octoprint.org/en/master/api/)
Hi,
Thanks for your work that helps a lot. Actually I am trying to develop a client to communicate with the Octoprint server. I want to receive the message from the server when I send a Gcode command by using websocket.
Currently, I an using Class WebSocketEventHandler. As shown in Octoprint server's terminal, there is a new connection from client. However, it closes immediately so that I can't send any message further.
2022-09-29 10:09:17,844 - octoprint.server.util.sockjs - INFO - New connection from client: ::1 2022-09-29 10:09:17,848 - octoprint.server.util.sockjs - INFO - Client connection closed: ::1
Have you tested it successfully before? I guess that maybe I need to authorize firstly by using the API key. But how can I realize it?
I don't find a suitable tutor.
Best,
David
Current examples are not working and when working should utilise much of the provided functionality. Some ideas:
I am done until select file in octo print but start function doesn't functional.
here is the error log of octo print command line
Changing monitoring state from "Operational" to "Starting"
Send: N0 M110 N0125
Recv: ok
Changing monitoring state from "Starting" to "Printing"
Send: N1 application/octet-stream82
Recv: echo:Unknown command: "$1 application/octet-stream"(2)
Recv: ok
Changing monitoring state from "Printing" to "Finishing"
Recv: T:25.9 /0.0 B:25.8 /0.0 T0:25.9 /0.0 @:0 B@:0 P:0.0 A:28.7
Send: N2 M400*37
Recv: ok
Changing monitoring state from "Finishing" to "Operational"
what is the problem?
attach my code below
`from tokenize import String
from django.http import HttpResponse
import os, subprocess
from octorest import OctoRest, WorkflowAppKeyRequestResult
from urllib import parse as urlparse
def index(request):
pwd = os.getcwd()
os.system("cd ../../")
pwd2 = os.getcwd()
# data = subprocess.check_output(['ls', '-l'])
client = make_client("http://114.70.21.171:5000/","08E4BE03835A4951B89DC40696B8153D") # 잘 연결된다
# fileNames = file_names(client) # 잘 들어온다
filename = tuple(['One_Hand_Book_Holder_0.2mm_PETG_MK3S_29m.gcode'])
upload(client,filename)
select(client,'local/One_Hand_Book_Holder_0.2mm_PETG_MK3S_29m.gcode')
start(client)
return HttpResponse("dsadsa: "+pwd+"\n"+pwd2+"\n ewqewq ")
# return HttpResponse("Hello, world. You're at the tookdak index.")
def make_client(url, apikey):
"""Creates and returns an instance of the OctoRest client.
Args:
url - the url to the OctoPrint server
apikey - the apikey from the OctoPrint server found in settings
"""
try:
client = OctoRest(url=url, apikey=apikey)
return client
except ConnectionError as ex:
# Handle exception as you wish
print(ex)
def file_names(client):
"""Retrieves the G-code file names from the
OctoPrint server and returns a string message listing the
file names.
Args:
client - the OctoRest client
"""
message = "The GCODE files currently on the printer are:\n\n"
for k in client.files()['files']:
message += k['name'] + "\n"
return message
def slicing_stl_file(client,file_name):
"""Slicing the stl file to Gcode file
OctoPrint server and returns a string message
Args:
client - the OctoRest client
file_name - target stl file name
"""
message = "The GCODE files currently on the printer are:\n\n"
for k in client.files()['files']:
message += k['name'] + "\n"
return message
def upload(self, file, *, location='local', select=False, print=False, userdata=None, path=None):
"""Upload file or create folder
http://docs.octoprint.org/en/master/api/files.html#upload-file-or-create-folder
Upload a given file
It can be a path or a tuple with a filename and a file-like object
"""
with self._file_tuple(file) as file_tuple:
files = {'file': file_tuple, 'select': (None, select), 'print': (None, print)}
if userdata:
files['userdata'] = (None, userdata)
if path:
files['path'] = (None, path)
return self._post('/api/files/{}'.format(location),files=files)
def start(self):
"""Issue a job command
http://docs.octoprint.org/en/master/api/job.html#issue-a-job-command
Starts the print of the currently selected file
Use select() to select a file
"""
data = {'command': 'start'}
self._post('/api/job', json=data, ret=False)
def restart(self):
"""Issue a job command
http://docs.octoprint.org/en/master/api/job.html#issue-a-job-command
Restart the print of the currently selected file from the beginning
There must be an active print job for this to work and the print job
must currently be paused
"""
data = {'command': 'restart'}
self._post('/api/job', json=data, ret=False)
def _post(self, path, data=None, files=None, json=None, ret=True):
"""
Perform HTTP POST on given path with the auth header
Path shall be the ending part of the URL,
i.e. it should not be full URL
Raises a RuntimeError when not 20x OK-ish
Returns JSON decoded data
"""
url = urlparse.urljoin(self.url, path)
response = self.session.post(url, data=data, files=files, json=json)
self._check_response(response)
if ret:
return response.json()
def select(self, location, *, print=False):
"""Issue a file command
http://docs.octoprint.org/en/master/api/files.html#issue-a-file-command
Selects a file for printing
Location is target/filename, defaults to local/filename
If print is True, the selected file starts to print immediately
"""
location = self._prepend_local(location)
data = {
'command': 'select',
'print': print,
}
self._post('/api/files/{}'.format(location), json=data, ret=False)
`
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.