forked from MachineryScience/Rockhopper
-
Notifications
You must be signed in to change notification settings - Fork 6
/
LinuxCNCWebSktSvr.py
2645 lines (2298 loc) · 136 KB
/
LinuxCNCWebSktSvr.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/python
# *****************************************************
# *****************************************************
# WebSocket Interface for MachineKit
#
# Usage: LinuxCNCWebSktSvr.py <LinuxCNC_INI_file_name>
#
# Provides a web server using normal HTTP/HTTPS communication
# to information about the running LinuxCNC system. Most
# data is transferred to and from the server over a
# WebSocket using JSON formatted commands and replies.
#
#
# *****************************************************
# *****************************************************
#
# Copyright 2012, 2013 Machinery Science, LLC
# Copyright 2020 Pocket NC, Inc.
#
import traceback
import sys
import os
import uuid
import linuxcnc
import datetime
import math
import tornado.ioloop
import tornado.web
import tornado.websocket
import logging
import json
import subprocess
import hal
import time
import MakeHALGraph
import re
import GCodeReader
from ConfigParser import SafeConfigParser
import hashlib
import base64
import socket
import threading
import signal
import glob
import shutil
import tempfile
import zipfile
from time import strftime
from optparse import OptionParser
from netifaces import interfaces, ifaddresses, AF_INET
from ini import get_ini_data, read_ini_data, write_ini_data, ini_differences, merge_ini_data, get_parameter, set_parameter
import machinekit.hal
from collections import deque
class WorkQueue(object):
def __init__(self):
self.queue = deque()
self.semaphore = threading.Semaphore(0)
self.thread = threading.Thread(target=self.doWork)
self.thread.start()
self.stopped = False
def doWork(self):
while True:
self.semaphore.acquire() # blocks when semaphore count is 0, otherwise, decrements semaphore count by 1
if self.stopped:
return
work = self.queue.pop()
work()
def addWork(self, work):
self.queue.append(work)
self.semaphore.release() # increments semaphore count by 1
def stop(self):
self.stopped = True # doWork will return right after unblocking if stopped is True
self.semaphore.release() # release the semaphore in case we're blocking
WORK_QUEUE = None
#import cProfile
#import pstats
#pr = cProfile.Profile()
#PREV_LOOP_TIME = 0
DEV = os.environ.get('DEV') == 'true'
if DEV:
import tornado.autoreload
logger = logging.getLogger('Rockhopper')
def setupLogger():
logger.setLevel(logging.DEBUG if DEV else logging.ERROR)
fh = logging.FileHandler('/var/log/linuxcnc_webserver.log')
fh.setLevel(logging.ERROR)
fh.setFormatter(logging.Formatter('%(asctime)sZ pid:%(process)s module:%(module)s %(message)s'))
logger.addHandler(fh)
if DEV:
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
sh.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(sh)
originRE = re.compile("https?://([a-z0-9]+\.)?pocketnc.com")
def set_date_string(dateString):
subprocess.call(['sudo', 'date', '-s', dateString])
# modified from https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
def toIntOrString(text):
try:
retval = int(text)
except ValueError:
retval = text
return retval
def natural_keys(text):
return [ toIntOrString(c) for c in re.split('[v.-]', text) ]
UpdateStatusPollPeriodInMilliSeconds = 50
UpdateLowPriorityStatusPollPeriodInMilliSeconds = 2000
UpdateErrorPollPeriodInMilliseconds = 50
eps = float(0.000001)
main_loop =tornado.ioloop.IOLoop.instance()
linuxcnc_command = linuxcnc.command()
# TODO - make this an env var or something?
POCKETNC_DIRECTORY = "/home/pocketnc/pocketnc"
sys.path.insert(0, os.path.join(POCKETNC_DIRECTORY, "Settings"))
import version as boardRevision
BOARD_REVISION = boardRevision.getVersion()
INI_DEFAULTS_FILE = os.path.join(POCKETNC_DIRECTORY, "Settings/versions/%s/PocketNC.ini" % BOARD_REVISION)
SETTINGS_PATH = os.path.join(POCKETNC_DIRECTORY, "Settings")
CALIBRATION_OVERLAY_FILE = os.path.join(POCKETNC_DIRECTORY, "Settings/CalibrationOverlay.inc")
A_COMP_FILE = os.path.join(POCKETNC_DIRECTORY, "Settings/a.comp")
B_COMP_FILE = os.path.join(POCKETNC_DIRECTORY, "Settings/b.comp")
INI_FILENAME = ''
INI_FILE_PATH = ''
INI_FILE_CACHE = None
CONFIG_FILENAME = '%s/Rockhopper/CLIENT_CONFIG.JSON' % POCKETNC_DIRECTORY
MAX_BACKPLOT_LINES=50000
lastLCNCerror = ""
options = ""
lastBackplotFilename = ""
lastBackplotData = ""
BackplotLock = threading.Lock()
uploadingFile = None
pressureData = []
temperatureData = []
def sigterm_handler(_signo, _stack_frame):
global WORK_QUEUE
if WORK_QUEUE:
WORK_QUEUE.stop()
main_loop.stop()
sys.exit(0)
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
# *****************************************************
# Class to poll linuxcnc for status. Other classes can request to be notified
# when a poll happens with the add/del_observer methods
# *****************************************************
class LinuxCNCStatusPoller(object):
def __init__(self, main_loop, period):
global lastLCNCerror
# open communications with linuxcnc
self.linuxcnc_status = linuxcnc.stat()
try:
self.linuxcnc_status.poll()
self.linuxcnc_is_alive = True
except:
self.linuxcnc_is_alive = False
self.linuxcnc_errors = linuxcnc.error_channel()
lastLCNCerror = ""
self.errorid = 0
# begin the poll-update loop of the linuxcnc system
self.scheduler = tornado.ioloop.PeriodicCallback( self.poll_update, period, io_loop=main_loop )
self.scheduler.start()
# begin the low priority poll-update loop of the linuxcnc system
self.scheduler_low_priority = tornado.ioloop.PeriodicCallback( self.poll_update_low_priority, UpdateLowPriorityStatusPollPeriodInMilliSeconds, io_loop=main_loop )
self.scheduler_low_priority.start()
# begin the poll_update_errors loop of the linuxcnc system
self.scheduler_errors = tornado.ioloop.PeriodicCallback( self.poll_update_errors, UpdateErrorPollPeriodInMilliseconds, io_loop=main_loop )
self.scheduler_errors.start()
# register listeners
self.observers = {}
self.observers_low_priority = {}
hss_ini_data = get_parameter(INI_FILE_CACHE, 'POCKETNC_FEATURES', HIGH_SPEED_SPINDLE)
self.is_hss = hss_ini_data is not None and hss_ini_data['values']['value'] == '1'
if self.is_hss:
# wait here until the hss userspace components are loaded
while True:
try:
self.hss_aborted_pin = machinekit.hal.Pin("hss_warmup.aborted")
self.hss_full_warmup_pin = machinekit.hal.Pin("hss_warmup.full_warmup_needed")
self.hss_p_abort_pin = machinekit.hal.Pin("hss_sensors.p_abort")
self.hss_p_detect_abort_pin = machinekit.hal.Pin("hss_sensors.p_detect_abort")
self.hss_t_abort_pin = machinekit.hal.Pin("hss_sensors.t_abort")
self.hss_t_detect_abort_pin = machinekit.hal.Pin("hss_sensors.t_detect_abort")
break
except:
time.sleep(.1)
else:
self.hss_aborted_pin = None
self.hss_full_warmup_pin = None
self.hss_p_abort_pin = None
self.hss_p_detect_abort_pin = None
self.hss_t_abort_pin = None
self.hss_t_detect_abort_pin = None
rtc_ini_data = get_parameter(INI_FILE_CACHE, 'POCKETNC_FEATURES', 'RUN_TIME_CLOCK')
has_rtc = rtc_ini_data is not None and rtc_ini_data['values']['value'] == '1'
if has_rtc:
safetyCounter = 0
while True:
try:
self.rtc_seconds_pin = machinekit.hal.Pin("run_time_clock.seconds")
break
except:
safetyCounter += 1
if safetyCounter > 1000:
break
time.sleep(0.1)
self.axis_velocities = {}
for n in range(5):
self.axis_velocities[n] = machinekit.hal.Pin("axis." + `n` + ".joint-vel-cmd")
interlock_ini_data = get_parameter(INI_FILE_CACHE, 'POCKETNC_FEATURES', INTERLOCK)
self.has_interlock = interlock_ini_data is not None and interlock_ini_data['values']['value'] == '1'
if self.has_interlock:
while True:
try:
self.interlock_pause_alert_pin = machinekit.hal.Pin("interlock.pause-alert")
self.interlock_spindle_stop_alert_pin = machinekit.hal.Pin("interlock.spindle-stop-alert")
self.interlock_exception_alert_pin = machinekit.hal.Pin("interlock.exception-alert")
break
except:
time.sleep(.01)
else:
self.interlock_pause_alert_pin = None
self.interlock_spindle_stop_alert_pin = None
self.interlock_exception_alert_pin = None
# HAL dictionaries of signals and pins
self.pin_dict = {}
self.sig_dict = {}
self.counter = 0
def has_observer_low_priority(self, id):
return True if self.observers_low_priority.get(id) else False
def add_observer_low_priority(self, id, callback):
self.observers_low_priority[id] = callback
def del_observer_low_priority(self, id):
del self.observers_low_priority[id]
def has_observer(self, id):
return True if self.observers.get(id) else False
def add_observer(self, id, callback):
self.observers[id] = callback
def del_observer(self, id):
del self.observers[id]
def clear_all(self, matching_connection):
self.obervers = {}
def poll_update_errors(self):
global lastLCNCerror
try:
if self.linuxcnc_is_alive is False:
return
if (self.hss_aborted_pin is not None) and self.hss_aborted_pin.get():
if (self.hss_full_warmup_pin is not None) and self.hss_full_warmup_pin.get():
lastLCNCerror = {
"kind": "spindle_warmpup",
"type":"error",
"text": "You must run the full spindle warm up sequence (approx. 50 minutes) since it hasn't been turned on in over 1 week.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
else:
lastLCNCerror = {
"kind": "spindle_warmpup",
"type":"error",
"text": "You must run the short spindle warm up sequence (approx. 10 minutes) since it hasn't been turned on in over 12 hours.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.hss_aborted_pin.set(0)
elif (self.hss_p_abort_pin is not None) and self.hss_p_abort_pin.get():
lastLCNCerror = {
"kind": "spindle_pressure",
"type":"error",
"text": "Spindle air supply pressure below minimum 20 PSI (0.138 MPA).",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.hss_p_abort_pin.set(0)
elif (self.hss_p_detect_abort_pin is not None) and self.hss_p_detect_abort_pin.get():
lastLCNCerror = {
"kind": "spindle_pressure_detect",
"type":"error",
"text": "Failed to detect air supply pressure sensor. Spindle cannot be turned on.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.hss_p_detect_abort_pin.set(0)
elif (self.hss_t_abort_pin is not None) and self.hss_t_abort_pin.get():
lastLCNCerror = {
"kind": "spindle_temperature",
"type":"error",
"text": "Ambient temperature is outside the spindle's safe operating range of 32-104F (0-40C).",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.hss_t_abort_pin.set(0)
elif (self.hss_t_detect_abort_pin is not None) and self.hss_t_detect_abort_pin.get():
lastLCNCerror = {
"kind": "spindle_pressure_detect",
"type":"error",
"text": "Failed to detect main board temperature sensor. Spindle cannot be turned on.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.hss_t_detect_abort_pin.set(0)
elif (self.interlock_pause_alert_pin is not None) and self.interlock_pause_alert_pin.get():
lastLCNCerror = {
"kind": "interlock_program",
"type":"error",
"text": "Enclosure opened while program running, program has been paused.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.interlock_pause_alert_pin.set(0)
elif (self.interlock_spindle_stop_alert_pin is not None) and self.interlock_spindle_stop_alert_pin.get():
lastLCNCerror = {
"kind": "interlock_program",
"type":"error",
"text": "Enclosure opened while spindle enabled, spindle has been stopped.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.interlock_spindle_stop_alert_pin.set(0)
elif (self.interlock_exception_alert_pin is not None) and self.interlock_exception_alert_pin.get():
lastLCNCerror = {
"kind": "interlock_exception",
"type":"error",
"text": "An exception has occured in the interlock HAL component, machine has been E-stopped as a precaution.",
"time":strftime("%Y-%m-%d %H:%M:%S"),
"id":self.errorid
}
self.errorid += 1
self.interlock_exception_alert_pin.set(0)
else:
if self.linuxcnc_errors is None:
self.linuxcnc_errors = linuxcnc.error_channel()
try:
error = self.linuxcnc_errors.poll()
if error:
kind, text = error
if kind in (linuxcnc.NML_ERROR, linuxcnc.OPERATOR_ERROR):
typus = "error"
else:
typus = "info"
lastLCNCerror = { "kind":kind, "type":typus, "text":text, "time":strftime("%Y-%m-%d %H:%M:%S"), "id":self.errorid }
self.errorid = self.errorid + 1
except:
pass
except:
logger.error("Exception during poll_update_errors: %s" % traceback.format_exc())
def poll_update_low_priority(self):
update_gcode_files() # update gcode files to catch case where
# someone adds or deletes files through
# other means than Rockhopper (i.e. through
# the terminal, ssh, etc.)
# logger.debug("Number of observers: %s" % (len(self.observers.keys()),))
# logger.debug("Number of low priority observers: %s" % (len(self.observers_low_priority.keys()),))
for (id,observer) in self.observers_low_priority.items():
try:
observer(id)
except Exception as ex:
logger.error("error in observer: %s" % traceback.format_exc())
self.del_observer_low_priority(id)
def poll_update(self):
global linuxcnc_command
# global PREV_LOOP_TIME
# now = time.time()
# logger.debug("BEGINNING OF POLL LOOP %10.5s" % ((now-PREV_LOOP_TIME)*1000))
# PREV_LOOP_TIME = now
# update linuxcnc status
if self.linuxcnc_is_alive:
try:
if self.linuxcnc_status is None:
self.linuxcnc_status = linuxcnc.stat()
linuxcnc_command = linuxcnc.command()
self.linuxcnc_status.poll()
except:
self.linuxcnc_status = None
linuxcnc_command = None
else:
self.linuxcnc_errors = None
self.linuxcnc_status = None
linuxcnc_command = None
# notify all obervers of new status data poll
for (id,observer) in self.observers.items():
try:
observer(id)
except Exception as ex:
logger.error("error in observer: %s" % traceback.format_exc())
self.del_observer(id)
# *****************************************************
# Global LinuxCNCStatus Polling Object
# *****************************************************
LINUXCNCSTATUS = None
# *****************************************************
# Functions for determining inequality for StatusItems
# *****************************************************
def isNotEqual(a,b):
return a != b
def isIteratorOfFloatsNotEqual(a,b):
for (old,new) in zip(a,b):
diff = abs(old-new)
if diff > .000001:
return True
return False
def get_gcode_files( directory ):
try:
return glob.glob( os.path.join(directory,'*.[nN][gG][cC]') )
except:
return []
def update_gcode_files():
global GCODE_FILES
GCODE_FILES = get_gcode_files(GCODE_DIRECTORY)
# *****************************************************
# Class to track an individual status item
# *****************************************************
class StatusItem( object ):
def __init__( self, name=None, valtype='', help='', watchable=True, isarray=False, arraylen=0, coreLinuxCNCVariable=True, isasync=False, isDifferent=isNotEqual, lowPriority=False, requiresFeature=None ):
self.name = name
self.valtype = valtype
self.help = help
self.isarray = isarray
self.arraylength = arraylen
self.watchable = watchable
self.coreLinuxCNCVariable = coreLinuxCNCVariable
self.isasync = isasync
self.halBinding = None
self.isDifferent = isDifferent
self.lowPriority = lowPriority
self.requiresFeature = requiresFeature
@staticmethod
def from_name( name ):
val = StatusItems.get( name, None )
if val is not None:
return val
if name.find('halpin_') is 0:
return StatusItem( name=name, valtype='halpin', help='HAL pin.', isarray=False )
elif name.find('halsig_') is 0:
return StatusItem( name=name, valtype='halsig', help='HAL signal.', isarray=False )
return None
# puts this object into the dictionary, with the key == self.name
def register_in_dict( self, dictionary ):
dictionary[ self.name ] = self
def to_json_compatible_form( self ):
return {
"name": self.name,
"valtype": self.valtype,
"help": self.help,
"isarray": self.isarray,
"watchable": self.watchable,
"coreLinuxCNCVariable": self.coreLinuxCNCVariable,
"lowPriority": self.lowPriority,
"requiresFeature": self.requiresFeature
}
def backplot_async( self, async_buffer, async_lock, linuxcnc_status_poller ):
global lastBackplotFilename
global lastBackplotData
def do_backplot( self, async_buffer, async_lock, filename ):
global MAX_BACKPLOT_LINES
global lastBackplotFilename
global lastBackplotData
global BackplotLock
BackplotLock.acquire()
try:
if lastBackplotFilename != filename:
gr = GCodeReader.GCodeRender( INI_FILENAME )
gr.load()
lastBackplotData = gr.to_json(maxlines=MAX_BACKPLOT_LINES)
lastBackplotFilename = filename
reply = {'data':lastBackplotData, 'code':LinuxCNCServerCommand.REPLY_COMMAND_OK }
except:
reply = {'data':'','code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
logger.error("Exception in do_backplot: %s" % traceback.format_exc())
BackplotLock.release()
async_lock.acquire()
async_buffer.append(reply)
async_lock.release()
return
if async_buffer is None or async_lock is None:
return { 'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND,'data':'' }
if lastBackplotFilename == linuxcnc_status_poller.linuxcnc_status.file:
return {'data':lastBackplotData, 'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
#thread = threading.Thread(target=do_backplot, args=(self, async_buffer, async_lock, linuxcnc_status_poller.linuxcnc_status.file))
#thread.start()
return { 'code':LinuxCNCServerCommand.REPLY_COMMAND_OK, 'data':'' }
def backplot( self ):
reply = ""
BackplotLock.acquire()
try:
gr = GCodeReader.GCodeRender( INI_FILENAME )
gr.load()
reply = gr.to_json(maxlines=MAX_BACKPLOT_LINES)
except:
logger.error("Exception in backplot: %s" % traceback.format_exc())
BackplotLock.release()
return reply
def check_if_rotary_motion_only( self ):
epsilon = 0.000001
is_linear_motion = abs(LINUXCNCSTATUS.axis_velocities[0].get()) > epsilon
is_linear_motion |= abs(LINUXCNCSTATUS.axis_velocities[1].get()) > epsilon
is_linear_motion |= abs(LINUXCNCSTATUS.axis_velocities[2].get()) > epsilon
is_rotary_motion = abs(LINUXCNCSTATUS.axis_velocities[3].get()) > epsilon
is_rotary_motion |= abs(LINUXCNCSTATUS.axis_velocities[4].get()) > epsilon
return is_rotary_motion and not is_linear_motion
def update_hss_sensor_data( self, new_reading, data_list, large_change_threshold ):
try:
newReading = float(new_reading)
# Always add to list if it is empty
if not data_list:
data_list.append([time.time(), newReading])
return
mostRecentReadingTime = data_list[-1][0]
nowTime = time.time()
# We want at least one reading per minute
shouldAppend = (nowTime - mostRecentReadingTime) > 60
# Always save reading if magnitude of change is large enough
if not shouldAppend:
change = newReading - data_list[-1][1]
shouldAppend = abs(change) > large_change_threshold
if shouldAppend:
data_list.append([nowTime, newReading])
# Remove any data points older than 1 hour
while ( nowTime - data_list[0][0] ) > 3600:
data_list.pop(0)
except:
logger.error("Exception in update_hss_sensor_data: %s" % traceback.format_exc())
def read_gcode_file( self, filename ):
try:
f = open(filename, 'r')
ret = f.read()
except:
logger.error("Exception in read_gcode_file: %s" % traceback.format_exc())
ret = ""
finally:
f.close()
return ret
@staticmethod
def get_ini_data_item(section, item_name):
try:
reply = StatusItem.get_ini_data( only_section=section.strip(), only_name=item_name.strip() )
except Exception as ex:
reply = {'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND,'data':''}
return reply
@staticmethod
def get_overlay_data():
try:
ini_data = read_ini_data(CALIBRATION_OVERLAY_FILE)
reply = {'data': ini_data, 'code': LinuxCNCServerCommand.REPLY_COMMAND_OK }
except Exception as ex:
reply = {'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND,'data':''}
return reply
# called in a "get_config" command to read the config file and output it's values
@staticmethod
def get_ini_data( only_section=None, only_name=None ):
try:
ini_data = get_ini_data(INI_FILE_CACHE, only_section, only_name)
reply = {'data': ini_data,'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
except Exception as ex:
reply = {'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND,'data':''}
return reply
def get_compensation( self ):
reply = { 'code': LinuxCNCServerCommand.REPLY_COMMAND_OK }
try:
data = {
'a': [],
'b': []
}
af = open(A_COMP_FILE, 'r')
a_data = af.read()
bf = open(B_COMP_FILE, 'r')
b_data = bf.read()
atriples = a_data.split()
btriples = b_data.split()
for ai in range(0, len(atriples), 3):
angle = float(atriples[ai])
forward = float(atriples[ai+1])
backward = float(atriples[ai+2])
data['a'].append([ angle, forward, backward ])
for bi in range(0, len(btriples), 3):
angle = float(btriples[bi])
forward = float(btriples[bi+1])
backward = float(btriples[bi+2])
data['b'].append([ angle, forward, backward ])
reply['data'] = data
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
finally:
try:
af.close()
bf.close()
except:
pass
return reply
def get_client_config( self ):
reply = { 'code': LinuxCNCServerCommand.REPLY_COMMAND_OK }
reply['data'] = CLIENT_CONFIG_DATA
return reply
def get_current_version(self):
try:
cur_version = subprocess.check_output(['git', 'describe'], cwd=POCKETNC_DIRECTORY).strip()
except:
return { "code": LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
return { "code": LinuxCNCServerCommand.REPLY_COMMAND_OK, "data": cur_version }
def get_versions(self):
try:
all_versions = subprocess.check_output(['git', 'tag', '-l'], cwd=POCKETNC_DIRECTORY).split()
all_versions.sort(key=natural_keys)
except:
return { "code": LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
return { "code": LinuxCNCServerCommand.REPLY_COMMAND_OK, "data": all_versions }
def list_gcode_files( self ):
code = LinuxCNCServerCommand.REPLY_COMMAND_OK
return { "code":code, "data": GCODE_FILES }
def detect_usb( self ):
detected = False
try:
# usbmount uses available dir with lowest number among /media/usb[0-7] as mount location
usbDirBase = "/media/usb"
usbDir = ""
for mountDirIdx in range(8):
usbDir = usbDirBase + str( mountDirIdx )
if ( os.path.exists(usbDir) and len(os.listdir(usbDir)) > 0 ):
detected = True
except:
pass
reply = { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":detected }
return reply
def usb_software_files(self):
try:
files = []
# usbmount uses available dir with lowest number among /media/usb[0-7] as mount location
usbDirBase = "/media/usb"
usbDir = ""
for mountDirIdx in range(8):
usbDir = usbDirBase + str( mountDirIdx )
files = [ f for f in os.listdir(usbDir) if f.startswith("pocketnc") and f.endswith('.p') ]
if ( os.path.exists(usbDir) and len(files) > 0 ):
break
except Exception as e:
code = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret["data"] = e.message
return { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":files }
def map_usb( self ):
try:
usbMap = { "detected" : False }
# usbmount uses available dir with lowest number among /media/usb[0-7] as mount location
usbDirBase = "/media/usb"
usbDir = ""
for mountDirIdx in range(8):
usbDir = usbDirBase + str( mountDirIdx )
if ( os.path.exists(usbDir) and len(os.listdir(usbDir)) > 0 ):
usbMap["detected"] = True
usbMap["mountPath"] = usbDir
break
if usbMap["detected"]:
startIdx = usbDir.rfind(os.sep) + 1
#adapted from http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/
for path, dirs, files in os.walk(usbDir):
currentDirs = path[startIdx:].split(os.sep)
# Don't add anything within a hidden dir to map
if any( d[0] == '.' or d == 'System Volume Information' for d in currentDirs ):
continue
# Navigate through the nested dicts until a new dict is created for the current location
currentLocation = usbMap
for d in currentDirs:
currentLocation = currentLocation.setdefault(d, {} )
for f in files:
if ( f[0] != '.' ) and ( f[-4:].lower() == '.ngc' ):
currentLocation[f] = None
except Exception as e:
code = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret["data"] = e.message
return { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":usbMap }
def get_users( self ):
return { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":userdict.keys() }
def get_system_status( self ):
code = LinuxCNCServerCommand.REPLY_COMMAND_OK
ret = { "data": {} }
try:
df_data = subprocess.check_output(['df']).split()
#df gives 6 columns of data. The 6th column, Mounted on, provides a search term for the root directory ("/") which is consistent across tested versions of df
#The 3 desired disk space values are located 4, 3, and 2 positions behind the location of this search term
totalIndex = df_data.index("/") - 4
(total,used,available) = [ int(x) for x in df_data[totalIndex:totalIndex+3] ]
logs_used = int(subprocess.check_output(['sudo', 'du', '-k', '-d', '0', '/var/log']).split()[0])
ncfiles_path = get_parameter(INI_FILE_CACHE, "DISPLAY", "PROGRAM_PREFIX")["values"]["value"]
ncfiles_used = int(subprocess.check_output(['du', '-k', '-d', '0', ncfiles_path]).split()[0])
ret["data"] = {
"disk": {
"total": total,
"other": total-available-logs_used-ncfiles_used,
"available": available,
"logs": logs_used,
"ncfiles": ncfiles_used
},
"addresses": [],
# Format date/time so that javascript can parse it simply with new Date(string) while
# and get the correct date and time regardless of time zone. The browser can then show
# the local time zone.
"date": str(datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y"))
}
for ifaceName in interfaces():
ret["data"]["addresses"] += [ i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}]) if i['addr'] not in ['127.0.0.1'] ]
ret["data"]["swap"] = {
"exists": os.path.isfile("/my_swap")
}
if ret["data"]["swap"]["exists"]:
ret["data"]["swap"]["size"] = os.path.getsize("/my_swap")
ret["data"]["swap"]["on"] = "my_swap" in subprocess.check_output(['sudo', 'swapon', '-s'])
except Exception as e:
code = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret["data"] = e.message
ret["code"] = code
return ret
def get_calibration_data( self ):
ret = { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":"" }
try:
tmpDir = tempfile.mkdtemp()
shutil.copy(CALIBRATION_OVERLAY_FILE, tmpDir)
shutil.copy(A_COMP_FILE, tmpDir)
shutil.copy(B_COMP_FILE, tmpDir)
shutil.make_archive(os.path.join(application_path,"static/calibration"), "zip", tmpDir)
ret['data'] = 'static/calibration.zip'
shutil.rmtree(tmpDir)
except:
logger.error("Exception in get_calibration_data: %s" % traceback.format_exc())
ret['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret['data'] = ''
return ret
def get_halgraph( self ):
ret = { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":"" }
try:
analyzer = MakeHALGraph.HALAnalyzer()
analyzer.parse_pins()
analyzer.write_svg( os.path.join(application_path,"static/halgraph.svg") )
ret['data'] = 'static/halgraph.svg'
except:
ret['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret['data'] = ''
return ret
def get_hal_binding( self ):
ret = { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":"" }
if self.halBinding is None:
try:
if self.name.find('halpin_') is 0:
self.halBinding = machinekit.hal.Pin( self.name[7:] )
else:
self.halBinding = machinekit.hal.Signal( self.name[7:] )
except RuntimeError as ex:
logger.error('RuntimeError error binding StatusItem attribute to HAL object: %s' % traceback.format_exc())
ret['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret['data'] = ''
return ret
try:
ret['data'] = self.halBinding.get()
except Exception as ex:
logger.error('Exception getting StatusItem HAL Pin value: %s' % (traceback.format_exc()))
ret['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret['data'] = ''
return ret
# called in on_new_poll to update the current value of a status item
def get_cur_status_value( self, linuxcnc_status_poller, item_index, command_dict, async_buffer=None, async_lock=None ):
global lastLCNCerror
ret = { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":"" }
try:
if (self.name == 'running'):
if linuxcnc_status_poller.linuxcnc_is_alive:
ret['data'] = 1
else:
ret['data'] = 0
return ret
if not linuxcnc_status_poller.linuxcnc_is_alive:
ret = { "code":LinuxCNCServerCommand.REPLY_LINUXCNC_NOT_RUNNING, "data":"Server is not running." }
return ret
if not self.coreLinuxCNCVariable:
# these are the "special" variables, not using the LinuxCNC status object
if (self.name.find('halpin_') is 0) or (self.name.find('halsig_') is 0):
ret = self.get_hal_binding()
if self.name.find('halpin_hss_sensors') is 0:
if( self.name.find('pressure') != -1 ):
self.update_hss_sensor_data(ret['data'], pressureData, 0.001)
elif( self.name.find('temperature') != -1 ):
self.update_hss_sensor_data(ret['data'], temperatureData, 0.1)
# elif (self.name.find('backplot_async') is 0):
# ret = self.backplot_async(async_buffer, async_lock,linuxcnc_status_poller)
# elif (self.name.find('backplot') is 0):
# ret['data'] = self.backplot()
elif (self.name == 'ini_file_name'):
ret['data'] = INI_FILENAME
elif (self.name == 'file_content'):
ret['data'] = self.read_gcode_file(linuxcnc_status_poller.linuxcnc_status.file)
elif (self.name == 'versions'):
ret = self.get_versions()
elif (self.name == 'current_version'):
ret = self.get_current_version()
elif (self.name == 'ls'):
ret = self.list_gcode_files()
elif (self.name == 'usb_detected'):
ret = self.detect_usb()
elif (self.name == 'usb_map'):
ret = self.map_usb()
elif (self.name == 'usb_software_files'):
ret = self.usb_software_files()
elif (self.name == 'halgraph'):
ret = self.get_halgraph()
elif (self.name == 'calibration_data'):
ret = self.get_calibration_data()
elif (self.name == 'system_status'):
ret = self.get_system_status()
elif (self.name == 'config'):
ret = StatusItem.get_ini_data()
elif (self.name == 'config_overlay'):
ret = StatusItem.get_overlay_data()
elif (self.name == 'config_item'):
ret = StatusItem.get_ini_data_item(command_dict.get("section", ''),command_dict.get("parameter", ''))
elif (self.name == 'client_config'):
ret = self.get_client_config()
elif (self.name == 'compensation'):
ret = self.get_compensation()
elif (self.name == 'users'):
ret = self.get_users()
elif (self.name == 'board_revision'):
ret['data'] = BOARD_REVISION
elif (self.name == 'dogtag'):
ret['data'] = subprocess.check_output(['cat', '/etc/dogtag']).strip()
elif (self.name == 'error'):
ret['data'] = lastLCNCerror
elif (self.name == 'rtc_seconds'):
if linuxcnc_status_poller.rtc_seconds_pin:
ret['data'] = linuxcnc_status_poller.rtc_seconds_pin.get()
elif (self.name == 'rotary_motion_only'):
ret['data'] = self.check_if_rotary_motion_only()
elif (self.name == 'pressure_data'):
ret['data'] = pressureData[:]
elif (self.name == 'temperature_data'):
ret['data'] = temperatureData[:]
else:
# Variables that use the LinuxCNC status poller
if self.isarray and command_dict.get("index", None) != None:
ret['data'] = (linuxcnc_status_poller.linuxcnc_status.__getattribute__( self.name ))[item_index]
else:
ret['data'] = linuxcnc_status_poller.linuxcnc_status.__getattribute__( self.name )
except Exception as ex :
logger.error("Exception in get_cur_status_value: %s" % traceback.format_exc())
ret['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
ret['data'] = ''
return ret
tool_table_entry_type = type( linuxcnc.stat().tool_table[0] )
tool_table_length = len(linuxcnc.stat().tool_table)
axis_length = len(linuxcnc.stat().axis)
class StatusItemEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, tool_table_entry_type):