This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathserial.js
1198 lines (1126 loc) · 47.8 KB
/
serial.js
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
/**
* @fileoverview Implements the PCx86 SerialPort component
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2020 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/shared/lib/defines.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
"use strict";
if (typeof module !== "undefined") {
var Str = require("../../shared/lib/strlib");
var Web = require("../../shared/lib/weblib");
var Component = require("../../shared/lib/component");
var State = require("../../shared/lib/state");
var PCx86 = require("./defines");
var Messages = require("./messages");
var ChipSet = require("./chipset");
}
/**
* SerialPort class
*
* The class property declarations below started as a way of informing the code inspector of the controlBuffer
* property, which remained undefined until a setBinding() call set it later, but I've since decided that explicitly
* initializing such properties in the constructor is a better way to go -- even though it's more code -- because
* JavaScript compilers are supposed to be happier when the underlying object structures aren't constantly changing.
*
* Besides, I'm not sure I want to get into documenting every property this way, for this or any/every other class,
* let alone getting into which ones should be considered private or protected, because PCjs isn't really a library
* for third-party apps.
*
* @class SerialPort
* @property {number} iAdapter
* @property {number} portBase
* @property {number} nIRQ
* @property {string|null} consoleBuffer
* @property {HTMLTextAreaElement} controlBuffer (DOM element bound to the port for rudimentary output; see transmitByte())
* @unrestricted (allows the class to define properties, both dot and named, outside of the constructor)
*/
class SerialPort extends Component {
/**
* SerialPort(parms)
*
* The SerialPort component has the following component-specific (parms) properties:
*
* adapter: 1 (port 0x3F8) or 2 (port 0x2F8); 0 if not defined
*
* binding: name of a control (based on its "binding" attribute) to bind to this port's I/O;
* as a special case, it can be set to "console" to direct all output to the component's default
* println() handler (eg, the Control Panel's "print" control, if any, or console.log() if using
* a DEBUG or non-COMPILED machine)
*
* tabSize: a non-zero number specifies the tab-stop multiple to use for automatic tab-to-space
* conversion; it applies only to the above binding, and the default is 0 (no tab conversion)
*
* charBOL: a non-zero number specifies the ASCII code of a character to display at the beginning
* of every line; it applies only to the above binding, and the default is 0 (no BOL character)
*
* In the future, we may support 'port' and 'irq' properties that allow the machine to define a non-standard
* serial port configuration, instead of only our pre-defined 'adapter' configurations.
*
* NOTE: Since the XSL file defines 'adapter' as a number, not a string, there's no need to use parseInt(),
* and as an added benefit, we don't need to worry about whether a hex or decimal format was used.
*
* This hard-coded approach mimics the original IBM PC Asynchronous Adapter configuration, which contained
* a pair of "shunt modules" that allowed the user to select a port address/IRQ combo of either 0x3F8/IRQ4
* ("Primary") or 0x2F8/IRQ3 ("Secondary").
*
* DOS names the first adapter listed by the ROM BIOS as "COM1", even if that adapter is a secondary adapter,
* so don't assume that COM1 always maps to port 0x3F8/IRQ4. Internally, I try avoid confusion by always
* starting with a primary adapter and giving that adapter an ID of "com1". But different operating systems
* may follow different device enumeration and naming conventions, so don't make too much of my internally
* assigned IDs.
*
* @this {SerialPort}
* @param {Object} parms
*/
constructor(parms)
{
super("SerialPort", parms, Messages.SERIAL);
this.iAdapter = parms['adapter'];
switch (this.iAdapter) {
case 1:
this.portBase = 0x3F8;
this.nIRQ = ChipSet.IRQ.COM1;
break;
case 2:
this.portBase = 0x2F8;
this.nIRQ = ChipSet.IRQ.COM2;
break;
default:
if (this.idComponent != "test") {
Component.warning("Unrecognized serial adapter #" + this.iAdapter);
return;
}
break;
}
/*
* consoleBuffer becomes a string that records serial port output if the 'binding' property is set to the
* reserved name "console". Nothing is written to the console, however, until a linefeed (0x0A) is output
* or the string length reaches a threshold (currently, 1024 characters).
*/
this.consoleBuffer = null;
/*
* controlBuffer is a DOM element bound to the port (currently used for output only; see transmitByte()).
*
* Example: CTTY COM2
*
* The CTTY DOS command redirects all CON I/O to the specified serial port (eg, COM2), which it assumes is
* connected to a serial terminal, and therefore anything it *transmits* via COM2 will be displayed by the
* terminal. It further assumes that anything typed on such a terminal is NOT displayed, so as DOS *receives*
* serial input, DOS *transmits* the appropriate characters back to the terminal via COM2.
*
* As a result, controlBuffer only needs to be updated by the transmitByte() function.
*/
this.controlBuffer = null;
/*
* If controlBuffer is being used AND 'tabSize' is set, then we make an attempt to monitor the characters
* being echoed via transmitByte(), maintain a logical column position, and convert any tabs into the appropriate
* number of spaces.
*
* Another controlBuffer feature is charBOL, which, if nonzero, specifies a character to automatically output
* at the beginning of every line. This probably isn't generally useful; I use it internally to preformat serial
* output.
*/
this.tabSize = parms['tabSize'] || 0;
this.charBOL = parms['charBOL'] || 0;
this.charPrev = 0;
this.iLogicalCol = 0;
this.bMSRInit = SerialPort.MSR.CTS | SerialPort.MSR.DSR;
this.fNullModem = true;
/*
* Normally, any HTML controls defined within the scope of the component's XML element are *implicitly*
* bound to us. For example, in the XML below, the textarea control will automatically trigger a call to
* setBinding() with sBinding set to "serialWindow" and control set to an HTMLTextAreaElement.
*
* <serial id="com1">
* <control type="container" class="pcjs-textarea">
* <control type="textarea" binding="serialWindow"/>
* </control>
* </serial>
*
* However, this component also supports an *explicit* binding attribute, which can either be the hard-coded
* name "console" (for routing all output to the system console) or the name of a control binding that has
* been defined in another component (eg, an HTMLTextAreaElement defined as part of the Control Panel layout).
*/
let sBinding = parms['binding'];
if (sBinding == "console") {
this.consoleBuffer = "";
} else {
/*
* If the SerialPort wants to bind to a control (eg, "print") in a DIFFERENT component (eg, "Panel"),
* then it specifies the name of that control with the 'binding' property. The SerialPort constructor
* will then call bindExternalControl(), which looks up the control, and then passes it to our own
* setBinding() handler.
*
* For bindExternalControl() to succeed, it also need to know the target component; for now, that's
* been hard-coded to "Panel", in part because that's one of the few components we can rely upon
* initializing before we do, but it would be a simple matter to include a component type or ID as part
* of the 'binding' property as well, if we need more flexibility later.
*
* NOTE: If sBinding is not the name of a valid Control Panel DOM element, this call does nothing.
*/
Component.bindExternalControl(this, sBinding);
}
/*
* No connection until initConnection() is called.
*/
this.sDataReceived = "";
this.connection = this.sendData = this.updateStatus = null;
this.fAutoFlow = false;
/*
* Export all functions required by bindConnection() or initConnection(), whichever is required.
*/
this['exports'] = {
'bind': this.bindConnection,
'connect': this.initConnection,
'receiveData': this.receiveData,
'receiveStatus': this.receiveStatus
};
}
/**
* bindConnection(connection, receiveData, fAutoFlow)
*
* This is basically a lighter-weight version of initConnection(), used by built-in components
* like TestController, as opposed to components in external machines, which require more work to connect.
*
* @this {SerialPort}
* @param {Component} connection
* @param {function()} receiveData
* @param {boolean} [fAutoFlow] (true to enable automatic flow control; default is false)
* @return {boolean}
*/
bindConnection(connection, receiveData, fAutoFlow = false)
{
if (!this.connection) {
this.connection = connection;
this.sendData = receiveData;
this.fAutoFlow = fAutoFlow;
return true;
}
return false;
}
/**
* bindMouse(id, mouse, fnUpdate)
*
* @this {SerialPort}
* @param {string} id
* @param {Mouse} mouse
* @param {function(number)} fnUpdate
* @return {Component|null}
*/
bindMouse(id, mouse, fnUpdate)
{
let component = null;
if (id == this.idComponent && !this.connection) {
this.connection = mouse;
this.updateStatus = fnUpdate;
this.fNullModem = false;
component = this;
}
return component;
}
/**
* setBinding(sHTMLType, sBinding, control, sValue)
*
* @this {SerialPort}
* @param {string} sHTMLType is the type of the HTML control (eg, "button", "list", "text", "submit", "textarea", "canvas")
* @param {string} sBinding is the value of the 'binding' parameter stored in the HTML control's "data-value" attribute (eg, "buffer")
* @param {HTMLElement} control is the HTML control DOM object (eg, HTMLButtonElement)
* @param {string} [sValue] optional data value
* @return {boolean} true if binding was successful, false if unrecognized binding request
*/
setBinding(sHTMLType, sBinding, control, sValue)
{
if (!sHTMLType || sHTMLType == "textarea") {
let serial = this;
this.bindings[sBinding] = this.controlBuffer = /** @type {HTMLTextAreaElement} */ (control);
/*
* By establishing an onkeypress handler here, we make it possible for DOS commands like
* "CTTY COM1" to more or less work (use "CTTY CON" to restore control to the DOS console).
*/
this.controlBuffer.onkeydown = function onKeyDown(event) {
/*
* This is required in addition to onkeypress, because it's the only way to prevent
* BACKSPACE (keyCode 8) from being interpreted by the browser as a "Back" operation;
* moreover, not all browsers generate an onkeypress notification for BACKSPACE.
*
* A related problem exists for Ctrl-key combinations in most Windows-based browsers
* (eg, IE, Edge, Chrome for Windows, etc), because keys like Ctrl-C and Ctrl-S have
* special meanings (eg, Copy, Save). To the extent the browser will allow it, we
* attempt to disable that default behavior when this control receives an onkeydown
* event for one of those keys (probably the only event the browser generates for them).
*/
event = event || window.event;
let keyCode = event.keyCode;
if (keyCode === 0x08 || event.ctrlKey && keyCode >= 0x41 && keyCode <= 0x5A) {
if (event.preventDefault) event.preventDefault();
if (keyCode > 0x40) keyCode -= 0x40;
serial.receiveData(keyCode);
}
return true;
};
this.controlBuffer.onkeypress = function onKeyPress(event) {
/*
* Browser-independent keyCode extraction; refer to onKeyPress() and the other key event
* handlers in keyboard.js.
*/
event = event || window.event;
let keyCode = event.which || event.keyCode;
serial.receiveData(keyCode);
/*
* Since we're going to remove the "readonly" attribute from the <textarea> control
* (so that the soft keyboard activates on iOS), instead of calling preventDefault() for
* selected keys (eg, the SPACE key, whose default behavior is to scroll the page), we must
* now call it for *all* keys, so that the keyCode isn't added to the control immediately,
* on top of whatever the machine is echoing back, resulting in double characters.
*/
if (event.preventDefault) event.preventDefault();
return true;
};
/*
* Now that we've added an onkeypress handler that calls preventDefault() for ALL keys, the control
* itself no longer needs the "readonly" attribute; we primarily need to remove it for iOS browsers,
* so that the soft keyboard will activate, but it shouldn't hurt to remove the attribute for all browsers.
*/
this.controlBuffer.removeAttribute("readonly");
return true;
}
// default:
// if (!this.iAdapter) {
// control.removeAttribute("readonly");
// }
// break;
// }
return false;
}
/**
* initBus(cmp, bus, cpu, dbg)
*
* @this {SerialPort}
* @param {Computer} cmp
* @param {BusX86} bus
* @param {CPUx86} cpu
* @param {DebuggerX86} dbg
*/
initBus(cmp, bus, cpu, dbg)
{
this.cmp = cmp;
if (this.iAdapter) {
this.bus = bus;
this.cpu = cpu;
this.dbg = dbg;
let serial = this;
this.timerReceiveNext = this.cpu.addTimer(this.id + ".receive", function receiveDataTimer() {
serial.receiveData();
});
this.timerTransmitNext = this.cpu.addTimer(this.id + ".transmit", function transmitDataTimer() {
serial.transmitData();
});
this.chipset = cmp.getMachineComponent("ChipSet");
bus.addPortInputTable(this, SerialPort.aPortInput, this.portBase);
bus.addPortOutputTable(this, SerialPort.aPortOutput, this.portBase);
}
this.setReady();
}
/**
* initConnection(fNullModem)
*
* If a machine 'connection' parameter exists of the form "{sourcePort}->{targetMachine}.{targetPort}",
* and "{sourcePort}" matches our idComponent, then look for a component with id "{targetMachine}.{targetPort}".
*
* If the target component is found, then verify that it has exported functions with the following names:
*
* receiveData(data): called when we have data to transmit; aliased internally to sendData(data)
* receiveStatus(pins): called when our control signals have changed; aliased internally to updateStatus(pins)
*
* For now, we're not going to worry about communication in the other direction, because when the target component
* performs its own initConnection(), it will find our receiveData() and receiveStatus() functions, at which point
* communication in both directions should be established, and the circle of life is complete.
*
* For added robustness, if the target machine initializes much more slowly than we do, and our connection attempt
* fails, that's OK, because when it finally initializes, its initConnection() will call our initConnection();
* if we've already initialized, no harm done.
*
* @this {SerialPort}
* @param {boolean} [fNullModem] (caller's null-modem setting, to ensure our settings are in agreement)
*/
initConnection(fNullModem)
{
if (!this.connection) {
let sConnection = this.cmp.getMachineParm('connection');
if (sConnection) {
let asParts = sConnection.split('->');
if (asParts.length == 2) {
let sSourceID = Str.trim(asParts[0]);
if (sSourceID != this.idComponent) return; // this connection string is intended for another instance
let sTargetID = Str.trim(asParts[1]);
this.connection = Component.getComponentByID(sTargetID);
if (this.connection) {
let exports = this.connection['exports'];
if (exports) {
let fnConnect = /** @function */ (exports['connect']);
if (fnConnect) fnConnect.call(this.connection, this.fNullModem);
this.sendData = exports['receiveData'];
if (this.sendData) {
this.fNullModem = fNullModem;
this.updateStatus = exports['receiveStatus'];
this.status("Connected %s.%s to %s", this.idMachine, sSourceID, sTargetID);
return;
}
}
}
}
/*
* Changed from notice() to status() because sometimes a connection fails simply because one of us is a laggard.
*/
this.status("Unable to establish connection: %s", sConnection);
}
}
}
/**
* powerUp(data, fRepower)
*
* @this {SerialPort}
* @param {Object|null} data
* @param {boolean} [fRepower]
* @return {boolean} true if successful, false if failure
*/
powerUp(data, fRepower)
{
if (!fRepower) {
/*
* This is as late as we can currently wait to make our first inter-machine connection attempt;
* even so, the target machine's initialization process may still be ongoing, so any connection
* may be not fully resolved until the target machine performs its own initConnection(), which will
* in turn invoke our initConnection() again.
*/
this.initConnection(this.fNullModem);
if (!data || !this.restore) {
this.reset();
} else {
if (!this.restore(data)) return false;
}
}
return true;
}
/**
* powerDown(fSave, fShutdown)
*
* @this {SerialPort}
* @param {boolean} [fSave]
* @param {boolean} [fShutdown]
* @return {Object|boolean} component state if fSave; otherwise, true if successful, false if failure
*/
powerDown(fSave, fShutdown)
{
return fSave? this.save() : true;
}
/**
* reset()
*
* @this {SerialPort}
*/
reset()
{
this.initState();
}
/**
* save()
*
* This implements save support for the SerialPort component.
*
* @this {SerialPort}
* @return {Object}
*/
save()
{
let state = new State(this);
state.set(0, this.saveRegisters());
return state.data();
}
/**
* restore(data)
*
* This implements restore support for the SerialPort component.
*
* @this {SerialPort}
* @param {Object} data
* @return {boolean} true if successful, false if failure
*/
restore(data)
{
return this.initState(data[0]);
}
/**
* initState(data)
*
* @this {SerialPort}
* @param {Array} [data]
* @return {boolean} true if successful, false if failure
*/
initState(data)
{
/*
* The NS8250A spec doesn't explicitly say what the RBR and THR are initialized to on a reset,
* but I think we can safely assume zeros. Similarly, we reset the baud rate Divisor Latch (wDL)
* to an arbitrary but consistent default (DL_DEFAULT).
*/
let i = 0;
if (data === undefined) {
data = [
0, // RBR
0, // THR
SerialPort.DL_DEFAULT, // DL
0, // IER
SerialPort.IIR.NO_INT, // IIR
0, // LCR
0, // MCR
SerialPort.LSR.THRE | SerialPort.LSR.TSRE, // LSR
this.bMSRInit, // MSR
[]
];
}
this.bRBR = data[i++];
this.bTHR = data[i++];
this.wDL = data[i++];
this.bIER = data[i++];
this.bIIR = data[i++];
this.bLCR = data[i++];
this.bMCR = data[i++];
this.bLSR = data[i++];
this.bMSR = data[i++];
this.abReceive = data[i];
return true;
}
/**
* saveRegisters()
*
* @this {SerialPort}
* @return {Array}
*/
saveRegisters()
{
let i = 0;
let data = [];
data[i++] = this.bRBR;
data[i++] = this.bTHR;
data[i++] = this.wDL;
data[i++] = this.bIER;
data[i++] = this.bIIR;
data[i++] = this.bLCR;
data[i++] = this.bMCR;
data[i++] = this.bLSR;
data[i++] = this.bMSR;
data[i] = this.abReceive;
return data;
}
/**
* getBaudTimeout()
*
* The 16-bit Divisor Latch is stored in wDL. If we take the frequency value 1843200 and divide it by wDL*128,
* we get the maximum number of bytes per second that the SerialPort interface should generate. For example,
* if a baud rate of 1200 is being used, the divisor will be 0x60 (96), so we calculate 1843200/(96*128) = 150,
* which means there should be a 1000ms/150 or 6.667ms delay between bytes delivered.
*
* @this {SerialPort}
* @return {number} (number of milliseconds per byte)
*/
getBaudTimeout()
{
let nBytesPerSecond = 1843200 / ((this.wDL || 1) << 7);
return (1000 / nBytesPerSecond)|0;
}
/**
* receiveData(data)
*
* This replaces the old sendRBR() function, which expected an Array of bytes. We still support that,
* but in order to support connections with other SerialPort components (ie, the PC8080 SerialPort), we
* have added support for numbers and strings as well. If no data is specified at all, then all we do
* is "clock" any remaining data into the receiver.
*
* @this {SerialPort}
* @param {number|string|Array} [data]
* @return {boolean} true if received, false if not
*/
receiveData(data)
{
if (data != null) {
if (typeof data == "number") {
this.abReceive.push(data);
}
else if (typeof data == "string") {
for (let i = 0; i < data.length; i++) {
this.abReceive.push(data.charCodeAt(i));
}
}
else {
this.abReceive = this.abReceive.concat(data);
}
}
this.advanceRBR();
return true; // for now, return true regardless, since we're buffering everything anyway
}
/**
* receiveStatus(pins)
*
* NOTE: Prior to the addition of this interface, the CTS and DSR bits were initialized set and remained set
* for the life of the machine. It is entirely appropriate that this is the only way those bits can be changed,
* because they represent external control signals.
*
* @this {SerialPort}
* @param {number} pins
*/
receiveStatus(pins)
{
let bMSROld = this.bMSR;
this.bMSR &= ~(SerialPort.MSR.CTS | SerialPort.MSR.DSR);
if (pins & RS232.CTS.MASK) {
this.bMSR |= SerialPort.MSR.CTS | SerialPort.MSR.DCTS;
}
if (pins & RS232.DSR.MASK) {
this.bMSR |= SerialPort.MSR.DSR | SerialPort.MSR.DDSR;
}
if (bMSROld != this.bMSR) this.updateIIR();
}
/**
* advanceRBR()
*
* @this {SerialPort}
*/
advanceRBR()
{
if (this.abReceive.length > 0 && !(this.bLSR & SerialPort.LSR.DR)) {
if (!this.fAutoFlow || (this.bMCR & SerialPort.MCR.RTS)) {
this.bRBR = this.abReceive.shift();
this.bLSR |= SerialPort.LSR.DR;
if (this.abReceive.length && this.cpu) {
this.cpu.setTimer(this.timerReceiveNext, this.getBaudTimeout());
}
}
}
this.updateIIR();
}
/**
* inRBR(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3F8 or 0x2F8)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inRBR(port, addrFrom)
{
let b = ((this.bLCR & SerialPort.LCR.DLAB) ? (this.wDL & 0xff) : this.bRBR);
this.printMessageIO(port, undefined, addrFrom, (this.bLCR & SerialPort.LCR.DLAB) ? "DLL" : "RBR", b);
this.bLSR &= ~SerialPort.LSR.DR;
this.advanceRBR();
return b;
}
/**
* inIER(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3F9 or 0x2F9)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inIER(port, addrFrom)
{
let b = ((this.bLCR & SerialPort.LCR.DLAB) ? (this.wDL >> 8) : this.bIER);
this.printMessageIO(port, undefined, addrFrom, (this.bLCR & SerialPort.LCR.DLAB) ? "DLM" : "IER", b);
return b;
}
/**
* inIIR(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FA or 0x2FA)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inIIR(port, addrFrom)
{
let b = this.bIIR;
/*
* Reading the IIR is supposed to clear the INT_THR condition (as is another write to the THR).
*/
if (b == SerialPort.IIR.INT_THR) {
this.bIIR = SerialPort.IIR.NO_INT;
}
this.printMessageIO(port, undefined, addrFrom, "IIR", b);
return b;
}
/**
* inLCR(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FB or 0x2FB)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inLCR(port, addrFrom)
{
let b = this.bLCR;
this.printMessageIO(port, undefined, addrFrom, "LCR", b);
return b;
}
/**
* inMCR(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FC or 0x2FC)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inMCR(port, addrFrom)
{
let b = this.bMCR;
this.printMessageIO(port, undefined, addrFrom, "MCR", b);
return b;
}
/**
* inLSR(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FD or 0x2FD)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inLSR(port, addrFrom)
{
let b = this.bLSR;
this.printMessageIO(port, undefined, addrFrom, "LSR", b);
return b;
}
/**
* inMSR(port, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FE or 0x2FE)
* @param {number} [addrFrom] (not defined whenever the Debugger tries to read the specified port)
* @return {number} simulated port value
*/
inMSR(port, addrFrom)
{
let b = this.bMSR;
this.bMSR &= ~(SerialPort.MSR.DCTS | SerialPort.MSR.DDSR);
this.printMessageIO(port, undefined, addrFrom, "MSR", b);
return b;
}
/**
* outTHR(port, bOut, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3F8 or 0x2F8)
* @param {number} bOut
* @param {number} [addrFrom] (not defined whenever the Debugger tries to write the specified port)
*/
outTHR(port, bOut, addrFrom)
{
let serial = this;
this.printMessageIO(port, bOut, addrFrom, (this.bLCR & SerialPort.LCR.DLAB) ? "DLL" : "THR");
if (this.bLCR & SerialPort.LCR.DLAB) {
this.wDL = (this.wDL & ~0xff) | bOut;
} else {
this.bTHR = bOut;
this.bLSR &= ~(SerialPort.LSR.THRE | SerialPort.LSR.TSRE);
/*
* If transmitByte() returned success, we used to immediately re-set the transmitter empty bits:
*
* this.bLSR |= (SerialPort.LSR.THRE | SerialPort.LSR.TSRE);
*
* But when we're connected to a virtual device that has no measurable delay, that sets the bits
* too quickly. We now arm a timer based on the programmed baud rate, and set the above bits only
* when that timer fires.
*
* Additionally, we no longer care if transmitByte() succeeds, because whether or not a connected
* device or component received the data is irrelevant to the internal mechanics of the serial port.
*
* TODO: Determine if we should also flush/zero bTHR after transmission.
*/
this.cpu.nonCPU(function() {
return serial.transmitByte(bOut);
});
this.cpu.setTimer(this.timerTransmitNext, this.getBaudTimeout());
this.updateIIR();
}
}
/**
* outIER(port, bOut, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3F9 or 0x2F9)
* @param {number} bOut
* @param {number} [addrFrom] (not defined whenever the Debugger tries to write the specified port)
*/
outIER(port, bOut, addrFrom)
{
this.printMessageIO(port, bOut, addrFrom, (this.bLCR & SerialPort.LCR.DLAB) ? "DLM" : "IER");
if (this.bLCR & SerialPort.LCR.DLAB) {
this.wDL = (this.wDL & 0xff) | (bOut << 8);
} else {
this.bIER = bOut;
}
}
/**
* outLCR(port, bOut, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FB or 0x2FB)
* @param {number} bOut
* @param {number} [addrFrom] (not defined whenever the Debugger tries to write the specified port)
*/
outLCR(port, bOut, addrFrom)
{
this.printMessageIO(port, bOut, addrFrom, "LCR");
this.bLCR = bOut;
}
/**
* outMCR(port, bOut, addrFrom)
*
* @this {SerialPort}
* @param {number} port (eg, 0x3FC or 0x2FC)
* @param {number} bOut
* @param {number} [addrFrom] (not defined whenever the Debugger tries to write the specified port)
*/
outMCR(port, bOut, addrFrom)
{
let delta = (bOut ^ this.bMCR);
this.printMessageIO(port, bOut, addrFrom, "MCR");
this.bMCR = bOut;
/*
* Whenever DTR or RTS changes, we also need to notify any connected machine or mouse, via updateStatus().
*/
if (delta & (SerialPort.MCR.DTR | SerialPort.MCR.RTS)) {
if (this.updateStatus) {
let pins = 0;
if (this.fNullModem) {
pins |= (bOut & SerialPort.MCR.RTS)? RS232.CTS.MASK : 0;
pins |= (bOut & SerialPort.MCR.DTR)? (RS232.DSR.MASK | RS232.CD.MASK): 0;
} else {
pins |= (bOut & SerialPort.MCR.RTS)? RS232.RTS.MASK : 0;
pins |= (bOut & SerialPort.MCR.DTR)? RS232.DTR.MASK : 0;
}
this.updateStatus.call(this.connection, pins);
}
/*
* Throw in a call to advanceRBR() for good measure, in case fAutoFlow is set and RTS was just enabled.
*/
this.advanceRBR();
}
}
/**
* updateIIR()
*
* @this {SerialPort}
*/
updateIIR()
{
let bIIR = -1;
/*
* We check all the interrupt conditions in priority order. TODO: Add INT_LSR.
*/
if ((this.bLSR & SerialPort.LSR.DR) && (this.bIER & SerialPort.IER.RBR_AVAIL)) {
bIIR = SerialPort.IIR.INT_RBR;
}
else if ((this.bLSR & SerialPort.LSR.THRE) && (this.bIER & SerialPort.IER.THR_EMPTY)) {
bIIR = SerialPort.IIR.INT_THR;
}
else if ((this.bMSR & (SerialPort.MSR.DCTS | SerialPort.MSR.DDSR)) && (this.bIER & SerialPort.IER.MSR_DELTA)) {
bIIR = SerialPort.IIR.INT_MSR;
}
if (bIIR >= 0) {
this.bIIR &= ~(SerialPort.IIR.NO_INT | SerialPort.IIR.INT_BITS);
this.bIIR |= bIIR;
/*
* I still throttle SerialPort interrupts by passing a hard-coded delay of 100 instructions to setIRR(),
* even though we are now (theoretically) honoring the programmed baud rate. The setIRR() delay does not
* ensure any particular baud rate, it simply gives the underlying Interrupt Service Routine (ISR) some
* breathing room.
*
* The Microsoft Windows 1.01 serial mouse driver ISR issues an EOI before it has safely exited, presumably
* relying on the fact that a 1200 baud serial device would not normally interrupt frequently enough to
* blow the stack. However, in PCx86, all you have to do is remove the delay below and enable Debugger
* messages on every serial interrupt and mouse event, eg:
*
* m serial on;m pic on;m mouse on
*
* to slow the machine down to the point where serial mouse interrupts overwhelm the ISR. The Debugger
* messages display the current stack pointer, which you can watch drop to zero and then wrap around, no
* doubt trampling lots of code and data along the way.
*
* This problem could also occur without being forced by the Debugger; eg, if your physical machine's mouse
* was configured for a high interrupt rate, and your browser generated mouse events at a comparable rate.
*/
if (this.chipset && this.nIRQ) this.chipset.setIRR(this.nIRQ, 100);
} else {
this.bIIR = SerialPort.IIR.NO_INT;
if (this.chipset && this.nIRQ) this.chipset.clearIRR(this.nIRQ);
}
}
/**
* transmitByte(b)
*
* @this {SerialPort}
* @param {number} b
* @return {boolean} true if transmitted, false if not
*/
transmitByte(b)
{
let fTransmitted = false;
this.printMessage("transmitByte(" + Str.toHexByte(b) + ")");
if (this.sendData) {
if (this.sendData.call(this.connection, b)) {
fTransmitted = true;
}
}
if (this.controlBuffer) {
if (b == 0x0D) {
this.iLogicalCol = 0;
}
else if (b == 0x08) {
this.controlBuffer.value = this.controlBuffer.value.slice(0, -1);
/*
* TODO: Back up the correct number of columns if the character erased was a tab.
*/
if (this.iLogicalCol > 0) this.iLogicalCol--;
}
else {
let s = Str.toASCIICode(b); // formerly: String.fromCharCode(b);
let nChars = s.length; // formerly: (b >= 0x20? 1 : 0);
if (b < 0x20 && nChars == 1) nChars = 0;
if (b == 0x09) {
let tabSize = this.tabSize || 8;
nChars = tabSize - (this.iLogicalCol % tabSize);
if (this.tabSize) s = Str.pad("", nChars);
}
if (!this.iLogicalCol && nChars) {
/*
* When BASIC.COM outputs a listing to a serial port, it ends every line with a CR (0x0D)
* but no LF (0x0A), which seems a bit odd. We fix that here.
*/
if (this.charPrev != 0x0A) s = "\n" + s;
if (this.charBOL) s = String.fromCharCode(this.charBOL) + s;
}
this.controlBuffer.value += s;
this.controlBuffer.scrollTop = this.controlBuffer.scrollHeight;
this.iLogicalCol += nChars;
}
this.charPrev = b;
fTransmitted = true;
}
else if (this.consoleBuffer != null) {
if (b == 0x0A || this.consoleBuffer.length >= 1024) {
this.println(this.consoleBuffer);
this.consoleBuffer = "";
}
if (b != 0x0A) {
this.consoleBuffer += String.fromCharCode(b);
}
fTransmitted = true;
}
return fTransmitted;
}