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 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 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)
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)
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)
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