def _get_printer_info(self, printer: Printer) -> Dict: printer_info = printer.__dict__.copy() octorest_client = None try: session = requests.Session() # overriding the default session OctoRest uses to set my desired timeout session.get = partial(session.get, timeout=3) octorest_client = OctoRest(url=printer.url, apikey=printer.apiKey, session=session) except (RuntimeError, requests.exceptions.ConnectionError): printer_info['state'] = "OctoPrint unavailable" return printer_info printer_info['state'] = octorest_client.state() # Get the printer model printer_profiles = octorest_client.printer_profiles()['profiles'] # Assuming printer_profiles is not empty, and there's one profile marked as default default_profile = next(profile for profile in printer_profiles.values() if profile['default'] is True) printer_info['model'] = default_profile['model'] printer_info['jobInfo'] = octorest_client.job_info() return printer_info
def main(): url = "http://octopi.local" user = "******" client = None try: client = OctoRest(url=url) except TypeError: raise NotImplementedError() # Decide what should happen now (result, api_key) = (None, None) try: (result, api_key) = client.try_get_api_key('my-app', user) except ConnectionError: raise NotImplementedError() # Decide what should happen now. Suggestion - tell the user the OctoPrint server is unreachable and that he should check the URL entered if result == WorkflowAppKeyRequestResult.WORKFLOW_UNSUPPORTED: raise NotImplementedError() # Decide what should happen now. Suggestion - fall back to asking the user to manually enter a valid API key. elif result == WorkflowAppKeyRequestResult.TIMED_OUT: # The user took too long to approve the API key request raise NotImplementedError() # Decide what should happen now elif result == WorkflowAppKeyRequestResult.NOPE: # The request has been denied raise NotImplementedError() # Decide what should happen now elif result == WorkflowAppKeyRequestResult.GRANTED: client.load_api_key(api_key) # You have to load the API key before sending any requests to the OctoPrint server pass # At this point you can use the client for whatever you wish raise NotImplementedError() # Decide what should happen now
def __init__(self, bot): self.bot = bot try: self.op_client = OctoRest(url="http://192.168.1.158/", apikey=Config().octopi_api_key) except ConnectionError as ex: logGeneric(ex)
def connect(self): #print("conect") try: self.client = OctoRest(url=self.url, apikey=self.apikey) except ConnectionError as ex: print("..............Connect error.....................") print(ex)
def add_printer( self, printer_name: str, url: str, user: Optional[str]) -> Tuple[AddPrinterResult, Optional[Dict]]: octorest_client = None try: octorest_client = OctoRest(url=url) except TypeError: return (AddPrinterResult.BAD_URL, None) (result, api_key) = (None, None) try: (result, api_key) = octorest_client.try_get_api_key('MahaPrinting', user) except requests.exceptions.ConnectionError: return (AddPrinterResult.BAD_URL, None) if result == WorkflowAppKeyRequestResult.WORKFLOW_UNSUPPORTED: return (AddPrinterResult.WORKFLOW_UNSUPPORTED, None) if result == WorkflowAppKeyRequestResult.TIMED_OUT: return (AddPrinterResult.API_KEY_REQUEST_TIMED_OUT, None) if result == WorkflowAppKeyRequestResult.NOPE: return (AddPrinterResult.API_KEY_REQUEST_DENIED, None) if result == WorkflowAppKeyRequestResult.GRANTED: printer_info = self._add_printer_no_url_validation( printer_name, url, api_key) return (AddPrinterResult.SUCCESS, printer_info) raise NotImplementedError( "An unsupported WorkflowAppKeyRequestResult value was encountered: " + result.name)
def get_printer_info(): try: client = OctoRest(url=ocfg['url'], apikey=ocfg['apikey']) message = "" message += str(client.version) + "\n" message += str(client.job_info()) + "\n" printing = client.printer()['state']['flags']['printing'] if printing: message += "Currently printing!\n" else: message += "Not currently printing...\n" return message except Exception as e: print(e)
def send_to_printer(self, print_id: int, printer_id: int, gcode_file: Optional[FileStorage] = None): printer = self.printer_record_repository.get_printer(printer_id) if printer is None: raise ValueError("No printer matches the given printer ID.") octorest_client = OctoRest(url=printer.url, apikey=printer.apiKey) print = self.print_record_repository.get_print(print_id) if print is None: raise ValueError("No print matches the given print ID.") uploaded_file_path_in_octoprint = None if gcode_file is None: print_file_path = self.uploads_manager.get_print_file_path(print) octorest_client.upload(print_file_path) uploaded_file_path_in_octoprint = Path(print_file_path).name else: validate_file_extension(gcode_file, ['gcode']) file_name = get_print_file_name_by_extension(print.id, 'gcode') octorest_client.upload((file_name, gcode_file)) uploaded_file_path_in_octoprint = file_name octorest_client.select(uploaded_file_path_in_octoprint, print=True) self.print_record_repository.change_print_status( print.id, PrintStatus.PRINTING)
def get_printer_info(): try: client = OctoRest(url="http://octopi.local", apikey="YouShallNotPass") message = "" message += str(client.version) + "\n" message += str(client.job_info()) + "\n" printing = client.printer()['state']['flags']['printing'] if printing: message += "Currently printing!\n" else: message += "Not currently printing...\n" return message except Exception as e: print(e)
def make_client(): try: client = OctoRest(url=cfg.octoprint["url"], apikey=cfg.octoprint["apikey"]) return client except Exception as e: print(e)
def init_client(self): print("Initializing OctoREST client...") while True: try: client = OctoRest(url="http://{}".format(self.octo_url), apikey=self.octo_key) print("Initialized OctoREST client") state = client.state() print(str(state)) print(str(client.connection_info())) # if "Error" in state or "Closed" in state: print("Printer is not connected. Trying to connect...") print(client.connect()) return client except Exception as ex: print( "Initialized of OctoREST client failed. Retrying in 10secs..." ) print(ex) time.sleep(10)
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 Exception as ex: # Handle exception as you wish print(ex)
def make_client(self, url=None, apikey=None): """ Creates and returns an instance of the OctoRest client. Parameters: url - the url to the octoprint server apikey - the apikey from the octoprint server found in settings """ if url is None: url = self.url if apikey is None: url = self.apikey try: client = OctoRest(url=url, apikey=apikey) return client except ConnectionError as ex: print(ex)
def add_printer_with_api_key( self, printer_name: str, url: str, api_key: str) -> Tuple[AddPrinterWithApiKeyResult, Optional[Dict]]: if not api_key: return (AddPrinterWithApiKeyResult.BAD_API_KEY, None) # Validate that the url and the API key are working try: OctoRest(url=url, apikey=api_key) except Exception as e: if e is requests.exceptions.ConnectionError or "Provided URL is" in str( e): return (AddPrinterWithApiKeyResult.BAD_URL, None) elif "Forbidden (403)" in str(e): return (AddPrinterWithApiKeyResult.BAD_API_KEY, None) else: raise e printer_info = self._add_printer_no_url_validation( printer_name, url, api_key) return (AddPrinterWithApiKeyResult.SUCCESS, printer_info)
def __init__(self, url, apikey): try: self.client = OctoRest(url=url, apikey=apikey) except ConnectionError as ex: # Handle exception as you wish print(ex)
def test_init_raises_with_bad_auth(self): with pytest.raises(RuntimeError): OctoRest(url=URL, apikey='nope')
class Printer(models.Model): url = models.CharField(max_length=120) apikey = models.CharField(max_length=120) name = models.CharField(max_length=120) IDa = models.CharField(max_length=120) urlCam = models.CharField(max_length=120) client = None def connect(self): #print("conect") try: self.client = OctoRest(url=self.url, apikey=self.apikey) except ConnectionError as ex: print("..............Connect error.....................") print(ex) def waitConnection(self): counter = 0 if(self.getPrinterPowerStatus() == "printer_power_status_off"): return False else: self.connect() while(self.client.connection_info()["current"]["state"] != "Operational" and counter < 40): self.client.connect(baudrate=115200) counter = counter + 1 print("conecting..." + self.client.connection_info()["current"]["state"] + str(counter)) if counter >= 40: return False else: return True def home(self, axes): if self.client == None: self.connect() return self.client.home(axes) def extrude(self): if self.client == None: self.connect() return self.client.extrude(25) def retract(self): if self.client == None: self.connect() return self.client.extrude(-25) def setToolTemp(self, t): if self.client == None: self.connect() return self.client.tool_target(t) def getToolTemp(self): if self.client == None: self.connect() try: if self.client.tool() == {}: return {'actual': 0, 'offset': 0, 'target': 0.0} else: return self.client.tool()["tool0"] except: return None def setBedTemp(self, t): if self.client == None: self.connect() return self.client.bed_target(t) def getBedTemp(self): if self.client == None: self.connect() try: if self.client.bed() == {}: return {'actual': 0, 'offset': 0, 'target': 0.0} else: return self.client.bed()["bed"] except: return None def getName(self): return self.name def getId(self): return self.IDa def getUrl(self): return self.url def getApiKey(self): return self.apikey def getUrlCam(self): return self.urlCam def toggleLed(self): myobj = {'pin': 'r1', 'command': 'update'} url = self.url + "api/plugin/octorelay?apikey=" + self.apikey return requests.post(url, json=myobj) def getLedStatus(self): myobj = {'pin': 'r1', 'command': 'getStatus'} url = self.url + "api/plugin/octorelay?apikey=" + self.apikey x = requests.post(url, json=myobj) dic = json.loads(x.text) return dic['status'] def getPrinterPowerStatus(self): myobj = {'command': 'getPSUState'} url = self.url + "api/plugin/psucontrol?apikey=" + self.apikey x = requests.post(url, json=myobj) dic = json.loads(x.text) print(dic) if dic['isPSUOn'] == False: return "printer_power_status_off" elif dic['isPSUOn'] == True: return "printer_power_status_on" def PrinterPowerOn(self): myobj = {'command': "turnPSUOn"} url = self.url + "api/plugin/psucontrol?apikey=" + self.apikey return requests.post(url, json=myobj) def printerPowerOFf(self): myobj = {'command': "turnPSUOff"} url = self.url + "api/plugin/psucontrol?apikey=" + self.apikey return requests.post(url, json=myobj) def getPrinterInfo(self): if self.client == None: self.connect() try: info = self.client.job_info(); #print(info) return info except Exception as e: print(e) def getError(self): URL = self.TSDurl + "accounts/login/" client = requests.session() errorTSD = False try: client.get(URL, timeout=3) # sets cookie except: errorTSD = True if(errorTSD): print("TSDERROR TIMEOPUT") return "TSDerror" else: csrftoken = client.cookies['csrftoken'] post_data = { "csrfmiddlewaretoken": csrftoken, 'login': self.TSDuser, 'password': self.TSDpass} headers = {'Referer': URL} response = client.post(URL, data=post_data, headers=headers) a = client.get( self.TSDurl + "api/v1/printers/" + self.TSDid ) client = None data = json.loads(a.text) try: return data["normalized_p"] except: return "TSDERROR" def getAllFilesAndFolders(self): r = requests.get(self.url + "api/files?apikey=" + self.apikey + "&recursive=true") print(self.url + "api/files?apikey=" + self.apikey + "&recursive=true") return r.text def getStatus(self): #r = requests.get(self.url[:-1]+":7125/server/info") return None def selectFile(self, filePath): path = "local/" + filePath.replace("@","/") path = "local/" + filePath.replace("*","/") if(self.client == None): self.connect() path = path.replace("@","/") path = path.replace(" ","_") print(path) self.client.select(path) return "done" def deleteFile(self, filePath): path = "local/" + filePath.replace("@","/") if(self.client == None): self.connect() r = requests.delete(self.url + "api/files/" + path + "?apikey=" + self.apikey ) return r.text def createFolder(self, folderPath): if(self.client == None): self.connect() path = folderPath.replace("@","/") data = {'foldername': path} return requests.post(self.url + "api/files/local" + "?apikey=" + self.apikey, data = data) def uploadFile(self, filePath, myfile): if(self.client == None): self.connect() path = filePath.replace("@","/") if(path != "local"): dataForm = {'path': path} else: dataForm = {'path': ""} dataFile = {'file': myfile} return requests.post(self.url + "api/files/local" + "?apikey=" + self.apikey, data = dataForm, files = dataFile) def printSelectedFile(self): if(self.client == None): self.connect() return self.client.start() def print(self, filePath): if(self.client == None): self.connect() self.selectFile(filePath) return self.client.start() def toggle(self): if(self.client == None): self.connect() return self.client.toggle() def cancel(self): if(self.client == None): self.connect() return self.client.cancel() def jog(self, x, y, z): if(self.client == None): self.connect() self.client.jog(x, y, z) return "done" def moveFile(self, name, path): name = name.replace("@","/") path = path.replace("@","/") if(self.client == None): self.connect() return self.client.move(name, path) return self.client.move(name, path)
def client(): return OctoRest(url=URL, apikey=APIKEY, session=None)
def test_init_works_with_good_auth(self): # Should not raise anything OctoRest(url=URL, apikey=APIKEY)
def test_disconnect(self, client): client.disconnect() assert client.state() in ['Offline', 'Closed'] def test_connect(self, client): ''' Since it's hard with betamax fixture to check state() multiple times in one test, this test hopes test_disconnect() was called before it. It is not possible to run it without it in record mode. TODO: Fix this ''' client.connect() cmd_wait(client, 'Detecting baudrate') assert client.state() in ['Connecting', 'Operational', 'Opening serial port'] client.disconnect() assert client.state() in ['Offline', 'Closed'] import json client = OctoRest(url=URL, apikey=APIKEY) client.new_folder('hello') f = client.files(recursive=False) print(json.dumps(f, indent=4)) g = client.files(recursive=True) print(json.dumps(f, indent=4)) print(f == g) print(client.version) client.gcode("M106") client.gcode("M106 \n G28 X Y Z \n M107")
) return print(file_info[0]) file_name = file_info[0]['title'] url = file_info[0]['url_private_download'] os.system("wget -d -O " + file_name + " --header='Authorization: Bearer TOKEN' " + url) os.system("mv " + str(file_name) + " ../uploads") print(printer_client) dir(printer_client) try: printer_client.upload("../uploads/" + file_name) printer_client.select(file_name) except: return except: return print("Uploaded file {}".format(file_info[0]['filetype'])) except: return printer_client = OctoRest(url="http://localhost:5000", apikey="API_KEY") rtm_client = RTMClient(token='TOKEN') rtm_client.start()
def make_client(): try: client = OctoRest(url=ocfg['url'], apikey=ocfg['apikey']) return client except Exception as e: print(e)
class Printer: def __init__(self, bot): self.bot = bot try: self.op_client = OctoRest(url="http://192.168.1.158/", apikey=Config().octopi_api_key) except ConnectionError as ex: logGeneric(ex) @commands.command(name='print', description="Gets the current printer status", brief="Is that 3D print done yet?", pass_context=True) async def print_status(self, context, rest: str = None): job_info = self.op_client.job_info() if rest is None: if job_info["state"] == "Printing": floor_percent = int( (job_info["progress"]["completion"] // 5) * 5) time_elapsed_nice = str( datetime.timedelta( seconds=job_info["progress"]["printTime"])) if job_info["progress"]["printTimeLeft"] is None: time_left_nice = "Calculating..." time_completion = "Waiting for estimate..." else: time_left_nice = str( datetime.timedelta( seconds=job_info["progress"]["printTimeLeft"])) time_completion = self.add_secs( datetime.datetime.now().time(), job_info["progress"] ["printTimeLeft"]).strftime("%I:%M %p") embed = Embed(title="Athol's 3D Printer", description="Printer is currently: Printing", color=0x0080ff) embed.add_field( name="Progress", value="[{}{}](https://github.com/james2hey/Milk) ({:.1f}%)" .format("■" * (floor_percent // 5), "□" * ((100 - floor_percent) // 5), job_info["progress"]["completion"]), inline=True) embed.add_field(name="File", value=job_info["job"]["file"]["name"].replace( ".gcode", ""), inline=False) embed.add_field(name="Time Elapsed", value=time_elapsed_nice, inline=True) embed.add_field(name="Estimated Time Left", value=time_left_nice, inline=True) embed.add_field(name="Estimated Completion Time", value=time_completion, inline=True) await self.bot.send_message(context.message.channel, embed=embed) else: embed = Embed(title="Athol's 3D Printer", description="Printer is currently: {}".format( job_info["state"]), color=0x0080ff) embed.add_field(name="State", value="{}".format(job_info["state"])) await self.bot.send_message(context.message.channel, embed=embed) else: if rest.lower() == "pause": if context.message.author.id == '311429319505346560': err_message = None try: paused = self.op_client.pause() except RuntimeError as e: err_message = "{}".format(e).split("OK:")[1].split( ",")[0].strip() if err_message: await self.bot.send_message( context.message.channel, "Error: {}".format(err_message)) else: await self.bot.send_message(context.message.channel, "Printer paused") else: scones = await self.bot.get_user_info('311429319505346560') await self.bot.send_message( context.message.channel, "Only {} can do that, sorry".format(scones.mention)) elif rest.lower() == "pic": if context.message.author.id == '311429319505346560': self.getImage() await self.bot.send_file(context.message.channel, 'temp/snapshot.jpg') else: scones = await self.bot.get_user_info('311429319505346560') await self.bot.send_message( context.message.channel, "Only {} can do that, sorry".format(scones.mention)) @staticmethod def add_secs(tm, secs): fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second) fulldate = fulldate + datetime.timedelta(seconds=secs) return fulldate.time() @staticmethod def getImage(): img_data = requests.get( "http://192.168.1.158/webcam/?action=snapshot").content with open('temp/snapshot.jpg', 'wb') as handler: handler.write(img_data)
def make_client(): try: client = OctoRest(url="http://octopi.local", apikey="YouShallNotPass") return client except Exception as e: print(e)
from octorest import OctoRest files = [] url = "http://baulne.paulf.tk:5002" api_key = "CC9AFBA1A56747029B3BCD7C6E3AA60E" ender3 = OctoRest(url=url, apikey=api_key) def retrieve_files(): return ender3.files()['files'] def order_files_type(files): return sorted(files, key=lambda i: i['type'])
class Printer: def __init__(self, url, apikey): try: self.client = OctoRest(url=url, apikey=apikey) except ConnectionError as ex: # Handle exception as you wish print(ex) def get_printer_info(self): try: message = "" message += str(self.client.version) + "\n" message += str(self.client.job_info()) + "\n" printing = self.client.printer()['state']['flags']['printing'] if printing: message += "Currently printing!\n" else: message += "Not currently printing...\n" return message except Exception as e: print(e) def home(self): self.client.connect() self.client.home() def setExtruderTemp(self, how): self.client.tool_target(how) def getExtruderTemp(self): dic = self.client.tool() print(self.client.tool()["tool0"]) def test(self): print(self.client.files_info(location="/")) def restartKlipper(self): r = requests.post("http://192.168.0.103:7125/machine/services/restart?service=klipper") return r.text def stuff(self): #r = requests.post('http://192.168.0.103:7125/machine/device_power/on?printer') print(self.client.select("local/Test_3_big.gcode")) def waitConnection(self): counter = 0 self.client.connect(baudrate = 250000) while(self.client.connection_info()["current"]["state"] != "Paused" and counter < 30): counter = counter + 1 print("conecting..." + self.client.connection_info()["current"]["state"] + str(counter)) self.client.users if counter >= 30: print("conection error") return False else: return True def disableMotors(self): self.client.system_commands return True