Skip to content

Instantly share code, notes, and snippets.

@Xoma163
Last active May 4, 2024 11:01
Show Gist options
  • Save Xoma163/de9eb65c43dc52e6f80ce057f982e95f to your computer and use it in GitHub Desktop.
Save Xoma163/de9eb65c43dc52e6f80ce057f982e95f to your computer and use it in GitHub Desktop.
Данный скрипт позволяет автоматически подключать 3D принтеры в Octoprint посредством API. Надоело жмать кнопочку. Повесить на кронтаб каждую минуту
class Printer:
def __init__(self, name, api_key, url):
self.name = name
self.octoprint_api_key = api_key
self.headers = {"X-Api-Key": self.octoprint_api_key, "Content-Type": "application/json"}
self.url = url
self.port = None
self.connection_info = self.get_connection_info()
def get_connection_info(self):
return requests.get(f"{self.url}/api/connection", headers=self.headers).json()
def disconnect(self):
data = {
"command": "disconnect"
}
r = requests.post(f"{self.url}/api/connection", data=json.dumps(data), headers=self.headers)
if r.status_code != 204:
raise Exception
print(f"Отключение принтера {self.name}")
def connect(self) -> bool:
data = {
"command": "connect",
"port": self.port,
"baudrate": 115200,
"save": True,
"autoconnect": True
}
r = requests.post(f"{self.url}/api/connection", data=json.dumps(data), headers=self.headers)
if r.status_code == 204:
time.sleep(3)
connection_info = self.get_connection_info()
if connection_info['current']['state'] == "Opening serial connection":
print("Принтер подключился к неверному порту. Переподключение")
self.disconnect()
raise RuntimeError
print(f"Подключение принтера {self.name} порта {self.port}")
def main():
printers = [
Printer("FBG5", "OCTOPRINT_API_KEY1", "http://IP1:PORT1"),
Printer("FBG6", "OCTOPRINT_API_KEY2", "http://IP2:PORT2")
]
for printer in printers:
state = printer.connection_info["current"]["state"]
if state not in ["Closed", 'Opening serial connection']:
continue
ports = printer.connection_info['options']['ports']
# Проставление приоритетного порта если он имеется
port_pref = printer.connection_info['options']['portPreference']
if port_pref:
try:
port_pref_index = ports.index(port_pref)
ports.insert(0, ports.pop(port_pref_index))
except IndexError:
pass
for port in ports:
try:
printer.port = port
printer.connect()
break
except RuntimeError as e:
print(e)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment