-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathLinuxCNCWebSktSvr.py
1802 lines (1561 loc) · 122 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
# -*- coding: cp1252 -*-
# *****************************************************
# *****************************************************
# WebServer Interface for LinuxCNC system
#
# 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
#
import sys
import os
import gc
import linuxcnc
import math
import tornado.ioloop
import tornado.web
import tornado.autoreload
import tornado.websocket
import logging
import json
import subprocess
import hal
import time
import MakeHALGraph
from copy import deepcopy
import re
import ssl
import GCodeReader
from ConfigParser import SafeConfigParser
import hashlib
import base64
#import rpdb2
import socket
import time
import threading
import fcntl
import signal
import select
import glob
from random import random
from time import strftime
from optparse import OptionParser
UpdateStatusPollPeriodInMilliSeconds = 50
UpdateHALPollPeriodInMilliSeconds = 500
UpdateErrorPollPeriodInMilliseconds = 25
eps = float(0.000001)
main_loop =tornado.ioloop.IOLoop.instance()
linuxcnc_command = linuxcnc.command()
INI_FILENAME = ''
INI_FILE_PATH = ''
CONFIG_FILENAME = 'CLIENT_CONFIG.JSON'
MAX_BACKPLOT_LINES=50000
instance_number = 0
lastLCNCerror = ""
options = ""
lastBackplotFilename = ""
lastBackplotData = ""
BackplotLock = threading.Lock()
# *****************************************************
# 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, UpdateStatusPollPeriodInMilliSeconds):
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, UpdateStatusPollPeriodInMilliSeconds, io_loop=main_loop )
self.scheduler.start()
# begin the poll-update 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.hal_observers = []
# HAL dictionaries of signals and pins
self.pin_dict = {}
self.sig_dict = {}
self.counter = 0
self.hal_poll_init()
def add_observer(self, callback):
self.observers.append(callback)
def del_observer(self, callback):
self.observers.remove(callback)
def add_hal_observer(self, callback):
self.hal_observers.append(callback)
def del_hal_observer(self, callback):
self.hal_observers.remove(callback)
def clear_all(self, matching_connection):
self.obervers = []
def hal_poll_init(self):
# halcmd can take 200ms or more to run, so run poll updates in a thread so as not to slow the server
# requests for hal pins and sigs will read the results from the most recent update
def hal_poll_thread(self):
global instance_number
myinstance = instance_number
pollStartDelay = 0
while (myinstance == instance_number):
# first, check if linuxcnc is running at all
# if (not os.path.isfile( '/tmp/linuxcnc.lock' ) or os.path.isfile('/tmp/linuxcnc.shutdown') ):
if (not os.path.isfile( '/tmp/linuxcnc.lock' ) ):
pollStartDelay = 0
self.hal_mutex.acquire()
try:
if ( self.linuxcnc_is_alive ):
print "LinuxCNC has stopped."
self.linuxcnc_is_alive = False
self.pin_dict = {}
self.sig_dict = {}
finally:
self.hal_mutex.release()
time.sleep(UpdateHALPollPeriodInMilliSeconds/1000.0)
continue
else:
if ( not self.linuxcnc_is_alive ):
print "LinuxCNC has started."
self.linuxcnc_is_alive = True
self.p = subprocess.Popen( ['halcmd', '-s', 'show', 'pin'] , stderr=subprocess.PIPE, stdout=subprocess.PIPE )
rawtuple = self.p.communicate()
if ( len(rawtuple[0]) <= 0 ):
time.sleep(UpdateHALPollPeriodInMilliSeconds/1000.0)
continue
raw = rawtuple[0].split('\n')
pins = [ filter( lambda a: a != '', [x.strip() for x in line.split(' ')] ) for line in raw ]
# UPDATE THE DICTIONARY OF PIN INFO
# Acquire the mutex so we don't step on other threads
self.hal_mutex.acquire()
try:
self.pin_dict = {}
self.sig_dict = {}
for p in pins:
if len(p) > 5:
# if there is a signal listed on this pin, make sure
# that signal is in our signal dictionary
self.sig_dict[ p[6] ] = p[3]
if len(p) >= 5:
self.pin_dict[ p[4] ] = p[3]
finally:
self.hal_mutex.release()
# before starting the next check, sleep a little so we don't use all the CPU
time.sleep(UpdateHALPollPeriodInMilliSeconds/1000.0)
print "HAL Monitor exiting... ",myinstance, instance_number
#Main part of hal_poll_init:
# Create a thread for checking the HAL pins and sigs
self.hal_mutex = threading.Lock()
self.hal_thread = threading.Thread(target = hal_poll_thread, args=(self,))
self.hal_thread.start()
def poll_update_errors(self):
global lastLCNCerror
if (self.linuxcnc_is_alive is False):
return
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
def poll_update(self):
global linuxcnc_command
# 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 observer in self.observers:
try:
observer()
except Exception as ex:
self.del_observer(observer)
# *****************************************************
# Global LinuxCNCStatus Polling Object
# *****************************************************
LINUXCNCSTATUS = []
# *****************************************************
# Class to track an individual status item
# *****************************************************
class StatusItem( object ):
def __init__( self, name=None, valtype='', help='', watchable=True, isarray=False, arraylen=0, requiresLinuxCNCUp=True, coreLinuxCNCVariable=True, isAsync=False ):
self.name = name
self.valtype = valtype
self.help = help
self.isarray = isarray
self.arraylength = arraylen
self.watchable = watchable
self.requiresLinuxCNCUp = requiresLinuxCNCUp
self.coreLinuxCNCVariable = coreLinuxCNCVariable
self.isasync = isAsync
@staticmethod
def from_name( name ):
global StatusItems
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 self.__dict__
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 ex:
reply = {'data':'','code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
print ex
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 ):
global MAX_BACKPLOT_LINES
global BackplotLock
reply = ""
BackplotLock.acquire()
try:
gr = GCodeReader.GCodeRender( INI_FILENAME )
gr.load()
reply = gr.to_json(maxlines=MAX_BACKPLOT_LINES);
except ex:
print ex
BackplotLock.release()
return reply
def read_gcode_file( self, filename ):
try:
f = open(filename, 'r')
ret = f.read()
except:
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
# 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 ):
global INIFileDataTemplate
global INI_FILENAME
global INI_FILE_PATH
INIFileData = deepcopy(INIFileDataTemplate)
sectionRegEx = re.compile( r"^\s*\[\s*(.+?)\s*\]" )
keyValRegEx = re.compile( r"^\s*(.+?)\s*=\s*(.+?)\s*$" )
try:
section = 'NONE'
comments = ''
idv = 1
with open( INI_FILENAME ) as file_:
for line in file_:
if line.lstrip().find('#') == 0 or line.lstrip().find(';') == 0:
comments = comments + line[1:]
else:
mo = sectionRegEx.search( line )
if mo:
section = mo.group(1)
hlp = ''
try:
if (section in ConfigHelp):
hlp = ConfigHelp[section]['']['help'].encode('ascii','replace')
except:
pass
if (only_section is None or only_section == section):
INIFileData['sections'][section] = { 'comment':comments, 'help':hlp }
comments = ''
else:
mo = keyValRegEx.search( line )
if mo:
hlp = ''
default = ''
try:
if (section in ConfigHelp):
if (mo.group(1) in ConfigHelp[section]):
hlp = ConfigHelp[section][mo.group(1)]['help'].encode('ascii','replace')
default = ConfigHelp[section][mo.group(1)]['default'].encode('ascii','replace')
except:
pass
if (only_section is None or (only_section == section and only_name == mo.group(1) )):
INIFileData['parameters'].append( { 'id':idv, 'values':{ 'section':section, 'name':mo.group(1), 'value':mo.group(2), 'comment':comments, 'help':hlp, 'default':default } } )
comments = ''
idv = idv + 1
reply = {'data':INIFileData,'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
except Exception as ex:
reply = {'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND,'data':''}
return reply
@staticmethod
def check_hal_file_listed_in_ini( filename ):
# check this is a valid hal file name
f = filename
found = False
halfiles = StatusItem.get_ini_data( only_section='HAL', only_name='HALFILE' )
halfiles = halfiles['data']['parameters']
for v in halfiles:
if (v['values']['value'] == f):
found = True
break
if not found:
halfiles = StatusItem.get_ini_data( only_section='HAL', only_name='POSTGUI_HALFILE' )
halfiles = halfiles['data']['parameters']
for v in halfiles:
if (v['values']['value'] == f):
found = True
break
return found
def get_client_config( self ):
global CONFIG_FILENAME
reply = { 'code': LinuxCNCServerCommand.REPLY_COMMAND_OK }
reply['data'] = '{}'
try:
fo = open( CONFIG_FILENAME, 'r' )
reply['data'] = fo.read()
except:
reply['data'] = '{}'
finally:
try:
fo.close()
except:
pass
return reply
def get_hal_file( self, filename ):
global INI_FILENAME
global INI_FILE_PATH
try:
reply = { 'code': LinuxCNCServerCommand.REPLY_COMMAND_OK }
# strip off just the filename, if a path was given
# we will only look in the config directory, so we ignore path
[h,f] = os.path.split( filename )
if not StatusItem.check_hal_file_listed_in_ini( f ):
reply['code']= LinuxCNCServerCommand.REPLY_ERROR_INVALID_PARAMETER
return reply
reply['data'] = ''
try:
fo = open( os.path.join( INI_FILE_PATH, f ), 'r' )
reply['data'] = fo.read()
except:
reply['data'] = ''
finally:
try:
fo.close()
except:
pass
except Exception as ex:
reply['data'] = ''
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
return reply
def list_gcode_files( self, directory ):
file_list = []
code = LinuxCNCServerCommand.REPLY_COMMAND_OK
try:
if directory is None:
directory = "."
directory = StatusItem.get_ini_data( only_section='DISPLAY', only_name='PROGRAM_PREFIX' )['data']['parameters'][0]['values']['value']
except:
pass
try:
file_list = glob.glob( os.path.join(directory,'*.ngc') )
except:
code = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
return { "code":code, "data":file_list, "directory":directory }
def get_users( self ):
global userdict
return { "code":LinuxCNCServerCommand.REPLY_COMMAND_OK, "data":userdict.keys() }
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
# 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 and self.requiresLinuxCNCUp ):
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):
linuxcnc_status_poller.hal_mutex.acquire()
try:
ret['data'] = linuxcnc_status_poller.pin_dict.get( self.name[7:], LinuxCNCServerCommand.REPLY_INVALID_COMMAND_PARAMETER )
if ( ret['data'] == LinuxCNCServerCommand.REPLY_INVALID_COMMAND_PARAMETER ):
ret['code'] = ret['data']
finally:
linuxcnc_status_poller.hal_mutex.release()
elif (self.name.find('halsig_') is 0):
linuxcnc_status_poller.hal_mutex.acquire()
try:
ret['data'] = linuxcnc_status_poller.sig_dict.get( self.name[7:], LinuxCNCServerCommand.REPLY_INVALID_COMMAND_PARAMETER )
if ( ret['data'] == LinuxCNCServerCommand.REPLY_INVALID_COMMAND_PARAMETER ):
ret['code'] = ret['data']
finally:
linuxcnc_status_poller.hal_mutex.release()
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 == 'ls'):
ret = self.list_gcode_files( command_dict.get("directory", None) )
elif (self.name == 'halgraph'):
ret = self.get_halgraph()
elif (self.name == 'config'):
ret = StatusItem.get_ini_data()
elif (self.name == 'config_item'):
ret = StatusItem.get_ini_data_item(command_dict.get("section", ''),command_dict.get("parameter", ''))
elif (self.name == 'halfile'):
ret = self.get_hal_file( command_dict.get("filename", '') )
elif (self.name == 'client_config'):
ret = self.get_client_config()
elif (self.name == 'users'):
ret = self.get_users()
elif (self.name == 'error'):
ret['data'] = lastLCNCerror
else:
# Variables that use the LinuxCNC status poller
if (self.isarray):
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 :
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):
global tool_table_entry_type
if isinstance(obj, tool_table_entry_type):
return list(obj)
if isinstance(obj, StatusItem):
return obj.to_json_compatible_form()
if isinstance(obj, CommandItem):
return { "name":obj.name, "paramTypes":obj.paramTypes, "help":obj.help }
return json.JSONEncoder.default(self, obj)
# *****************************************************
# Global list of possible status items from linuxcnc
# *****************************************************
StatusItems = {}
StatusItem( name='acceleration', watchable=True, valtype='float', help='Default acceleration. Reflects INI file value [TRAJ]DEFAULT_ACCELERATION' ).register_in_dict( StatusItems )
StatusItem( name='active_queue', watchable=True, valtype='int' , help='Number of motions blending' ).register_in_dict( StatusItems )
StatusItem( name='actual_position', watchable=True, valtype='float[]', help='Current trajectory position. Array of floats: (x y z a b c u v w). In machine units.' ).register_in_dict( StatusItems )
StatusItem( name='adaptive_feed_enabled', watchable=True, valtype='int', help='status of adaptive feedrate override' ).register_in_dict( StatusItems )
StatusItem( name='ain', watchable=True, valtype='float[]', help='current value of the analog input pins' ).register_in_dict( StatusItems )
StatusItem( name='angular_units', watchable=True, valtype='string' , help='From [TRAJ]ANGULAR_UNITS ini value' ).register_in_dict( StatusItems )
StatusItem( name='aout', watchable=True, valtype='float[]', help='Current value of the analog output pins' ).register_in_dict( StatusItems )
StatusItem( name='axes', watchable=True, valtype='int' , help='From [TRAJ]AXES ini value' ).register_in_dict( StatusItems )
StatusItem( name='axis_mask', watchable=True, valtype='int' , help='Mask of axis available. X=1, Y=2, Z=4 etc.' ).register_in_dict( StatusItems )
StatusItem( name='block_delete', watchable=True, valtype='bool' , help='Block delete currently on/off' ).register_in_dict( StatusItems )
StatusItem( name='command', watchable=True, valtype='string' , help='Currently executing command' ).register_in_dict( StatusItems )
StatusItem( name='current_line', watchable=True, valtype='int' , help='Currently executing line' ).register_in_dict( StatusItems )
StatusItem( name='current_vel', watchable=True, valtype='float' , help='Current velocity in cartesian space' ).register_in_dict( StatusItems )
StatusItem( name='cycle_time', watchable=True, valtype='float' , help='From [TRAJ]CYCLE_TIME ini value' ).register_in_dict( StatusItems )
StatusItem( name='debug', watchable=True, valtype='int' , help='Debug flag' ).register_in_dict( StatusItems )
StatusItem( name='delay_left', watchable=True, valtype='float' , help='remaining time on dwell (G4) command, seconds' ).register_in_dict( StatusItems )
StatusItem( name='din', watchable=True, valtype='int[]' , help='current value of the digital input pins' ).register_in_dict( StatusItems )
StatusItem( name='distance_to_go', watchable=True, valtype='float' , help='remaining distance of current move, as reported by trajectory planner, in cartesian space' ).register_in_dict( StatusItems )
StatusItem( name='dout', watchable=True, valtype='int[]' , help='current value of the digital output pins' ).register_in_dict( StatusItems )
StatusItem( name='dtg', watchable=True, valtype='float[]', help='remaining distance of current move, as reported by trajectory planner, as a pose (tuple of 9 floats). ' ).register_in_dict( StatusItems )
StatusItem( name='echo_serial_number', watchable=True, valtype='int' , help='The serial number of the last completed command sent by a UI to task. All commands carry a serial number. Once the command has been executed, its serial number is reflected in echo_serial_number' ).register_in_dict( StatusItems )
StatusItem( name='enabled', watchable=True, valtype='int' , help='trajectory planner enabled flag' ).register_in_dict( StatusItems )
StatusItem( name='estop', watchable=True, valtype='int' , help='estop flag' ).register_in_dict( StatusItems )
StatusItem( name='exec_state', watchable=True, valtype='int' , help='Task execution state. EMC_TASK_EXEC_ERROR = 1, EMC_TASK_EXEC_DONE = 2, EMC_TASK_EXEC_WAITING_FOR_MOTION = 3, EMC_TASK_EXEC_WAITING_FOR_MOTION_QUEUE = 4,EMC_TASK_EXEC_WAITING_FOR_IO = 5, EMC_TASK_EXEC_WAITING_FOR_MOTION_AND_IO = 7,EMC_TASK_EXEC_WAITING_FOR_DELAY = 8, EMC_TASK_EXEC_WAITING_FOR_SYSTEM_CMD = 9, EMC_TASK_EXEC_WAITING_FOR_SPINDLE_ORIENTED = 10' ).register_in_dict( StatusItems )
StatusItem( name='feed_hold_enabled', watchable=True, valtype='int' , help='enable flag for feed hold' ).register_in_dict( StatusItems )
StatusItem( name='feed_override_enabled', watchable=True, valtype='int' , help='enable flag for feed override' ).register_in_dict( StatusItems )
StatusItem( name='feedrate', watchable=True, valtype='float' , help='current feedrate' ).register_in_dict( StatusItems )
StatusItem( name='file', watchable=True, valtype='string' , help='currently executing gcode file' ).register_in_dict( StatusItems )
StatusItem( name='file_content', coreLinuxCNCVariable=False, watchable=False,valtype='string' , help='currently executing gcode file contents' ).register_in_dict( StatusItems )
StatusItem( name='flood', watchable=True, valtype='int' , help='flood enabled' ).register_in_dict( StatusItems )
StatusItem( name='g5x_index', watchable=True, valtype='int' , help='currently active coordinate system, G54=0, G55=1 etc.' ).register_in_dict( StatusItems )
StatusItem( name='g5x_offset', watchable=True, valtype='float[]', help='offset of the currently active coordinate system, a pose' ).register_in_dict( StatusItems )
StatusItem( name='g92_offset', watchable=True, valtype='float[]', help='pose of the current g92 offset' ).register_in_dict( StatusItems )
StatusItem( name='gcodes', watchable=True, valtype='int[]' , help='currently active G-codes. Tuple of 16 ints.' ).register_in_dict( StatusItems )
StatusItem( name='homed', watchable=True, valtype='int' , help='flag for homed state' ).register_in_dict( StatusItems )
StatusItem( name='id', watchable=True, valtype='int' , help='currently executing motion id' ).register_in_dict( StatusItems )
StatusItem( name='inpos', watchable=True, valtype='int' , help='machine-in-position flag' ).register_in_dict( StatusItems )
StatusItem( name='input_timeout', watchable=True, valtype='int' , help='flag for M66 timer in progress' ).register_in_dict( StatusItems )
StatusItem( name='interp_state', watchable=True, valtype='int' , help='Current state of RS274NGC interpreter. EMC_TASK_INTERP_IDLE = 1,EMC_TASK_INTERP_READING = 2,EMC_TASK_INTERP_PAUSED = 3,EMC_TASK_INTERP_WAITING = 4' ).register_in_dict( StatusItems )
StatusItem( name='interpreter_errcode', watchable=True, valtype='int' , help='Current RS274NGC interpreter return code. INTERP_OK=0, INTERP_EXIT=1, INTERP_EXECUTE_FINISH=2, INTERP_ENDFILE=3, INTERP_FILE_NOT_OPEN=4, INTERP_ERROR=5' ).register_in_dict( StatusItems )
StatusItem( name='joint_actual_position', watchable=True, valtype='float[]' ,help='Actual joint positions' ).register_in_dict( StatusItems )
StatusItem( name='joint_position', watchable=True, valtype='float[]', help='Desired joint positions' ).register_in_dict( StatusItems )
StatusItem( name='kinematics_type', watchable=True, valtype='int' , help='identity=1, serial=2, parallel=3, custom=4 ' ).register_in_dict( StatusItems )
StatusItem( name='limit', watchable=True, valtype='int[]' , help='Tuple of axis limit masks. minHardLimit=1, maxHardLimit=2, minSoftLimit=4, maxSoftLimit=8' ).register_in_dict( StatusItems )
StatusItem( name='linear_units', watchable=True, valtype='int' , help='reflects [TRAJ]LINEAR_UNITS ini value' ).register_in_dict( StatusItems )
StatusItem( name='lube', watchable=True, valtype='int' , help='lube on flag' ).register_in_dict( StatusItems )
StatusItem( name='lube_level', watchable=True, valtype='int' , help='reflects iocontrol.0.lube_level' ).register_in_dict( StatusItems )
StatusItem( name='max_acceleration', watchable=True, valtype='float' , help='Maximum acceleration. reflects [TRAJ]MAX_ACCELERATION ' ).register_in_dict( StatusItems )
StatusItem( name='max_velocity', watchable=True, valtype='float' , help='Maximum velocity, float. reflects [TRAJ]MAX_VELOCITY.' ).register_in_dict( StatusItems )
StatusItem( name='mcodes', watchable=True, valtype='int[]' , help='currently active M-codes. tuple of 10 ints.' ).register_in_dict( StatusItems )
StatusItem( name='mist', watchable=True, valtype='int' , help='mist on flag' ).register_in_dict( StatusItems )
StatusItem( name='motion_line', watchable=True, valtype='int' , help='source line number motion is currently executing' ).register_in_dict( StatusItems )
StatusItem( name='motion_mode', watchable=True, valtype='int' , help='motion mode' ).register_in_dict( StatusItems )
StatusItem( name='motion_type', watchable=True, valtype='int' , help='Trajectory planner mode. EMC_TRAJ_MODE_FREE = 1 = independent-axis motion, EMC_TRAJ_MODE_COORD = 2 coordinated-axis motion, EMC_TRAJ_MODE_TELEOP = 3 = velocity based world coordinates motion' ).register_in_dict( StatusItems )
StatusItem( name='optional_stop', watchable=True, valtype='int' , help='option stop flag' ).register_in_dict( StatusItems )
StatusItem( name='paused', watchable=True, valtype='int' , help='motion paused flag' ).register_in_dict( StatusItems )
StatusItem( name='pocket_prepped', watchable=True, valtype='int' , help='A Tx command completed, and this pocket is prepared. -1 if no prepared pocket' ).register_in_dict( StatusItems )
StatusItem( name='position', watchable=True, valtype='float[]', help='Trajectory position, a pose.' ).register_in_dict( StatusItems )
StatusItem( name='probe_tripped', watchable=True, valtype='int' , help='Flag, true if probe has tripped (latch)' ).register_in_dict( StatusItems )
StatusItem( name='probe_val', watchable=True, valtype='int' , help='reflects value of the motion.probe-input pin' ).register_in_dict( StatusItems )
StatusItem( name='probed_position', watchable=True, valtype='float[]', help='position where probe tripped' ).register_in_dict( StatusItems )
StatusItem( name='probing', watchable=True, valtype='int' , help='flag, true if a probe operation is in progress' ).register_in_dict( StatusItems )
StatusItem( name='program_units', watchable=True, valtype='int' , help='one of CANON_UNITS_INCHES=1, CANON_UNITS_MM=2, CANON_UNITS_CM=3' ).register_in_dict( StatusItems )
StatusItem( name='queue', watchable=True, valtype='int' , help='current size of the trajectory planner queue' ).register_in_dict( StatusItems )
StatusItem( name='queue_full', watchable=True, valtype='int' , help='the trajectory planner queue is full' ).register_in_dict( StatusItems )
StatusItem( name='read_line', watchable=True, valtype='int' , help='line the RS274NGC interpreter is currently reading' ).register_in_dict( StatusItems )
StatusItem( name='rotation_xy', watchable=True, valtype='float' , help='current XY rotation angle around Z axis' ).register_in_dict( StatusItems )
StatusItem( name='settings', watchable=True, valtype='float[]', help='Current interpreter settings. settings[0] = sequence number, settings[1] = feed rate, settings[2] = speed' ).register_in_dict( StatusItems )
StatusItem( name='spindle_brake', watchable=True, valtype='int' , help='spindle brake flag' ).register_in_dict( StatusItems )
StatusItem( name='spindle_direction', watchable=True, valtype='int' , help='rotational direction of the spindle. forward=1, reverse=-1' ).register_in_dict( StatusItems )
StatusItem( name='spindle_enabled', watchable=True, valtype='int' , help='spindle enabled flag' ).register_in_dict( StatusItems )
StatusItem( name='spindle_increasing', watchable=True, valtype='int' , help='' ).register_in_dict( StatusItems )
StatusItem( name='spindle_override_enabled', watchable=True, valtype='int' , help='spindle override enabled flag' ).register_in_dict( StatusItems )
StatusItem( name='spindle_speed', watchable=True, valtype='float' , help='spindle speed value, rpm, > 0: clockwise, < 0: counterclockwise' ).register_in_dict( StatusItems )
StatusItem( name='spindlerate', watchable=True, valtype='float' , help='spindle speed override scale' ).register_in_dict( StatusItems )
StatusItem( name='state', watchable=True, valtype='int' , help='current command execution status, int. One of RCS_DONE=1, RCS_EXEC=2, RCS_ERROR=3' ).register_in_dict( StatusItems )
StatusItem( name='task_mode', watchable=True, valtype='int' , help='current task mode, int. one of MODE_MDI=3, MODE_AUTO=2, MODE_MANUAL=1' ).register_in_dict( StatusItems )
StatusItem( name='task_paused', watchable=True, valtype='int' , help='task paused flag' ).register_in_dict( StatusItems )
StatusItem( name='task_state', watchable=True, valtype='int' , help='Current task state. one of STATE_ESTOP=1, STATE_ESTOP_RESET=2, STATE_ON=4, STATE_OFF=3' ).register_in_dict( StatusItems )
StatusItem( name='tool_in_spindle', watchable=True, valtype='int' , help='current tool number' ).register_in_dict( StatusItems )
StatusItem( name='tool_offset', watchable=True, valtype='float' , help='offset values of the current tool' ).register_in_dict( StatusItems )
StatusItem( name='velocity', watchable=True, valtype='float' , help='default velocity, float. reflects [TRAJ]DEFAULT_VELOCITY' ).register_in_dict( StatusItems )
StatusItem( name='ls', coreLinuxCNCVariable=False, watchable=True, valtype='string[]',help='Get a list of gcode files. Optionally specify directory with "directory":"string", or default directory will be used. Only *.ngc files will be listed.' ).register_in_dict( StatusItems )
StatusItem( name='backplot', coreLinuxCNCVariable=False, watchable=False, valtype='string[]',help='Backplot information. Potentially very large list of lines.' ).register_in_dict( StatusItems )
StatusItem( name='backplot_async', coreLinuxCNCVariable=False, watchable=False, valtype='string[]', isAsync=True, help='Backplot information. Potentially very large list of lines.' ).register_in_dict( StatusItems )
StatusItem( name='config', coreLinuxCNCVariable=False, watchable=False, valtype='dict', help='Config (ini) file contents.', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
StatusItem( name='config_item', coreLinuxCNCVariable=False, watchable=False, valtype='dict', help='Specific section/name from the config file. Pass in section=??? and name=???.', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
StatusItem( name='halfile', coreLinuxCNCVariable=False, watchable=False, valtype='string', help='Contents of a hal file. Pass in filename=??? to specify the hal file name', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
StatusItem( name='halgraph', coreLinuxCNCVariable=False, watchable=False, valtype='string', help='Filename of the halgraph generated from the currently running instance of LinuxCNC. Filename will be "halgraph.svg"' ).register_in_dict( StatusItems )
StatusItem( name='ini_file_name', coreLinuxCNCVariable=False, watchable=True, valtype='string', help='INI file to use for next LinuxCNC start.', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
StatusItem( name='client_config', coreLinuxCNCVariable=False, watchable=True, valtype='string', help='Client Configuration.', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
StatusItem( name='users', coreLinuxCNCVariable=False, watchable=True, valtype='string', help='Web server user list.', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
StatusItem( name='error', coreLinuxCNCVariable=False, watchable=True, valtype='dict', help='Error queue.' ).register_in_dict( StatusItems )
StatusItem( name='running', coreLinuxCNCVariable=False, watchable=True, valtype='int', help='True if linuxcnc is up and running.', requiresLinuxCNCUp=False ).register_in_dict( StatusItems )
# Array Status items
StatusItem( name='tool_table', watchable=True, valtype='float[]', help='list of tool entries. Each entry is a sequence of the following fields: id, xoffset, yoffset, zoffset, aoffset, boffset, coffset, uoffset, voffset, woffset, diameter, frontangle, backangle, orientation', isarray=True, arraylen=tool_table_length ).register_in_dict( StatusItems )
StatusItem( name='axis', watchable=True, valtype='dict' , help='Axis Dictionary', isarray=True, arraylen=axis_length ).register_in_dict( StatusItems )
# *****************************************************
# Class to issue cnc commands
# *****************************************************
class CommandItem( object ):
# Command types
MOTION=0
HAL=1
SYSTEM=2
def __init__( self, name=None, paramTypes=[], help='', command_type=MOTION ):
self.name = name
self.paramTypes = paramTypes
self.help = help
for idx in xrange(0, len(paramTypes)):
paramTypes[idx]['ordinal'] = str(idx)
self.type = command_type
# puts this object into the dictionary, with the key == self.name
def register_in_dict( self, dictionary ):
dictionary[ self.name ] = self
# called in a "put_config" command to write INI data to INI file, completely re-writing the file
def put_ini_data( self, commandDict ):
global INI_FILENAME
global INI_FILE_PATH
reply = { 'code': LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
try:
# construct the section list
sections = {}
sections_sorted = []
for line in commandDict['data']['parameters']:
sections[line['values']['section']] = line['values']['section']
for section in sections:
sections_sorted.append( section )
sections_sorted = sorted(sections_sorted)
inifile = open(INI_FILENAME, 'w', 1)
for section in sections_sorted:
# write out the comments before the section header
if (section in commandDict['data']['sections']):
commentlines = commandDict['data']['sections'][section]['comment'].split('\n')
for c_line in commentlines:
if len(c_line) > 0:
inifile.write( '#' + c_line + '\n' )
#write the section header
inifile.write( '[' + section + ']\n' )
#write the key/value pairs
for line in commandDict['data']['parameters']:
if line['values']['section'] == section :
if (len(line['values']['comment']) > 0):
commentlines = line['values']['comment'].split('\n')
for c_line in commentlines:
if len(c_line) > 0:
inifile.write( '#' + c_line +'\n' )
if (len(line['values']['name']) > 0):
inifile.write( line['values']['name'] + '=' + line['values']['value'] + '\n' )
inifile.write('\n\n')
inifile.close()
reply['code'] = LinuxCNCServerCommand.REPLY_COMMAND_OK
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
finally:
try:
inifile.close()
except:
pass
return reply
def put_client_config( self, key, value ):
global CONFIG_FILENAME
reply = {'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
try:
fo = open( CONFIG_FILENAME, 'r' )
jsonobj = json.loads( fo.read() );
jsonobj[key] = value;
except:
jsonobj = {}
finally:
fo.close()
try:
fo = open( CONFIG_FILENAME, 'w' )
fo.write( json.dumps(jsonobj) )
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
finally:
try:
fo.close()
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
return reply
def put_gcode_file( self, filename, data ):
global linuxcnc_command
reply = {'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
try:
# strip off just the filename, if a path was given
# we will only look in the config directory, so we ignore path
[h,f] = os.path.split( filename )
path = StatusItem.get_ini_data( only_section='DISPLAY', only_name='PROGRAM_PREFIX' )['data']['parameters'][0]['values']['value']
try:
fo = open( os.path.join( path, f ), 'w' )
fo.write(data)
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
finally:
try:
fo.close()
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
if (reply['code'] == LinuxCNCServerCommand.REPLY_COMMAND_OK):
(linuxcnc_command.program_open( os.path.join( path, f ) ) )
except Exception as ex:
print ex
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
return reply
# writes the specified HAL file to disk
def put_hal_file( self, filename, data ):
global INI_FILENAME
global INI_FILE_PATH
reply = {'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
try:
# strip off just the filename, if a path was given
# we will only look in the config directory, so we ignore path
[h,f] = os.path.split( filename )
if not StatusItem.check_hal_file_listed_in_ini( f ):
reply['code']=LinuxCNCServerCommand.REPLY_ERROR_INVALID_PARAMETER
return reply
try:
fo = open( os.path.join( INI_FILE_PATH, f ), 'w' )
fo.write(data)
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
finally:
try:
fo.close()
except:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
except Exception as ex:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
return reply
def shutdown_linuxcnc( self ):
try:
displayname = StatusItem.get_ini_data( only_section='DISPLAY', only_name='DISPLAY' )['data']['parameters'][0]['values']['value']
p = subprocess.Popen( ['pkill', displayname] , stderr=subprocess.STDOUT )
return {'code':LinuxCNCServerCommand.REPLY_COMMAND_OK }
except:
return {'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
def start_linuxcnc( self ):
global INI_FILENAME
global INI_FILE_PATH
p = subprocess.Popen(['pidof', '-x', 'linuxcnc'], stdout=subprocess.PIPE )
result = p.communicate()[0]
if len(result) > 0:
return {'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND}
subprocess.Popen(['linuxcnc', INI_FILENAME], stderr=subprocess.STDOUT )
return {'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
def add_user( self, username, password ):
try:
proc = subprocess.Popen(['python', 'AddUser.py', username, password], stderr=subprocess.STDOUT )
proc.communicate()
readUserList()
return {'code':LinuxCNCServerCommand.REPLY_COMMAND_OK}
except:
pass
def execute( self, passed_command_dict, linuxcnc_status_poller ):
global INI_FILENAME
global INI_FILE_PATH
global lastLCNCerror
global linuxcnc_command
try:
paramcnt = 0
params = []
if ((linuxcnc_command is None or (not linuxcnc_status_poller.linuxcnc_is_alive)) and not (self.type == CommandItem.SYSTEM)):
return { 'code':LinuxCNCServerCommand.REPLY_LINUXCNC_NOT_RUNNING }
for paramDesc in self.paramTypes:
paramval = passed_command_dict.get( paramDesc['pname'], None )
if paramval is None:
paramval = passed_command_dict.get( paramDesc['ordinal'], None )
paramtype = paramDesc['ptype']
if (paramval is not None):
if (paramtype == 'lookup'):
params.append( linuxcnc.__getattribute__( paramval.strip() ) )
elif (paramtype == 'float'):
params.append( float( paramval ) )
elif (paramtype == 'int'):
params.append( int( paramval ) )
else:
params.append(paramval)
else:
if not paramDesc['optional']:
return { 'code':LinuxCNCServerCommand.REPLY_MISSING_COMMAND_PARAMETER + ' ' + paramDesc['name'] }
else:
break
if (self.type == CommandItem.MOTION):
# execute command as a linuxcnc module call
(linuxcnc_command.__getattribute__( self.name ))( *params )
elif (self.type == CommandItem.HAL):
# implement the command as a halcommand
p = subprocess.Popen( ['halcmd'] + filter( lambda a: a != '', [x.strip() for x in params[0].split(' ')]), stderr=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=(1024*64) )
stdouterr = p.communicate()
reply = {}
reply['code'] = LinuxCNCServerCommand.REPLY_COMMAND_OK
reply['data'] = {}
reply['data']['out']=stdouterr[0]
reply['data']['err']=stdouterr[1]
return reply
elif (self.type == CommandItem.SYSTEM):
# command is a special system command
reply = {}
if (self.name == 'ini_file_name'):
INI_FILENAME = passed_command_dict.get( 'ini_file_name', INI_FILENAME )
[INI_FILE_PATH, x] = os.path.split( INI_FILENAME )
reply['code'] = LinuxCNCServerCommand.REPLY_COMMAND_OK
elif (self.name == 'config'):
reply = self.put_ini_data(passed_command_dict)
elif (self.name == 'clear_error'):
lastLCNCerror = ""
elif (self.name == 'halfile'):
reply = self.put_hal_file( filename=passed_command_dict.get('filename',passed_command_dict['0']).strip(), data=passed_command_dict.get('data', passed_command_dict.get['1']) )
elif (self.name == 'shutdown'):
reply = self.shutdown_linuxcnc()
elif (self.name == 'startup'):
reply = self.start_linuxcnc()
elif (self.name == 'program_upload'):
reply = self.put_gcode_file(filename=passed_command_dict.get('filename',passed_command_dict['0']).strip(), data=passed_command_dict.get('data', passed_command_dict['1']))
elif (self.name == 'save_client_config'):
reply = self.put_client_config( (passed_command_dict.get('key', passed_command_dict.get('0'))), (passed_command_dict.get('value', passed_command_dict.get('1'))) );
elif (self.name == 'add_user'):
reply = self.add_user( passed_command_dict.get('username',passed_command_dict['0']).strip(), passed_command_dict.get('password',passed_command_dict['1']).strip() )
else:
reply['code'] = LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND
return reply
else:
return { 'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
return { 'code':LinuxCNCServerCommand.REPLY_COMMAND_OK }
except:
return { 'code':LinuxCNCServerCommand.REPLY_ERROR_EXECUTING_COMMAND }
# Custom Command Items
CommandItems = {}
CommandItem( name='halcmd', paramTypes=[ {'pname':'param_string', 'ptype':'string', 'optional':False} ], help='Call halcmd. Results returned in a string.', command_type=CommandItem.HAL ).register_in_dict( CommandItems )
CommandItem( name='ini_file_name', paramTypes=[ {'pname':'ini_file_name', 'ptype':'string', 'optional':False} ], help='Set the INI file to use on next linuxCNC load.', command_type=CommandItem.SYSTEM ).register_in_dict( CommandItems )
# Pre-defined Command Items
CommandItem( name='abort', paramTypes=[], help='send EMC_TASK_ABORT message' ).register_in_dict( CommandItems )
CommandItem( name='auto', paramTypes=[ {'pname':'auto', 'ptype':'lookup', 'lookup-vals':['AUTO_RUN','AUTO_STEP','AUTO_RESUME','AUTO_PAUSE'], 'optional':False }, {'pname':'run_from', 'ptype':'int', 'optional':True} ], help='run, step, pause or resume a program. auto legal values: AUTO_RUN, AUTO_STEP, AUTO_RESUME, AUTO_PAUSE' ).register_in_dict( CommandItems )
CommandItem( name='brake', paramTypes=[ {'pname':'onoff', 'ptype':'lookup', 'lookup-vals':['BRAKE_ENGAGE','BRAKE_RELEASE'], 'optional':False} ], help='engage or release spindle brake. Legal values: BRAKE_ENGAGE or BRAKE_RELEASE' ).register_in_dict( CommandItems )
CommandItem( name='debug', paramTypes=[ {'pname':'onoff', 'ptype':'int', 'optional':False} ], help='set debug level bit-mask via EMC_SET_DEBUG message' ).register_in_dict( CommandItems )
CommandItem( name='feedrate', paramTypes=[ {'pname':'rate', 'ptype':'float', 'optional':False} ], help='set the feedrate' ).register_in_dict( CommandItems )
CommandItem( name='flood', paramTypes=[ {'pname':'onoff', 'ptype':'lookup', 'lookup-vals':['FLOOD_ON','FLOOD_OFF'], 'optional':False} ], help='turn on/off flood coolant. Legal values: FLOOD_ON, FLOOD_OFF' ).register_in_dict( CommandItems )
CommandItem( name='home', paramTypes=[ {'pname':'axis', 'ptype':'int', 'optional':False} ], help='home a given axis' ).register_in_dict( CommandItems )