-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
2858 lines (2132 loc) · 90.1 KB
/
main.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
#!/usr/bin/env python
#
# File: main.py
# Description: Main Program
#
# Copyright 2016 Martin Bienz, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
#application name
mytitle="SDPremote.1"
print "------------------------------------------------------------------"
print mytitle+" Copyright (C) 2016 Martin Bienz, [email protected]"
print "This program comes with ABSOLUTELY NO WARRANTY."
print "This is free software, and you are welcome to redistribute it"
print "under certain conditions; check the license for details."
print "------------------------------------------------------------------"
print "importing modules..."
import os
import subprocess
import sys
#check if the current working directory is the main directory, if not abort or change to it
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
if not os.path.dirname(__file__) == "": #should this not be == script_dir?
#change it to the script directory here
print ""
print "WARNING: Working directory changing to the scripts root directory."
os.chdir(script_dir)
print "OK: Changed to "+script_dir
print ""
#print "ERROR: Working directory must be the applications root directory, aborting."
#sys.exit()
import time
import signal
import datetime
import math
import platform
import argparse
import re
#Files Stuff
import shutil
import zipfile
#threading stuff
import multiprocessing #for the Q / Serial
#web stuff
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver
import uuid
import json
#pygame stuff
import pygame
from pygame.locals import *
#my own classes
import serialProcess
import gpioProcess
import mjpegcam
import helpers
print "importing modules...done."
#GLOBALS--------------------------------------------------------------------------------------------
inifile="settings.ini"
screens = {1: "Home", 2: "Camera preview", 3: "Timelapse folders"}
screens_count=len(screens)
current_screen = 1
recordingstatus="Loading..."
#TL Flag for autostart identification... NOT really used... just in case
autostarted=False
#Enable to allow for touch input
touchenabled = True
mousevisible = True
#VARS for PYGAME custom events
MOUSELONGPRESS=pygame.USEREVENT+1
SWIPE=pygame.USEREVENT+2
#headless (no render pygame) and windowed vs fullscreen (will set via cmdline args)
headless = False
windowed = True
#Used to set Tornado to debugmode (will not pre-cache but allways reload)....PUT TO False if not developping!
TornadoDebug=False
# Global DICTs
#printerstatus = {}
printerstatus = {"status": "connecting..",
"initok": False,
"isheatingup": False,
"isprinting": False,
"isstreaming": False,
"streamingmode": "",
"temp": (0.0, 0.0,0.0,0.0),
"progress": (0.0, 0 ,0),
"progress_time": (datetime.datetime.now().strftime("%d.%B %Y %H:%M"), helpers.seconds_to_dhms_string(datetime.timedelta(seconds=+1).total_seconds()), "00:00:00"),
"file": ("", 0),
"sdrefresh": time.time(),
"sdfiles": [],
"print_start_countdown": -1
}
emailstatus = { }
systemuser = {"hostname": helpers.gethostname(), "ip": helpers.get_local_ip(), "system": platform.system(), "username": None, "sudo": False, "sudo_uid": None, "sudo_gid": None, "gpio_enabled": gpioProcess.gpioProcess_mp.enabled}
websocketclients = dict()
#GLOBALS - Path REL-------------------------------------------------------------------------------------
resourcesdir = os.path.join("resources")#"./resources/"
webdir = os.path.join("web")#"./web/"
gcode_dirs = {"root_dir" : os.path.join(webdir, "g-codefiles"),
"sd-card_dir" : "sd-card",
"print_dir" : "print"}
timelapsedir = os.path.join("web", "timelapse")#"./web/timelapse"
generalpicsdir = os.path.join(timelapsedir, "general") #"./web/timelapse"
#GLOBALS - Path ABS-------------------------------------------------------------------------------------
cwd = os.path.join(script_dir, webdir) # used by static file server, better to use the full path for tornado's template handler
#SKIN settings--------------------------------------------------------------------------------------
bgcolor = pygame.Color('#cccccc')
button_red = pygame.Color(240,150,150)
button_red_on = pygame.Color(240,40,40)
button_green = pygame.Color(150,240,150)
button_green_on = pygame.Color(40,240,40)
button_blue = pygame.Color(150,150,240)
button_blue_on = pygame.Color(40,40,240)
button_yellow = pygame.Color(240,240,150)
button_yellow_on = pygame.Color(240,240,40)
buttoncolor = pygame.Color('#969696')
buttonhighlightcolor = pygame.Color('#eddb26') #YELLOW
buttonhighlightcolor = pygame.Color('#d67979') #RED
buttonhighlightcolor = pygame.Color('#fafafa') #almost WHITE
buttonfontcolor = pygame.Color('#404040')
buttonbordercolor = pygame.Color('#8a8a8a')
generalfontcolor = pygame.Color('#404040')
darkfontcolor = pygame.Color('#101010')
lightfontcolor = pygame.Color('#eeeeee')
progress_fg_color = pygame.Color('#3c82c8') #blue
buttonborder = 4
buttonfontsize=30
buttonfontsize_sm=15
generalfontsize=20
#webserver / command handler helper defs------------------------------------------------------------
def gettldirs(d):
return sorted(filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)]), None, None, False)
def gettlfiles(d):
return sorted([name for name in os.listdir(d) if os.path.isfile(os.path.join(d,name))], None, None, False)
def getgcodefileinfo(f):
d=os.path.join(gcode_dirs["root_dir"], gcode_dirs["print_dir"])
file=os.path.join(d, f)
linecount=0
filament_radius = 2.85/2 #to calculate the lenght from the mm^3 material settings
#this will probably only be ok for cura generatod files
info = {"filename": f,
"size": helpers.bytes2human(os.path.getsize(file)),
"lastmodified": datetime.datetime.fromtimestamp(os.path.getmtime(file)).strftime("%d.%B %Y %H:%M"),
"linecount": 0,
"print_time": "n/a",
"material": "n/a",
"layer_count": "n/a",
"flavor": "n/a",
"generator": "n/a",
"sliced_at": "n/a",
"basic_settings": "n/a",
}
searches = {";Layer count:": "layer_count",
";LAYER_COUNT": "layer_count",
";Print time: ": "print_time",
";TIME:": "print_time",
";Filament used:": "material",
";MATERIAL:": "material",
"; filament used =": "material",
";FLAVOR:": "flavor",
"; gcode_flavor = ": "flavor",
";Sliced at:": "sliced_at",
";Basic settings:": "basic_settings",
";CURA_PROFILE_STRING:": "generator",
";Generated with ": "generator",
"; generated by ": "generator"
}
with open(file, 'r') as inF:
for line in inF:
#count lines while we are at it...
linecount=linecount+1
for search, storein in searches.items():
if search in line:
#specials mainly for cura / um more can be added if required...
if search == ";CURA_PROFILE_STRING:":
info[storein]="Cura"
break
if search == ";MATERIAL:":
mat_mm3=int(line[line.find(search) + len(search):].strip())
mat_filament=mat_mm3/(math.pi*math.pow(filament_radius, 2))
info[storein]=str(mat_mm3) + " mm^3, or " + str(round(mat_filament,2)) + " mm of filament (D=" + str(filament_radius*2) + ")"
break
if search == ";TIME:":
mytimes=int(line[line.find(search) + len(search):].strip())
info[storein]=str(mytimes)+"s, est. "+helpers.seconds_to_dhms_string(mytimes)
break
#standard
info[storein]=line[line.find(search) + len(search):].strip()
info["linecount"]=linecount
return info
def getgcodefiles():
d=os.path.join(gcode_dirs["root_dir"], gcode_dirs["print_dir"])
if not os.path.exists(d):
os.makedirs(d)
helpers.fix_ownership(d)
filelist = []
totalsize = 0
sorteddirlist = sorted(os.listdir(d))
for name in sorteddirlist:
entry=os.path.join(d,name)
if os.path.isfile(entry):
info = {
"filename": name,
"directory": d,
"size": helpers.bytes2human(os.path.getsize(entry)),
"lastmodified": datetime.datetime.fromtimestamp(os.path.getmtime(entry)).strftime("%d.%B %Y %H:%M"),
}
filelist.append(info)
totalsize=totalsize+os.path.getsize(entry)
total={"size": helpers.bytes2human(totalsize), "count": len(filelist)}
return filelist, total
#return sorted([name for name in os.listdir(d) if os.path.isfile(os.path.join(d,name))], None, None, False)
def delgcodefile(f):
d=os.path.join(gcode_dirs["root_dir"], gcode_dirs["print_dir"])
myfile = os.path.join(d, f)
try:
os.remove(myfile)
except OSError:
print OSError
def deltldir(d):
try:
os.remove(os.path.join(timelapsedir, d+'.zip'))
except OSError:
pass
return shutil.rmtree(os.path.join(timelapsedir, d))
def deltlfiles(d):
for myfile in d:
try:
os.remove(myfile)
except OSError:
print OSError
def rentldir(d, newd):
try:
os.rename(os.path.join(timelapsedir, d), os.path.join(timelapsedir, newd))
helpers.fix_ownership(os.path.join(timelapsedir, newd))
except OSError:
pass
def zipdir(path, zip):
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file), os.path.basename(os.path.join(root, file)))
def ziptldir(d):
try:
os.remove(os.path.join(timelapsedir, d+'.zip'))
except OSError:
pass
zipf = zipfile.ZipFile(os.path.join(timelapsedir, d+'.zip'), 'w')
zipdir(os.path.join(timelapsedir, d), zipf)
zipf.close()
helpers.fix_ownership(os.path.join(timelapsedir, d+'.zip'))
def writetldirs(handler):
mydirs=gettldirs(timelapsedir)
content=[]
for item in mydirs:
fcount = len([name for name in os.listdir(item) if os.path.isfile(os.path.join(item,name))])
totsize = helpers.bytes2human(sum(os.path.getsize(os.path.join(item,name)) for name in os.listdir(item) if os.path.isfile(os.path.join(item,name))))
if not fcount == 0:
thumbnail=sorted([ name for name in os.listdir(item) if os.path.isfile(os.path.join(item,name))])[-1]
else:
thumbnail="../../images/nocam.png"
info = {
"directory": item,
"count": fcount,
"size": totsize,
"thumbnail": thumbnail,
}
content.append(info)
handler.write(json.dumps({"info": content}))
#webserver------------------------------------------------------------------------------------------------------------
#WebsocketHandler HTML5 and other websocket capable clients
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self, *args):
self.id = uuid.uuid4()
self.stream.set_nodelay(True)
#Store the client
websocketclients[self.id] = {"id": self.id, "object": self}
#Send wellcome msg
self.write_message("You are connected with id " + str(self.id))
websocketclients[self.id]["object"].write_message({"cmd": "TIME", "data": (time.time(),30.1)})
def on_message(self, message):
"""
when we receive some message we want some message handler..
for this example i will just print message to console
"""
print "Client %s received a message : %s" % (self.id, message)
def on_close(self):
if self.id in websocketclients:
del websocketclients[self.id]
print 'closed connection'+ str(self.id)
def check_origin(self, origin):
#print origin
return True
# Classic COMMAND handler
class CommandHandler(tornado.web.RequestHandler):
def get(self, url = '/'):
#print 'get'
self.handleRequest()
def post(self, url = '/'):
#print 'post'
self.handleRequest()
# handle both GET and POST requests with the same function
def handleRequest( self ):
global serialQ
global printerstatus
global emailstatus
global sp
# is op to decide what kind of command is being sent
op = self.get_argument('op',None)
#print op
#print self.request.arguments
#this will print the complete request / all fields, like remote_ip browser, local etc.
#print(repr(self.request))
if op == "startstopserial":
cmd=self.get_argument('cmd',"")
info = "n/a"
if cmd=="start":
#re-create the deamon
sp = serialProcess.SerialProcess_mp(cfg.settings["Serial"]["serial_port"], cfg.settings["Serial"]["serial_baud"], .1, taskQ, resultQ, gcode_dirs)
if sp.initOK:
sp.daemon = True
sp.start()
info=cfg.settings["Serial"]["serial_port"] + " @ " + cfg.settings["Serial"]["serial_baud"] + " baud, OPEN"
else:
info=sp.tryopen()
sp.close()
sp = None
if cmd=="stop":
info=sp.close()
sp = None
self.write(json.dumps({"info": info}))
if op == "startstopmjpg":
cmd=self.get_argument('cmd',"")
x=mjpg_cmd(cmd)
startstop_camera(cmd)
self.write(json.dumps({"info": x}))
if op == "savesd":
filename=self.get_argument('filename',"")
taskQ.put({"CMD": "SAVESD", "DATA": filename})
if op == "streamfile":
filename=self.get_argument('filename',"")
taskQ.put({"CMD": "STREAMFILE", "DATA": filename})
if op == "abortprint":
taskQ.put({"CMD": "ABORTPRINT"})
self.write(json.dumps({"info": "Abort sent."}))
if op == "serialstatus":
#print myfiles
self.write(json.dumps({"seriallog": serialQ}))
if op == "sendgcode":
gcodecmd=self.get_argument('command',"M105")
SendGodeLog(gcodecmd)
#q = self.application.settings.get('queue')
#q.put({"CMD": "SERIAL", "DATA": gcodecmd})
#updateSerialLog("sent: "+gcodecmd)
if op == "sendgcodespecial":
#cmd = self.get_argument('command', None)
#q = self.application.settings.get('queue')
SendGcodeSpecial(self.request.arguments)
if op == "restartserver":
EndMe(self.get_argument('mode',None))
if op == "getsettings":
self.write(json.dumps(cfg.settings))
if op == "savesettings":
settingstemp = json.loads(self.get_argument('config', None))
cfg.settings=settingstemp
cfg.Save()
#need to set new timer intervall
mjpgCam.interval=int(cfg.settings["General"]["pics_per_second"])
self.write(json.dumps({"status": "ok"}))
#received a "checkup" operation command from the browser:
if op == "toggletimelapse":
ToggleTimeLapse(self.get_argument('tlfolder',None))
#mjpgCam.toggleTL(self.get_argument('tlfolder',None))
#self.write("OK")
if op == "screenshot":
ssfile = mjpgCam.TakeScreenShot()
self.write(json.dumps({"ssfile": ssfile}))
if op == "testmail":
#if mjpgCam.connected:
email_attachement = os.path.join("web", "images", "nocam.png")#"./web/timelapse"
#email_attachement = None
email_text="Test e-mail sent.\n"
status=helpers.send_mail_async(cfg.settings["General"]["email_to"], cfg.settings["General"]["email_from"],
mytitle + " - Test e-mail " + datetime.datetime.now().strftime("%d.%B %Y %H:%M"), email_text,email_attachement,
cfg.settings["General"]["email_user"], cfg.settings["General"]["email_pw"],
cfg.settings["General"]["email_server"], int(cfg.settings["General"]["email_server_port"]),
send_testmail_async_complete
)
self.write(json.dumps({"status": status}))
if op == "deltldir":
deltldir(self.get_argument('tlfolder',None))
writetldirs(self)
if op == "deltlfiles":
filestodel=self.get_arguments('tlfiles')
filespathtodel = []
for f in filestodel:
filespathtodel.append (os.path.join(timelapsedir, self.get_argument('tlfolder',None),f))
deltlfiles(filespathtodel)
myfiles=gettlfiles(os.path.join(timelapsedir, self.get_argument('tlfolder',None)))
self.write(json.dumps({"files": myfiles, "foldername": self.get_argument('tlfolder',None) }))
if op == "delgcodefile":
filetodel=self.get_argument('gcodefile')
delgcodefile(filetodel)
myfiles, total=getgcodefiles()
self.write(json.dumps({"files": myfiles, "total": total}))
if op == "getgcodefileinfo":
myfileinfo=getgcodefileinfo(self.get_argument('gcodefile'))
self.write(json.dumps({"info": myfileinfo}))
if op == "rentldir":
rentldir(self.get_argument('tlfolder',None), self.get_argument('tlfolder_new',None))
writetldirs(self)
if op == "ziptldir":
ziptldir(self.get_argument('tlfolder',None))
self.write(json.dumps({"zip": os.path.join(timelapsedir, self.get_argument('tlfolder',None)+'.zip')}))
if op == "gettlfiles":
myfiles=gettlfiles(os.path.join(timelapsedir, self.get_argument('tlfolder',None)))
#print myfiles
self.write(json.dumps({"files": myfiles, "foldername": self.get_argument('tlfolder',None) }))
if op == "getgcodefiles":
myfiles, total=getgcodefiles()
self.write(json.dumps({"files": myfiles, "total": total}))
if op == "gettldirs":
writetldirs(self)
if op == "checkup":
usage=helpers.disk_usage(cwd)
spaceusedpercent=round(float(usage.used)/float(usage.total)*100,2)
spacefreepercent=round(float(usage.free)/float(usage.total)*100,2)
if mjpgCam.is_running:
tlstat="stop timelapse"
tlmsg="Rec: " + mjpgCam.tlfolder + ", " + str(mjpgCam.getindex()-1) + " ps/"+ str(cfg.settings["General"]["pics_per_second"]) +"s."
else:
tlstat="start timelapse"
tlmsg="Not recording."
if not mjpgCam.connected: tlmsg+=" Cam offline."
recordingstatus=tlmsg
status = { "camonline": mjpgCam.connected,
"spacetotal": helpers.bytes2human(usage.total),
"spaceused": helpers.bytes2human(usage.used),
"spacefree": helpers.bytes2human(usage.free),
"spacefreepercent": spacefreepercent,
"spaceusedpercent": spaceusedpercent,
"tlon": mjpgCam.is_running,
"tlstatus": tlstat,
"piccounter": mjpgCam.getindex(),
"tlfolder": mjpgCam.tlfolder_full,
"tlfolder_name": mjpgCam.tlfolder,
"recordingstatus": recordingstatus
}
#turn it to JSON and send it to the browser
self.write( json.dumps({"cam": status, "printer": printerstatus, "email": emailstatus} ) )
#clear the emailstatus once written so its not send again and again... ;)
emailstatus = { }
# forms that post /upload land here and save the files in /temp/
class UploadHandler(tornado.web.RequestHandler):
def post(self):
target_dir = self.get_body_argument('dest-folder', default="tmp", strip=False)
dest_folder = os.path.join(gcode_dirs["root_dir"], target_dir)
#if the destination exists, ok, else create it
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)
helpers.fix_ownership(dest_folder)
file1 = self.request.files['InputFile'][0]
original_fname = file1['filename']
output_file = open(os.path.join(dest_folder, original_fname), 'wb')
output_file.write(file1['body'])
output_file.close()
helpers.fix_ownership(os.path.join(dest_folder, original_fname))
self.finish("UPLOAD: " + original_fname + " is uploaded.")
print "UPLOAD: " + output_file.name
# send the index file
class IndexHandler(tornado.web.RequestHandler):
def get(self, url = "/"):
#global serverip, tornadoport
if (url=="/"):
the_file="index.html"
else:
the_file=url
#if (url == "base.html"):
# self.render(os.path.join(cwd, url), servername=helpers.gethostname())
#else:
self.render(os.path.join(cwd, the_file), servername=helpers.gethostname(), osname=platform.system(), title=mytitle)
def post(self, url ='/'):
self.get(url)
#Pygame Classes & DEFs-----------------------------------------------------------------------------------------------
class RenderMonitorScreen:
def __init__ (self):
#320 x 200 surface with alpha
self.notiscreen = pygame.Surface((320, 200),SRCALPHA)
self.left=0
self.width=self.notiscreen.get_width()
self.height=self.notiscreen.get_height()
self.top=0
#icons
self.icon_cam = pygame.image.load(os.path.join(resourcesdir, "icon_camera-50.png")).convert_alpha()
self.icon_hdd = pygame.image.load(os.path.join(resourcesdir, "icon_hdd-50.png")).convert_alpha()
self.icon_3dp = pygame.image.load(os.path.join(resourcesdir, "icon_3dprinter-50.png")).convert_alpha()
#Font
self.font = pygame.font.Font(None, generalfontsize)
#Progressbars
self.surf_progress_hdd=RenderProgressBar(50,11)
self.surf_progress_print=RenderProgressBar(50,11)
self.mycounter = 0 #testing the redraw process
def draw(self):
#get all status stuff first
#Diskstatus
usage=helpers.disk_usage(cwd)
spaceusedpercent=round(float(usage.used)/float(usage.total)*100,2)
spacefreepercent=round(float(usage.free)/float(usage.total)*100,2)
txt_free_space=helpers.bytes2human(usage.free) + " (" + str(spacefreepercent) + "%)"
#Camera status
if mjpgCam.is_running:
txt_cam_status="online, recording"
txt_cam_folder=mjpgCam.tlfolder
txt_cam_pic_status=str(mjpgCam.getindex()-1) + " ps/"+ str(cfg.settings["General"]["pics_per_second"]) +"s."
else:
txt_cam_status="not recording"
if not mjpgCam.connected: txt_cam_status+=", camera offline"
txt_cam_folder="n/a"
txt_cam_pic_status="0" + " ps/"+ str(cfg.settings["General"]["pics_per_second"]) +"s."
#Printerstatus
if not printerstatus:
printer_status = "n/a"
printer_isprinting = False
printer_file = "n/a"
printer_nozzle = "n/a"
printer_HB = "n/a"
printer_progress = 0
printer_progress_timeleft = "00:00:00"
else:
printer_status = printerstatus["status"]
printer_isprinting = printerstatus["isprinting"]
printer_file = printerstatus["file"][0] + " (" + helpers.bytes2human(printerstatus["file"][1]) + ")"
printer_nozzle = str(printerstatus["temp"][0]) + " / " + str(printerstatus["temp"][1])
printer_HB = str(printerstatus["temp"][2]) + " / " + str(printerstatus["temp"][3])
printer_progress = round(float(printerstatus["progress"][0])/100,2)
printer_progress_timeleft = printerstatus["progress_time"][2]
#clear the surface
self.notiscreen.fill((204, 204, 204,200))
#draw the icons
self.notiscreen.blit(self.icon_cam,(10,10))
self.notiscreen.blit(self.icon_hdd,(10,70))
self.notiscreen.blit(self.icon_3dp,(10,130))
#Titles and Text
#CAMERA
self.notiscreen.blit(self.font.render(txt_cam_status, True, darkfontcolor),(65,16))
title_surf=self.font.render("name: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,29))
self.notiscreen.blit(self.font.render(txt_cam_folder, True, darkfontcolor),(65+title_surf.get_width(),29))
title_surf=self.font.render("status: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,42))
self.notiscreen.blit(self.font.render(txt_cam_pic_status, True, darkfontcolor),(65+title_surf.get_width(),42))
#HDD
title_surf=self.font.render("diskstatus: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,81))
self.notiscreen.blit(self.surf_progress_hdd.updatesurface(usage.used/float(usage.total)),(65+title_surf.get_width(),81))
title_surf=self.font.render("freespace: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,94))
self.notiscreen.blit(self.font.render(txt_free_space, True, darkfontcolor),(65+title_surf.get_width(),94))
#3dprinter
# status
self.notiscreen.blit(self.font.render(printer_status, True, darkfontcolor),(65,136))
# Temperatures
title_surf=self.font.render("nozzle: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,149))
title_nozzle=self.font.render(printer_nozzle, True, darkfontcolor)
self.notiscreen.blit(title_nozzle,(65+title_surf.get_width(),149))
dist=65+title_surf.get_width()+5+title_nozzle.get_width()
title_surf=self.font.render("hb: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(dist,149))
self.notiscreen.blit(self.font.render(printer_HB, True, darkfontcolor),(dist+title_surf.get_width(),149))
if printer_isprinting:
# File and status printing
title_surf=self.font.render("printing: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,163))
title_file=self.font.render(printer_file, True, darkfontcolor)
self.notiscreen.blit(title_file,(65+title_surf.get_width(),163))
self.notiscreen.blit(self.surf_progress_print.updatesurface(printer_progress),(65+title_surf.get_width()+5+title_file.get_width(),163))
title_surf=self.font.render("print time left: ", True, generalfontcolor)
self.notiscreen.blit(title_surf,(65,176))
self.notiscreen.blit(self.font.render(printer_progress_timeleft, True, darkfontcolor),(65+title_surf.get_width(),176))
#blit the finished screen
screen.blit(self.notiscreen,(0,0))
class RenderMenuScreen:
def __init__ (self):
#320 x 200 surface with alpha
self.notiscreen = pygame.Surface((320, 200),SRCALPHA)
self.left=0
self.width=self.notiscreen.get_width()
self.height=self.notiscreen.get_height()
self.top=0
#Font
self.font = pygame.font.Font(None, generalfontsize+3)
self.mainmenu = RenderMenu(False, False)
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_3dprinter-50.png"), "", "mainmenuscreen.toggle(); set_mode(1); ", size=(50,40), xb=10, yb=5)
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_camera-50.png"), "", "mainmenuscreen.toggle(); set_mode(2); ", size=(50,40), xb=70, yb=5)
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_folder-50.png"), "", "mainmenuscreen.toggle(); set_mode(3); ", size=(50,40), xb=130, yb=5)
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_timer-50.png"), "start timelapse", "ToggleTimeLapse();", size=(145,40), xb=10, yb=65, font_size=20, icon_size=(20,20))
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_camera-50.png"), "take picture", "TakePicture();", size=(145,40), xb=160, yb=65, font_size=20, icon_size=(20,20))
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_lights_off-50.png"), "Off", "mynotism.triggershow(1, 'Sending light OFF ('+cfg.settings['Printer']['gcode_lights_off']+')'); SendGodeLog(cfg.settings['Printer']['gcode_lights_off']); ", size=(70,40), xb=160, yb=110, font_size=20, icon_size=(20,20))
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_lights_on-50.png"), "On", "mynotism.triggershow(1, 'Sending light ON ('+cfg.settings['Printer']['gcode_lights_on']+')'); SendGodeLog(cfg.settings['Printer']['gcode_lights_on']); ", size=(70,40), xb=235, yb=110, font_size=20, icon_size=(20,20))
#self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_restart-50.png"), "restart", "RestartServer(); mainmenuscreen.toggle()", size=(145,40), xb=10, yb=155, font_size=20, icon_size=(20,20))
#self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_shutdown-50.png"), "shutdown", "ShutdownServer(); mainmenuscreen.toggle()", size=(145,40), xb=160, yb=155, font_size=20, icon_size=(20,20))
#update, now calls the Dialog to ask for shutdown / restart
self.mainmenu.AddButton(os.path.join(resourcesdir, "icon_shutdown-50.png"), "Power", "PowerOptionsDialog()", size=(145,40), xb=10, yb=110, font_size=20, icon_size=(20,20))
self.visible = False
def checkinput(self, event):
self.mainmenu.checkinput(event)
def toggle(self):
if self.visible == True:
self.visible = False
else:
self.visible = True
def draw(self):
if not self.visible: return
#clear the surface
self.notiscreen.fill((234, 234, 234, 220))
#self.notiscreen.blit(self.font.render("Menu", True, darkfontcolor),(10,1))
self.notiscreen.blit(self.font.render("Commands", True, darkfontcolor),(10,50))
#self.notiscreen.blit(self.font.render("Lights", True, darkfontcolor),(110,120))
#blit the finished screen
screen.blit(self.notiscreen,(0,0))
self.mainmenu.draw()
class RenderSimpleDialog:
def __init__ (self):
#320 x 200 surface with alpha
self.notiscreen = pygame.Surface((320, 240),SRCALPHA)
self.str_title = "n/a"
self.str_text = "n/a"
self.myfunc = None
self.left=0
self.width=self.notiscreen.get_width()
self.height=self.notiscreen.get_height()
self.top=0
#Fonts
self.font = pygame.font.Font(None, generalfontsize+5)
self.font_b = pygame.font.Font(None, generalfontsize+5)
#self.font_b.set_bold(True)
self.mainmenu = RenderMenu(False, False)
self.update_window()
self.visible = False
self.name="default"
def reset(self):
self.remove_all_buttons()
self.str_title = "n/a"
self.str_text = "n/a"
self.name="default"
self.myfunc = None
def set_specialsurface_function(self, func):
self.myfunc = func
self.update_window()
def set_button_text(self, index, mytext):
self.mainmenu.updatebuttontext(index, mytext)
def set_button_action(self, index, action):
self.mainmenu.updatebuttonaction(index, action)
def set_window_title(self, newtitle):
self.str_title=newtitle
self.update_window()
def set_text(self, newtext):
self.str_text=newtext
self.update_window()
def add_button(self, icon=None, text="", action="", size=(90,40), xb=10, yb=185, col=buttoncolor, col_over=buttonhighlightcolor):
self.mainmenu.AddButton(icon, text, action , size=size, xb=xb, yb=yb, font_size=20, icon_size=(20,20), bc_on=col_over, bc_off=col)
def remove_button(self, index):
self.mainmenu.RemoveButton(index)
def remove_all_buttons(self):
self.mainmenu.RemoveAllButtons()
return True
def update_window(self):
#create Background the surface
self.notiscreen.fill((234, 234, 234, 220))
#create the rounded window and blit it to the screen
window=GetWindowSurface((310, 230))
self.notiscreen.blit(window, (5,5))
pygame.draw.line(self.notiscreen, buttonbordercolor, (5, 175), (314,175), 2)
#write the title on top
self.notiscreen.blit(self.font_b.render(self.str_title, True, generalfontcolor),(10,10))
if not self.myfunc:
#write the text
drawTextSurface(self.notiscreen, self.str_text, lightfontcolor, (10,45,300,120), self.font, aa=False, bkg=pygame.Color('#bbbbbb'))
def checkinput(self, event):
self.mainmenu.checkinput(event)
def toggle(self):
if self.visible == True:
self.visible = False
else:
self.visible = True
def draw(self):
if not self.visible: return
#blit the special surface if set
if self.myfunc:
self.notiscreen = self.myfunc(self.notiscreen)
#blit the finished screen
screen.blit(self.notiscreen,(0,0))
#draw the menu / buttons on top
self.mainmenu.draw()
class RenderProgressBar:
def __init__ (self, w, h):
#indicator, progressbar
self.w=w
self.h=h
self.x=0
self.y=0
self.progress_surface = pygame.Surface((self.w+1, self.h+1))
self.progress_surface = self.progress_surface.convert_alpha()
def updatesurface(self, value):
self.progress_surface.fill((255, 255, 255,0)) # 4 = 0 for full alpha
pygame.draw.rect(self.progress_surface, (140,140,140), (self.x,self.y, self.w ,self.h), 2)
neww=(value)*(self.w-5)
pygame.draw.rect(self.progress_surface, progress_fg_color, (self.x+3, self.y+3 , neww, self.h-5), 0)
return self.progress_surface
class RenderStatusBar:
def __init__ (self):
self.notiscreen = pygame.Surface((320, 40),SRCALPHA)
self.notiscreen.fill((110, 110, 110, 240) ,special_flags=BLEND_RGBA_MAX)
#Blit the Logo
self.notiscreen.blit(my_logo,(0,0))
self.left=0
self.width=self.notiscreen.get_width()
self.height=self.notiscreen.get_height()
self.top=pygame.display.Info().current_h-self.height
#prep font
self.font_title = pygame.font.Font(None, 35)
self.font_subtitle = pygame.font.Font(None, 15)
self.mainmenucontrol = RenderMenu(False, False)
self.mainmenucontrol.AddButton(os.path.join(resourcesdir, "icon_menu_black-40.png"), "", "mainmenuscreen.toggle()", size=(40,38), xb=280-5, yb=201)
#self.temp_menu = pygame.image.load(os.path.join(resourcesdir, "icon_menu_white-40.png")).convert_alpha()
def checkinput(self, event):
self.mainmenucontrol.checkinput(event)
def draw(self):
text_title = self.font_title.render(mytitle, True, (255, 255, 255))
text_subtitle =self.font_subtitle.render("server @ http://"+ systemuser["ip"] + ":" + cfg.settings["Webserver"]["tornadoport"], True, (200, 200, 200))
#BLIT the screen noti background
screen.blit(self.notiscreen,(self.left, self.top))
#screen.blit(self.temp_menu,(self.width-55,self.top))
screen.blit(text_title, (self.left+10+35, self.top+4))
screen.blit(text_subtitle, (self.left+10+35, self.top+28))
self.mainmenucontrol.draw()
class RenderNotification:
def __init__ (self, size=(300,40)):
bottom_spacing = 5 #distance from the bottom screen
border=buttonborder