-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·562 lines (502 loc) · 22.9 KB
/
Copy pathmain.py
File metadata and controls
executable file
·562 lines (502 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
#!/usr/bin/python
# kivy imports
from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.config import Config
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.utils import get_color_from_hex as rgb
from kivy.garden.graph import Graph, MeshLinePlot, SmoothLinePlot
# other imports
import time
import os
from math import sin, cos
import requests
import json
import configparser
import sys
from subprocess import *
import pprint
from collections import deque # Fast pops from the ends of lists
import os_utils
# Temperature lists
hotendactual_list = deque([])
hotendtarget_list = deque([])
bedactual_list = deque([])
bedtarget_list = deque([])
g_hotend_actual = 0
g_hotend_target = 0
g_bed_actual = 0
g_bed_target = 0
# Initialize Temperature lists
temperature_list_size = 201
temperature_graph_time_max = 30000 # Minutes * 10000
for i in range(temperature_list_size):
hotendactual_list.append(0)
hotendtarget_list.append(0)
bedactual_list.append(0)
bedtarget_list.append(0)
# Fill timestamp list with 1000x time vals in seconds
graphtime_list = []
for i in range(temperature_list_size): # Fill the list with zeros
graphtime_list.append(0)
graphtime_list[0] = temperature_graph_time_max
for i in range(temperature_list_size - 1): # Replace values with decreasing seconds from 30 to 0
val = graphtime_list[i] - (temperature_graph_time_max / (temperature_list_size - 1))
graphtime_list[i + 1] = (val)
# Read settings from the config file
settings = configparser.ConfigParser()
settings.read('octoprint.cfg')
host = settings.get('APISettings', 'host')
nicname = settings.get('APISettings', 'nicname')
apikey = settings.get('APISettings', 'apikey')
debug = int(settings.get('Debug', 'debug_enabled'))
hotend_max = int(settings.get('MaxTemps', 'hotend_max'))
bed_max = int(settings.get('MaxTemps', 'bed_max'))
invert_X = int(settings.get('AxisInvert', 'invert_X'))
invert_Y = int(settings.get('AxisInvert', 'invert_Y'))
invert_Z = int(settings.get('AxisInvert', 'invert_Z'))
# Define Octoprint constants
httptimeout = 3 # http request timeout in seconds
printerapiurl = 'http://' + host + '/api/printer'
printheadurl = 'http://' + host + '/api/printer/printhead'
bedurl = 'http://' + host + '/api/printer/bed'
toolurl = 'http://' + host + '/api/printer/tool'
jobapiurl = 'http://' + host + '/api/job'
connectionurl = 'http://' + host + '/api/connection'
commandurl = 'http://' + host + '/api/printer/command'
headers = {'X-Api-Key': apikey, 'content-type': 'application/json'}
if debug:
print("*********** DEBUG ENABLED ************")
print(headers)
bed_temp_val = 0.0
hotend_temp_val = 0.0
jogincrement = 10
platform = sys.platform # Grab platform name for platform specific commands
start_time = time.time()
################################
# Load the Kivy widget layout
Builder.load_file('panels.kv')
class Panels(TabbedPanel):
global bed_max
global hotend_max
def gettemps(self, *args):
global g_hotend_actual
global g_hotend_target
global g_bed_actual
global g_bed_target
self.ids.hotendslider.max = hotend_max
self.ids.bedslider.max = bed_max
try:
if debug:
print('[GET TEMPS] Trying /printer API request to Octoprint...')
r = requests.get(printerapiurl, headers=headers, timeout=httptimeout)
if debug:
print('[GET TEMPS] STATUS CODE: ', str(r.status_code))
except requests.exceptions.RequestException as e:
r = False
if debug:
print('[GET TEMPS] ERROR: Couldn\'t contact Octoprint /printer API')
print(e)
if r and r.status_code == 200:
if debug:
print('[GET TEMPS] JSON Data: ' + str(r.json()))
if r and r.status_code == 200 and 'tool0' in r.json()['temperature']:
printeronline = True
g_hotend_actual = int(r.json()['temperature']['tool0']['actual'])
g_hotend_target = int(r.json()['temperature']['tool0']['target'])
g_bed_actual = int(r.json()['temperature']['bed']['actual'])
g_bed_target = int(r.json()['temperature']['bed']['target'])
printing = r.json()['state']['flags']['printing']
paused = r.json()['state']['flags']['paused']
operational = r.json()['state']['flags']['operational']
if debug:
print(' BED ACTUAL: ' + str(g_bed_actual))
print('HOTEND ACTUAL: ' + str(g_hotend_actual))
print(' PRINTING: ' + str(printing))
print(' PAUSED: ' + str(paused))
print(' OPERATIONAL: ' + str(operational))
# Update text color on Temps tab if values are above 40C
if g_bed_actual > 40:
self.ids.tab3_bed_actual.color = [1, 0, 0, 1]
else:
self.ids.tab3_bed_actual.color = [1, 1, 1, 1]
if g_bed_target > 40:
self.ids.tab3_bed_target.color = [1, 0, 0, 1]
else:
self.ids.tab3_bed_target.color = [1, 1, 1, 1]
if g_hotend_actual > 40:
self.ids.tab3_hotend_actual.color = [1, 0, 0, 1]
else:
self.ids.tab3_hotend_actual.color = [1, 1, 1, 1]
if g_hotend_target > 40:
self.ids.tab3_hotend_target.color = [1, 0, 0, 1]
else:
self.ids.tab3_hotend_target.color = [1, 1, 1, 1]
# Enable/Disable extruder buttons
if g_hotend_actual < 130 or printing or paused:
self.ids.extrude.disabled = True
self.ids.retract.disabled = True
else:
self.ids.extrude.disabled = False
self.ids.retract.disabled = False
# Set pause/resume label on pause button
if paused:
self.ids.pausebutton.text = 'Resume'
else:
self.ids.pausebutton.text = 'Pause'
# Enable/Disable print job buttons
if printing or paused:
self.ids.printbutton.disabled = True
self.ids.cancelbutton.disabled = False
self.ids.pausebutton.disabled = False
else:
self.ids.printbutton.disabled = False
self.ids.cancelbutton.disabled = True
self.ids.pausebutton.disabled = True
# Set position of slider pointer
self.ids.hotendpb.value = (g_hotend_actual / self.ids.hotendslider.max) * 100
self.ids.bedpb.value = (g_bed_actual / self.ids.bedslider.max) * 100
# Update temperature values with new data
self.ids.bed_actual.text = str(g_bed_actual) + u"\u00b0" + ' C'
self.ids.hotend_actual.text = str(g_hotend_actual) + u"\u00b0" + ' C'
if g_bed_target > 0:
self.ids.bed_target.text = str(g_bed_target) + u"\u00b0" + ' C'
else:
self.ids.bed_target.text = 'OFF'
if g_hotend_target > 0:
self.ids.hotend_target.text = str(g_hotend_target) + u"\u00b0" + ' C'
else:
self.ids.hotend_target.text = 'OFF'
else:
if r:
print('Error. API Status Code: ', str(r.status_code)) # Print API status code if we have one
# If we can't get any values from Octoprint just fill values with not available.
self.ids.bed_actual.text = 'N/A'
self.ids.hotend_actual.text = 'N/A'
self.ids.bed_target.text = 'N/A'
self.ids.hotend_target.text = 'N/A'
def home(self, *args):
axis = args[0]
print('HOME AXIS: ' + axis)
if axis == 'xy':
homedata = {'command': 'home', 'axes': ['x', 'y']}
else:
homedata = {'command': 'home', 'axes': ['z']}
try:
if debug:
print('[HOME ' + axis + '] Trying /API request to Octoprint...')
r = requests.post(printheadurl, headers=headers, json=homedata, timeout=httptimeout)
if debug:
print('[HOME ' + axis + '] STATUS CODE: ' + str(r.status_code))
except requests.exceptions.RequestException as e:
r = False
if debug:
print('ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def jogaxis(self, *args):
axis = args[0]
direction = args[1]
global invert_X
global invert_Y
global invert_Z
global jogincrement
invert_axis = {'x': invert_X, 'y': invert_Y, 'z': invert_Z}
print('AXIS: ' + axis)
print('DIRECTION: ' + direction)
print('INCREMENT: ' + str(jogincrement))
if direction == 'up' or direction == 'forward' or direction == 'left':
if invert_axis[axis]:
inc = jogincrement * -1
else:
inc = jogincrement
if direction == 'down' or direction == 'backward' or direction == 'right':
if invert_axis[axis]:
inc = jogincrement
else:
inc = jogincrement * -1
jogdata = {'command': 'jog', axis: inc}
print('JOGDATA: ' + str(jogdata))
try:
if debug:
print('[JOG ' + axis + ' ' + direction + '] Trying /API request to Octoprint...')
r = requests.post(printheadurl, headers=headers, json=jogdata, timeout=httptimeout)
if debug:
print('STATUS CODE: ' + str(r.status_code))
except requests.exceptions.RequestException as e:
r = False
if debug:
print('ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def jogincrement(self, *args):
global jogincrement
if debug:
print('[JOG INCREMENT] Button pressed')
print('[JOG INCREMENT] INC: ' + str(args[0]))
jogincrement = args[0]
def connect(self, *args):
connectiondata = {'command': 'connect', 'port': '/dev/ttyACM0', 'baudrate': 250000,
'save': False, 'autoconnect': False}
try:
if debug:
print('[CONNECT] Trying /job API request to Octoprint...')
print('[CONNECT] ' + connectionurl + str(connectiondata))
r = requests.post(connectionurl, headers=headers, json=connectiondata, timeout=httptimeout)
if debug:
print('[CONNECT] STATUS CODE: ' + str(r.status_code))
print('[CONNECT] RESPONSE: ' + r.text)
except requests.exceptions.RequestException as e:
r = False
if debug:
print('[CONNECT] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def disconnect(self, *args):
disconnectdata = {'command': 'disconnect'}
try:
if debug:
print('[DISCONNECT] Trying /job API request to Octoprint...')
print('[DISCONNECT] ' + connectionurl + str(disconnectdata))
r = requests.post(connectionurl, headers=headers, json=disconnectdata, timeout=httptimeout)
if debug:
print('[DISCONNECT] STATUS CODE: ' + str(r.status_code))
print('[DISCONNECT] RESPONSE: ' + r.text)
except requests.exceptions.RequestException as e:
r = False
if debug:
print('[DISCONNECT] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def setbedtarget(self, *args):
bedsliderval = args[0]
bedtargetdata = {'command': 'target', 'target': bedsliderval}
if debug:
print('[BED TARGET] New Value: ' + str(bedsliderval) + ' C')
try:
if debug:
print('[BED TARGET] Trying /API request to Octoprint...')
r = requests.post(bedurl, headers=headers, json=bedtargetdata, timeout=httptimeout)
if debug:
print ('[BED TARGET] STATUS CODE: ' + str(r.status_code))
except requests.exceptions.RequestException as e:
print('[BED TARGET] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
r = False
def sethotendtarget(self, *args):
hotendsliderval = args[0]
hotendtargetdata = {'command': 'target', 'targets': {'tool0': hotendsliderval}}
if debug:
print('[HOTEND TARGET] New Value: ' + str(hotendsliderval) + ' C')
try:
if debug:
print('[HOTEND TARGET] Trying /API request to Octoprint...')
r = requests.post(toolurl, headers=headers, json=hotendtargetdata, timeout=httptimeout)
if debug:
print('[HOTEND TARGET] STATUS CODE: ' + str(r.status_code))
except requests.exceptions.RequestException as e:
r = False
if debug:
print('[HOTEND TARGET] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def extrudefilament(self, *args):
posneg = args[0]
extrudeamount = (int(self.ids.extrudeamount.text) * posneg)
if debug:
print('[EXTRUDE FILAMENT] Amount: ' + str(extrudeamount))
extrudedata = {'command': 'extrude', 'amount': extrudeamount}
if debug:
print('[EXTRUDE FILAMENT] Extruding: ' + str(extrudeamount) + ' mm')
try:
if debug:
print ('[EXTRUDE FILAMENT] Trying /API request to Octoprint...')
r = requests.post(toolurl, headers=headers, json=extrudedata, timeout=httptimeout)
if debug:
print('[EXTRUDE FILAMENT] STATUS CODE: ' + str(r.status_code))
except requests.exceptions.RequestException as e:
r = False
if debug:
print('[EXTRUDE FILAMENT] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def fanspeed(self, *args):
speed_percent = int(args[0])
speed_pwm = int(speed_percent * 2.551)
fan_gcode = 'M106 S' + str(speed_pwm)
fancmd = {"commands": [fan_gcode]}
if debug:
print('[FAN CONTROL] Speed: ' + str(speed_pwm))
print('[FAN CONTROL] ' + str(fancmd))
try:
r = requests.post(commandurl, headers=headers, json=fancmd, timeout=httptimeout)
except requests.exceptions.RequestException as e:
r = False
def jobcontrol(self, *args):
jobcommand = args[0]
jobdata = {'command': jobcommand}
try:
if debug:
print ('[JOB COMMAND] Trying /API request to Octoprint...')
# Send job request to the job api
r = requests.post(jobapiurl, headers=headers, json=jobdata, timeout=httptimeout)
if debug:
print ('[JOB COMMAND] STATUS CODE: ' + str(r.status_code))
print ('[JOB COMMAND] COMMAND: ' + str(jobcommand))
print ('[JOB COMMAND] BUTTON TEXT: ' + self.ids.pausebutton.text)
# Update pause button text
if r.status_code == 204 and jobcommand == 'pause' and self.ids.pausebutton.text == 'Pause':
self.ids.pausebutton.text = 'Resume'
elif r.status_code == 204 and jobcommand == 'pause' and self.ids.pausebutton.text == 'Resume':
self.ids.pausebutton.text = 'Pause'
except requests.exceptions.RequestException as e:
r = False
if debug:
print ('[JOB COMMAND] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
def getstats(self, *args):
try:
if debug:
print ('[GET STATS] Trying /job API request to Octoprint...')
r = requests.get(jobapiurl, headers=headers, timeout=1)
except requests.exceptions.RequestException as e:
r = False
if debug:
print('[GET STATS] ERROR: Couldn\'t contact Octoprint /job API')
print(e)
if r and r.status_code == 200:
if debug:
print ('[GET STATS] JSON Data: ' + str(r.json()))
printerstate = r.json()['state']
jobfilename = r.json()['job']['file']['name']
jobpercent = r.json()['progress']['completion']
jobprinttime = r.json()['progress']['printTime']
jobprinttimeleft = r.json()['progress']['printTimeLeft']
if debug:
print ('[GET STATS] Printer state: ' + printerstate)
print ('[GET STATS] Job percent: ' + str(jobpercent) + '%')
if jobfilename is not None:
jobfilenamefull = jobfilename
jobfilename = jobfilename[:25] # Shorten filename to 25 characters
self.ids.jobfilename.text = jobfilename
self.ids.jobfilenamefull.text = jobfilenamefull
else:
self.ids.jobfilename.text = '-'
if printerstate is not None:
self.ids.printerstate.text = printerstate
self.ids.printerstate2.text = printerstate
self.ids.printerstate3.text = printerstate
else:
self.ids.printerstate.text = 'Unknown'
self.ids.printerstate2.text = 'Unknown'
self.ids.printerstate3.text = 'Unknown'
if jobpercent is not None:
jobpercent = int(jobpercent)
self.ids.jobpercent.text = str(jobpercent) + '%'
self.ids.progressbar.value = jobpercent
else:
self.ids.jobpercent.text = '---%'
self.ids.progressbar.value = 0
if jobprinttime is not None:
hours = int(jobprinttime / 60 / 60)
if hours > 0:
minutes = int(jobprinttime / 60) - (60 * hours)
else:
minutes = int(jobprinttime / 60)
seconds = int(jobprinttime % 60)
self.ids.jobprinttime.text = str(hours).zfill(2) + ':' + \
str(minutes).zfill(2) + ':' + str(seconds).zfill(2)
else:
self.ids.jobprinttime.text = '00:00:00'
if jobprinttimeleft is not None:
hours = int(jobprinttimeleft / 60 / 60)
if hours > 0:
minutes = int(jobprinttimeleft / 60) - (60 * hours)
else:
minutes = int(jobprinttimeleft / 60)
seconds = int(jobprinttimeleft % 60)
self.ids.jobprinttimeleft.text = str(hours).zfill(2) + \
':' + str(minutes).zfill(2) + ':' + str(seconds).zfill(2)
else:
self.ids.jobprinttimeleft.text = '00:00:00'
else:
if r:
print ('Error. API Status Code: ' + str(r.status_code)) # Print API status code if we have one
# If we can't get any values from Octoprint API fill with these values.
self.ids.jobfilename.text = 'N/A'
self.ids.printerstate.text = 'Unknown'
self.ids.printerstate2.text = 'Unknown'
self.ids.printerstate3.text = 'Unknown'
self.ids.jobpercent.text = 'N/A'
self.ids.progressbar.value = 0
self.ids.jobprinttime.text = '--:--:--'
self.ids.jobprinttimeleft.text = '--:--:--'
def update_ip_addr(self, *args):
ip_addr = os_utils.get_ip_address(platform, nicname, debug)
if ip_addr:
self.ids.ip_addr.text = str(ip_addr)
else:
self.ids.ip_addr.text = 'Unknown Platform'
def button_restart_os(self, *args):
command = args[0]
os_utils.restart_os(platform, command, debug)
def button_exit_app(self, *args):
os_utils.exit_app()
def button_restart_networking(self, *args):
os_utils.restart_networking(platform, nicname, debug)
def graphpoints(self, *args):
global g_hotend_actual
global g_hotend_target
global g_bed_actual
global g_bed_target
hotendactual_plot = SmoothLinePlot(color=[1, 0, 0, 1])
hotendtarget_plot = MeshLinePlot(color=[1, 0, 0, .75])
bedactual_plot = SmoothLinePlot(color=[0, 0, 1, 1])
bedtarget_plot = MeshLinePlot(color=[0, 0, 1, .75])
# Update temperature graph arrays with new data
hotendactual_list.popleft()
hotendactual_list.append(g_hotend_actual)
hotendtarget_list.popleft()
hotendtarget_list.append(g_hotend_target)
bedactual_list.popleft()
bedactual_list.append(g_bed_actual)
bedtarget_list.popleft()
bedtarget_list.append(g_bed_target)
# Build list of plot points tuples from temp and time lists
hotendactual_points_list = []
hotendtarget_points_list = []
bedactual_points_list = []
bedtarget_points_list = []
for i in range(temperature_list_size):
hotendactual_points_list.append((graphtime_list[i] / 1000.0 * -1, int(hotendactual_list[i])))
hotendtarget_points_list.append((graphtime_list[i] / 1000.0 * -1, int(hotendtarget_list[i])))
bedactual_points_list.append((graphtime_list[i] / 1000.0 * -1, int(bedactual_list[i])))
bedtarget_points_list.append((graphtime_list[i] / 1000.0 * -1, int(bedtarget_list[i])))
# Remove all old plots from the graph before drawing new ones
while(len(self.my_graph.plots) != 0):
# TODO - add a counter so we can abort after a certain number of tries.
self.my_graph.remove_plot(self.my_graph.plots[0])
# Draw the new graphs
hotendactual_plot.points = hotendactual_points_list
self.my_graph.add_plot(hotendactual_plot)
hotendtarget_plot.points = hotendtarget_points_list
self.my_graph.add_plot(hotendtarget_plot)
bedactual_plot.points = bedactual_points_list
self.my_graph.add_plot(bedactual_plot)
bedtarget_plot.points = bedtarget_points_list
self.my_graph.add_plot(bedtarget_plot)
class TabbedPanelApp(App):
def build(self):
Window.size = (800, 480)
panels = Panels()
Clock.schedule_once(panels.gettemps, 0.5) # Update bed and hotend at startup
Clock.schedule_interval(panels.gettemps, 5) # Update bed and hotend temps every 5 seconds
Clock.schedule_interval(panels.getstats, 5) # Update job stats every 5 seconds
Clock.schedule_once(panels.update_ip_addr, 0.5) # Update IP addr once right away
Clock.schedule_interval(panels.update_ip_addr, 30) # Then update IP every 30 seconds
Clock.schedule_once(panels.graphpoints, 1) # Update graphs right away at startup
graph_interval = ((temperature_graph_time_max / 1000) /(temperature_list_size - 1)) * 60
print('Graph update interval:', graph_interval, ' seconds')
Clock.schedule_interval(panels.graphpoints, graph_interval) # Update graphs every 10 seconds
return panels
if __name__ == '__main__':
TabbedPanelApp().run()