-
Notifications
You must be signed in to change notification settings - Fork 39
/
web_dwc2.py
1657 lines (1438 loc) · 50.5 KB
/
web_dwc2.py
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# A Json api to get data from klippy through http
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import json
import threading
from multiprocessing import Process, Queue
# for webserver
import tornado.web
import tornado.gen
import base64
import uuid
import os
import datetime
import re
import time
import util
import shutil
import gcode as kgcode
import serial
#
class web_dwc2:
##
# Stuff arround klippers extras logic
##
# init who?
def __init__(self, config):
self.klipper_ready = False
self.popup = None
self.message = None
# get config
self.config = config
self.adress = config.get( 'listen_adress', "127.0.0.1" )
self.port = config.getint( "listen_port", 4711 )
self.webpath = config.get( 'web_path', "dwc2/web" )
self.printername = config.get( 'printer_name', "Klipper" )
# klippy objects
self.current_tool = -1
self.bed_mesh = None
self.printer = config.get_printer()
self.reactor = self.printer.get_reactor()
self.gcode = self.printer.lookup_object('gcode')
self.gcode_io = self.printer.lookup_object("gcode_io")
self.configfile = self.printer.lookup_object('configfile').read_main_config()
self.stepper_enable = self.printer.load_object(config, "stepper_enable")
# gcode execution needs
self.gcode_queue = [] # containing gcode user pushes from dwc2
self.gcode_reply = [] # contains the klippy replys
self.klipper_macros = []
self.mutex = self.reactor.mutex()
# once klipper is ready start pre_flight function - not happy with this. If klipper fails to launch -> no web if?
self.printer.register_event_handler("klippy:ready", self.handle_ready)
self.printer.register_event_handler("klippy:disconnect", self.shutdown)
self.start_time = time.time()
# grab stuff from config file
self.klipper_config = self.printer.get_start_args()['config_file']
self.sdpath = self.configfile.getsection("virtual_sdcard").get("path", None)
self.sdpath = os.path.normpath(os.path.expanduser(self.sdpath))
if not self.sdpath:
logging.error( "DWC2 failed to start, no sdcard configured" )
return
self.kin_name = self.configfile.getsection("printer").get("kinematics")
self.web_root = self.sdpath + "/" + self.webpath
if not os.path.isfile( self.web_root + "/" + "index.html" ):
logging.error( "DWC2 failed to start, no webif found in " + self.web_root )
return
self.gcode.register_output_handler(self.gcode_response)
# manage client sessions
self.sessions = {}
self.status_0 = {}
self.status_1 = {}
self.status_2 = {}
self.status_3 = {}
self.file_infos = {} # just read files once
self.dwc2()
logging.basicConfig(level=logging.DEBUG)
# function once reactor calls, once klipper feels good
def handle_ready(self):
# klippy related
self.current_tool = 0
self.chamber = self.printer.lookup_object('chamber', None)
self.heater_bed = self.printer.lookup_object('heater_bed', None)
self.fan = self.printer.lookup_object('fan', None)
self.sdcard = self.printer.lookup_object('virtual_sdcard', None)
self.toolhead = self.printer.lookup_object('toolhead', None)
# hopeflly noone get more than 4 extruders up :D
self.extruders = [ self.printer.lookup_object('extruder', None) ]
for i in range(1,10):
app = self.printer.lookup_object('extruder%d' % (i,), None)
if app:
self.extruders.append(app)
self.kinematics = self.toolhead.get_kinematics()
# print data for tracking layers during print
self.print_data = {} # printdata/layertimes etc
self.klipper_ready = True
self.get_klipper_macros()
# registering command
self.gcode.register_command( 'M292', self.cmd_M292,
desc="okay button in DWC2")
# reactor calls this on klippy restart
def shutdown(self):
# kill the thread here
logging.info( "DWC2 shuting down - as klippy is shutdown" )
self.ioloop.stop()
self.http_server.stop()
self.sessions = {}
##
# Webserver and related
##
# launch webserver
def dwc2(self):
def tornado_logger(req):
fressehaltn = []
fressehaltn = [ "/favicon.ico", "/rr_status?type=1", "/rr_status?type=2", "/rr_status?type=3", "/rr_reply", "/rr_config" ]
values = [str(time.time())[-8:], req.request.remote_ip, req.request.method, req.request.uri]
if req.request.uri not in fressehaltn:
logging.info("DWC2:" + " - ".join(values)) # bind this to debug later
def launch_tornado(application):
#time.sleep(10) # delay startup so dwc2 can timeout
logging.info( "DWC2 starting at: http://" + str(self.adress) + ":" + str(self.port) )
self.http_server = tornado.httpserver.HTTPServer( application, max_buffer_size=500*1024*1024 )
self.http_server.listen( self.port )
self.ioloop = tornado.ioloop.IOLoop.current()
self.ioloop.start()
def debug_console(self):
logging.debug( "Start debbug console:\n")
import pdb; pdb.set_trace()
#
cookie_secret = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes) # random cookie
# define the threading aplication
application = tornado.web.Application(
[
tornado.web.url(r"/css/(.*)", tornado.web.StaticFileHandler, {"path": self.web_root + "/css/"}),
tornado.web.url(r"/js/(.*)", tornado.web.StaticFileHandler, {"path": self.web_root + "/js/"}),
tornado.web.url(r"/fonts/(.*)", tornado.web.StaticFileHandler, {"path": self.web_root + "/fonts/"}),
tornado.web.url(r"/(rr_.*)", self.req_handler, { "web_dwc2": self } ),
tornado.web.url(r"/.*", self.dwc_handler,{"p_": self.web_root}, name="main"),
],
cookie_secret=cookie_secret,
log_function=tornado_logger)
self.tornado = threading.Thread( target=launch_tornado, args=(application,) )
self.tornado.daemon = True
self.tornado.start()
#dbg = threading.Thread( target=debug_console, args=(self,) )
#dbg.start()
# the main webpage to serve the client browser itself
class dwc_handler(tornado.web.RequestHandler):
def initialize(self, p_):
self.web_root = p_
def get(self):
def index():
rq_path = self.web_root + "/index.html"
self.render( rq_path )
if self.request.uri == "/": # redirect ti index.html(dwc2)
index()
elif ".htm" in self.request.uri: # covers others like dwc1
self.render( self.web_root + self.request.uri )
elif ".json" in self.request.uri: # covers dwc1 settingsload
if os.path.isfile(self.web_root + self.request.uri):
pass
else:
self.write( { "err": 1 } )
elif os.path.isfile(self.web_root + self.request.uri):
with open(self.web_root + self.request.uri, "rb") as f:
self.write( f.read() )
self.finish()
else:
logging.warn( "DWC2 - unhandled request in dwc_handler: " + self.request.uri + " redirecting to index.")
index()
#for handling request dwc2 is sending
class req_handler(tornado.web.RequestHandler):
def initialize(self, web_dwc2):
self.web_dwc2 = web_dwc2
self.repl_ = {"err":1}
@tornado.gen.coroutine
def get(self, *args):
if self.request.remote_ip not in self.web_dwc2.sessions.keys() and "rr_connect" not in self.request.uri and self.request.remote_ip != '127.0.0.1':
# response 408 timeout to force the webif reload after klippy restarts us
self.clear()
self.set_status(408)
self.finish()
return
# dwc connect request
if "rr_connect" in self.request.uri:
self.repl_ = self.web_dwc2.rr_connect(self)
# there is no rr_configfile so return empty
elif "rr_configfile" in self.request.uri:
self.repl_ = { "err" : 0 }
elif "rr_config" in self.request.uri:
self.repl_ = self.web_dwc2.rr_config()
# filehandling - delete files/folders
elif "rr_delete" in self.request.uri:
self.repl_ = self.web_dwc2.rr_delete( self )
# disconnect
elif "/rr_disconnect" in self.request.uri:
self.repl_ = { "err" : 0 }
# filehandling . download
elif "rr_download" in self.request.uri:
self.repl_ = self.web_dwc2.rr_download(self)
# filehandling - dirlisting
elif "rr_filelist" in self.request.uri:
self.repl_ = self.web_dwc2.rr_filelist(self)
# filehandling - dirlisting for dwc 1
elif "rr_files" in self.request.uri:
self.repl_ = self.web_dwc2.rr_files(self)
# filehandling - fileinfo / gcodeinfo
elif "rr_fileinfo" in self.request.uri:
self.repl_ = yield self.web_dwc2.rr_fileinfo(self)
# gcode request
elif "rr_gcode" in self.request.uri:
self.repl_ = self.web_dwc2.rr_gcode( self )
return
# filehandling - dircreation
elif "rr_mkdir" in self.request.uri:
self.web_dwc2.rr_mkdir(self)
return
elif "rr_move" in self.request.uri:
self.repl_ = self.web_dwc2.rr_move(self)
# gcode reply
elif "rr_reply" in self.request.uri:
self.web_dwc2.rr_reply(self)
return
# status replys
elif "rr_status" in self.request.uri:
if not self.web_dwc2.klipper_ready:
self.web_dwc2.rr_status_0()
self.repl_ = self.web_dwc2.status_0
else:
# there are 3 types of status requests:
t_ = int( self.get_argument('type') )
if t_ == 1:
self.web_dwc2.rr_status_1()
self.repl_ = self.web_dwc2.status_1
elif t_ == 2:
self.web_dwc2.rr_status_2()
self.repl_ = self.web_dwc2.status_2
elif t_ == 3:
self.web_dwc2.rr_status_3()
self.repl_ = self.web_dwc2.status_3
else:
logging.warn(" DWC2 - error in rr_status \n" + str(t_) )
if self.repl_ == {"err":1}:
logging.warn("DWC2 - unhandled ?GET? " + self.request.uri)
try:
if self.repl_:
self.write( json.dumps(self.repl_) )
except Exception as e:
logging.warn( "DWC2 - error in write: " + str(e) )
def post(self, *args):
# filehandling - uploads
if "rr_upload" in self.request.uri:
self.repl_ = self.web_dwc2.rr_upload(self)
try:
self.write( json.dumps(self.repl_) )
except Exception as e:
logging.warn( "DWC2 - error in write: " + str(e) )
def decode_argument(self, value, name=None):
return value.encode('UTF-8') if isinstance(value, unicode) else value
##
# All the crazy shit dc42 fiddled together in c
##
# dwc rr_connect
def rr_connect(self, web_):
# better error?
repl_ = {
"err":0,
"sessionTimeout":8000, # config value?
"boardType":"unknown" # has klippy this data?
}
user_cookie = web_.request.headers.get("Cookie")
user_ip = web_.request.remote_ip
self.sessions[user_ip] = user_cookie
return repl_
# dwc rr_config
def rr_config(self):
try:
max_acc = self.toolhead.max_accel
max_vel = self.toolhead.max_velocity
rails_ = self.kinematics.rails
extru_ = self.extruders
except Exception as e:
max_acc = []
max_vel = []
rails_ = []
extru_ = []
ax_ = [[],[]]
for r_ in rails_:
min_pos, max_pos = r_.get_range()
ax_[0].append(min_pos)
ax_[1].append(max_pos)
repl_ = {
"axisMins": [ x for x in ax_[0] ],
"axisMaxes": [ x for x in ax_[1] ],
"accelerations": [ max_acc for x in ax_[0] ],
"currents": [ 0 for x in ax_[0] ] + [ 0 for ex_ in extru_ if ex_ is not None ] , # can we fetch data from tmc drivers here ?
"firmwareElectronics": util.get_cpu_info(),
"firmwareName": "Klipper",
"firmwareVersion": self.printer.get_start_args()['software_version'],
"dwsVersion": self.printer.get_start_args()['software_version'],
"firmwareDate": "2018-12-24b1", # didnt get that from klippy
"idleCurrentFactor": 30,
"idleTimeout": 30,
"minFeedrates": [ 5 for x in ax_[0] ] + [ 5 for ex_ in extru_ if ex_ is not None ] ,
"maxFeedrates": [ max_vel for x in ax_[0] ] + [ min(75,max_vel) for ex_ in extru_ if ex_ is not None ] # unitconversion ?
}
return repl_
# simple dir/fileremover
def rr_delete(self, web_):
# lazymode_
path_ = self.sdpath + web_.get_argument('name').replace("0:", "")
if os.path.isdir(path_):
shutil.rmtree(path_)
if os.path.isfile(path_):
os.remove(path_)
if path_ in self.file_infos.keys():
self.file_infos.pop(path_, None)
return {'err': 0}
# dwc rr_download - lacks logging
def rr_download(self, web_):
path_ = self.sdpath + web_.get_argument('name').replace("0:", "")
# ovverride for config file
if "/sys/" in path_ and "config.g" in web_.get_argument('name').replace("0:", ""):
path_ = self.klipper_config
# handle heigthmap
if 'heightmap.csv' in path_:
repl_ = self.get_heigthmap()
if repl_:
with open(path_, "w") as f:
for line in repl_:
f.write( line + '\n')
if os.path.isfile(path_):
# handles regular files
web_.set_header( 'Content-Type', 'application/force-download' )
web_.set_header( 'Content-Disposition', 'attachment; filename=%s' % os.path.basename(path_) )
with open(path_, "rb") as f:
web_.write( f.read() )
else:
return {"err":1}
# dwc rr_files - dwc1 thing
def rr_files(self, web_):
path_ = self.sdpath + web_.get_argument('dir').replace("0:", "")
repl_ = {
"dir": web_.get_argument('dir') ,
"first": web_.get_argument('first', 0) ,
"files": [] ,
"next": 0 ,
"err": 0
}
# if rrf is requesting directory, it has to be there.
if not os.path.exists(path_):
os.makedirs(path_)
# append elements to files list matching rrf syntax
for el_ in os.listdir(path_):
el_path = path_ + "/" + el_
repl_['files'].append( "*" + str(el_) if os.path.isdir(el_path) else str(el_) )
return repl_
# dwc rr_filelist
def rr_filelist(self, web_):
path_ = self.sdpath + web_.get_argument('dir').replace("0:", "")
# creating the infoblock
repl_ = {
"dir": web_.get_argument('dir') ,
"first": web_.get_argument('first', 0) ,
"files": [] ,
"next": 0
}
# if rrf is requesting directory, it has to be there.
if not os.path.exists(path_):
os.makedirs(path_)
# whitespace uploads via nfs/samba
for file in os.listdir(path_):
os.rename(os.path.join(path_, file), os.path.join(path_, file.replace(' ', '_')))
# append elements to files list matching rrf syntax
for el_ in os.listdir(path_):
el_path = path_ + "/" + str(el_)
repl_['files'].append({
"type": "d" if os.path.isdir(el_path) else "f" ,
"name": str(el_) ,
"size": os.stat(el_path).st_size ,
"date": datetime.datetime.fromtimestamp(os.stat(el_path).st_mtime).strftime("%Y-%m-%dT%H:%M:%S")
})
# add klipper macros as virtual files
if "/macros" in web_.get_argument('dir').replace("0:", ""):
for macro_ in self.klipper_macros:
repl_['files'].append({
"type": "f" ,
"name": macro_ ,
"size": 1 ,
"date": datetime.datetime.fromtimestamp(os.stat(self.klipper_config).st_mtime).strftime("%Y-%m-%dT%H:%M:%S")
})
# virtual config file
elif "/sys" in web_.get_argument('dir').replace("0:", ""):
repl_['files'].append({
"type": "f",
"name": "config.g" ,
"size": os.stat(self.klipper_config).st_size ,
"date": datetime.datetime.fromtimestamp(os.stat(self.klipper_config).st_mtime).strftime("%Y-%m-%dT%H:%M:%S")
})
return repl_
# dwc fileinfo - getting gcode info
@tornado.gen.coroutine
def rr_fileinfo(self, web_):
try:
path_ = self.sdpath + web_.get_argument('name').replace("0:", "")
except:
path_ = self.sdcard.current_file.name
if not os.path.isfile(path_):
return { "err": 1 }
if not path_ in self.file_infos.keys():
dict_ = Queue()
proc_ = Process(target=self.read_gcode, args=(path_,dict_))
proc_.start()
proc_.join(5)
self.file_infos[path_] = dict_.get()
return self.file_infos[path_]
# dwc rr_gcode - append to gcode_queue
def rr_gcode(self, web_):
# handover to klippy as: [ "G28", "M114", "G1 X150", etc... ]
gcodes = str( web_.get_argument('gcode') ).replace('0:', '').replace('"', '').split("\n")
rrf_commands = {
'G10': self.cmd_G10 , # set heaters temp
'M0': self.cmd_M0 , # cancel SD print
'M24': self.cmd_M24 , # resume sdprint
'M25': self.cmd_M25 , # pause print
'M32': self.cmd_M32 , # Start sdprint
'M98': self.cmd_M98 , # run macro
'M106': self.cmd_M106 , # set fan
'M120': self.cmd_M120 , # save gcode state
'M121': self.cmd_M121 , # restore gcode state
'M140': self.cmd_M140 , # set bedtemp(limit to 0 mintemp)
'M290': self.cmd_M290 , # set babysteps
'M999': self.cmd_M999 # issue restart
}
# allow - set heater, cancelprint, set bed, ,pause, resume, set fan, set speedfactor, set extrusion multipler, babystep, ok in popup
midprint_allow = [ 'DUMP_TMC', 'G10', 'GET_POSITION', 'HELP', 'M0', 'M140', 'M24', 'M25', 'M104', 'M106', 'M107', 'M112', 'M114', 'M115', 'M140', 'M204', 'M220', 'M221', 'M290', 'M292', 'QUERY_FILAMENT_SENSOR', 'SET_TMC_CURRENT', 'SET_PIN',
'SET_PRESSURE_ADVANCE', 'SET_VELOCITY_LIMIT', 'T' ]
# Handle emergencys - just do it now
for code in gcodes:
if 'M112' in code:
self.cmd_M112(0)
# start to prepare commands
while gcodes:
# parse commands
params, gcmd = self.parse_params(gcodes.pop(0))
# defaulting to original
handover = params['#original']
# handle toolchanges
if re.match('^T(-)?\d$', params['#command']):
self.current_tool = abs(int(params['T']))
if params['#command'] == 'T-1':
continue
# prevent midprint accidents
stat_ = self.get_printer_status()
if stat_ in [ 'P', 'D', 'R' ] and params['#command'] not in midprint_allow :
web_.write( json.dumps({'buff': 0, 'err': 0}) )
continue
# rewrite rrfs specials to klipper readable format
if params['#command'] in rrf_commands.keys():
func_ = rrf_commands.get(params['#command'])
handover = func_(params)
if handover == 0:
self.gcode_reply.append("ok\n")
# if we set things directly in klipper we dont need to pipe gcodes
if handover:
self.gcode_queue.append(handover)
web_.write( json.dumps({'buff': 1, 'err': 0}) )
web_.finish()
self.reactor.register_callback(self.gcode_reactor_callback,waketime=self.reactor.monotonic() + 0.1)
# dwc rr_move - backup printer.cfg
def rr_move(self, web_):
if "/sys/" in web_.get_argument('old').replace("0:", "") and "config.g" in web_.get_argument('old').replace("0:", ""):
src_ = self.klipper_config
dst_ = self.klipper_config + ".backup"
else:
src_ = self.sdpath + web_.get_argument('old').replace("0:", "")
dst_ = self.sdpath + web_.get_argument('new').replace("0:", "")
try:
shutil.move( src_ , dst_)
except Exception as e:
return {"err": 1}
return {"err": 0}
# dwc rr_mkdir
def rr_mkdir(self, web_):
path_ = self.sdpath + web_.get_argument('dir').replace("0:", "").replace(' ', '_')
if not os.path.exists(path_):
os.makedirs(path_)
return {'err': 0}
return {'err': 1}
# dwc rr_reply - fetces gcodes
def rr_reply(self, web_):
while self.gcode_reply:
msg = self.gcode_reply.pop(0).replace("!!", "Error: ").replace("//", "Warning: ")
web_.write( msg )
# rr_status_0 if klipper is down/failed to start
def rr_status_0(self):
# just put in things really needed to make dwc2 happy
if self.status_0.get("output", {}).get("message", None) :
self.status_0.update({ "output": {} })
self.message = None
self.status_0.update({
"status": self.get_printer_status(),
"seq": len(self.gcode_reply),
"coords": {
"xyz": [] ,
"machine": [] ,
"extr": []
},
"speeds": {},
"sensors": {
"fanRPM": 0
},
"params": {
"fanPercent": [] ,
"extrFactors": []
} ,
"temps": {
"bed": { "active": 0 },
"state": [],
"extra": [{}],
"current": [],
"tools": {
"active": []
},
"names": []
} ,
"probe": {} ,
"axisNames": "" ,
"tools": [] ,
"volumes": 1,
"mountedVolumes": 1 ,
"name": self.printername
})
if self.popup:
self.status_0.update(
self.popup
)
# dwc rr_status 1
def rr_status_1(self):
now = self.reactor.monotonic() + 0.25
extr_stat = self.get_extr_stats(now)
bed_stats = self.get_bed_stats(now)
gcode_stats = self.gcode.get_status(now)
if self.fan:
fan_stats = [ self.fan.get_status(now) ] # this can be better
else:
fan_stats = []
if self.status_1.get("output", {}).get("message", None) :
self.status_1.update({ "output": {} })
self.message = None
self.status_1.update({
"status": self.get_printer_status(),
"coords": {
"axesHomed": self.get_axes_homed(),
"xyz": self.toolhead.get_position()[:3] ,
"machine": [ 0, 0, 0 ], # what ever this is? no documentation.
"extr": self.toolhead.get_position()[3:]
},
"speeds": {
"requested": gcode_stats['speed'] / 60 * gcode_stats['speed_factor'] ,
"top": 0 # not available on klipepr
},
"currentTool": self.current_tool, # must be at least 1 ! learned the hardway....
"params": {
"atxPower": 0,
"fanPercent": [ fan_['speed']*100 for fan_ in fan_stats ] ,
"speedFactor": gcode_stats['speed_factor'] * 100,
"extrFactors": [ gcode_stats['extrude_factor'] * 100 ],
"babystep": gcode_stats['homing_zpos']
},
"seq": len(self.gcode_reply),
"sensors": {
"probeValue": 0,
"fanRPM": 0
},
"temps": {
"bed": {
"current": bed_stats['actual'] ,
"active": bed_stats['target'] ,
"state": bed_stats['state'] ,
"heater": 0
},
#"chamber": {
# "current": 19.5,
# "active": 0,
# "state": 0,
# "heater": 2
#},
"current": [ bed_stats['actual'] ] + [ ex_['actual'] for ex_ in extr_stat ] ,
"state": [ bed_stats['state'] ] + [ ex_['state'] for ex_ in extr_stat ] ,
"tools": {
"active": [ [ ex_['target'] ] for ex_ in extr_stat ],
"standby": [ [ 0 ] for ex_ in extr_stat ]
},
"extra": [
{
"name": "*MCU",
"temp": 0
}
]
},
"time": time.time() - self.start_time ,
#https://github.com/chrishamm/DuetWebControl/blob/92daf5d98db5def091a3f1a9d4324e1b953fc649/src/store/machine/connector/PollConnector.js#L470
#"output": {
# "message": "Titten!"
#}
#"output": {
# "msgBox": {
# "mode": 2,
# "title": "testtitle",
# "msg": "hello world",
# "timeout": 5000, # can be zero?
# "controls": 0
# }
#} # ok is M292
})
if self.message:
self.status_1.update(
self.message
)
if self.popup:
self.status_1.update(
self.popup
)
if self.chamber:
chamber_stats = self.chamber.get_status(0)
self.status_1['temps'].update({
"chamber": {
"current": chamber_stats.get("temp") ,
"active": chamber_stats.get("target", -1) ,
"state": chamber_stats.get("state") ,
"heater": 2 , # extruders + bett ?
},
"current": self.status_1['temps']['current'] + [ chamber_stats.get("temp") ],
"state": self.status_1['temps']['state'] + [ chamber_stats.get("state") ] ,
})
# dwc rr_status 2
def rr_status_2(self):
now = self.reactor.monotonic() + 0.25
extr_stat = self.get_extr_stats(now)
bed_stats = self.get_bed_stats(now)
gcode_stats = self.gcode.get_status(now)
if self.fan:
fan_stats = [ self.fan.get_status(now) ] # this can be better
else:
fan_stats = []
if self.status_2.get("output", {}).get("message", None) :
self.status_2.update({ "output": {} })
self.message = None
# dummy data
self.status_2.update({
"status": self.get_printer_status() ,
"coords": {
"axesHomed": self.get_axes_homed() ,
"xyz": self.toolhead.get_position()[:3] ,
"machine": [ 0, 0, 0 ] ,
"extr": self.toolhead.get_position()[3:]
},
"speeds": {
"requested": gcode_stats['speed'] / 60 * gcode_stats['speed_factor'] ,
"top": 0 # not available on klipepr
},
"currentTool": self.current_tool,
"params": {
"atxPower": 0 ,
"fanPercent": [ fan_['speed']*100 for fan_ in fan_stats ] ,
"fanNames": [ "" for fan_ in fan_stats ],
"speedFactor": gcode_stats['speed_factor'] * 100,
"extrFactors": [ gcode_stats['extrude_factor'] * 100 ],
"babystep": gcode_stats['homing_zpos']
},
"seq": len(self.gcode_reply),
"sensors": {
"probeValue": 0,
"fanRPM": 0
},
"temps": {
"bed": {
"current": bed_stats['actual'] ,
"active": bed_stats['target'] ,
"state": bed_stats['state'] ,
"heater": 0
},
#"chamber": {
# "current": 19.6,
# "active": 0,
# "state": 0,
# "heater": 2
#},
"current": [ bed_stats['actual'] ] + [ ex_['actual'] for ex_ in extr_stat ] ,
"state": [ bed_stats['state'] ] + [ ex_['state'] for ex_ in extr_stat ] ,
"names": [ "Bed" ] + [ ex_['name'] for ex_ in extr_stat ] ,
"tools": {
"active": [ [ ex_['target'] ] for ex_ in extr_stat ],
"standby": [ [ 0 ] for ex_ in extr_stat ]
},
"extra": [
{
"name": "*MCU",
"temp": 0
}
]
},
"time": time.time() - self.start_time,
"coldExtrudeTemp": max( [ ex_['min_extrude_temp'] for ex_ in extr_stat ] + [0] ),
"coldRetractTemp": max( [ ex_['min_extrude_temp'] for ex_ in extr_stat ] + [0] ),
"compensation": "None",
"controllableFans": len( fan_stats ),
"tempLimit": max( [ ex_['max_temp'] for ex_ in extr_stat ] + [0] ),
"endstops": 4088, # what does this do?
"firmwareName": "Klipper",
"geometry": self.kin_name,
"axes": len(self.get_axes_homed()),
"totalAxes": len(self.get_axes_homed()) + len( [ 1 for ex_ in extr_stat ] ),
"axisNames": "XYZ", #+ "".join([ "U" for ex_ in extr_stat ]),
"volumes": 1,
"mountedVolumes": 1,
"name": self.printername,
"probe": {
"threshold": 100,
"height": 0,
"type": 8
},
"tools": [
{
"number": extr_stat.index(ex_),
"name": ex_['name'],
"heaters": [ extr_stat.index(ex_) + 1 ] ,
"drives": [ extr_stat.index(ex_) ] ,
"axisMap": [ 1 ],
"fans": 1,
"filament": "",
"offsets": [ 0, 0, 0 ]
} for ex_ in extr_stat ]
,
#"mcutemp": {
# "min": 30.1,
# "cur": 36.8,
# "max": 37
#},
#"vin": {
# "min": 24.2,
# "cur": 24.3,
# "max": 24.5
#}
#https://github.com/chrishamm/DuetWebControl/blob/92daf5d98db5def091a3f1a9d4324e1b953fc649/src/store/machine/connector/PollConnector.js#L470
#"output": {
# "message": "Titten!"
#}
#"output": {
# "msgBox": {
# "mode": 2,
# "title": "testtitle",
# "msg": "hello world",
# "timeout": 5000, # can be zero?
# "controls": 1
# }
#}
})
if self.message:
self.status_2.update(
self.message
)
if self.popup:
self.status_2.update(
self.popup
)
if self.chamber:
chamber_stats = self.chamber.get_status(0)
self.status_2['temps'].update({
"chamber": {
"current": chamber_stats.get("temp") ,
"active": chamber_stats.get("target", -1) ,
"state": chamber_stats.get("state") ,
"heater": 2 , # extruders + bett ?
},
"current": self.status_2['temps']['current'] + [ chamber_stats.get("temp") ],
"state": self.status_2['temps']['state'] + [ chamber_stats.get("state") ] ,
"names": self.status_2['temps']['names'] + [ "Chamber" ]
})
# dwc rr_status 3
def rr_status_3(self):
if self.status_3.get("output", {}).get("message", None) :
self.status_3.update({ "output": {} })
self.message = None
now = self.reactor.monotonic() + 0.25
self.extr_stat = self.get_extr_stats(now)
extr_stat = self.extr_stat
bed_stats = self.get_bed_stats(now)
gcode_stats = self.gcode.get_status(now)
if self.fan:
fan_stats = [ self.fan.get_status(now) ] # this can be better
else:
fan_stats = []
self.status_3.update({
"status": self.get_printer_status() ,
"coords": {
"axesHomed": self.get_axes_homed() ,
"xyz": self.toolhead.get_position()[:3] ,
"machine": [ 0, 0, 0 ] ,
"extr": self.toolhead.get_position()[3:]
},
"speeds": {
"requested": gcode_stats['speed'] / 60 * gcode_stats['speed_factor'] ,
"top": 0 # not available on klipepr
},
"currentTool": self.current_tool ,
"params": {
"atxPower": 0 ,
"fanPercent": [ fan_['speed']*100 for fan_ in fan_stats ] ,
"fanNames": [ "" for fan_ in fan_stats ],
"speedFactor": gcode_stats['speed_factor'] * 100,
"extrFactors": [ gcode_stats['extrude_factor'] * 100 ],
"babystep": gcode_stats['homing_zpos']
},
"seq": len(self.gcode_reply),
"sensors": {
"probeValue": 0,
"fanRPM": 0
},
"temps": {
"bed": {
"current": bed_stats['actual'] ,
"active": bed_stats['target'] ,
"state": bed_stats['state'] ,
"heater": 0
},
"current": [ bed_stats['actual'] ] + [ ex_['actual'] for ex_ in extr_stat ] ,
"state": [ bed_stats['state'] ] + [ ex_['state'] for ex_ in extr_stat ] ,
"names": [ "Bed" ] + [ ex_['name'] for ex_ in extr_stat ],
"tools": {
"active": [ [ ex_['target'] ] for ex_ in extr_stat ],
"standby": [ [ 0 ] for ex_ in extr_stat ]
},
"extra": [
{
"name": "*MCU",
"temp": 0
}
]
},
"time": time.time() - self.start_time,
"currentLayer": self.print_data.get('curr_layer', 1) ,
"currentLayerTime": self.print_data.get('curr_layer_dur', 1),
"extrRaw": [ sum([ ex_['pos'] for ex_ in extr_stat ]) - self.print_data.get('extr_start', 1) ],
"fractionPrinted": self.sdcard.get_status(now).get('progress', 0) , # percent done
"filePosition": self.sdcard.file_position,
"firstLayerDuration": self.print_data.get('firstlayer_dur', 1) if self.print_data.get('firstlayer_dur', 0) > 0 else self.print_data.get('curr_layer_dur', 1),
"firstLayerHeight": self.file_infos.get('running_file', {}).get('firstLayerHeight', 0.2),
"printDuration": self.print_data.get('print_dur', 1) ,
"warmUpDuration": self.print_data.get('heat_time', 1),
"timesLeft": {
"file": self.print_data['tleft_file'],
"filament": self.print_data['tleft_filament'],
"layer": self.print_data['tleft_layer']
}
})
if self.message:
self.status_3.update(
self.message
)
if self.popup:
self.status_3.update(
self.popup
)
if self.chamber:
chamber_stats = self.chamber.get_status(0)
self.status_3['temps'].update({
"chamber": {
"current": chamber_stats.get("temp") ,
"active": chamber_stats.get("target", -1) ,
"state": chamber_stats.get("state") ,
"heater": 2 , # extruders + bett ?
},
"current": self.status_3['temps']['current'] + [ chamber_stats.get("temp") ],
"state": self.status_3['temps']['state'] + [ chamber_stats.get("state") ] ,
"names": self.status_3['temps']['names'] + [ "Chamber" ]
})
# dwc rr_upload - uploading files to sdcard
def rr_upload(self, web_):
path_ = self.sdpath + web_.get_argument('name').replace("0:", "").replace(' ', '_')
dir_ = os.path.dirname(path_)
ret_ = {"err":1}
if not os.path.exists(dir_):
os.makedirs(dir_)
# klipper config ecxeption