-
Notifications
You must be signed in to change notification settings - Fork 9
/
dwserver.py
1538 lines (1430 loc) · 51.6 KB
/
dwserver.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
import time
from struct import *
from ctypes import *
import traceback
import os
import re
import sys
import platform
from dwconstants import *
from dwchannel import *
from dwfile import DWFile
from dwutil import *
from dwlib import canonicalize
from cococas import *
import multiprocessing
NULL_SECTOR = NULL * SECSIZ
def _playsound(name, d, block):
import playsound
from playsound import playsound
pwd = os.getcwd()
os.chdir(d)
playsound(name, block)
os.chdir(pwd)
class DWServer:
def __init__(self, args, conn, version, instances, instance):
self.conn = conn
self.files = [None] * 256
self.channels = {}
self.connections = {}
self.debug = False
self.timeout = 0.25
self.version = version
self.vprinter = None
self.emCeeDir = []
self.emCeeDirIdx = 0
if args.experimental:
if 'printer' in args.experimental:
print("DWServer: Enabling experimental printing support")
from dwprinter import DWPrinter
self.vprinter = DWPrinter(args)
if 'ssh' in args.experimental:
print("DWServer: Enabling experimental ssh support")
if 'playsound' in args.experimental:
print("DWServer: Enabling experimental playsound support")
import playsound
from playsound import playsound
self.aliases = {'mc':{}, 'dload':{}, 'namedobj': {}, 'playsound':{}}
self.dirs = {'dw': os.getcwd(), 'mc': os.getcwd(), 'dload': os.getcwd(), 'namedobj': os.getcwd(), 'playsound': os.getcwd() }
self.instances = instances
self.instance = instance
self.hdbdos = args.hdbdos
self.dosplus = args.dosplus
self.offset = eval(args.offset)
self.args = args
self.dload = False
self.namedObjDrive = None
self.comboLock = 0
self.procs = []
def _isNamedObjDrive(self, drive):
if self.namedObjDrive is None:
return False
if drive != self.namedObjDrive:
return False
if self.files[drive] is None:
return False
return True
def registerConn(self, conn):
n = None
i = 0
si = "1"
while i <= len(self.connections):
n = self.connections.get(si, None)
if not n:
break
i += 1
si = "%d" % (i + 1)
self.connections[si] = conn
return si
def open(self, disk, fileName, stream=False, mode="rb+", create=False, offset=None, hdbdos=None, raw=False, eolxlate=False, proto='dw', dosplus=None):
if offset is None:
offset = self.offset
if hdbdos is None:
hdbdos = self.hdbdos
if dosplus is None:
dosplus = self.dosplus
if proto in self.dirs:
print("chdir: %s: %s" % (proto, self.dirs[proto]))
os.chdir(self.dirs[proto])
self.files[disk] = DWFile(fileName, mode, stream=stream, offset=offset, raw=raw, eolxlate=eolxlate, proto=proto, dosplus=dosplus)
print(
'%s: disk=%d file=%s stream=%s mode=%s' %
('Created' if create else 'Opened', disk, fileName, stream, mode))
self.files[disk].seek(0)
self.files[disk].hdbdos = hdbdos
def close(self, disk):
d = self.files[disk]
if d and isinstance(d, DWFile):
name = d.file.name
print('Closing: disk=%d file=%s' % (disk, d.name))
d.file.flush()
os.fsync(d.file.fileno())
d.file.close()
if d.remote and not d.stream:
d._delete()
if self._isNamedObjDrive(disk):
self.namedObjDrive = None
if d:
self.files[disk] = None
def closeAll(self):
for disk in range(len(self.files)):
if self.files[disk]:
self.close(disk)
def reset(self, disk):
df = self.files[disk]
fileName = df.name
stream = df.stream
mode = df.mode
offset = df.offset
hdbdos = df.hdbdos
dosplus = df.dosplus
raw = df.raw
eolxlate = df.eolxlate
proto = df.proto
print('Reset: disk=%d file=%s' % (int(disk), fileName))
self.close(disk)
self.open(disk, fileName, stream=stream, mode=mode, offset=offset,
hdbdos=hdbdos, raw=df.raw, eolxlate=eolxlate, proto=proto,
dosplus=dosplus)
def cmdStat(self, cmd):
info = self.conn.read(STATSIZ, self.timeout)
if not info:
print "cmd=%0x cmdStat timeout getting info" % (ord(cmd))
return
(disk, stat) = unpack(">BB", info)
if self.debug:
print "cmd=%0x cmdStat disk=%d stat=%s" % (
ord(cmd), disk, hex(stat))
def cmdRead(self, cmd, flags=''):
disk = -1
lsn = -1
rc = E_OK
info = self.conn.read(INFOSIZ, self.timeout)
if not info:
print "cmd=%0x cmdRead timeout getting info" % (ord(cmd))
return
# rc = E_READ
# rc = E_CRC # force a re-read
# if rc == E_OK:
(disk, lsn) = unpack(">BI", info[0] + NULL + info[1:])
if self.debug:
print "cmd=%0x cmdRead disk=%d lsn=%d" % (ord(cmd), disk, lsn)
data = NULL_SECTOR
if rc == E_OK:
if self.files[disk] is None:
rc = E_NOTRDY
# XXX: Not needed if set on open and updated on write
# if rc == E_OK and lsn == 0:
# self.files[disk].guessMaxLsn()
if rc == E_OK and lsn >= self.files[disk].maxLsn and not self.hdbdos:
rc = E_EOF
if rc == E_OK:
try:
if self._isNamedObjDrive(disk):
flags += 'O'
if not self._isNamedObjDrive(disk) and self.hdbdos:
disk = lsn / 630
lsn = lsn - (disk * 630)
else:
lsn += self.files[disk].offset
self.files[disk].seek(lsn * SECSIZ)
assert(self.files[disk].tell() == (lsn * SECSIZ))
except BaseException:
raise
rc = E_SEEK
data = NULL_SECTOR
print " rc=%d" % rc
if rc == E_OK:
try:
data = self.files[disk].file.read(SECSIZ)
if len(data) == 0:
data = NULL_SECTOR
flags += 'E'
except BaseException:
rc = E_READ
self.conn.write(chr(rc))
self.conn.write(dwCrc16(data))
self.conn.write(data)
if self.debug:
print " rc=%d" % rc
def cmdReRead(self, cmd):
self.cmdRead(cmd, 'R')
def cmdReadEx(self, cmd, flags=''):
disk = -1
lsn = -1
rc = E_OK
flags = ''
info = self.conn.read(INFOSIZ, self.timeout)
if not info:
print "cmd=%0x cmdReadEx timeout getting info" % (ord(cmd))
return
# rc = E_READ
# rc = E_CRC # force a re-read
if rc == E_OK:
(disk, lsn) = unpack(">BI", info[0] + NULL + info[1:])
data = NULL_SECTOR
if self.files[disk] is None:
rc = E_NOTRDY
# print " rc=%d" % rc
# XXX: not needed if it's set on open and updated on write
# if rc == E_OK and lsn == 0:
# self.files[disk].guessMaxLsn()
if rc == E_OK and lsn >= self.files[disk].maxLsn and not self.hdbdos:
rc = E_EOF
if rc == E_OK:
try:
if self._isNamedObjDrive(disk):
flags += 'O'
if not self._isNamedObjDrive(disk) and self.hdbdos:
disk = lsn / 630
lsn = lsn - (disk * 630)
flags += "H"
else:
lsn += self.files[disk].offset
if self.files[disk].dosplus:
flags +="D"
lsn -= 1
self.files[disk].seek(lsn * SECSIZ)
assert(self.files[disk].tell() == (lsn * SECSIZ))
except BaseException:
rc = E_SEEK
# print " rc=%d" % rc
traceback.print_exc()
if rc == E_OK:
try:
data = self.files[disk].file.read(SECSIZ)
# if data:
# pass
# print "cmdReadEx read %d" % len(data)
if len(data) == 0:
# Seek past EOF, just return 0'ed data
data = NULL_SECTOR
flags += 'E'
# print "cmdReadEx eof read %d" % len(data)
except BaseException:
rc = E_READ
data = NULL_SECTOR
# print " rc=%d" % rc
traceback.print_exc()
# print "cmdReadEx sending %d" % len(data)
dataCrc = dwCrc16(data)
self.conn.write(data)
crc = self.conn.read(CRCSIZ, self.timeout)
if not crc:
print "cmd=%0x cmdReadEx timeout getting crc" % (ord(cmd))
# return
rc = E_CRC
# print " len(info)=%d" % len(info)
# (crc,) = unpack(">H", info)
if rc == E_OK:
if crc != dataCrc:
print "CRC: read", hex(
unpack(
">H", crc)[0]), "expected", hex(
unpack(
">H", dataCrc)[0])
rc = E_CRC
self.conn.write(chr(rc))
elif rc != E_CRC:
self.conn.write(chr(rc))
if self.debug or rc != E_OK:
print "cmd=%0x cmdReadEx disk=%d lsn=%d rc=%d f=%s" % (
ord(cmd), disk, lsn, rc, flags)
# print " rc=%d" % rc
def cmdReReadEx(self, cmd):
self.cmdReadEx(cmd, 'R')
def cmdWrite(self, cmd, flags=''):
# print "cmd=%0x cmdWrite" % ord(cmd)
rc = E_OK
disk = -1
lsn = -1
data = ''
info = self.conn.read(INFOSIZ, self.timeout)
if not info:
print "cmd=%0x cmdWrite timeout getting info" % (ord(cmd))
return
# rc = E_WRITE
# rc = E_CRC # force a re-write
if rc == E_OK:
data = self.conn.read(SECSIZ, self.timeout)
if not data:
print "cmd=%0x cmdWrite timeout getting data" % (ord(cmd))
# return
# rc = E_WRITE
rc = E_CRC # force a re-write
if rc == E_OK:
crc = self.conn.read(CRCSIZ, self.timeout)
if not crc:
print "cmd=%0x cmdWrite timeout getting crc" % (ord(cmd))
# return
rc = E_CRC # force a re-write
else:
(disk, lsn) = unpack(">BI", info[0] + NULL + info[1:])
if crc != dwCrc16(data):
rc = E_CRC
if rc == E_OK and self.files[disk] is None:
rc = E_NOTRDY
if rc == E_OK:
# Note: Write is allowed for non-os9 images
if self.files[disk].os9Image and lsn >= self.files[disk].maxLsn:
rc = E_EOF
if rc == E_OK:
try:
if self._isNamedObjDrive(disk):
flags += 'O'
if not self._isNamedObjDrive(disk) and self.hdbdos:
disk = lsn / 630
lsn = lsn - (disk * 630)
flags += "H"
else:
lsn += self.files[disk].offset
if self.files[disk].dosplus:
flags +="D"
lsn -= 1
self.files[disk].seek(lsn * SECSIZ)
except BaseException:
traceback.print_exc()
rc = E_SEEK
if rc == E_OK:
try:
self.files[disk].file.write(data)
self.files[disk].file.flush()
except Exception as e:
rc = E_WRITE
if e.message == 'File not open for writing':
rc = E_WRPROT
print traceback.print_exc()
if rc == E_OK:
if (lsn == 0) or (
not self.files[disk].os9Image and lsn >= self.files[disk].maxLsn):
self.files[disk].guessMaxLsn()
# if crc != dwCrc16(data):
# rc=E_CRC
self.conn.write(chr(rc))
if self.debug or rc != E_OK:
print "cmd=%0x cmdWrite disk=%d lsn=%d rc=%d f=%s" % (
ord(cmd), disk, lsn, rc, flags)
# print " rc=%d" % rc
def cmdReWrite(self, cmd):
self.cmdWrite(cmd, 'R')
# XXX Java version will return oldest data first
def cmdSerRead(self, cmd):
data = NULL * 2
msg = "NoData"
# msg = ""
for channel in self.channels:
nchannel = ord(channel)
ow = self.channels[channel].outWaiting()
if ow < 0:
# Channel is closing
data = chr(16)
data += channel
msg = "channel=%d Closing" % nchannel
if self.channels[channel].state == DWV_S_CLOSED:
self.channels[channel].close()
del self.channels[channel]
break
elif ow == 0:
continue
elif ow < 3:
data = chr(1 + nchannel)
data += self.channels[channel].read(1)
msg = "channel=%d ByteWaiting=(%s)" % (nchannel, data[1])
break
else:
data = chr(17 + nchannel)
data += chr(ow)
msg = "channel=%d BytesWaiting=%d" % (nchannel, ow)
break
# elif ow<0:
# # Channel is closing
# data = chr(16)
# data += chr(1)
self.conn.write(data)
if self.debug and msg:
print "cmd=%0x serRead %s" % (ord(cmd), msg)
# XXX
def cmdReset(self, cmd):
if self.debug:
print "cmd=%0x cmdReset" % ord(cmd)
# XXX
def cmdInit(self, cmd):
for drive in range(len(self.files)):
if not self.files[drive]:
continue
self.reset(drive)
for channel in self.channels:
self.channels[channel].close()
if self.debug:
print(
"cmd=%0x cmdInit channel=%d closed" %
(ord(cmd), ord(channel)))
for channel in self.channels.keys():
del self.channels[channel]
if self.debug:
print "cmd=%0x cmdInit" % ord(cmd)
def cmdNop(self, cmd):
if self.debug:
print "cmd=%0x cmdNop" % ord(cmd)
# XXX
def cmdTerm(self, cmd):
if self.debug:
print "cmd=%0x cmdTerm" % ord(cmd)
# enhanced DwInit with combo lock
# Combo lock stage 1: send 'p' OP_DWINIT must return 'p'
# Combo lock stage 2: send 'y' OP_DWINIT must return 'y'
# Combo lock stage 3: send request for information page
# Server Enabled Features Page 1: 'E'
# Bit definitions - see FEATURE defs in dwconstants.py
# combo lock disabled
# Server Available Features Page 1: 'F'
# Bit definitions - see FEATURE defs in dwconstants.py
# combo lock disabled
# Server Version Page 1: 'V'
# bits 4-7 major binary 0-15
# bits 0-3 minor msb bcd 0-9
# combo lock disabled
# Server Version Page 2: 'v'
# bits 4-7 minor lsb bcd 0-9
# bits 0-3 sub - 0=none, 1='a', 2='b' etc.
# combo lock disabled
def cmdDWInit(self, cmd):
r = 0xff
clientID = self.conn.read(1, self.timeout)
if not clientID:
clientID = '\xff'
if self.debug:
print("Combo Lock: %0x" % self.comboLock)
print("Client Id: %0x(%s)" % (ord(clientID),clientID=='p'))
if self.comboLock == 0:
if clientID == 'p':
r = ord(clientID)
self.comboLock = 1
else:
self.comboLock = 0
elif self.comboLock == 1:
if clientID == 'y':
r = ord(clientID)
self.comboLock = 2
else:
self.comboLock = 0
elif self.comboLock == 2:
r = 0
if clientID == 'E':
r |= FEATURE_EMCEE
r |= FEATURE_DLOAD if self.dload else 0
r |= FEATURE_HDBDOS if self.hdbdos else 0
r |= FEATURE_DOSPLUS if self.dosplus else 0
if 'printer' in self.args.experimental:
r |= FEATURE_PRINTER
if 'ssh' in self.args.experimental:
r |= FEATURE_SSH
if 'playsound' in self.args.experimental:
r |= FEATURE_PLAYSND
self.comboLock = 0
if clientID == 'F':
r |= FEATURE_EMCEE
r |= FEATURE_DLOAD
r |= FEATURE_HDBDOS
r |= FEATURE_DOSPLUS
r |= FEATURE_PRINTER
r |= FEATURE_SSH
r |= FEATURE_PLAYSND
self.comboLock = 0
elif clientID == 'V':
r |= (PYDW_VERSION_MAJOR << 4) & 0xf0
minorMsb = (PYDW_VERSION_MINOR//10) & 0x0f
r |= minorMsb
self.comboLock = 0
elif clientID == 'v':
minorLsb = (PYDW_VERSION_MINOR%10)
r |= (minorLsb << 4) & 0xf0
code = (ord(PYDW_VERSION_SUB)-ord('a')+1) if PYDW_VERSION_SUB else 0
r |= code & 0x0f
self.comboLock = 0
else:
self.comboLock = 0
else:
self.comboLock = 0
if self.debug:
print "cmd=%0x cmdDWInit cl=%0x id=%0x r=%0x" % (ord(cmd), self.comboLock, ord(clientID), r)
self.conn.write(chr(r))
def cmdTime(self, cmd):
t = ''
now = time.localtime()
t += chr(now.tm_year - 1900)
t += chr(now.tm_mon)
t += chr(now.tm_mday)
t += chr(now.tm_hour)
t += chr(now.tm_min)
t += chr(now.tm_sec)
self.conn.write(t)
if self.debug:
print "cmd=%0x cmdTime %s" % (ord(cmd), time.ctime())
def cmdSerSetStat(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerSetStat timeout getting channel" % (ord(cmd)))
return
# if channel not in self.channels:
# print("cmd=%0x cmdSerSetStat bad channel=%d" % (ord(cmd),ord(channel)))
# return
code = self.conn.read(1, self.timeout)
if not code:
print(
"cmd=%0x cmdSerSetStat channel=%d timeout getting code" %
(ord(cmd), ord(channel)))
return
data = ''
if code == SS_Open:
self.channels[channel] = DWVModem(self, channel, debug=self.debug)
if self.debug:
print("cmd=%0x SS_Open channel=%d" % (ord(cmd), ord(channel)))
if code == SS_ComSt:
data = self.conn.read(26, self.timeout)
if channel not in self.channels:
print(
"cmd=%0x cmdSerSetStat bad channel=%d code=%0x" %
(ord(cmd), ord(channel), ord(code)))
# return
elif code == SS_Close:
self.channels[channel].close()
del self.channels[channel]
if self.debug:
print("cmd=%0x SS_Close channel=%d" % (ord(cmd), ord(channel)))
if self.debug:
print("cmd=%0x cmdSerSetStat channel=%d code=%0x len=%d" %
(ord(cmd), ord(channel), ord(code), len(data)))
def cmdSerGetStat(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerGetStat timeout getting channel" % (ord(cmd)))
return
if channel not in self.channels:
print(
"cmd=%0x cmdSerGetStat bad channel=%d" %
(ord(cmd), ord(channel)))
return
code = self.conn.read(1, self.timeout)
if not code:
print(
"cmd=%0x cmdSerGetStat channel=%d timeout getting code" %
(ord(cmd), ord(channel)))
return
if self.debug:
print(
"cmd=%0x cmdSerGetStat channel=%d code=%0x" %
(ord(cmd), ord(channel), ord(code)))
def cmdSerInit(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerInit timeout getting channel" % (ord(cmd)))
return
if channel in self.channels:
print(
"cmd=%0x cmdSerInit existing channel=%d" %
(ord(cmd), ord(channel)))
return
self.channels[channel] = DWVModem(self, channel, debug=self.debug)
if self.debug:
print("cmd=%0x cmdSerInit channel=%d" % (ord(cmd), ord(channel)))
def cmdSerTerm(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerTerm timout getting channel" % (ord(cmd)))
return
if channel not in self.channels:
print(
"cmd=%0x cmdSerTerm bad channel=%d" %
(ord(cmd), ord(channel)))
return
self.channels[channel].close()
del self.channels[channel]
if self.debug:
print("cmd=%0x cmdSerTerm channel=%d" % (ord(cmd), ord(channel)))
def cmdFastWrite(self, cmd):
channel = chr(ord(cmd) - 0x80)
if channel not in self.channels:
print(
"cmd=%0x cmdFastWrite bad channel=%d" %
(ord(cmd), ord(channel)))
return
byte = self.conn.read(1, self.timeout)
if not byte:
print(
"cmd=%0x cmdFastWrite channel=%d timeout" %
(ord(cmd), ord(channel)))
return
self.channels[channel].write(byte)
self.channels[channel]._cmdWorker()
if self.debug:
print(
"cmd=%0x cmdFastWrite channel=%d byte=%0x" %
(ord(cmd), ord(channel), ord(byte)))
def cmdSerReadM(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerReadM timout getting channel" % (ord(cmd)))
return
if channel not in self.channels:
print(
"cmd=%0x cmdSerReadM bad channel=%d" %
(ord(cmd), ord(channel)))
return
num = self.conn.read(1, self.timeout)
if not num:
print(
"cmd=%0x cmdSerReadM channel=%d timeout getting count" %
(ord(cmd), ord(channel)))
return
data = self.channels[channel].read(ord(num))
self.conn.write(data)
if self.debug:
print(
"cmd=%0x cmdSerReadM channel=%d num=%d" %
(ord(cmd), ord(channel), ord(num)))
def cmdSerWriteM(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerWriteM timout getting channel" % (ord(cmd)))
return
if channel not in self.channels:
print(
"cmd=%0x cmdSerWriteM bad channel=%d" %
(ord(cmd), ord(channel)))
return
num = self.conn.read(1, self.timeout)
if not num:
print(
"cmd=%0x cmdSerWriteM channel=%d timeout getting count" %
(ord(cmd), ord(channel)))
return
data = self.conn.read(ord(num), self.timeout)
self.channels[channel].write(data)
if self.debug:
print(
"cmd=%0x cmdSerWriteM channel=%d num=%d" %
(ord(cmd), ord(channel), ord(num)))
self.channels[channel]._cmdWorker()
def cmdSerWrite(self, cmd):
channel = self.conn.read(1, self.timeout)
if not channel:
print("cmd=%0x cmdSerWrite timout getting channel" % (ord(cmd)))
return
if channel not in self.channels:
print(
"cmd=%0x cmdSerWrite bad channel=%d" %
(ord(cmd), ord(channel)))
return
byte = self.conn.read(1, self.timeout)
if not byte:
print(
"cmd=%0x cmdSerWrite channel=%d timeout getting byte" %
(ord(cmd), ord(channel)))
return
self.channels[channel].write(byte)
if self.debug:
print(
"cmd=%0x cmdSerWrite channel=%d byte=%0x" %
(ord(cmd), ord(channel), ord(byte)))
self.channels[channel]._cmdWorker()
def cmdPrint(self, cmd):
data = self.conn.read(1, self.timeout)
if self.vprinter:
self.vprinter.write(data)
else:
print(
"cmd=%0x cmdPrint byte=%0x WARN: printing not enabled" %
(ord(cmd), ord(data)))
if self.debug:
print("cmd=%0x cmdPrint byte=%0x" % (ord(cmd), ord(data)))
def cmdPrintFlush(self, cmd):
if self.vprinter:
self.vprinter.printFlush()
else:
print(
"cmd=%0x cmdPrintFlush WARN: printing not enabled" %
(ord(cmd)))
if self.debug:
print("cmd=%0x cmdPrintFlush" % (ord(cmd)))
def _NamedObjCore(self, mode):
drive = 255
fn = None
data = self.conn.read(1, self.timeout)
if not data:
drive = 0
if drive:
nameLen = ord(data)
fn = self.conn.read(nameLen, self.timeout)
if not fn:
drive = 0
if drive:
fn2 = self.aliases['namedobj'].get(fn.upper(), None)
if fn2 != None:
print('Alias: %s -> %s' % (fn, fn2))
fn = fn2
exists = os.path.exists(fn)
if mode.startswith('r'):
if not exists:
drive = 0
else:
if (self.files[drive] is None) or (self.files[drive] and self.files[drive].file.name != fn):
self.open(drive, fn, mode='ab+', raw=True, proto='namedobj', dosplus=False)
self.NamedObjDrive = drive
if mode.startswith('w'):
if exists:
drive = 0
else:
self.open(drive, fn, mode='ab+', raw=True, proto='namedobj', dosplus=False)
self.namedObjDrive = drive
self.conn.write(chr(drive))
return drive, fn
def cmdNamedObjMount(self, cmd):
drive, fn = self._NamedObjCore('r')
if drive == 0:
print("cmd=%0x cmdNamedObjMount: Error: %s" % (ord(cmd), fn))
if self.debug:
print("cmd=%0x cmdNamedObjMount drive=%d" % (ord(cmd), drive))
def cmdNamedObjCreate(self, cmd):
drive, fn = self._NamedObjCore('w')
if drive == 0:
print("cmd=%0x cmdNamedObjCreate: Error: %s" % (ord(cmd), fn))
if self.debug:
print("cmd=%0x cmdNamedObjCreate drive=%d" % (ord(cmd), drive))
# $FA - PlaySound Extension
# Plays a sound out of the default system audio device
#
# Prerequisites: Must enable experimental feature flag:
# -x playsound
# option experimental playsound
#
# Byte Value Description
# ---- ----- ------------
# 1 $FA OP_PLAYSOUND
# 2 N Length
# 3+N - Filename
#
# Return Value:
# 0 - OK
# $F4 - ERROR - File not found
# $FA - ERROR - Playsound Not enabled
#
def _doPlaySound(self, name):
err = E_OK
if 'playsound' in self.args.experimental:
import playsound
from playsound import playsound
else:
err = E_PLAYSOUND
print("Playsound not enabled. use: -x playsound")
if not err:
fn2 = self.aliases['playsound'].get(name.upper(), None)
if fn2 != None:
print('Alias: %s -> %s' % (name, fn2))
name = fn2
pwd = os.getcwd()
os.chdir(self.dirs['playsound'])
try:
if not os.path.exists(name):
err = E_READ
except TypeError:
err = E_READ
os.chdir(pwd)
if not err:
direct = False
#if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# machine = platform.machine()
# if machine.startswith('arm') or machine.startswith('aarch'):
# direct = True
if direct:
_playsound(name, False)
else:
proc = multiprocessing.Process(target=_playsound, args=(name, self.dirs['playsound'], True))
self.procs.append(proc)
proc.start()
return err
def cmdPlaySound(self, cmd):
err = E_OK
if 'playsound' not in self.args.experimental:
err = E_PLAYSOUND
print("Playsound not enabled. use: -x playsound")
data = self.conn.read(1, self.timeout)
length = unpack(">B", data)[0]
name = None
if length > 0:
name = self.conn.read(length, self.timeout)
else:
err = E_READ
if not err:
err = self._doPlaySound(name)
self.conn.write(chr(err))
if self.debug or err:
print("cmd=%0x rc=%d playsound(%s)" % (ord(cmd), err, name))
def cmdPlaySoundStop(self, cmd):
count = len(self.procs)
for proc in self.procs:
proc.terminate()
self.procs = []
if self.debug:
print("cmd=%0x playsound stop: %d procs" % (ord(cmd), count))
def cmdErr(self, cmd):
print("cmd=%0x cmdErr" % ord(cmd))
# raise Exception("cmd=%0x cmdErr" % ord(cmd))
# ## EmCee Server # ##
def _emCeeLoadFile(self, filnum, fname, fmode, ftyp=0, opn=False, error=0):
address = 0
size = 0
checksum = 0
if not error:
try:
fname = self.aliases['mc'].get(fname.upper(), fname)
os.chdir(self.dirs['mc'])
if os.path.exists(fname):
self.files[filnum] = CocoCas(fname, fmode)
self.files[filnum].seek()
# self.files[filnum] = MlFileReader(fname, fmode, ftyp)
# if ftyp == 2: # ml file
# self.files[filnum].readHeader()
# address = self.files[filnum].addr
# size = self.files[filnum]# .
else:
error = E_MC_NE
except IOError as e:
if e.errno == 21:
error = E_MC_FN
elif e.errno == 13:
error = E_MC_FM
else:
error = E_MC_FS
except BaseException as e:
error = E_MC_IO
if not error:
try:
data = self.files[filnum].read(temp=True)
stat = self.files[filnum].stat()
size = stat['blk']['blklen']
address = stat['nf']['current']
# length = min(SECSIZ, self.files[filnum].length)
# data = self.files[filnum].tempRead(length)
if data:
checksum = unpack(">H", dwCrc16(data))[0]
else:
error = E_MC_IO
except BaseException:
error = E_MC_IO
if error:
checksum = error
if opn:
response = chr(error)
else:
response = pack(">HHH", address, size, checksum)
self.conn.write(response)
return error
def _emCeeSaveFile(self, filnum, name, mode, exaddr, size, error):
if not error:
name = self.aliases['mc'].get(name.upper(), name)
self.files[filnum] = CocoCas(name, 'wb')
load = start = ascflg = 0
ascflg = 0xff
if mode == 2:
load = size
start = exaddr
filetype = 2 # ml
ascflg = 0
elif mode == 0:
filetype = 0 # basic
ascflg = 0 # basic
else:
filetype = 1 # data
os.chdir(self.dirs['mc'])
nf = CocoCasNameFile(
filename=name.split(os.path.sep)[-1].split('.')[0][:8].upper(),
filetype=filetype,
ascflg=ascflg,
gap=1,
load=load,
start=start,
)
nfblk = CocoCasBlock(nf.getBlockData(), blktyp=0) # namefile
self.files[filnum].nf = nf
self.files[filnum].writeBlock(nfblk)
self.conn.write(chr(error))
return error
def cmdEmCeeLoadFile(self, cmd):
error = 0
info = self.conn.read(2, self.timeout)
if not info:
print(
"cmd=%0x cmdEmCeeLoadFile timout getting command info" %
(ord(cmd)))
error = E_MC_IO # IO ERROR
if not error:
ftyp = ord(info[0])
fnamelen = ord(info[1])
fname = self.conn.read(fnamelen, self.timeout)
if not fname:
print(
"cmd=%0x cmdEmCeeLoadFile timout getting file name" %
(ord(cmd)))
error = E_MC_FN
if not error:
error = self._emCeeLoadFile(0, fname, 'rb', ftyp)
if error:
print("cmd=%0x cmdEmCeeLoadFile error=%d" % (ord(cmd), error))
return
elif self.debug:
print("cmd=%0x cmdEmCeeLoadFile" % ord(cmd))
def cmdEmCeeOpenFile(self, cmd):
fmodes = {
1: 'rb',
2: 'wb+',
3: 'ab+',
}
error = 0
info = self.conn.read(2, self.timeout)
if not info:
print(
"cmd=%0x cmdEmCeeLoadFile timout getting command info" %
(ord(cmd)))
error = E_MC_IO # IO ERROR
if not error:
finfo = ord(info[0])
filnum = finfo & 0x0f
fmode = fmodes[((finfo & 0xc0) >> 6)]
fnamelen = ord(info[1])
fname = self.conn.read(fnamelen, self.timeout)
if not fname:
print(
"cmd=%0x cmdEmCeeLoadFile timout getting file name" %
(ord(cmd)))
error = E_MC_FN
if fmode.startswith('r'):
error = self._emCeeLoadFile(
filnum, fname, fmode, opn=True, error=error)