Skip to content

[Simulator] Initial data logging #922

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Aug 31, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lang/ui.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,10 @@
"defaultMessage": "Light level",
"description": "Light level title"
},
"simulator-log": {
"defaultMessage": "Data log",
"description": "Data log title"
},
"simulator-loud": {
"defaultMessage": "Loud",
"description": "Sound level high threshold marker hover text"
Expand Down
4 changes: 4 additions & 0 deletions lang/ui.fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,10 @@
"defaultMessage": "Light level",
"description": "Light level title"
},
"simulator-log": {
"defaultMessage": "Data log",
"description": "Data log title"
},
"simulator-loud": {
"defaultMessage": "Loud",
"description": "Sound level high threshold marker hover text"
Expand Down
4 changes: 4 additions & 0 deletions lang/ui.lol.json
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,10 @@
"defaultMessage": "Light level",
"description": "Light level title"
},
"simulator-log": {
"defaultMessage": "Data log",
"description": "Data log title"
},
"simulator-loud": {
"defaultMessage": "Loud",
"description": "Sound level high threshold marker hover text"
Expand Down
17 changes: 16 additions & 1 deletion src/device/simulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
} from "./device";

// Simulator-only events.
export const EVENT_LOG_DATA = "log_data";
export const EVENT_LOG_DELETE = "log_delete";
export const EVENT_RADIO_DATA = "radio_data";
export const EVENT_RADIO_GROUP = "radio_group";
export const EVENT_RADIO_RESET = "radio_reset";
Expand Down Expand Up @@ -54,6 +56,11 @@ export interface EnumSensor {

export type Sensor = RangeSensor | EnumSensor;

export interface LogEntry {
headings?: string[];
data?: string[];
}

export interface SimulatorState {
radio: RadioState;

Expand Down Expand Up @@ -114,7 +121,6 @@ export class SimulatorDeviceConnection
// Not an event for us.
return;
}

switch (event.data.kind) {
case "ready": {
this.state = event.data.state;
Expand Down Expand Up @@ -150,6 +156,15 @@ export class SimulatorDeviceConnection
}
break;
}
case "log_output": {
console.log(event.data);
this.emit(EVENT_LOG_DATA, event.data);
break;
}
case "log_delete": {
this.emit(EVENT_LOG_DELETE, {});
break;
}
case "serial_output": {
const text = event.data.data;
if (typeof text === "string") {
Expand Down
6 changes: 6 additions & 0 deletions src/messages/ui.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1867,6 +1867,12 @@
"value": "Light level"
}
],
"simulator-log": [
{
"type": 0,
"value": "Data log"
}
],
"simulator-loud": [
{
"type": 0,
Expand Down
6 changes: 6 additions & 0 deletions src/messages/ui.fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1867,6 +1867,12 @@
"value": "Light level"
}
],
"simulator-log": [
{
"type": 0,
"value": "Data log"
}
],
"simulator-loud": [
{
"type": 0,
Expand Down
6 changes: 6 additions & 0 deletions src/messages/ui.lol.json
Original file line number Diff line number Diff line change
Expand Up @@ -1811,6 +1811,12 @@
"value": "Light level"
}
],
"simulator-log": [
{
"type": 0,
"value": "Data log"
}
],
"simulator-loud": [
{
"type": 0,
Expand Down
20 changes: 20 additions & 0 deletions src/simulator/DataLogging.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { toCsv } from "./DataLogging";

describe("toCsv", () => {
it("works for a basic case", () => {
expect(
toCsv({
headings: ["A", "B"],
data: [{ data: ["1", "2"] }, { data: ["3", "4"] }],
})
).toEqual("A,B\r\n1,2\r\n3,4");
});
it("escapes content", () => {
expect(
toCsv({
headings: ['"A\n', "B"],
data: [{ data: ["1", "\r2,"] }, { data: ["3", "4"] }],
})
).toEqual(`"""A\n",B\r\n1,"\r2,"\r\n3,4`);
});
});
142 changes: 142 additions & 0 deletions src/simulator/DataLogging.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/**
* (c) 2022, Micro:bit Educational Foundation and contributors
*
* SPDX-License-Identifier: MIT
*/
import {
Button,
HStack,
Icon,
Stack,
Table,
TableContainer,
Tbody,
Td,
Text,
Th,
Thead,
Tr,
VStack,
} from "@chakra-ui/react";
import { ReactNode, useCallback } from "react";
import { RiDownload2Line, RiErrorWarningLine } from "react-icons/ri";
import { DataLog, useDataLog } from "./data-logging-hooks";

export interface DataLoggingProps {
icon: ReactNode;
logFull: boolean;
minimised: boolean;
}

const DataLoggingModule = ({ icon, logFull, minimised }: DataLoggingProps) => {
const dataLog = useDataLog();
const handleDownload = useCallback(() => {
const blob = new Blob([toCsv(dataLog)], {
type: "text/csv;charset=utf-8",
});
saveAs(blob, "data-log.csv");
}, [dataLog]);
if (minimised) {
return (
<HStack justifyContent="space-between" width="100%">
{icon}
<Text>{dataLog.data.length} rows</Text>
<Button
size="sm"
leftIcon={<RiDownload2Line />}
onClick={handleDownload}
>
Download
</Button>
</HStack>
);
}
const hasContent = dataLog.headings.length > 0;
return (
<Stack spacing={3}>
<TableContainer
h="2xs"
bgColor="white"
borderRadius="md"
display={hasContent ? "block" : "flex"}
overflowY="auto"
>
{hasContent ? (
<Table variant="striped" colorScheme="blackAlpha" position="relative">
<Thead>
<Tr>
{dataLog.headings.map((heading) => (
<Th
px={1.5}
key={heading}
color="gray.800"
position="sticky"
top={0}
bgColor="white"
>
{heading}
</Th>
))}
</Tr>
</Thead>
<Tbody>
{dataLog.data.map((row, rowNum) => (
<Tr key={rowNum}>
{row.data.map((cell, headingIndex) => {
return (
<Td
key={dataLog.headings[headingIndex]}
p={1.5}
isNumeric={!row.isHeading}
>
{cell}
</Td>
);
})}
</Tr>
))}
</Tbody>
</Table>
) : (
<VStack flex="1 1 auto" justifyContent="center">
<Notice>No log entries.</Notice>
</VStack>
)}
</TableContainer>
<HStack justifyContent="space-between" fontWeight="semibold">
<HStack spacing={1}>
{logFull && (
<>
<Icon as={RiErrorWarningLine} />
<Text>Log full</Text>
</>
)}
</HStack>
<Button leftIcon={<RiDownload2Line />} onClick={handleDownload}>
Download data
</Button>
</HStack>
</Stack>
);
};

const Notice = ({ children }: { children: ReactNode }) => (
<Text color="gray.700" p={1}>
{children}
</Text>
);

// Exported for testing.
export const toCsv = (log: DataLog) => {
const escape = (content: string): string => {
if (/[\n\r",]/.test(content)) {
return `"${content.replaceAll('"', '""')}"`;
}
return content;
};
const rows = [log.headings, ...log.data.map((d) => d.data)];
const lines = rows.map((row) => row.map(escape));
return lines.join("\r\n");
};

export default DataLoggingModule;
10 changes: 6 additions & 4 deletions src/simulator/Simulator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ const Simulator = ({
showSimulatorButtonRef,
minWidth,
}: SimulatorProps) => {
// This needs the domain to be updated before we release.
// const url = "https://stage-python-simulator.microbit.org/simulator.html";
const url =
"https://review-python-simulator.microbit.org/alt-data-logging/simulator.html";

const ref = useRef<HTMLIFrameElement>(null);
const intl = useIntl();
const simulatorTitle = intl.formatMessage({ id: "simulator-title" });
Expand Down Expand Up @@ -89,10 +94,7 @@ const Simulator = ({
<Box
ref={ref}
as="iframe"
// This needs changing before we release.
src={`https://stage-python-simulator.microbit.org/simulator.html?color=${encodeURIComponent(
brand500
)}`}
src={`${url}?color=${encodeURIComponent(brand500)}`}
title={simulatorTitle}
name={simulatorTitle}
frameBorder="no"
Expand Down
Loading