From 7450cc21b99306c019a04a828e0433d299ef107e Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 14:13:18 +0800 Subject: [PATCH 1/6] DEV-1473: Shimmer Capture on the Java driver, to shimmer-host-core's CAPTURE.md A Swing Shimmer Capture on this repository's driver, in ShimmerPCBasicExamples (com.shimmerresearch.capture, ./gradlew runCapture). It does what shimmer-host-core's bindings/CAPTURE.md says every Capture app does, as far as the driver can today, so its figures and files compare with the host-core apps': - Bluetooth Classic, one device, through BasicShimmerBluetoothManagerPc with its BLE (gRPC) server not started; - CAPTURE.md's figures, counted as it defines them (missing samples from gaps in the device timestamps, reception, delay, Rx /s, last sample, PRR, battery, link lost, errors, the hardware / firmware summary); - start, stop, the plot in CAPTURE.md's panels, and Record to CSV in its format (names, units, the driver's channel order, JavaScript number text, RFC 4180, CRLF); - read battery and status, the red LED, read and set the clock, the Bluetooth module, the sampling rate, start and stop SD logging, and the driver's own sensor and settings dialogs. The README lists what CAPTURE.md asks for that the driver has no command for yet (data-rate test, factory test, names, SD card over Bluetooth, the SD config file update, module update) and what this app does not do yet. CaptureRulesTest (13 tests) uses host-core's Java Capture test inputs and results for the numbers, cells, file names and figures. CI does not build this module; built, tested and started locally. Co-Authored-By: Claude Opus 5.5 --- ShimmerPCBasicExamples/build.gradle | 8 + .../capture/CaptureDevice.java | 505 +++++++++++++++++ .../shimmerresearch/capture/CsvRecording.java | 222 ++++++++ .../com/shimmerresearch/capture/Panels.java | 68 +++ .../com/shimmerresearch/capture/PlotView.java | 174 ++++++ .../com/shimmerresearch/capture/README.md | 113 ++++ .../capture/ReceptionStats.java | 123 +++++ .../capture/ShimmerCaptureJava.java | 507 ++++++++++++++++++ .../capture/CaptureRulesTest.java | 248 +++++++++ 9 files changed, 1968 insertions(+) create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/Panels.java create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ReceptionStats.java create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java create mode 100644 ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java diff --git a/ShimmerPCBasicExamples/build.gradle b/ShimmerPCBasicExamples/build.gradle index 213a64eab..1b2b83527 100644 --- a/ShimmerPCBasicExamples/build.gradle +++ b/ShimmerPCBasicExamples/build.gradle @@ -59,3 +59,11 @@ dependencies { implementation name: 'ShimmerBiophysicalProcessingLibrary_Rev_0_11' implementation 'com.parse.bolts:bolts-tasks:1.4.0' } + +// Shimmer Capture on the Java driver (DEV-1473): ./gradlew runCapture +tasks.register('runCapture', JavaExec) { + group = 'application' + description = 'Runs Shimmer Capture on the Java driver (com.shimmerresearch.capture.ShimmerCaptureJava)' + classpath = sourceSets.main.runtimeClasspath + mainClass = 'com.shimmerresearch.capture.ShimmerCaptureJava' +} diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java new file mode 100644 index 000000000..3c94e4b93 --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java @@ -0,0 +1,505 @@ +package com.shimmerresearch.capture; + +import java.io.File; +import java.io.IOException; + +import com.shimmerresearch.bluetooth.ShimmerBluetooth; +import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_STATE; +import com.shimmerresearch.driver.BasicProcessWithCallBack; +import com.shimmerresearch.driver.CallbackObject; +import com.shimmerresearch.driver.Configuration; +import com.shimmerresearch.driver.ObjectCluster; +import com.shimmerresearch.driver.ShimmerDevice; +import com.shimmerresearch.driver.ShimmerMsg; +import com.shimmerresearch.driver.shimmer2r3.BluetoothModuleVersionDetails; +import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; +import com.shimmerresearch.driverUtilities.ShimmerBattStatusDetails; +import com.shimmerresearch.exceptions.ShimmerException; +import com.shimmerresearch.tools.bluetooth.BasicShimmerBluetoothManagerPc; + +/** + * One Shimmer3 or Shimmer3R over Bluetooth Classic, on the Java driver: its link (through the + * driver's Bluetooth manager), the commands Capture sends it, and what it shows. No Swing. + *

+ * The driver answers most commands by updating its own state rather than with an event, so the + * window reads that state back on its refresh timer. + */ +public final class CaptureDevice { + + /** What the window is told; called on the driver's thread */ + public interface Listener { + void log(String text); + void stateChanged(String state); + void sample(ObjectCluster sample, double deviceMs, double hostMs); + } + + private static final String CAL = CHANNEL_TYPE.CAL.toString(); + + private final BasicShimmerBluetoothManagerPc mManager; + private final Listener mListener; + private final ReceptionStats mStats = new ReceptionStats(System.nanoTime() / 1000000L); + + private volatile String mPort; + private volatile String mState = "DISCONNECTED"; + private volatile int mLinkLost; + private volatile int mErrors; + private volatile String mLastError = ""; + private volatile double mPrr = Double.NaN; + private volatile double mBattPercent = Double.NaN; + private volatile long mClockReadAtHostMs = -1; + private volatile long mClockValueSeen = 0; + + private final Object mRecordingLock = new Object(); + private CsvRecording mRecording; + private volatile boolean mRecordRequested; + private File mRecordFolder; + + public CaptureDevice(BasicShimmerBluetoothManagerPc manager, Listener listener) { + mManager = manager; + mListener = listener; + new BasicProcessWithCallBack() { + @Override + protected void processMsgFromCallback(ShimmerMsg msg) { + onMessage(msg); + } + }.setWaitForData(manager.callBackObject); + } + + // ------------------------------------------------------------------ + // The link + // ------------------------------------------------------------------ + + /** Opens the paired unit's serial port (a COM port on Windows), which connects to it, and runs the driver's handshake */ + public void connect(String port) { + mPort = port; + mListener.log("Connecting on " + port); + mManager.connectShimmerThroughCommPort(port); + } + + /** Stops a stream, then closes the link */ + public void disconnect() { + ShimmerBluetooth sb = shimmer(); + if (sb != null && sb.isStreaming()) { + sb.stopStreaming(); + } + stopRecording("the link was closed"); + if (mPort != null) { + mManager.disconnectShimmer(mPort); + } + } + + public String getPort() { + return mPort; + } + + /** The connected driver device, or null */ + public ShimmerBluetooth shimmer() { + if (mPort == null) { + return null; + } + ShimmerDevice d = mManager.getShimmerDeviceBtConnected(mPort); + return d instanceof ShimmerBluetooth ? (ShimmerBluetooth) d : null; + } + + public String getState() { + return mState; + } + + public boolean isReady() { + return "READY".equals(mState); + } + + public boolean isStreaming() { + return "STREAMING".equals(mState); + } + + public boolean isConnected() { + return shimmer() != null && !"DISCONNECTED".equals(mState) && !"FAILED".equals(mState) && !"CONNECTING".equals(mState); + } + + /** CAPTURE.md's states, from the driver's: CONNECTED is READY, a stream (with logging or not) is STREAMING */ + static String captureState(BT_STATE state) { + switch (state) { + case CONNECTING: + return "CONNECTING"; + case CONNECTED: + case SDLOGGING: + return "READY"; + case STREAMING: + case STREAMING_AND_SDLOGGING: + return "STREAMING"; + case CONFIGURING: + return "CONFIGURING"; + case CONNECTION_FAILED: + return "FAILED"; + case DISCONNECTED: + case CONNECTION_LOST: + default: + return "DISCONNECTED"; + } + } + + private void onMessage(ShimmerMsg msg) { + int id = msg.mIdentifier; + if (id == ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE) { + CallbackObject cb = (CallbackObject) msg.mB; + if (cb.mState == null) { + return; + } + if (cb.mState == BT_STATE.CONNECTION_LOST) { + mLinkLost++; + mListener.log("Link lost"); + stopRecording("the link was lost"); + } + if (cb.mState == BT_STATE.CONNECTION_FAILED) { + error("Connection failed"); + } + String state = captureState(cb.mState); + if (!state.equals(mState)) { + if ("STREAMING".equals(mState) && !"STREAMING".equals(state)) { + stopRecording("the stream stopped"); + } + mState = state; + mListener.log("State " + state + " (driver " + cb.mState + ")"); + mListener.stateChanged(state); + } + } + else if (id == ShimmerBluetooth.MSG_IDENTIFIER_NOTIFICATION_MESSAGE) { + CallbackObject cb = (CallbackObject) msg.mB; + if (cb.mIndicator == ShimmerBluetooth.NOTIFICATION_SHIMMER_FULLY_INITIALIZED) { + mListener.log("Initialised: " + getSummary()); + mListener.stateChanged(mState); + } + else if (cb.mIndicator == ShimmerBluetooth.NOTIFICATION_SHIMMER_START_STREAMING) { + ShimmerBluetooth sb = shimmer(); + mStats.reset(sb == null ? Double.NaN : sb.getSamplingRateShimmer(), monotonicMs()); + mListener.log("Streaming started"); + } + else if (cb.mIndicator == ShimmerBluetooth.NOTIFICATION_SHIMMER_STOP_STREAMING) { + mListener.log("Streaming stopped"); + stopRecording("the stream stopped"); + } + } + else if (id == ShimmerBluetooth.MSG_IDENTIFIER_DATA_PACKET) { + ObjectCluster sample = (ObjectCluster) msg.mB; + double deviceMs = sample.getFormatClusterValue(Configuration.Shimmer3.ObjectClusterSensorName.TIMESTAMP, CAL); + double hostMs = sample.getFormatClusterValue(Configuration.Shimmer3.ObjectClusterSensorName.SYSTEM_TIMESTAMP, CAL); + if (Double.isNaN(hostMs)) { + hostMs = System.currentTimeMillis(); + } + mStats.onSample(deviceMs, hostMs, monotonicMs()); + double prr = sample.getFormatClusterValue("Packet_Reception_Rate_Trial", CAL); + if (!Double.isNaN(prr)) { + mPrr = prr; + } + double batt = sample.getFormatClusterValue("Batt_Percentage", CAL); + if (!Double.isNaN(batt)) { + mBattPercent = batt; + } + record(sample, hostMs); + mListener.sample(sample, deviceMs, hostMs); + } + } + + // ------------------------------------------------------------------ + // Commands + // ------------------------------------------------------------------ + + public void readBattery() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Read battery"); + sb.readBattery(); + } + } + + public void readStatus() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Read status"); + sb.readStatusLogAndStream(); + } + } + + public void startStreaming() { + ShimmerBluetooth sb = require(); + if (sb == null) { + return; + } + try { + sb.startStreaming(); + } catch (ShimmerException e) { + error("Start: " + e.getMessage()); + } + } + + public void stopStreaming() { + ShimmerBluetooth sb = require(); + if (sb != null) { + sb.stopStreaming(); + } + } + + /** Writes the sampling rate, as the driver writes it with its sensors' rates */ + public void writeSamplingRate(double hz) { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Write sampling rate " + hz + " Hz"); + sb.writeShimmerAndSensorsSamplingRate(hz); + } + } + + public void readClock() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Read clock"); + mClockReadAtHostMs = System.currentTimeMillis(); + sb.readRealTimeClock(); + } + } + + /** Sets the device's clock from this host's, then reads it back */ + public void setClock() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Set clock from this host"); + sb.writeRealTimeClock(); + mClockReadAtHostMs = System.currentTimeMillis(); + sb.readRealTimeClock(); + } + } + + /** Toggles the firmware's red LED override, then reads the status, whose flag says whether it is on */ + public void toggleRedLed() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Toggle red LED"); + sb.toggleLed(); + sb.readStatusLogAndStream(); + } + } + + public void readBluetoothModule() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Read Bluetooth module"); + sb.readBtFwVersion(); + } + } + + /** Sets the clock from this host's (unless it logs already), starts logging, then reads the status */ + public void startLogging() { + ShimmerBluetooth sb = require(); + if (sb == null) { + return; + } + if (!sb.isSDLogging()) { + sb.writeRealTimeClock(); + } + mListener.log("Start logging"); + sb.startSDLogging(); + sb.readStatusLogAndStream(); + } + + public void stopLogging() { + ShimmerBluetooth sb = require(); + if (sb != null) { + mListener.log("Stop logging"); + sb.stopSDLogging(); + sb.readStatusLogAndStream(); + } + } + + private ShimmerBluetooth require() { + ShimmerBluetooth sb = shimmer(); + if (sb == null) { + error("No device connected"); + } + return sb; + } + + private void error(String text) { + mErrors++; + mLastError = text; + mListener.log("ERROR " + text); + } + + // ------------------------------------------------------------------ + // Recording + // ------------------------------------------------------------------ + + /** Starts a recording with the next sample, in {@code folder} */ + public void startRecording(File folder) { + synchronized (mRecordingLock) { + mRecordFolder = folder; + mRecordRequested = true; + } + mListener.log("Recording starts with the next sample"); + } + + public void stopRecording(String why) { + synchronized (mRecordingLock) { + mRecordRequested = false; + if (mRecording != null) { + try { + mRecording.close(); + mListener.log("Recording closed (" + why + "): " + mRecording.getRows() + " rows, " + mRecording.getFile()); + } catch (IOException e) { + error("Recording close: " + e.getMessage()); + } + mRecording = null; + } + } + } + + public boolean isRecording() { + return mRecordRequested; + } + + public File getRecordingFile() { + synchronized (mRecordingLock) { + return mRecording == null ? null : mRecording.getFile(); + } + } + + private void record(ObjectCluster sample, double hostMs) { + synchronized (mRecordingLock) { + if (!mRecordRequested) { + return; + } + try { + if (mRecording == null) { + ShimmerBluetooth sb = shimmer(); + mRecording = new CsvRecording(mRecordFolder, getPlatform(), sb == null ? null : sb.getMacId(), sample, + System.currentTimeMillis()); + mListener.log("Recording to " + mRecording.getFile()); + } + mRecording.append(sample, hostMs); + } catch (IOException e) { + error("Recording: " + e.getMessage()); + mRecordRequested = false; + mRecording = null; + } + } + } + + // ------------------------------------------------------------------ + // What it shows + // ------------------------------------------------------------------ + + public ReceptionStats.Snapshot snapshot(boolean endWindow) { + return mStats.snapshot(monotonicMs(), endWindow); + } + + public int getLinkLost() { + return mLinkLost; + } + + public int getErrors() { + return mErrors; + } + + public String getLastError() { + return mLastError; + } + + public double getPrr() { + return mPrr; + } + + /** {@code Batt_Percentage} from the stream, or the battery read's percent; NaN where neither is known */ + public double getBatteryPercent() { + if (!Double.isNaN(mBattPercent)) { + return mBattPercent; + } + ShimmerBluetooth sb = shimmer(); + ShimmerBattStatusDetails b = sb == null ? null : sb.getBattStatusDetails(); + if (b != null && b.getBattVoltageParsed() != null && !b.getBattVoltageParsed().isEmpty()) { + return b.getEstimatedChargePercentage(); + } + return Double.NaN; + } + + /** {@code Shimmer3R} or {@code Shimmer3}, as a recording's name has it */ + public String getPlatform() { + ShimmerBluetooth sb = shimmer(); + return sb != null && sb.isShimmerGen3R() ? "Shimmer3R" : "Shimmer3"; + } + + /** The INITIALISED summary: board, firmware, rate and packet size */ + public String getSummary() { + ShimmerBluetooth sb = shimmer(); + if (sb == null) { + return "-"; + } + return sb.getHardwareVersionParsed() + " " + sb.getExpansionBoardParsedWithVer() + ", " + + sb.getFirmwareVersionParsed() + ", " + trim(sb.getSamplingRateShimmer()) + " Hz, packet size " + + sb.getPacketSize(); + } + + /** The battery as the last read gave it: volts, percent, the charger's state */ + public String getBatteryDetails() { + ShimmerBluetooth sb = shimmer(); + ShimmerBattStatusDetails b = sb == null ? null : sb.getBattStatusDetails(); + if (b == null || b.getBattVoltageParsed() == null || b.getBattVoltageParsed().isEmpty()) { + return "not read"; + } + return b.getBattVoltageParsed() + ", " + b.getEstimatedChargePercentageParsed() + ", " + b.getChargingStatusParsed(); + } + + /** The status flags as the last status read left them */ + public String getStatusDetails() { + ShimmerBluetooth sb = shimmer(); + if (sb == null) { + return "-"; + } + return "docked " + yes(sb.isDocked()) + ", sensing " + yes(sb.isSensing()) + ", RTC set " + yes(sb.mIsRtcSet) + + ", SD logging " + yes(sb.isSDLogging()) + ", streaming " + yes(sb.isStreaming()) + + ", SD in " + yes(sb.isSDPresent()) + ", SD error " + yes(sb.isSDError()) + + ", red LED " + yes(sb.mIsRedLedOn) + ", USB " + yes(sb.isUsbPluggedIn()); + } + + public String getMac() { + ShimmerBluetooth sb = shimmer(); + return sb == null ? "-" : sb.getMacId(); + } + + public String getBluetoothModule() { + ShimmerBluetooth sb = shimmer(); + BluetoothModuleVersionDetails d = sb == null ? null : sb.getBtFwVerDetails(); + if (d == null || d.mBtModuleVersionParsed == BluetoothModuleVersionDetails.BT_MODULE_VERSION.NOT_READ) { + return "not read"; + } + return d.mBtModuleVersionReceived + " (" + d.getUserFriendlyName() + ")"; + } + + /** + * The device's clock as last read, in this host's local time, and its difference from this + * host's clock when the read was sent (the driver does not report when the reply came). + */ + public String getClockDetails() { + ShimmerBluetooth sb = shimmer(); + if (sb == null || sb.mShimmerLastReadRtcValueMilliSecs <= 0 || mClockReadAtHostMs < 0) { + return "not read"; + } + long device = sb.mShimmerLastReadRtcValueMilliSecs; + if (device != mClockValueSeen) { + mClockValueSeen = device; + } + return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date(device)) + + String.format(" (device - host: %+d ms)", device - mClockReadAtHostMs); + } + + private static String yes(boolean b) { + return b ? "yes" : "no"; + } + + static String trim(double v) { + return CsvRecording.number(v); + } + + private static long monotonicMs() { + return System.nanoTime() / 1000000L; + } + +} diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java new file mode 100644 index 000000000..804db1061 --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java @@ -0,0 +1,222 @@ +package com.shimmerresearch.capture; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; + +import com.shimmerresearch.driver.FormatCluster; +import com.shimmerresearch.driver.ObjectCluster; +import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; + +/** + * One recording of the stream, written as shimmer-host-core's bindings/CAPTURE.md ("Files") has + * every Capture app write it, and as shimmer-capture-web writes it, so that one script reads any + * app's files: + *

+ * The columns are taken from the first sample, in the driver's own order, which is the order the + * library reproduces. + */ +public final class CsvRecording implements AutoCloseable { + + static final String CRLF = "\r\n"; + private static final long FLUSH_MS = 1000; + private static final String CAL = CHANNEL_TYPE.CAL.toString(); + private static final String UNCAL = CHANNEL_TYPE.UNCAL.toString(); + static final String TIMESTAMP = "Timestamp"; + + /** A column after HostTime_ms and TIMESTAMP: a channel in one format */ + static final class Column { + final String channel; + final String format; + final String name; + final String units; + + Column(String channel, String format, String units) { + this.channel = channel; + this.format = format; + this.name = channel + (CAL.equals(format) ? "_CAL" : "_RAW"); + this.units = units == null ? "" : units; + } + } + + /** The columns of a sample, in the driver's order: each channel calibrated, then raw */ + static List columnsOf(ObjectCluster sample) { + List columns = new ArrayList(); + for (String channel : sample.getChannelNamesByInsertionOrder()) { + Collection formats = sample.getCollectionOfFormatClusters(channel); + FormatCluster cal = ObjectCluster.returnFormatCluster(formats, CAL); + FormatCluster raw = ObjectCluster.returnFormatCluster(formats, UNCAL); + if (cal != null) { + columns.add(new Column(channel, CAL, cal.mUnits)); + } + if (raw != null && !TIMESTAMP.equals(channel)) { + columns.add(new Column(channel, UNCAL, raw.mUnits)); + } + } + return columns; + } + + final File file; + private final Writer out; + private final List columns; + private long rows; + private long flushedAt; + + /** Creates the file in {@code folder} and writes its two header rows, with the columns of {@code first} */ + public CsvRecording(File folder, String platform, String macAddress, ObjectCluster first, long startedMs) throws IOException { + if (!folder.isDirectory() && !folder.mkdirs()) { + throw new IOException("cannot make " + folder); + } + file = new File(folder, fileName(platform, macAddress, startedMs, TimeZone.getDefault())); + columns = columnsOf(first); + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); + List names = new ArrayList(); + names.add("HostTime_ms"); + names.add("TIMESTAMP"); + List units = new ArrayList(); + units.add("ms"); + units.add("ticks"); + for (Column c : columns) { + names.add(c.name); + units.add(c.units); + } + writeRow(names); + writeRow(units); + out.flush(); + flushedAt = System.currentTimeMillis(); + } + + public File getFile() { + return file; + } + + public long getRows() { + return rows; + } + + /** One sample, received at {@code hostMs} (ms since the Unix epoch) */ + public void append(ObjectCluster sample, double hostMs) throws IOException { + StringBuilder row = new StringBuilder(); + row.append(number(Math.floor(hostMs + 0.5))).append(','); + row.append(number(sample.getFormatClusterValue(TIMESTAMP, UNCAL))); + for (Column c : columns) { + row.append(',').append(number(sample.getFormatClusterValue(c.channel, c.format))); + } + out.write(row.append(CRLF).toString()); + rows++; + long now = System.currentTimeMillis(); + if (now - flushedAt >= FLUSH_MS) { + out.flush(); + flushedAt = now; + } + } + + @Override + public void close() throws IOException { + out.close(); + } + + private void writeRow(List cells) throws IOException { + StringBuilder row = new StringBuilder(); + for (int i = 0; i < cells.size(); i++) { + row.append(i == 0 ? "" : ",").append(cell(cells.get(i))); + } + out.write(row.append(CRLF).toString()); + } + + /** {@code Shimmer3R_2F31_20261103_142501.csv}: the MAC's last four hex digits, upper case, 0000 for none */ + static String fileName(String platform, String macAddress, long startedMs, TimeZone zone) { + String hex = (macAddress == null ? "" : macAddress).replaceAll("[^0-9A-Fa-f]", "").toUpperCase(Locale.ROOT); + SimpleDateFormat stamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ROOT); + stamp.setTimeZone(zone); + return platform + "_" + (hex.isEmpty() ? "0000" : hex.substring(Math.max(0, hex.length() - 4))) + "_" + + stamp.format(new Date(startedMs)) + ".csv"; + } + + /** + * A value as JavaScript's Number.prototype.toString writes it: the shortest digits that read back + * to the same double; plain from 1e-7 up to 1e21, with an exponent outside ({@code 1.5e-7}, + * {@code 1.5e+21}); a whole number with no decimal point; {@code NaN}, {@code Infinity}, + * {@code -Infinity}. Java's Double.toString is not always the shortest before Java 19, so the + * digits are found here. + */ + static String number(double value) { + if (Double.isNaN(value)) { + return "NaN"; + } + if (Double.isInfinite(value)) { + return value < 0 ? "-Infinity" : "Infinity"; + } + if (value == 0) { + return "0"; + } + if (value == Math.rint(value) && Math.abs(value) < 1e15) { + return Long.toString((long) value); + } + double magnitude = Math.abs(value); + BigDecimal exact = new BigDecimal(magnitude); + BigDecimal shortest = exact; + for (int precision = 1; precision <= 17; precision++) { + BigDecimal rounded = exact.round(new MathContext(precision, RoundingMode.HALF_EVEN)); + if (rounded.doubleValue() == magnitude) { + shortest = rounded; + break; + } + } + shortest = shortest.stripTrailingZeros(); + String digits = shortest.unscaledValue().toString(); + int k = digits.length(); + // n: where the decimal point goes, counted from the first digit + int n = k - shortest.scale(); + String sign = value < 0 ? "-" : ""; + if (k <= n && n <= 21) { + return sign + digits + zeros(n - k); + } + if (0 < n && n <= 21) { + return sign + digits.substring(0, n) + "." + digits.substring(n); + } + if (-6 < n && n <= 0) { + return sign + "0." + zeros(-n) + digits; + } + String fraction = k > 1 ? "." + digits.substring(1) : ""; + return sign + digits.charAt(0) + fraction + (n > 0 ? "e+" : "e-") + Math.abs(n - 1); + } + + /** A cell as RFC 4180 has it: white space runs made one space, quoted (quotes doubled) if it holds a comma or a quote */ + static String cell(String text) { + String one = text.trim().replaceAll("\\s+", " "); + return one.contains(",") || one.contains("\"") ? "\"" + one.replace("\"", "\"\"") + "\"" : one; + } + + private static String zeros(int count) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < count; i++) { + b.append('0'); + } + return b.toString(); + } + +} diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/Panels.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/Panels.java new file mode 100644 index 000000000..38c48f65f --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/Panels.java @@ -0,0 +1,68 @@ +package com.shimmerresearch.capture; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +/** + * Which plot panel a channel goes in, by the start of its name, as shimmer-host-core's + * bindings/CAPTURE.md ("The plot") has every Capture app group them. The driver's channel names + * are the library's. + */ +public final class Panels { + + public static final List ALL = Collections.unmodifiableList(Arrays.asList( + "Low-noise accel", "Wide-range accel", "Gyro", "Mag", "Battery", "Pressure", "Temperature", + "ADC", "ExG", "GSR", "PPG", "Other")); + + private static final Pattern ADC = Pattern.compile("(Int|Ext)_Exp_A\\d+"); + private static final Pattern EXG = Pattern.compile("(ExG[12]_CH|Test_CHIP[12]_CH|ECG_|EMG_).*"); + private static final Pattern EXG_STATUS = Pattern.compile(".*_Status\\d"); + private static final Pattern PPG = Pattern.compile("PPG\\d?_A\\d+"); + + private Panels() { + } + + /** The panel for a channel, or null for the timestamps and the reception figures, which are not plotted */ + public static String of(String name) { + if (name.contains("Timestamp") || name.startsWith("Packet_Reception_Rate")) { + return null; + } + if (name.startsWith("Accel_LN_")) { + return "Low-noise accel"; + } + if (name.startsWith("Accel_WR_")) { + return "Wide-range accel"; + } + if (name.startsWith("Gyro_")) { + return "Gyro"; + } + if (name.startsWith("Mag_")) { + return "Mag"; + } + if (name.equals("Battery")) { + return "Battery"; + } + if (name.startsWith("Pressure_")) { + return "Pressure"; + } + if (name.startsWith("Temperature_") || name.equals("Skin_Temperature")) { + return "Temperature"; + } + if (ADC.matcher(name).matches()) { + return "ADC"; + } + if (EXG.matcher(name).matches() && !EXG_STATUS.matcher(name).matches()) { + return "ExG"; + } + if (name.startsWith("GSR_")) { + return "GSR"; + } + if (PPG.matcher(name).matches()) { + return "PPG"; + } + return "Other"; + } + +} diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java new file mode 100644 index 000000000..fc2ce8297 --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java @@ -0,0 +1,174 @@ +package com.shimmerresearch.capture; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.JPanel; + +/** + * One plot panel: the channels of one group (Panels), each a line over a window of 5, 10 or 30 s + * of device time, the y axis fitted to what is shown. Points are added on any thread; painting is + * on the Swing thread. + */ +public final class PlotView extends JPanel { + + private static final long serialVersionUID = 1L; + /** 30 s at 1024 Hz, with room */ + private static final int CAPACITY = 32768; + private static final Color[] COLORS = { + new Color(0x1F77B4), new Color(0xD62728), new Color(0x2CA02C), new Color(0xFF7F0E), + new Color(0x9467BD), new Color(0x8C564B), new Color(0xE377C2), new Color(0x17BECF)}; + + private static final class Series { + final double[] t = new double[CAPACITY]; + final double[] v = new double[CAPACITY]; + int start; + int size; + + void add(double time, double value) { + int end = (start + size) % CAPACITY; + t[end] = time; + v[end] = value; + if (size < CAPACITY) { + size++; + } else { + start = (start + 1) % CAPACITY; + } + } + } + + private final String mTitle; + private final Map mSeries = new LinkedHashMap(); + private volatile double mWindowMs = 10000; + + public PlotView(String title) { + mTitle = title; + setPreferredSize(new Dimension(600, 160)); + setBackground(Color.WHITE); + } + + public String getTitle() { + return mTitle; + } + + public void setWindowSeconds(double seconds) { + mWindowMs = seconds * 1000.0; + } + + public synchronized void add(String channel, double timeMs, double value) { + Series s = mSeries.get(channel); + if (s == null) { + s = new Series(); + mSeries.put(channel, s); + } + s.add(timeMs, value); + } + + public synchronized void clear() { + mSeries.clear(); + } + + public synchronized boolean isEmpty() { + return mSeries.isEmpty(); + } + + @Override + protected synchronized void paintComponent(Graphics g0) { + super.paintComponent(g0); + Graphics2D g = (Graphics2D) g0; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + int w = getWidth(); + int h = getHeight(); + int left = 64; + int right = 8; + int top = 18; + int bottom = 16; + g.setColor(Color.DARK_GRAY); + g.drawString(mTitle, left, 13); + + double latest = Double.NEGATIVE_INFINITY; + for (Series s : mSeries.values()) { + if (s.size > 0) { + latest = Math.max(latest, s.t[(s.start + s.size - 1) % CAPACITY]); + } + } + if (latest == Double.NEGATIVE_INFINITY) { + return; + } + double from = latest - mWindowMs; + double min = Double.POSITIVE_INFINITY; + double max = Double.NEGATIVE_INFINITY; + for (Series s : mSeries.values()) { + for (int i = 0; i < s.size; i++) { + int k = (s.start + i) % CAPACITY; + if (s.t[k] >= from && !Double.isNaN(s.v[k]) && !Double.isInfinite(s.v[k])) { + min = Math.min(min, s.v[k]); + max = Math.max(max, s.v[k]); + } + } + } + if (min == Double.POSITIVE_INFINITY) { + return; + } + if (max - min < 1e-9) { + max += 0.5; + min -= 0.5; + } + int plotW = Math.max(1, w - left - right); + int plotH = Math.max(1, h - top - bottom); + g.setColor(new Color(0xE0E0E0)); + g.drawRect(left, top, plotW, plotH); + g.setColor(Color.GRAY); + FontMetrics fm = g.getFontMetrics(); + String maxText = format(max); + String minText = format(min); + g.drawString(maxText, left - 4 - fm.stringWidth(maxText), top + fm.getAscent()); + g.drawString(minText, left - 4 - fm.stringWidth(minText), top + plotH); + g.drawString(String.format("%.0f s", mWindowMs / 1000.0), left, h - 3); + + int colour = 0; + int legendX = left + 80; + g.setStroke(new BasicStroke(1.2f)); + for (Map.Entry e : mSeries.entrySet()) { + Series s = e.getValue(); + Color c = COLORS[colour++ % COLORS.length]; + g.setColor(c); + List points = new ArrayList(); + for (int i = 0; i < s.size; i++) { + int k = (s.start + i) % CAPACITY; + if (s.t[k] < from || Double.isNaN(s.v[k]) || Double.isInfinite(s.v[k])) { + continue; + } + int x = left + (int) Math.round((s.t[k] - from) / mWindowMs * plotW); + int y = top + plotH - (int) Math.round((s.v[k] - min) / (max - min) * plotH); + points.add(new int[] {x, y}); + } + int step = Math.max(1, points.size() / (plotW * 2)); + for (int i = step; i < points.size(); i += step) { + int[] a = points.get(i - step); + int[] b = points.get(i); + g.drawLine(a[0], a[1], b[0], b[1]); + } + g.drawString(e.getKey(), legendX, 13); + legendX += fm.stringWidth(e.getKey()) + 14; + } + } + + private static String format(double v) { + double a = Math.abs(v); + if (a != 0 && (a < 0.01 || a >= 1e6)) { + return String.format("%.3g", v); + } + return String.format("%.2f", v); + } + +} diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md new file mode 100644 index 000000000..e81183a4f --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md @@ -0,0 +1,113 @@ +# Shimmer Capture on the Java driver + +Shimmer Capture built on this repository's Java driver, in Swing. It does what shimmer-host-core's +`bindings/CAPTURE.md` says every Capture app does, as far as the Java driver can do it today. It +shows the same figures under the same names and writes the same CSV files, so a result from this app +compares with the host-core apps'. A stream that loses samples in one app and not in the other is the +link or the platform, not the app. DEV-1473. + +It connects a Shimmer3 or Shimmer3R over **Bluetooth Classic**, one device at a time, through the +driver's Bluetooth manager (`BasicShimmerBluetoothManagerPc`, its BLE server not started). + +## Running it + +From `ShimmerPCBasicExamples`: + +``` +./gradlew runCapture +``` + +Or in Eclipse, run `com.shimmerresearch.capture.ShimmerCaptureJava` as a Java application. + +Pick the paired Shimmer's serial port, then click **Connect**: + +- **Windows:** its outgoing COM port (Bluetooth settings, More Bluetooth settings, COM Ports). +- **macOS:** `/dev/cu.Shimmer3R-XXXX`. +- **Linux:** `/dev/rfcomm`. + +A Shimmer holds one link at a time, so close Consensys, and anything else connected to it, first. + +Recordings go to `Shimmer Capture` in Documents. + +## What it does + +- **Figures,** CAPTURE.md's table, on the left: + - Device, Link (`Classic, `), State, Rate Hz, Rx /s, Samples, Missing, Reception, PRR, + Delay ms, Last sample, Battery, Link lost, Errors, Data rate, Hardware / firmware. + - Missing, Reception, Delay, Rx /s and Last sample are counted exactly as CAPTURE.md defines them. + The tests use host-core's Java Capture test inputs and results. +- **Stream tab:** + - Start, Stop and Record to CSV. + - The plot, in CAPTURE.md's panels by channel name: 5, 10 or 30 s, calibrated or raw, Clear. +- **Device tab:** + - Read battery, Read status, Toggle red LED (then the status, whose flag says whether it is on). + - Read clock, Set clock (from this host's, then read back), Read Bluetooth module. + - Start logging (the clock set first unless it logs already) and Stop logging, each followed by a + status read. + - The sampling rate: 51.2 to 1024 Hz, written as the driver writes it. + - **Sensors...** and **Settings...**: the driver's own configuration dialogs. + - The chosen device's battery (volts, percent, charger), the status's nine flags, its MAC, its + Bluetooth module and its clock. +- **The log** at the bottom. + +**The recording** is CAPTURE.md's, so one script reads any app's files: +- **Name:** `__.csv`, the start in local time. +- **Header rows:** `HostTime_ms`, `TIMESTAMP`, then each channel the driver decodes as + `_CAL`, then `_RAW`, in the driver's own order. The raw `Timestamp` is `TIMESTAMP` + alone. Then a row of units. +- **Rows:** one per sample, each value written as JavaScript writes a number. RFC 4180 cells, CRLF + line ends. +- **When it closes:** when the recording stops, the stream stops, or the link drops. + +The driver reports most answers by updating its own state rather than with an event. So the window +reads that state back twice a second, and a figure or detail can take up to half a second to show an +answer. + +## Not yet + +What CAPTURE.md asks for that this app does not do: + +**The Java driver has no such command yet:** +- the data-rate test (the Data rate figure shows `-`); +- the factory self-test; +- the names (the expansion board EEPROM's name record) and the reboot on disconnect; +- the SD card over Bluetooth (browse, download, delete); +- the SD configuration file's update (the driver knows `UPD_SDLOG_CFG_COMMAND` but has no call that + sends it); +- the Bluetooth module's update; +- calibration editing as CAPTURE.md has it. + +**Not built in this app yet:** +- **Several devices at once.** +- **BLE:** the manager's gRPC BLE server. +- **USB / the dock protocol,** and the multi-slot base. +- **The clock drift,** and the clock's round trip: the clock difference is taken from when the read + was sent. +- **The configuration editor:** CAPTURE.md's sensor names, problems and the bytes changed, rather than + the driver's dialogs. +- **The Reception chart.** +- **The event log's** filters, Save and Copy summary. +- **The recorded sensor,** and with it the no-hardware check CAPTURE.md asks for. +- **The state names:** they are the driver's, mapped to CAPTURE.md's. CONNECTED and SDLOGGING are + READY, a stream with or without logging is STREAMING, and a lost link is DISCONNECTED, counted in + Link lost. The driver has no STARTING, STOPPING or TESTING. + +## Tests + +`./gradlew :test --tests 'com.shimmerresearch.capture.*'` runs `CaptureRulesTest`. It covers: +- the recording's numbers, cells, file name, columns and units; +- the figures' arithmetic; +- the plot panels; +- the state mapping. + +CI does not build this module, so run the tests locally. + +## What is where + +| File | What it is | +|---|---| +| `ShimmerCaptureJava` | The window and `main` | +| `CaptureDevice` | One device on the driver: the link, the commands, what it shows; no Swing | +| `ReceptionStats` | The figures' arithmetic | +| `CsvRecording` | The CSV | +| `Panels`, `PlotView` | The plot | diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ReceptionStats.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ReceptionStats.java new file mode 100644 index 000000000..553f2b1ce --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ReceptionStats.java @@ -0,0 +1,123 @@ +package com.shimmerresearch.capture; + +/** + * How well the samples are arriving, counted as shimmer-host-core's bindings/CAPTURE.md defines + * its figures, so that this app's figures compare with every other Capture app's: + *
    + *
  • Missing: a step of more than one sampling period between consecutive device + * timestamps ({@code Timestamp}, calibrated, ms) counts the samples that should have filled it, + * {@code round(step / period) - 1};
  • + *
  • Reception: {@code received / (received + missing)}, in percent;
  • + *
  • Delay: each sample's arrival ({@code System_Timestamp}) minus its device time, less + * the least such difference so far, now and worst;
  • + *
  • Rx /s over the last second, and how long ago the last sample came.
  • + *
+ * Times are passed in, so the arithmetic is tested without a clock. Thread-safe: samples come on + * the driver's thread, snapshots are taken on the window's. + */ +public final class ReceptionStats { + + /** The figures at one moment, and over the window since the snapshot before */ + public static final class Snapshot { + public final long samples; + public final long missing; + /** Percent; NaN before any sample */ + public final double reception; + /** The latest sample's delay and the worst so far, ms; NaN before any timed sample */ + public final double delayMs; + public final double maxDelayMs; + /** Since the last sample arrived, ms; -1 before any */ + public final long sinceLastMs; + public final long windowSamples; + public final double windowSeconds; + + Snapshot(long samples, long missing, double delayMs, double maxDelayMs, long sinceLastMs, long windowSamples, + double windowSeconds) { + this.samples = samples; + this.missing = missing; + this.reception = percent(samples, missing); + this.delayMs = delayMs; + this.maxDelayMs = maxDelayMs; + this.sinceLastMs = sinceLastMs; + this.windowSamples = windowSamples; + this.windowSeconds = windowSeconds; + } + + /** Samples received per second over the window: the Rx /s figure */ + public double rxPerSecond() { + return windowSeconds > 0 ? windowSamples / windowSeconds : 0; + } + } + + private double periodMs = Double.NaN; + private long samples; + private long missing; + private double lastDeviceMs = Double.NaN; + private double minOffsetMs = Double.NaN; + private double lastOffsetMs = Double.NaN; + private double maxDelayMs = Double.NaN; + private long lastArrivedAt = -1; + private long windowSamples; + private long windowStart; + + public ReceptionStats(long nowMs) { + reset(Double.NaN, nowMs); + } + + /** Starts counting afresh, for a stream at {@code samplingRateHz} */ + public synchronized void reset(double samplingRateHz, long nowMs) { + periodMs = samplingRateHz > 0 ? 1000.0 / samplingRateHz : Double.NaN; + samples = 0; + missing = 0; + lastDeviceMs = Double.NaN; + minOffsetMs = Double.NaN; + lastOffsetMs = Double.NaN; + maxDelayMs = Double.NaN; + lastArrivedAt = -1; + windowSamples = 0; + windowStart = nowMs; + } + + /** One sample: its device time (ms, NaN if none), its arrival on the wall clock (ms), and now on a monotonic clock */ + public synchronized void onSample(double deviceMs, double arrivalMs, long nowMs) { + samples++; + windowSamples++; + lastArrivedAt = nowMs; + if (Double.isNaN(deviceMs)) { + return; + } + if (!Double.isNaN(lastDeviceMs) && !Double.isNaN(periodMs)) { + long gap = Math.round((deviceMs - lastDeviceMs) / periodMs) - 1; + if (gap > 0) { + missing += gap; + } + } + lastDeviceMs = deviceMs; + if (Double.isNaN(arrivalMs)) { + return; + } + double offset = arrivalMs - deviceMs; + if (Double.isNaN(minOffsetMs) || offset < minOffsetMs) { + minOffsetMs = offset; + } + lastOffsetMs = offset; + double delay = offset - minOffsetMs; + maxDelayMs = Double.isNaN(maxDelayMs) ? delay : Math.max(maxDelayMs, delay); + } + + /** The figures now; with {@code endWindow} the window starts again (once a second, for Rx /s) */ + public synchronized Snapshot snapshot(long nowMs, boolean endWindow) { + Snapshot s = new Snapshot(samples, missing, lastOffsetMs - minOffsetMs, maxDelayMs, + lastArrivedAt < 0 ? -1 : nowMs - lastArrivedAt, windowSamples, (nowMs - windowStart) / 1000.0); + if (endWindow) { + windowSamples = 0; + windowStart = nowMs; + } + return s; + } + + static double percent(long received, long missing) { + return received + missing > 0 ? 100.0 * received / (received + missing) : Double.NaN; + } + +} diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java new file mode 100644 index 000000000..78e113c5b --- /dev/null +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java @@ -0,0 +1,507 @@ +package com.shimmerresearch.capture; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.UIManager; +import javax.swing.table.DefaultTableModel; + +import com.shimmerresearch.bluetooth.ShimmerBluetooth; +import com.shimmerresearch.driver.ObjectCluster; +import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; +import com.shimmerresearch.guiUtilities.configuration.EnableSensorsDialog; +import com.shimmerresearch.guiUtilities.configuration.SensorConfigDialog; +import com.shimmerresearch.tools.bluetooth.BasicShimmerBluetoothManagerPc; + +import jssc.SerialPortList; + +/** + * Shimmer Capture on the Java driver: what shimmer-host-core's bindings/CAPTURE.md says every + * Capture app does, as far as the Java driver can do it today, over Bluetooth Classic, one device + * at a time. The same figures under the same names and the same CSV files as the host-core apps, so + * that a result from this app compares with theirs. What the driver cannot do yet is listed in + * README.md. + */ +public final class ShimmerCaptureJava implements CaptureDevice.Listener { + + static final String[] FIGURES = {"Device", "Link", "State", "Rate Hz", "Rx /s", "Samples", "Missing", + "Reception", "PRR", "Delay ms", "Last sample", "Battery", "Link lost", "Errors", "Data rate", + "Hardware / firmware"}; + static final String[] RATES = {"51.2", "102.4", "128", "204.8", "256", "512", "1024"}; + private static final String CAL = CHANNEL_TYPE.CAL.toString(); + private static final String UNCAL = CHANNEL_TYPE.UNCAL.toString(); + + /** Bluetooth Classic only: the manager's BLE server (gRPC) is not started */ + private final BasicShimmerBluetoothManagerPc mManager = new BasicShimmerBluetoothManagerPc(false); + private final CaptureDevice mDevice; + private final File mFolder = new File(new File(System.getProperty("user.home"), "Documents"), "Shimmer Capture"); + + private final JFrame mFrame = new JFrame("Shimmer Capture (Java driver)"); + private final JComboBox mPorts = new JComboBox(); + private final DefaultTableModel mFigures = new DefaultTableModel(new Object[] {"Figure", "Value"}, 0) { + private static final long serialVersionUID = 1L; + @Override public boolean isCellEditable(int r, int c) { return false; } + }; + private final JTextArea mLog = new JTextArea(8, 80); + private final JTextArea mDetails = new JTextArea(9, 60); + private final JComboBox mWindow = new JComboBox(new String[] {"5", "10", "30"}); + private final JComboBox mFormat = new JComboBox(new String[] {"Calibrated", "Raw"}); + private final JComboBox mRate = new JComboBox(RATES); + private final JButton mRecord = new JButton("Record to CSV"); + private final JLabel mRecordLabel = new JLabel(" "); + private final Map mPlots = new LinkedHashMap(); + private final JPanel mPlotPanel = new JPanel(); + private final List mReadyOnly = new ArrayList(); + private final List mReadyOrStreaming = new ArrayList(); + private final List mStreamingOnly = new ArrayList(); + private final List mConnectedOnly = new ArrayList(); + private final SimpleDateFormat mLogTime = new SimpleDateFormat("HH:mm:ss.SSS"); + private long mLastWindowEnd = System.currentTimeMillis(); + + public static void main(String[] args) { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception e) { + // the default look then + } + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new ShimmerCaptureJava().show(); + } + }); + } + + public ShimmerCaptureJava() { + mDevice = new CaptureDevice(mManager, this); + build(); + refreshPorts(); + new Timer(500, new ActionListener() { + public void actionPerformed(ActionEvent e) { + refresh(); + } + }).start(); + new Timer(100, new ActionListener() { + public void actionPerformed(ActionEvent e) { + for (PlotView p : mPlots.values()) { + p.repaint(); + } + } + }).start(); + } + + void show() { + mFrame.setVisible(true); + } + + // ------------------------------------------------------------------ + // Layout + // ------------------------------------------------------------------ + + private void build() { + mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mFrame.setSize(1280, 860); + + JPanel top = new JPanel(new FlowLayout(FlowLayout.LEFT)); + top.add(new JLabel("Bluetooth Classic port")); + mPorts.setEditable(true); + mPorts.setPreferredSize(new Dimension(160, 26)); + mPorts.setToolTipText("The paired Shimmer's outgoing COM port (Windows), /dev/cu.Shimmer3R-XXXX (macOS) or /dev/rfcomm (Linux)"); + top.add(mPorts); + top.add(button("Refresh", null, new ActionListener() { + public void actionPerformed(ActionEvent e) { + refreshPorts(); + } + })); + top.add(button("Connect", null, new ActionListener() { + public void actionPerformed(ActionEvent e) { + Object port = mPorts.getSelectedItem(); + if (port == null || port.toString().trim().isEmpty()) { + log("Choose a port first"); + return; + } + if (mDevice.isConnected()) { + log("Already connected on " + mDevice.getPort() + ": one device at a time"); + return; + } + clearPlots(); + mDevice.connect(port.toString().trim()); + } + })); + top.add(button("Disconnect", mConnectedOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.disconnect(); + } + })); + + JTable figures = new JTable(mFigures); + figures.getColumnModel().getColumn(0).setPreferredWidth(110); + figures.getColumnModel().getColumn(1).setPreferredWidth(260); + for (String f : FIGURES) { + mFigures.addRow(new Object[] {f, "-"}); + } + JScrollPane figuresScroll = new JScrollPane(figures); + figuresScroll.setPreferredSize(new Dimension(380, 400)); + + JTabbedPane tabs = new JTabbedPane(); + tabs.addTab("Stream", buildStreamTab()); + tabs.addTab("Device", buildDeviceTab()); + + JSplitPane centre = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, figuresScroll, tabs); + centre.setDividerLocation(390); + + mLog.setEditable(false); + JScrollPane logScroll = new JScrollPane(mLog); + logScroll.setBorder(BorderFactory.createTitledBorder("Log")); + JSplitPane main = new JSplitPane(JSplitPane.VERTICAL_SPLIT, centre, logScroll); + main.setResizeWeight(0.78); + + mFrame.getContentPane().setLayout(new BorderLayout()); + mFrame.getContentPane().add(top, BorderLayout.NORTH); + mFrame.getContentPane().add(main, BorderLayout.CENTER); + mFrame.setLocationRelativeTo(null); + updateEnabled(); + } + + private JComponent buildStreamTab() { + JPanel bar = new JPanel(new FlowLayout(FlowLayout.LEFT)); + bar.add(button("Start", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + clearPlots(); + mDevice.startStreaming(); + } + })); + bar.add(button("Stop", mStreamingOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.stopStreaming(); + } + })); + mRecord.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (mDevice.isRecording()) { + mDevice.stopRecording("stopped"); + } else { + mDevice.startRecording(mFolder); + } + } + }); + mStreamingOnly.add(mRecord); + bar.add(mRecord); + bar.add(mRecordLabel); + bar.add(new JLabel(" Window s")); + mWindow.setSelectedItem("10"); + mWindow.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + double s = Double.parseDouble(mWindow.getSelectedItem().toString()); + for (PlotView p : mPlots.values()) { + p.setWindowSeconds(s); + } + } + }); + bar.add(mWindow); + mFormat.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + clearPlots(); + } + }); + bar.add(mFormat); + bar.add(button("Clear", null, new ActionListener() { + public void actionPerformed(ActionEvent e) { + clearPlots(); + } + })); + + mPlotPanel.setLayout(new BoxLayout(mPlotPanel, BoxLayout.Y_AXIS)); + for (String panel : Panels.ALL) { + PlotView v = new PlotView(panel); + v.setWindowSeconds(10); + v.setVisible(false); + mPlots.put(panel, v); + mPlotPanel.add(v); + } + JPanel tab = new JPanel(new BorderLayout()); + tab.add(bar, BorderLayout.NORTH); + tab.add(new JScrollPane(mPlotPanel), BorderLayout.CENTER); + return tab; + } + + private JComponent buildDeviceTab() { + JPanel commands = new JPanel(new GridLayout(0, 3, 6, 6)); + commands.setBorder(BorderFactory.createTitledBorder("Commands")); + commands.add(button("Read battery", mReadyOrStreaming, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.readBattery(); + } + })); + commands.add(button("Read status", mReadyOrStreaming, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.readStatus(); + } + })); + commands.add(button("Toggle red LED", mReadyOrStreaming, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.toggleRedLed(); + } + })); + commands.add(button("Read clock", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.readClock(); + } + })); + commands.add(button("Set clock", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.setClock(); + } + })); + commands.add(button("Read Bluetooth module", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.readBluetoothModule(); + } + })); + commands.add(button("Start logging", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.startLogging(); + } + })); + commands.add(button("Stop logging", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.stopLogging(); + } + })); + JPanel rate = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0)); + rate.add(mRate); + rate.add(button("Set rate (Hz)", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + mDevice.writeSamplingRate(Double.parseDouble(mRate.getSelectedItem().toString())); + } + })); + commands.add(rate); + commands.add(button("Sensors...", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + ShimmerBluetooth sb = mDevice.shimmer(); + if (sb != null) { + new EnableSensorsDialog(sb, mManager).showDialog(); + } + } + })); + commands.add(button("Settings...", mReadyOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + ShimmerBluetooth sb = mDevice.shimmer(); + if (sb != null) { + new SensorConfigDialog(sb, mManager).showDialog(); + } + } + })); + + mDetails.setEditable(false); + JScrollPane details = new JScrollPane(mDetails); + details.setBorder(BorderFactory.createTitledBorder("The device")); + + JPanel notYet = new JPanel(new FlowLayout(FlowLayout.LEFT)); + notYet.add(new JLabel("Not in the Java driver yet (see README): the data-rate test, the factory self-test, " + + "the names, the SD card over Bluetooth, the SD configuration file update, the clock drift, calibration.")); + + JPanel tab = new JPanel(new BorderLayout()); + tab.add(commands, BorderLayout.NORTH); + tab.add(details, BorderLayout.CENTER); + tab.add(notYet, BorderLayout.SOUTH); + return tab; + } + + private static JButton button(String text, List group, ActionListener l) { + JButton b = new JButton(text); + b.addActionListener(l); + if (group != null) { + group.add(b); + } + return b; + } + + private void refreshPorts() { + Object current = mPorts.getSelectedItem(); + mPorts.removeAllItems(); + List names = new ArrayList(Arrays.asList(SerialPortList.getPortNames())); + for (String n : names) { + mPorts.addItem(n); + } + if (current != null) { + mPorts.setSelectedItem(current); + } + } + + // ------------------------------------------------------------------ + // Refresh + // ------------------------------------------------------------------ + + private void updateEnabled() { + boolean ready = mDevice.isReady(); + boolean streaming = mDevice.isStreaming(); + boolean connected = mDevice.isConnected(); + for (JButton b : mReadyOnly) { + b.setEnabled(ready); + } + for (JButton b : mReadyOrStreaming) { + b.setEnabled(ready || streaming); + } + for (JButton b : mStreamingOnly) { + b.setEnabled(streaming); + } + for (JButton b : mConnectedOnly) { + b.setEnabled(connected); + } + mRecord.setText(mDevice.isRecording() ? "Stop recording" : "Record to CSV"); + } + + private void refresh() { + long now = System.currentTimeMillis(); + boolean endWindow = now - mLastWindowEnd >= 1000; + if (endWindow) { + mLastWindowEnd = now; + } + ReceptionStats.Snapshot s = mDevice.snapshot(endWindow); + ShimmerBluetooth sb = mDevice.shimmer(); + String state = mDevice.getState(); + set("Device", sb == null ? "-" : sb.getShimmerUserAssignedName()); + set("Link", mDevice.getPort() == null ? "-" : "Classic, " + mDevice.getPort()); + set("State", state); + set("Rate Hz", sb == null ? "-" : CaptureDevice.trim(sb.getSamplingRateShimmer())); + if (endWindow) { + set("Rx /s", String.format("%.0f", s.rxPerSecond())); + } + set("Samples", Long.toString(s.samples)); + set("Missing", Long.toString(s.missing)); + set("Reception", Double.isNaN(s.reception) ? "-" : String.format("%.2f %%", s.reception)); + set("PRR", Double.isNaN(mDevice.getPrr()) ? "-" : String.format("%.2f %%", mDevice.getPrr())); + set("Delay ms", Double.isNaN(s.delayMs) ? "-" : String.format("%.0f (worst %.0f)", s.delayMs, s.maxDelayMs)); + set("Last sample", lastSample(s.sinceLastMs, "STREAMING".equals(state))); + double batt = mDevice.getBatteryPercent(); + set("Battery", Double.isNaN(batt) ? "-" : String.format("%.0f %%", batt)); + set("Link lost", Integer.toString(mDevice.getLinkLost())); + set("Errors", mDevice.getErrors() == 0 ? "0" : mDevice.getErrors() + ": " + mDevice.getLastError()); + set("Data rate", "- (no data-rate test in the Java driver)"); + set("Hardware / firmware", mDevice.getSummary()); + + mDetails.setText("Battery: " + mDevice.getBatteryDetails() + "\n" + + "Status: " + mDevice.getStatusDetails() + "\n" + + "MAC: " + mDevice.getMac() + "\n" + + "Bluetooth module: " + mDevice.getBluetoothModule() + "\n" + + "Clock: " + mDevice.getClockDetails() + "\n" + + "Logging: " + (sb == null ? "-" : (sb.isSDLogging() ? "yes" : "no")) + "\n"); + + File rec = mDevice.getRecordingFile(); + mRecordLabel.setText(rec == null ? (mDevice.isRecording() ? "waiting for the first sample" : " ") : rec.getName()); + updateEnabled(); + } + + /** The Last sample figure: how long ago, marked stalled after 1 s while streaming; - before any */ + static String lastSample(long sinceMs, boolean streaming) { + if (sinceMs < 0) { + return "-"; + } + return String.format(java.util.Locale.ROOT, "%.1f s ago", sinceMs / 1000.0) + (streaming && sinceMs > 1000 ? ", stalled" : ""); + } + + private void set(String figure, String value) { + for (int r = 0; r < mFigures.getRowCount(); r++) { + if (figure.equals(mFigures.getValueAt(r, 0))) { + if (!value.equals(mFigures.getValueAt(r, 1))) { + mFigures.setValueAt(value, r, 1); + } + return; + } + } + } + + private void clearPlots() { + for (PlotView p : mPlots.values()) { + p.clear(); + p.setVisible(false); + } + mPlotPanel.revalidate(); + } + + // ------------------------------------------------------------------ + // CaptureDevice.Listener, on the driver's thread + // ------------------------------------------------------------------ + + @Override + public void log(final String text) { + final String line = mLogTime.format(new Date()) + " " + text + "\n"; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + mLog.append(line); + mLog.setCaretPosition(mLog.getDocument().getLength()); + } + }); + } + + @Override + public void stateChanged(String state) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + refresh(); + } + }); + } + + @Override + public void sample(ObjectCluster sample, double deviceMs, double hostMs) { + if (Double.isNaN(deviceMs)) { + return; + } + String format = mFormat.getSelectedIndex() == 0 ? CAL : UNCAL; + final List shown = new ArrayList(); + for (String channel : sample.getChannelNamesByInsertionOrder()) { + String panel = Panels.of(channel); + if (panel == null) { + continue; + } + double v = sample.getFormatClusterValue(channel, format); + if (Double.isNaN(v) && UNCAL.equals(format)) { + continue; // calibrated only, such as Batt_Percentage + } + PlotView view = mPlots.get(panel); + if (view.isEmpty()) { + shown.add(view); + } + view.add(channel, deviceMs, v); + } + if (!shown.isEmpty()) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + for (PlotView v : shown) { + v.setVisible(true); + } + mPlotPanel.revalidate(); + } + }); + } + } + +} diff --git a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java new file mode 100644 index 000000000..347eaf4f4 --- /dev/null +++ b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java @@ -0,0 +1,248 @@ +package com.shimmerresearch.capture; + +import static org.junit.Assert.*; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; +import java.util.TimeZone; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_STATE; +import com.shimmerresearch.driver.ObjectCluster; +import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; + +/** + * The rules shimmer-host-core's bindings/CAPTURE.md sets every Capture app, with the inputs and + * results of that repository's Java Capture tests (RecordingTest, ReceptionStatsTest), so that this + * app's figures and files are the same as those apps'. + */ +public class CaptureRulesTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private static final double RATE_HZ = 51.2; + private static final double PERIOD_MS = 1000.0 / RATE_HZ; + + // ------------------------------------------------------------------ + // The recording + // ------------------------------------------------------------------ + + @Test + public void valuesAreWrittenAsJavaScriptWritesThem() { + assertEquals("1420786", CsvRecording.number(1420786.0)); + assertEquals("0", CsvRecording.number(-0.0)); + assertEquals("-3", CsvRecording.number(-3.0)); + assertEquals("9.62", CsvRecording.number(9.62)); + assertEquals("-9.62", CsvRecording.number(-9.62)); + assertEquals("0.30000000000000004", CsvRecording.number(0.1 + 0.2)); + assertEquals("NaN", CsvRecording.number(Double.NaN)); + assertEquals("Infinity", CsvRecording.number(Double.POSITIVE_INFINITY)); + assertEquals("-Infinity", CsvRecording.number(Double.NEGATIVE_INFINITY)); + assertEquals("0.000015", CsvRecording.number(0.000015)); + assertEquals("1.5e-7", CsvRecording.number(1.5e-7)); + assertEquals("1e-7", CsvRecording.number(1e-7)); + assertEquals("10000000000000000", CsvRecording.number(1e16)); + assertEquals("1.5e+21", CsvRecording.number(1.5e21)); + assertEquals("282879384806159000", CsvRecording.number(2.82879384806159E17)); + assertEquals("1.18575755e-316", CsvRecording.number(1.18575755E-316)); + assertEquals("1790960000331.5", CsvRecording.number(1790960000331.5)); + } + + @Test + public void aCellIsEscapedAsRfc4180HasIt() { + assertEquals("m/(s^2)", CsvRecording.cell("m/(s^2)")); + assertEquals("\"a,b\"", CsvRecording.cell("a,b")); + assertEquals("\"say \"\"hi\"\"\"", CsvRecording.cell("say \"hi\"")); + assertEquals("two lines", CsvRecording.cell(" two\r\nlines ")); + } + + @Test + public void aRecordingIsNamedForItsPlatformMacAndLocalStart() { + TimeZone utc = TimeZone.getTimeZone("UTC"); + long started = 1793000000000L; // 2026-10-26 07:33:20 UTC + assertEquals("Shimmer3R_2F31_20261026_073320.csv", CsvRecording.fileName("Shimmer3R", "E747AA7D2F31", started, utc)); + assertEquals("Shimmer3_0000_20261026_073320.csv", CsvRecording.fileName("Shimmer3", null, started, utc)); + assertEquals("Shimmer3_BE69_20261026_083320.csv", + CsvRecording.fileName("Shimmer3", "00:06:66:66:be:69", started, TimeZone.getTimeZone("GMT+01:00"))); + } + + /** A sample as the driver builds one: each channel calibrated and raw, the host's channels calibrated only */ + private static ObjectCluster sample(double ticks, double hostMs) { + ObjectCluster o = new ObjectCluster(); + String cal = CHANNEL_TYPE.CAL.toString(); + String raw = CHANNEL_TYPE.UNCAL.toString(); + o.addData("Timestamp", CHANNEL_TYPE.UNCAL, "no_units", ticks); + o.addData("Timestamp", CHANNEL_TYPE.CAL, "mSecs", ticks / 32.768); + o.addData("GSR_Skin_Conductance", CHANNEL_TYPE.UNCAL, "uS", 1203); + o.addData("GSR_Skin_Conductance", CHANNEL_TYPE.CAL, "uS", 9.62); + o.addData("Accel_LN_X", CHANNEL_TYPE.UNCAL, "no_units", 2047); + o.addData("Accel_LN_X", CHANNEL_TYPE.CAL, "m/(s^2)", 0.1 + 0.2); + o.addData("System_Timestamp", CHANNEL_TYPE.CAL, "mSecs", hostMs); + assertNotNull(cal); + assertNotNull(raw); + return o; + } + + @Test + public void theHeaderRowsAreTheNamesThenTheUnitsWithTheRawTimestampAsTimestampAlone() throws Exception { + File folder = tmp.newFolder("rec"); + CsvRecording r = new CsvRecording(folder, "Shimmer3R", "E747AA7D2F31", sample(1420786, 1790960000331.4), 1792999200000L); + r.append(sample(1420786, 1790960000331.4), 1790960000331.4); + r.append(sample(1421426, 1790960000351.0), 1790960000351.0); + r.close(); + assertTrue(r.getFile().getName().startsWith("Shimmer3R_2F31_")); + String text = new String(Files.readAllBytes(r.getFile().toPath()), StandardCharsets.UTF_8); + assertTrue("every line ends CRLF", text.endsWith("\r\n")); + assertFalse("no bare LF", text.replace("\r\n", "").contains("\n")); + String[] rows = text.split("\r\n", -1); + assertEquals(5, rows.length); + List names = Arrays.asList(rows[0].split(",")); + assertEquals(Arrays.asList("HostTime_ms", "TIMESTAMP", "Timestamp_CAL", "GSR_Skin_Conductance_CAL", + "GSR_Skin_Conductance_RAW", "Accel_LN_X_CAL", "Accel_LN_X_RAW", "System_Timestamp_CAL"), names); + assertEquals("ms,ticks,mSecs,uS,uS,m/(s^2),no_units,mSecs", rows[1]); + String[] first = rows[2].split(","); + assertEquals(names.size(), first.length); + assertEquals("1790960000331", first[0]); + assertEquals("1420786", first[1]); + assertEquals("9.62", first[3]); + assertEquals("1203", first[4]); + assertEquals("0.30000000000000004", first[5]); + assertEquals(2, r.getRows()); + } + + // ------------------------------------------------------------------ + // The figures + // ------------------------------------------------------------------ + + @Test + public void missingSamplesAreCountedFromGapsInTheDeviceTimestamps() { + ReceptionStats stats = new ReceptionStats(0); + stats.reset(RATE_HZ, 0); + int[] periods = {0, 1, 3, 4, 6}; + for (int i = 0; i < periods.length; i++) { + stats.onSample(periods[i] * PERIOD_MS, 1000 + periods[i] * PERIOD_MS, 100 * (i + 1)); + } + ReceptionStats.Snapshot s = stats.snapshot(1000, false); + assertEquals(5, s.samples); + assertEquals(2, s.missing); + assertEquals(100.0 * 5 / 7, s.reception, 1e-9); + } + + @Test + public void aStepIsRoundedToWholePeriods() { + ReceptionStats stats = new ReceptionStats(0); + stats.reset(RATE_HZ, 0); + stats.onSample(0, 0, 0); + stats.onSample(1.4 * PERIOD_MS, 0, 0); + assertEquals(0, stats.snapshot(0, false).missing); + stats.onSample(3.0 * PERIOD_MS, 0, 0); + assertEquals(1, stats.snapshot(0, false).missing); + } + + @Test + public void receptionIsReceivedOverReceivedPlusMissing() { + assertEquals(75.0, ReceptionStats.percent(3, 1), 1e-12); + assertEquals(100.0, ReceptionStats.percent(10, 0), 1e-12); + assertTrue(Double.isNaN(new ReceptionStats(0).snapshot(0, false).reception)); + } + + @Test + public void delayIsArrivalLessDeviceTimeLessTheLeastSoFar() { + ReceptionStats stats = new ReceptionStats(0); + stats.reset(RATE_HZ, 0); + double[] offsets = {5, 0, 30, 10}; + for (int i = 0; i < offsets.length; i++) { + stats.onSample(i * PERIOD_MS, i * PERIOD_MS + offsets[i], 0); + } + ReceptionStats.Snapshot s = stats.snapshot(0, false); + assertEquals(10, s.delayMs, 1e-9); + assertEquals(30, s.maxDelayMs, 1e-9); + } + + @Test + public void rxPerSecondIsTheSamplesOverTheLastWindow() { + ReceptionStats stats = new ReceptionStats(0); + stats.reset(RATE_HZ, 0); + for (int i = 0; i < 51; i++) { + stats.onSample(i * PERIOD_MS, i * PERIOD_MS, 10 * i); + } + assertEquals(51.0, stats.snapshot(1000, true).rxPerSecond(), 1e-9); + assertEquals(0.0, stats.snapshot(2000, true).rxPerSecond(), 1e-9); + assertEquals(51, stats.snapshot(2000, true).samples); + } + + @Test + public void lastSampleIsMarkedStalledAfterASecondWhileStreaming() { + ReceptionStats stats = new ReceptionStats(0); + stats.reset(RATE_HZ, 0); + assertEquals(-1, stats.snapshot(500, false).sinceLastMs); + assertEquals("-", ShimmerCaptureJava.lastSample(-1, true)); + stats.onSample(0, 0, 1000); + assertEquals(1500, stats.snapshot(2500, false).sinceLastMs); + assertEquals("1.5 s ago, stalled", ShimmerCaptureJava.lastSample(1500, true)); + assertEquals("1.5 s ago", ShimmerCaptureJava.lastSample(1500, false)); + assertEquals("0.2 s ago", ShimmerCaptureJava.lastSample(200, true)); + } + + @Test + public void aResetStartsAfresh() { + ReceptionStats stats = new ReceptionStats(0); + stats.reset(RATE_HZ, 0); + stats.onSample(0, 0, 0); + stats.onSample(4 * PERIOD_MS, 0, 0); + stats.reset(RATE_HZ, 0); + ReceptionStats.Snapshot s = stats.snapshot(0, false); + assertEquals(0, s.samples); + assertEquals(0, s.missing); + } + + // ------------------------------------------------------------------ + // The plot and the state + // ------------------------------------------------------------------ + + @Test + public void channelsGoInThePanelsCaptureMdNames() { + assertEquals("Low-noise accel", Panels.of("Accel_LN_X")); + assertEquals("Wide-range accel", Panels.of("Accel_WR_Z")); + assertEquals("Gyro", Panels.of("Gyro_Y")); + assertEquals("Mag", Panels.of("Mag_X")); + assertEquals("Battery", Panels.of("Battery")); + assertEquals("Pressure", Panels.of("Pressure_BMP280")); + assertEquals("Temperature", Panels.of("Temperature_BMP280")); + assertEquals("Temperature", Panels.of("Skin_Temperature")); + assertEquals("ADC", Panels.of("Int_Exp_A12")); + assertEquals("ADC", Panels.of("Ext_Exp_A7")); + assertEquals("ExG", Panels.of("ExG1_CH1_24BIT")); + assertEquals("ExG", Panels.of("ECG_LL-RA_24BIT")); + assertEquals("Other", Panels.of("ExG1_Status1")); + assertEquals("GSR", Panels.of("GSR_Skin_Conductance")); + assertEquals("PPG", Panels.of("PPG_A13")); + assertEquals("PPG", Panels.of("PPG1_A12")); + assertEquals("Other", Panels.of("Sound_Level")); + assertEquals("Other", Panels.of("Batt_Percentage")); + assertNull(Panels.of("Timestamp")); + assertNull(Panels.of("System_Timestamp_Plot")); + assertNull(Panels.of("Packet_Reception_Rate_Trial")); + } + + @Test + public void theDriversStatesAreCaptureMdsStates() { + assertEquals("READY", CaptureDevice.captureState(BT_STATE.CONNECTED)); + assertEquals("READY", CaptureDevice.captureState(BT_STATE.SDLOGGING)); + assertEquals("STREAMING", CaptureDevice.captureState(BT_STATE.STREAMING)); + assertEquals("STREAMING", CaptureDevice.captureState(BT_STATE.STREAMING_AND_SDLOGGING)); + assertEquals("CONNECTING", CaptureDevice.captureState(BT_STATE.CONNECTING)); + assertEquals("CONFIGURING", CaptureDevice.captureState(BT_STATE.CONFIGURING)); + assertEquals("FAILED", CaptureDevice.captureState(BT_STATE.CONNECTION_FAILED)); + assertEquals("DISCONNECTED", CaptureDevice.captureState(BT_STATE.CONNECTION_LOST)); + assertEquals("DISCONNECTED", CaptureDevice.captureState(BT_STATE.DISCONNECTED)); + } + +} From b8eb607c2f1ea81152f17e1a8c76937b8663ddb3 Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 14:22:47 +0800 Subject: [PATCH 2/6] DEV-1473: event markers in Shimmer Capture, marked on the plot as the button is pressed Stacked on DEV-971's Java event channel (#348). The Stream tab's Event markers button opens its window (byte 232, opt in, live records, status, event files), and each button or TTL edge is drawn on every plot panel shown, placed by its own Shimmer clock against the samples' device time. Co-Authored-By: Claude Opus 5.5 --- .../com/shimmerresearch/capture/PlotView.java | 34 +++++++++++ .../com/shimmerresearch/capture/README.md | 22 +++++++ .../capture/ShimmerCaptureJava.java | 58 +++++++++++++++++++ 3 files changed, 114 insertions(+) diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java index fc2ce8297..1d7e25765 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java @@ -46,8 +46,22 @@ void add(double time, double value) { } } + /** An event marker: a vertical line at a device time, with a short label */ + private static final class Marker { + final double t; + final String label; + final Color color; + + Marker(double t, String label, Color color) { + this.t = t; + this.label = label; + this.color = color; + } + } + private final String mTitle; private final Map mSeries = new LinkedHashMap(); + private final List mMarkers = new ArrayList(); private volatile double mWindowMs = 10000; public PlotView(String title) { @@ -75,6 +89,15 @@ public synchronized void add(String channel, double timeMs, double value) { public synchronized void clear() { mSeries.clear(); + mMarkers.clear(); + } + + /** Marks an event at {@code timeMs} of device time, on the same axis as the samples */ + public synchronized void addMarker(double timeMs, String label, Color color) { + mMarkers.add(new Marker(timeMs, label, color)); + if (mMarkers.size() > 500) { + mMarkers.remove(0); + } } public synchronized boolean isEmpty() { @@ -161,6 +184,17 @@ protected synchronized void paintComponent(Graphics g0) { g.drawString(e.getKey(), legendX, 13); legendX += fm.stringWidth(e.getKey()) + 14; } + + g.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {4f, 3f}, 0f)); + for (Marker m : mMarkers) { + if (m.t < from || m.t > latest) { + continue; + } + int x = left + (int) Math.round((m.t - from) / mWindowMs * plotW); + g.setColor(m.color); + g.drawLine(x, top, x, top + plotH); + g.drawString(m.label, x + 3, top + plotH - 3); + } } private static String format(double v) { diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md index e81183a4f..4fc01db9f 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md @@ -111,3 +111,25 @@ CI does not build this module, so run the tests locally. | `ReceptionStats` | The figures' arithmetic | | `CsvRecording` | The CSV | | `Panels`, `PlotView` | The plot | + +## Event markers + +The Stream tab's **Event markers...** opens the event channel window (`EventMarkersFrame`, DEV-971, +stacked on ShimmerResearch/Shimmer-Java-Android-API#348). It covers a Shimmer3R on LogAndStream +v1.01.026 or later: +- byte 232: the button mode, what starts logging, and the TTL input; +- opt in and out of live records, with sequence gaps flagged; +- the status, and an event file read from a card. + +While streaming, each button press and release, and each TTL edge, is also drawn on every plot panel +shown, as a dashed line labelled `press`, `release`, `TTL high` or `TTL low`. The plot's x axis is the +samples' device time, and a record carries the same clock in full: its low 24 bits line up with a +packet's timestamp. + +To try it: +1. Connect, then open Event markers. +2. Set the button to mode 5 (every press recorded) and click Write. +3. Click Opt in. +4. Start streaming and press the button. + +Markers are not written to the CSV. diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java index 78e113c5b..e28ec015a 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java @@ -35,6 +35,9 @@ import com.shimmerresearch.bluetooth.ShimmerBluetooth; import com.shimmerresearch.driver.ObjectCluster; +import com.shimmerresearch.driver.ShimmerDevice; +import com.shimmerresearch.driver.shimmer2r3.EventRecord; +import com.shimmerresearch.simpleexamples.EventMarkersFrame; import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; import com.shimmerresearch.guiUtilities.configuration.EnableSensorsDialog; import com.shimmerresearch.guiUtilities.configuration.SensorConfigDialog; @@ -84,6 +87,9 @@ public final class ShimmerCaptureJava implements CaptureDevice.Listener { private final List mConnectedOnly = new ArrayList(); private final SimpleDateFormat mLogTime = new SimpleDateFormat("HH:mm:ss.SSS"); private long mLastWindowEnd = System.currentTimeMillis(); + /** The latest sample's device time (Timestamp, calibrated, ms): the plot's x axis, to place event markers on */ + private volatile double mLastDeviceMs = Double.NaN; + private EventMarkersFrame mEventMarkers; public static void main(String[] args) { try { @@ -236,6 +242,13 @@ public void actionPerformed(ActionEvent e) { clearPlots(); } })); + JButton events = button("Event markers...", mConnectedOnly, new ActionListener() { + public void actionPerformed(ActionEvent e) { + openEventMarkers(); + } + }); + events.setToolTipText("The button and TTL event channel (Shimmer3R, LogAndStream v1.01.026 on): byte 232, opt in, live records; each edge is marked on the plot"); + bar.add(events); mPlotPanel.setLayout(new BoxLayout(mPlotPanel, BoxLayout.Y_AXIS)); for (String panel : Panels.ALL) { @@ -438,6 +451,50 @@ private void set(String figure, String value) { } } + private void openEventMarkers() { + if (mEventMarkers == null || !mEventMarkers.isDisplayable()) { + mEventMarkers = new EventMarkersFrame(new EventMarkersFrame.Host() { + @Override + public ShimmerDevice getConnectedDevice() { + return mDevice.shimmer(); + } + + @Override + public void plotEventRecord(ShimmerBluetooth shimmer, EventRecord record) { + markEvent(record); + } + }); + mEventMarkers.setLocationRelativeTo(mFrame); + } + mEventMarkers.refresh(); + mEventMarkers.setVisible(true); + mEventMarkers.toFront(); + } + + /** + * Marks an event record's edge on every panel shown, and logs it. The plot's x axis is the + * samples' device time, and a record carries the same clock in full: its low 24 bits line up + * with a packet's timestamp, which the driver unwraps from where the stream began. Called on + * the Swing thread. + */ + void markEvent(EventRecord record) { + log("Event seq " + record.getSequenceNumber() + ": " + record.getDescription()); + double latest = mLastDeviceMs; + if (!record.isEdge() || Double.isNaN(latest) || !mDevice.isStreaming()) { + return; + } + double ticksPerMs = EventRecord.TICKS_PER_SECOND / 1000.0; + double eventMs = record.getTicksOnStreamTimeline(latest * ticksPerMs) / ticksPerMs; + java.awt.Color colour = record.getChannel() == EventRecord.CHANNEL_TTL ? new java.awt.Color(0x6A1B9A) : java.awt.Color.RED; + String label = record.getChannel() == EventRecord.CHANNEL_TTL ? (record.isTtlHigh() ? "TTL high" : "TTL low") + : (record.isButtonDown() ? "press" : "release"); + for (PlotView p : mPlots.values()) { + if (!p.isEmpty()) { + p.addMarker(eventMs, label, colour); + } + } + } + private void clearPlots() { for (PlotView p : mPlots.values()) { p.clear(); @@ -475,6 +532,7 @@ public void sample(ObjectCluster sample, double deviceMs, double hostMs) { if (Double.isNaN(deviceMs)) { return; } + mLastDeviceMs = deviceMs; String format = mFormat.getSelectedIndex() == 0 ? CAL : UNCAL; final List shown = new ArrayList(); for (String channel : sample.getChannelNamesByInsertionOrder()) { From 9940febf3a280185f421f788d8a61005caea609c Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 15:56:42 +0800 Subject: [PATCH 3/6] DEV-1473: README names #349 as part of the stack Co-Authored-By: Claude Opus 5.5 --- .../src/main/java/com/shimmerresearch/capture/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md index 4fc01db9f..f397dcb47 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md @@ -115,8 +115,8 @@ CI does not build this module, so run the tests locally. ## Event markers The Stream tab's **Event markers...** opens the event channel window (`EventMarkersFrame`, DEV-971, -stacked on ShimmerResearch/Shimmer-Java-Android-API#348). It covers a Shimmer3R on LogAndStream -v1.01.026 or later: +from ShimmerResearch/Shimmer-Java-Android-API#348 and #349, which this branch is stacked on). It +covers a Shimmer3R on LogAndStream v1.01.026 or later: - byte 232: the button mode, what starts logging, and the TTL input; - opt in and out of live records, with sequence gaps flagged; - the status, and an event file read from a card. From 13b4ef3f27d74328ffa104dc23bf0d76a6c63f4f Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 17:21:35 +0800 Subject: [PATCH 4/6] DEV-1473: README names #343, now merged, for the event markers window Co-Authored-By: Claude Fable 5.2 --- .../src/main/java/com/shimmerresearch/capture/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md index f397dcb47..0a1d8d42e 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md @@ -115,7 +115,7 @@ CI does not build this module, so run the tests locally. ## Event markers The Stream tab's **Event markers...** opens the event channel window (`EventMarkersFrame`, DEV-971, -from ShimmerResearch/Shimmer-Java-Android-API#348 and #349, which this branch is stacked on). It +from ShimmerResearch/Shimmer-Java-Android-API#343). It covers a Shimmer3R on LogAndStream v1.01.026 or later: - byte 232: the button mode, what starts logging, and the TTL input; - opt in and out of live records, with sequence gaps flagged; From 6daa86d3bded2ead0fcb78d72cf5f42b6b588d87 Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 17:26:22 +0800 Subject: [PATCH 5/6] DEV-1473: close the recording with the window, paint the plot off the driver's lock Found in review of the Capture app: - Closing the window stops a stream, closes a recording and closes the link before it exits. It exited at once, so a recording's rows since its last one-second flush were lost. - A paint copies out the points in its window under the lock, then draws without it. It held the lock add() takes on the driver's thread for the whole paint, and made an array per point. - A recording is closed when a write fails, and when its header rows fail. - Connect is refused while a connect is under way. - The plot's format is kept in a field, not read from its box on the driver's thread. - STREAMING_LOGGED_DATA is STREAMING. It fell through to DISCONNECTED. Co-Authored-By: Claude Fable 5.2 --- .../capture/CaptureDevice.java | 15 +- .../shimmerresearch/capture/CsvRecording.java | 15 +- .../com/shimmerresearch/capture/PlotView.java | 128 ++++++++++++------ .../com/shimmerresearch/capture/README.md | 3 +- .../capture/ShimmerCaptureJava.java | 26 +++- .../capture/CaptureRulesTest.java | 1 + 6 files changed, 143 insertions(+), 45 deletions(-) diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java index 3c94e4b93..6c62aac74 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java @@ -113,6 +113,11 @@ public boolean isStreaming() { return "STREAMING".equals(mState); } + /** A connect has begun and the driver has not yet said how it ended */ + public boolean isConnecting() { + return "CONNECTING".equals(mState); + } + public boolean isConnected() { return shimmer() != null && !"DISCONNECTED".equals(mState) && !"FAILED".equals(mState) && !"CONNECTING".equals(mState); } @@ -127,6 +132,7 @@ static String captureState(BT_STATE state) { return "READY"; case STREAMING: case STREAMING_AND_SDLOGGING: + case STREAMING_LOGGED_DATA: return "STREAMING"; case CONFIGURING: return "CONFIGURING"; @@ -378,7 +384,14 @@ private void record(ObjectCluster sample, double hostMs) { } catch (IOException e) { error("Recording: " + e.getMessage()); mRecordRequested = false; - mRecording = null; + if (mRecording != null) { + try { + mRecording.close(); + } catch (IOException closing) { + // the write's error is the one reported + } + mRecording = null; + } } } } diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java index 804db1061..c8a0d9c88 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CsvRecording.java @@ -103,9 +103,18 @@ public CsvRecording(File folder, String platform, String macAddress, ObjectClust names.add(c.name); units.add(c.units); } - writeRow(names); - writeRow(units); - out.flush(); + try { + writeRow(names); + writeRow(units); + out.flush(); + } catch (IOException e) { + try { + out.close(); + } catch (IOException closing) { + // the write's error is the one reported + } + throw e; + } flushedAt = System.currentTimeMillis(); } diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java index 1d7e25765..fde0938b1 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/PlotView.java @@ -17,7 +17,7 @@ /** * One plot panel: the channels of one group (Panels), each a line over a window of 5, 10 or 30 s * of device time, the y axis fitted to what is shown. Points are added on any thread; painting is - * on the Swing thread. + * on the Swing thread, and holds the lock only to copy out what it will draw. */ public final class PlotView extends JPanel { @@ -104,8 +104,63 @@ public synchronized boolean isEmpty() { return mSeries.isEmpty(); } + /** What one paint draws of a series: its points inside the window, copied out */ + private static final class Shown { + final String name; + final double[] t; + final double[] v; + + Shown(String name, double[] t, double[] v) { + this.name = name; + this.t = t; + this.v = v; + } + } + + /** + * Copies out what is inside the window, and the markers. This is all a paint does under the + * lock that add() takes on the driver's thread, so drawing never holds a sample up. + * + * @return the latest time of any series, or NaN where there is no point + */ + private synchronized double copyShown(double windowMs, List shown, List markers) { + double latest = Double.NEGATIVE_INFINITY; + for (Series s : mSeries.values()) { + if (s.size > 0) { + latest = Math.max(latest, s.t[(s.start + s.size - 1) % CAPACITY]); + } + } + if (latest == Double.NEGATIVE_INFINITY) { + return Double.NaN; + } + double from = latest - windowMs; + for (Map.Entry e : mSeries.entrySet()) { + Series s = e.getValue(); + // times rise, so the window is the newest points: count back to its start + int n = 0; + while (n < s.size && s.t[(s.start + s.size - 1 - n) % CAPACITY] >= from) { + n++; + } + double[] t = new double[n]; + double[] v = new double[n]; + int first = s.start + s.size - n; + for (int i = 0; i < n; i++) { + int k = (first + i) % CAPACITY; + t[i] = s.t[k]; + v[i] = s.v[k]; + } + shown.add(new Shown(e.getKey(), t, v)); + } + markers.addAll(mMarkers); + return latest; + } + + private static boolean finite(double v) { + return !Double.isNaN(v) && !Double.isInfinite(v); + } + @Override - protected synchronized void paintComponent(Graphics g0) { + protected void paintComponent(Graphics g0) { super.paintComponent(g0); Graphics2D g = (Graphics2D) g0; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); @@ -118,24 +173,21 @@ protected synchronized void paintComponent(Graphics g0) { g.setColor(Color.DARK_GRAY); g.drawString(mTitle, left, 13); - double latest = Double.NEGATIVE_INFINITY; - for (Series s : mSeries.values()) { - if (s.size > 0) { - latest = Math.max(latest, s.t[(s.start + s.size - 1) % CAPACITY]); - } - } - if (latest == Double.NEGATIVE_INFINITY) { + double windowMs = mWindowMs; + List shown = new ArrayList(); + List markers = new ArrayList(); + double latest = copyShown(windowMs, shown, markers); + if (Double.isNaN(latest)) { return; } - double from = latest - mWindowMs; + double from = latest - windowMs; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; - for (Series s : mSeries.values()) { - for (int i = 0; i < s.size; i++) { - int k = (s.start + i) % CAPACITY; - if (s.t[k] >= from && !Double.isNaN(s.v[k]) && !Double.isInfinite(s.v[k])) { - min = Math.min(min, s.v[k]); - max = Math.max(max, s.v[k]); + for (Shown s : shown) { + for (int i = 0; i < s.v.length; i++) { + if (finite(s.v[i])) { + min = Math.min(min, s.v[i]); + max = Math.max(max, s.v[i]); } } } @@ -156,41 +208,41 @@ protected synchronized void paintComponent(Graphics g0) { String minText = format(min); g.drawString(maxText, left - 4 - fm.stringWidth(maxText), top + fm.getAscent()); g.drawString(minText, left - 4 - fm.stringWidth(minText), top + plotH); - g.drawString(String.format("%.0f s", mWindowMs / 1000.0), left, h - 3); + g.drawString(String.format("%.0f s", windowMs / 1000.0), left, h - 3); int colour = 0; int legendX = left + 80; g.setStroke(new BasicStroke(1.2f)); - for (Map.Entry e : mSeries.entrySet()) { - Series s = e.getValue(); - Color c = COLORS[colour++ % COLORS.length]; - g.setColor(c); - List points = new ArrayList(); - for (int i = 0; i < s.size; i++) { - int k = (s.start + i) % CAPACITY; - if (s.t[k] < from || Double.isNaN(s.v[k]) || Double.isInfinite(s.v[k])) { + for (Shown s : shown) { + g.setColor(COLORS[colour++ % COLORS.length]); + // at most two points a pixel are drawn + int step = Math.max(1, s.t.length / (plotW * 2)); + boolean have = false; + int lastX = 0; + int lastY = 0; + for (int i = 0; i < s.t.length; i += step) { + if (!finite(s.v[i])) { continue; } - int x = left + (int) Math.round((s.t[k] - from) / mWindowMs * plotW); - int y = top + plotH - (int) Math.round((s.v[k] - min) / (max - min) * plotH); - points.add(new int[] {x, y}); - } - int step = Math.max(1, points.size() / (plotW * 2)); - for (int i = step; i < points.size(); i += step) { - int[] a = points.get(i - step); - int[] b = points.get(i); - g.drawLine(a[0], a[1], b[0], b[1]); + int x = left + (int) Math.round((s.t[i] - from) / windowMs * plotW); + int y = top + plotH - (int) Math.round((s.v[i] - min) / (max - min) * plotH); + if (have) { + g.drawLine(lastX, lastY, x, y); + } + have = true; + lastX = x; + lastY = y; } - g.drawString(e.getKey(), legendX, 13); - legendX += fm.stringWidth(e.getKey()) + 14; + g.drawString(s.name, legendX, 13); + legendX += fm.stringWidth(s.name) + 14; } g.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {4f, 3f}, 0f)); - for (Marker m : mMarkers) { + for (Marker m : markers) { if (m.t < from || m.t > latest) { continue; } - int x = left + (int) Math.round((m.t - from) / mWindowMs * plotW); + int x = left + (int) Math.round((m.t - from) / windowMs * plotW); g.setColor(m.color); g.drawLine(x, top, x, top + plotH); g.drawString(m.label, x + 3, top + plotH - 3); diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md index 0a1d8d42e..477533440 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md @@ -57,7 +57,8 @@ Recordings go to `Shimmer Capture` in Documents. alone. Then a row of units. - **Rows:** one per sample, each value written as JavaScript writes a number. RFC 4180 cells, CRLF line ends. -- **When it closes:** when the recording stops, the stream stops, or the link drops. +- **When it closes:** when the recording stops, the stream stops, the link drops, or the window is + closed. The driver reports most answers by updating its own state rather than with an event. So the window reads that state back twice a second, and a figure or detail can take up to half a second to show an diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java index e28ec015a..3b3424811 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java @@ -6,6 +6,8 @@ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -89,6 +91,8 @@ public final class ShimmerCaptureJava implements CaptureDevice.Listener { private long mLastWindowEnd = System.currentTimeMillis(); /** The latest sample's device time (Timestamp, calibrated, ms): the plot's x axis, to place event markers on */ private volatile double mLastDeviceMs = Double.NaN; + /** The plot's format, as the Stream tab's box has it; read on the driver's thread */ + private volatile boolean mPlotRaw; private EventMarkersFrame mEventMarkers; public static void main(String[] args) { @@ -131,7 +135,20 @@ void show() { // ------------------------------------------------------------------ private void build() { - mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + // Closing the window stops a stream, closes a recording (so its last rows are written) and + // closes the link, then exits + mFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); + mFrame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + try { + mDevice.stopRecording("the window was closed"); + mDevice.disconnect(); + } finally { + System.exit(0); + } + } + }); mFrame.setSize(1280, 860); JPanel top = new JPanel(new FlowLayout(FlowLayout.LEFT)); @@ -152,6 +169,10 @@ public void actionPerformed(ActionEvent e) { log("Choose a port first"); return; } + if (mDevice.isConnecting()) { + log("Already connecting on " + mDevice.getPort()); + return; + } if (mDevice.isConnected()) { log("Already connected on " + mDevice.getPort() + ": one device at a time"); return; @@ -233,6 +254,7 @@ public void actionPerformed(ActionEvent e) { bar.add(mWindow); mFormat.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { + mPlotRaw = mFormat.getSelectedIndex() == 1; clearPlots(); } }); @@ -533,7 +555,7 @@ public void sample(ObjectCluster sample, double deviceMs, double hostMs) { return; } mLastDeviceMs = deviceMs; - String format = mFormat.getSelectedIndex() == 0 ? CAL : UNCAL; + String format = mPlotRaw ? UNCAL : CAL; final List shown = new ArrayList(); for (String channel : sample.getChannelNamesByInsertionOrder()) { String panel = Panels.of(channel); diff --git a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java index 347eaf4f4..a33708bd4 100644 --- a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java +++ b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java @@ -238,6 +238,7 @@ public void theDriversStatesAreCaptureMdsStates() { assertEquals("READY", CaptureDevice.captureState(BT_STATE.SDLOGGING)); assertEquals("STREAMING", CaptureDevice.captureState(BT_STATE.STREAMING)); assertEquals("STREAMING", CaptureDevice.captureState(BT_STATE.STREAMING_AND_SDLOGGING)); + assertEquals("STREAMING", CaptureDevice.captureState(BT_STATE.STREAMING_LOGGED_DATA)); assertEquals("CONNECTING", CaptureDevice.captureState(BT_STATE.CONNECTING)); assertEquals("CONFIGURING", CaptureDevice.captureState(BT_STATE.CONFIGURING)); assertEquals("FAILED", CaptureDevice.captureState(BT_STATE.CONNECTION_FAILED)); From 1854435dcb24d52c012baed63f40a25e21cab25f Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 17:46:04 +0800 Subject: [PATCH 6/6] DEV-1473: name a recording by the MAC read from the configuration over a COM port Connected by its COM port, the unit's Bluetooth MAC is null: the manager has no address to give it, and the driver's getMacId() then never looks at the MAC in the configuration read on connect (bytes 224-229). So recordings were named Shimmer3R_0000_... and the device panel showed no MAC; seen on a Shimmer3R on COM32 whose MAC ends 2F31. CaptureDevice.macIdOf() falls back to that MAC, unless it is erased (FF) or zero. CaptureRulesTest gains two tests; the first failed before the fix. Co-Authored-By: Claude Opus 5.5 --- .../capture/CaptureDevice.java | 23 +++++++++- .../capture/CaptureRulesTest.java | 45 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java index 6c62aac74..e65481d49 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java @@ -11,6 +11,7 @@ import com.shimmerresearch.driver.ObjectCluster; import com.shimmerresearch.driver.ShimmerDevice; import com.shimmerresearch.driver.ShimmerMsg; +import com.shimmerresearch.driver.ShimmerObject; import com.shimmerresearch.driver.shimmer2r3.BluetoothModuleVersionDetails; import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; import com.shimmerresearch.driverUtilities.ShimmerBattStatusDetails; @@ -376,7 +377,7 @@ private void record(ObjectCluster sample, double hostMs) { try { if (mRecording == null) { ShimmerBluetooth sb = shimmer(); - mRecording = new CsvRecording(mRecordFolder, getPlatform(), sb == null ? null : sb.getMacId(), sample, + mRecording = new CsvRecording(mRecordFolder, getPlatform(), sb == null ? null : macIdOf(sb), sample, System.currentTimeMillis()); mListener.log("Recording to " + mRecording.getFile()); } @@ -474,7 +475,25 @@ public String getStatusDetails() { public String getMac() { ShimmerBluetooth sb = shimmer(); - return sb == null ? "-" : sb.getMacId(); + return sb == null ? "-" : macIdOf(sb); + } + + /** + * The unit's MAC, for the recording's name and the device panel. Connected by its COM port, + * the driver's getMacId() is empty: the manager sets the Bluetooth MAC to null, having no + * address, and getMacId() then never looks at the one in the configuration read on connect + * (bytes 224-229). So that one is used next, unless it is erased (FF) or zero. + */ + static String macIdOf(ShimmerDevice device) { + String mac = device.getMacId(); + if ((mac == null || mac.isEmpty()) && device instanceof ShimmerObject) { + String fromConfig = ((ShimmerObject) device).getMacIdFromInfoMem(); + if (fromConfig != null && fromConfig.matches("[0-9A-Fa-f]{12}") + && !fromConfig.matches("[Ff]{12}") && !fromConfig.matches("0{12}")) { + mac = fromConfig; + } + } + return mac == null ? "" : mac; } public String getBluetoothModule() { diff --git a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java index a33708bd4..84fdd94b6 100644 --- a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java +++ b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java @@ -14,8 +14,13 @@ import org.junit.rules.TemporaryFolder; import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_STATE; +import com.shimmerresearch.driver.Configuration.COMMUNICATION_TYPE; import com.shimmerresearch.driver.ObjectCluster; import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; +import com.shimmerresearch.driverUtilities.ShimmerVerDetails.FW_ID; +import com.shimmerresearch.driverUtilities.ShimmerVerDetails.HW_ID; +import com.shimmerresearch.driverUtilities.ShimmerVerObject; +import com.shimmerresearch.pcDriver.ShimmerPC; /** * The rules shimmer-host-core's bindings/CAPTURE.md sets every Capture app, with the inputs and @@ -73,6 +78,46 @@ public void aRecordingIsNamedForItsPlatformMacAndLocalStart() { CsvRecording.fileName("Shimmer3", "00:06:66:66:be:69", started, TimeZone.getTimeZone("GMT+01:00"))); } + /** + * Connected by its COM port, a Shimmer's Bluetooth MAC is null: the manager has no address to + * give it. The MAC is still in the configuration read on connect (bytes 224-229), and the + * recording's name and the device panel use that. + */ + @Test + public void overAComPortTheMacComesFromTheConfiguration() { + ShimmerVerObject s3r = new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25); + ShimmerPC source = new ShimmerPC("COM98"); + source.setShimmerVersionObjectAndCreateSensorMap(s3r); + byte[] config = source.generateConfigBytesForWritingToShimmer().clone(); + byte[] mac = { (byte) 0xE7, 0x47, (byte) 0xAA, 0x7D, 0x2F, 0x31 }; + System.arraycopy(mac, 0, config, 224, mac.length); + + ShimmerPC shimmer = new ShimmerPC("COM32"); + shimmer.setMacIdFromUart(null); // as ShimmerBluetoothManager sets it for a COM port + shimmer.setShimmerVersionObjectAndCreateSensorMap(s3r); + shimmer.configBytesParse(config, COMMUNICATION_TYPE.BLUETOOTH); + + assertEquals("E747AA7D2F31", CaptureDevice.macIdOf(shimmer)); + assertEquals("Shimmer3R_2F31_20261026_073320.csv", + CsvRecording.fileName("Shimmer3R", CaptureDevice.macIdOf(shimmer), 1793000000000L, TimeZone.getTimeZone("UTC"))); + } + + @Test + public void erasedMacBytesAreNoMac() { + ShimmerVerObject s3r = new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25); + ShimmerPC source = new ShimmerPC("COM98"); + source.setShimmerVersionObjectAndCreateSensorMap(s3r); + byte[] config = source.generateConfigBytesForWritingToShimmer().clone(); + for (int i = 224; i < 230; i++) { + config[i] = (byte) 0xFF; + } + ShimmerPC shimmer = new ShimmerPC("COM32"); + shimmer.setMacIdFromUart(null); + shimmer.setShimmerVersionObjectAndCreateSensorMap(s3r); + shimmer.configBytesParse(config, COMMUNICATION_TYPE.BLUETOOTH); + assertEquals("", CaptureDevice.macIdOf(shimmer)); + } + /** A sample as the driver builds one: each channel calibrated and raw, the host's channels calibrated only */ private static ObjectCluster sample(double ticks, double hostMs) { ObjectCluster o = new ObjectCluster();