pxt-calliope/sim/state/serial.ts

90 lines
2.3 KiB
TypeScript
Raw Normal View History

2016-08-30 20:51:32 +02:00
namespace pxsim {
2017-12-15 23:45:38 +01:00
const SERIAL_BUFFER_LENGTH = 16;
2016-08-30 20:51:32 +02:00
export class SerialState {
serialIn: string[] = [];
2021-11-25 17:27:39 +01:00
constructor(private readonly runtime: Runtime, private readonly board: BaseBoard) {
this.board.addMessageListener(this.handleMessage.bind(this))
}
private handleMessage(msg: SimulatorMessage) {
if (msg.type === "serial") {
const data = (<SimulatorSerialMessage>msg).data || "";
this.receiveData(data);
}
}
2017-12-15 23:45:38 +01:00
public receiveData(data: string) {
2016-08-30 20:51:32 +02:00
this.serialIn.push();
}
readSerial() {
let v = this.serialIn.shift() || "";
return v;
}
serialOutBuffer: string = "";
writeSerial(s: string) {
2017-12-15 23:45:38 +01:00
this.serialOutBuffer += s;
if (/\n/.test(this.serialOutBuffer) || this.serialOutBuffer.length > SERIAL_BUFFER_LENGTH) {
Runtime.postMessage(<SimulatorSerialMessage>{
type: 'serial',
data: this.serialOutBuffer,
id: runtime.id,
sim: true
})
this.serialOutBuffer = '';
2016-08-30 20:51:32 +02:00
}
}
}
}
namespace pxsim.serial {
export function writeString(s: string) {
board().writeSerial(s);
}
export function writeBuffer(buf: RefBuffer) {
// TODO
}
export function readUntil(del: string): string {
return readString();
2016-08-30 20:51:32 +02:00
}
export function readString(): string {
2016-08-30 20:51:32 +02:00
return board().serialState.readSerial();
}
export function onDataReceived(delimiters: string, handler: RefAction) {
let b = board();
b.bus.listen(DAL.MICROBIT_ID_SERIAL, DAL.MICROBIT_SERIAL_EVT_DELIM_MATCH, handler);
}
export function redirect(tx: number, rx: number, rate: number) {
// TODO?
}
2017-12-15 23:45:38 +01:00
export function redirectToUSB() {
// TODO
}
export function setRxBufferSize(size: number) {
// TODO
}
export function setTxBufferSize(size: number) {
// TODO
}
export function readBuffer(length: number) {
2020-08-19 22:03:58 +02:00
length |= 0;
if (length <= 0)
length = 64;
return pins.createBuffer(length);
}
2020-08-19 22:03:58 +02:00
export function setBaudRate(rate: number) {
// TODO
}
2016-08-30 20:51:32 +02:00
}