From 2219568c5230137a57fda4aacc6af45498e51748 Mon Sep 17 00:00:00 2001 From: JongChern Date: Mon, 16 Nov 2026 11:48:46 +0800 Subject: [PATCH] DEV-1478: Shimmer Capture's microphone - audio recording, sound level, audio status The Java Shimmer Capture app gets the microphone half of shimmer-host-core's CAPTURE.md "Event markers and audio recording", on the driver calls DEV-1459 brought to master (#353) and the sound level channel from DEV-1413 (#346). - EventMarkersFrame, now "Event markers and audio": configuration byte 233's audio recording mode (Off, Fingerprint only, Fingerprint and raw audio, Raw audio only) and Sound Level, written with the whole configuration and read back, then an inquiry for the channel list; Read audio status from READY. - Raw audio records speech: Write asks first where the new mode keeps raw audio and the unit's own does not, and writes nothing on No. The driver's raw audio switch is set for that one write and put back. - MicrophoneSettings: byte 233's rules without Swing, so they are tested. - Device tab: the status's Recording audio and Audio fault flags where the unit records audio, and whether the firmware has the event markers and audio recording. - CaptureRulesTest: 11 tests, byte 233 as written checked on a ShimmerPC. - README. Co-Authored-By: Claude Opus 5.5 --- .../capture/CaptureDevice.java | 27 ++- .../com/shimmerresearch/capture/README.md | 61 +++++-- .../capture/ShimmerCaptureJava.java | 6 +- .../simpleexamples/EventMarkersFrame.java | 162 ++++++++++++++++-- .../simpleexamples/MicrophoneSettings.java | 148 ++++++++++++++++ .../capture/CaptureRulesTest.java | 145 ++++++++++++++++ 6 files changed, 521 insertions(+), 28 deletions(-) create mode 100644 ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/simpleexamples/MicrophoneSettings.java diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java index e65481d49..5f05835a7 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/CaptureDevice.java @@ -16,6 +16,7 @@ import com.shimmerresearch.driverUtilities.ChannelDetails.CHANNEL_TYPE; import com.shimmerresearch.driverUtilities.ShimmerBattStatusDetails; import com.shimmerresearch.exceptions.ShimmerException; +import com.shimmerresearch.simpleexamples.MicrophoneSettings; import com.shimmerresearch.tools.bluetooth.BasicShimmerBluetoothManagerPc; /** @@ -461,7 +462,10 @@ public String getBatteryDetails() { return b.getBattVoltageParsed() + ", " + b.getEstimatedChargePercentageParsed() + ", " + b.getChargingStatusParsed(); } - /** The status flags as the last status read left them */ + /** + * The status flags as the last status read left them. A unit that records audio adds the two + * audio flags, which it sends in its status whenever either changes. + */ public String getStatusDetails() { ShimmerBluetooth sb = shimmer(); if (sb == null) { @@ -470,7 +474,26 @@ public String getStatusDetails() { 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()); + + ", red LED " + yes(sb.mIsRedLedOn) + ", USB " + yes(sb.isUsbPluggedIn()) + + (MicrophoneSettings.recordsAudio(sb) ? ", " + MicrophoneSettings.audioFlags(sb.isAudioRecording(), sb.isAudioFault()) : ""); + } + + /** Whether the firmware has the event markers and audio recording, from what the driver asked at connect */ + public String getFeatures() { + ShimmerBluetooth sb = shimmer(); + if (sb == null) { + return "-"; + } + return features(sb.isEventChannelSupported(), MicrophoneSettings.recordsAudio(sb)); + } + + /** + * The event markers as yes, no or not asked yet. Audio recording is yes or no: the driver keeps + * no "not asked yet" for it, so a v1.01.025 unit reads no until it has answered GET_AUDIO_STATUS. + */ + static String features(Boolean eventChannel, boolean recordsAudio) { + return "event markers " + (eventChannel == null ? "not asked yet" : yes(eventChannel)) + + ", audio recording " + yes(recordsAudio); } public String getMac() { diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md index 477533440..bfe550c12 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/README.md @@ -38,7 +38,10 @@ Recordings go to `Shimmer Capture` in Documents. 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. + - The plot, in CAPTURE.md's panels by channel name: 5, 10 or 30 s, calibrated or raw, Clear. A + Shimmer3R's `Sound_Level` (nominal dB(A)) is in the Other panel, without the samples where the + unit has no level yet. + - **Event markers and audio...**: the event channel and the microphone (below). - **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. @@ -48,6 +51,10 @@ Recordings go to `Shimmer Capture` in Documents. - **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. + - Where the unit records audio, the status's two audio flags too: Recording audio and Audio + fault. The unit sends its status whenever either changes. + - Whether the firmware has the event markers (yes, no, or not asked yet) and audio recording + (yes or no), from what the driver asks at connect. - **The log** at the bottom. **The recording** is CAPTURE.md's, so one script reads any app's files: @@ -56,7 +63,8 @@ Recordings go to `Shimmer Capture` in Documents. `_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. + line ends. `Sound_Level_CAL` is `NaN` where the unit has no level yet, and `Sound_Level_RAW` is + then `-32768`. - **When it closes:** when the recording stops, the stream stops, the link drops, or the window is closed. @@ -92,14 +100,22 @@ What CAPTURE.md asks for that this app does not do: - **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. +- **Event markers and audio,** which CAPTURE.md also lists as not yet in any app: the records saved + as CSV; an event file opened from disk is here, but not a WAV header or a fingerprint file; and + the `events/` and `audio/` files downloaded with their session (no SD card over Bluetooth in the + driver). +- **Audio recording's "not asked yet":** the driver keeps none, so a v1.01.025 unit shows no until + it has answered GET_AUDIO_STATUS, which the driver asks at connect. ## Tests `./gradlew :test --tests 'com.shimmerresearch.capture.*'` runs `CaptureRulesTest`. It covers: -- the recording's numbers, cells, file name, columns and units; +- the recording's numbers, cells, file name, columns and units, the sound level's among them; - the figures' arithmetic; - the plot panels; -- the state mapping. +- the state mapping; +- the microphone: the four audio modes, when Write asks before raw audio, what byte 233 is written + as (with and without the answer yes, and the sound level bit), and the audio flags as shown. CI does not build this module, so run the tests locally. @@ -112,25 +128,50 @@ CI does not build this module, so run the tests locally. | `ReceptionStats` | The figures' arithmetic | | `CsvRecording` | The CSV | | `Panels`, `PlotView` | The plot | +| `simpleexamples.EventMarkersFrame` | The event markers and audio window, shared with `SensorMapsExample` | +| `simpleexamples.MicrophoneSettings` | Byte 233's rules: the audio modes, raw audio, the sound level; no Swing | -## Event markers +## Event markers and audio -The Stream tab's **Event markers...** opens the event channel window (`EventMarkersFrame`, DEV-971, -from ShimmerResearch/Shimmer-Java-Android-API#343). It -covers a Shimmer3R on LogAndStream v1.01.026 or later: +The Stream tab's **Event markers and audio...** opens the window for CAPTURE.md's "Event markers +and audio recording" (`EventMarkersFrame`: DEV-971, from ShimmerResearch/Shimmer-Java-Android-API#343, +and DEV-1478). It covers a Shimmer3R on LogAndStream v1.01.026 or later, and the top line says +whether the unit has each part. + +**Event markers:** - 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. +**Audio,** configuration byte 233: +- **Audio recording:** Off, Fingerprint only, Fingerprint and raw audio, or Raw audio only. That is + what the unit saves in `audio/` on its card while it logs. +- **Sound level:** the `Sound_Level` channel, from v1.01.026. Writing it asks the unit for its + channel list again, since it adds or removes a channel. +- **Write** writes the whole configuration and reads it back, so the line below it shows what the + unit kept. Raw audio records speech: where the new mode keeps raw audio and the unit's own does + not, Write asks first and writes nothing if the answer is no. The driver's own rule otherwise + writes the mode without the raw audio. +- **Read audio status** (GET_AUDIO_STATUS), from READY only: the driver reads its reply between + commands, not between data packets. It shows the Recording audio and Audio fault flags. + 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. +To try the markers: +1. Connect, then open Event markers and audio. 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. + +To try the microphone: +1. Connect, then open Event markers and audio. +2. Set Audio recording to Fingerprint only, tick Sound level, and click Write. +3. Check the line under the buttons for what the unit kept. +4. Start streaming: `Sound_Level` appears in the Other panel. +5. Stop streaming, start logging on the Device tab, then click Read audio status to see whether it + is recording audio. diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java index 3b3424811..ce98ba24a 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/capture/ShimmerCaptureJava.java @@ -264,12 +264,13 @@ public void actionPerformed(ActionEvent e) { clearPlots(); } })); - JButton events = button("Event markers...", mConnectedOnly, new ActionListener() { + JButton events = button("Event markers and audio...", 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"); + events.setToolTipText("Shimmer3R, LogAndStream v1.01.026 on: the button and TTL event channel (byte 232, opt in, live records, each edge" + + " marked on the plot) and the microphone (byte 233: audio recording and the sound level; the audio status)"); bar.add(events); mPlotPanel.setLayout(new BoxLayout(mPlotPanel, BoxLayout.Y_AXIS)); @@ -444,6 +445,7 @@ private void refresh() { mDetails.setText("Battery: " + mDevice.getBatteryDetails() + "\n" + "Status: " + mDevice.getStatusDetails() + "\n" + + "Firmware has: " + mDevice.getFeatures() + "\n" + "MAC: " + mDevice.getMac() + "\n" + "Bluetooth module: " + mDevice.getBluetoothModule() + "\n" + "Clock: " + mDevice.getClockDetails() + "\n" diff --git a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/simpleexamples/EventMarkersFrame.java b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/simpleexamples/EventMarkersFrame.java index 535ba750e..e37e800e9 100644 --- a/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/simpleexamples/EventMarkersFrame.java +++ b/ShimmerPCBasicExamples/src/main/java/com/shimmerresearch/simpleexamples/EventMarkersFrame.java @@ -52,7 +52,10 @@ *
  • the live records after an opt-in, with sequence gaps flagged, and each * one marked on the main window's plot;
  • *
  • the event channel status;
  • - *
  • an event file from a card, its header and records.
  • + *
  • an event file from a card, its header and records;
  • + *
  • the microphone (DEV-1478): configuration byte 233, the audio recording + * mode and the sound level, written and read back; the audio status, with + * its two flags.
  • * */ public class EventMarkersFrame extends JFrame implements EventChannelListener { @@ -88,6 +91,10 @@ public interface Host { private final JCheckBox mChkTtl = new JCheckBox("Record TTL input"); private final JLabel mLblConfig = new JLabel(" "); private final JLabel mLblCounters = new JLabel(" "); + private final JComboBox mComboAudioMode = new JComboBox(MicrophoneSettings.modeNames().toArray(new String[0])); + private final JCheckBox mChkSoundLevel = new JCheckBox("Sound level (the Sound_Level channel, nominal dB(A))"); + private final JLabel mLblAudio = new JLabel(" "); + private final JLabel mLblAudioStatus = new JLabel(" "); private final JTextArea mTxtStatus = new JTextArea(5, 40); private final JTextArea mTxtFile = new JTextArea(6, 40); @@ -109,11 +116,11 @@ public interface Host { private final SimpleDateFormat mLocal = new SimpleDateFormat("HH:mm:ss.SSS"); public EventMarkersFrame(Host host) { - super("Event markers (DEV-971)"); + super("Event markers and audio"); mHost = host; mUtc.setTimeZone(TimeZone.getTimeZone("UTC")); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - setSize(new Dimension(1000, 720)); + setSize(new Dimension(1000, 840)); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { @@ -147,6 +154,10 @@ public void actionPerformed(ActionEvent e) { return; } sb.readEventChannelSupport(); + // v1.01.025 says whether it records audio only by answering GET_AUDIO_STATUS + if(sb.isAudioStatusToAsk()) { + sb.readAudioStatus(); + } refreshLater(); } }); @@ -179,16 +190,7 @@ public void actionPerformed(ActionEvent e) { })); configButtons.add(button("Read back", new ActionListener() { public void actionPerformed(ActionEvent e) { - ShimmerBluetooth sb = shimmer(); - if(sb==null) { - return; - } - if(sb.isStreaming() || sb.isSDLogging()) { - warn("Stop streaming and logging first: the firmware refuses configuration reads and writes while sensing."); - return; - } - sb.readConfigBytes(); - refreshLater(); + readBack(); } })); c.gridx = 1; @@ -197,6 +199,45 @@ public void actionPerformed(ActionEvent e) { config.add(mLblConfig, c); top.add(config); + // --- Configuration byte 233: the microphone + JPanel audio = new JPanel(new GridBagLayout()); + audio.setBorder(BorderFactory.createTitledBorder("Audio, configuration byte 233 (written with the whole configuration)")); + c = new GridBagConstraints(); + c.insets = new Insets(2, 4, 2, 4); + c.anchor = GridBagConstraints.WEST; + c.gridx = 0; c.gridy = 0; + audio.add(new JLabel("Audio recording"), c); + c.gridx = 1; + mComboAudioMode.setToolTipText("What the unit saves from its microphone while it logs to its SD card (audio/ on the card)"); + audio.add(mComboAudioMode, c); + c.gridx = 0; c.gridy = 1; c.gridwidth = 2; + mChkSoundLevel.setToolTipText("A channel in the data: in the plot's Other panel and the CSV. LogAndStream v1.01.026 on."); + audio.add(mChkSoundLevel, c); + c.gridwidth = 1; + JPanel audioButtons = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0)); + audioButtons.add(button("Write", new ActionListener() { + public void actionPerformed(ActionEvent e) { + writeAudio(); + } + })); + audioButtons.add(button("Read back", new ActionListener() { + public void actionPerformed(ActionEvent e) { + readBack(); + } + })); + audioButtons.add(button("Read audio status", new ActionListener() { + public void actionPerformed(ActionEvent e) { + readAudioStatus(); + } + })); + c.gridx = 1; c.gridy = 2; + audio.add(audioButtons, c); + c.gridx = 0; c.gridy = 3; c.gridwidth = 2; + audio.add(mLblAudio, c); + c.gridy = 4; + audio.add(mLblAudioStatus, c); + top.add(audio); + // --- Live records JPanel live = new JPanel(new FlowLayout(FlowLayout.LEFT)); live.setBorder(BorderFactory.createTitledBorder("Live records over Bluetooth (this connection only)")); @@ -315,13 +356,17 @@ public void refresh() { if(!(device instanceof ShimmerBluetooth)) { mLblSupport.setText("No Shimmer3 / Shimmer3R connected"); mLblConfig.setText(" "); + mLblAudio.setText(" "); + mLblAudioStatus.setText(" "); return; } ShimmerBluetooth sb = (ShimmerBluetooth) device; attach(sb); Boolean supported = sb.isEventChannelSupported(); mLblSupport.setText(sb.getFirmwareVersionParsed() + " - event channel: " - + (supported==null? "not asked yet" : (supported? "yes" : "no"))); + + (supported==null? "not asked yet" : (supported? "yes" : "no")) + + ", audio recording: " + (MicrophoneSettings.recordsAudio(sb)? "yes" : "no")); + refreshAudio(sb); if(sb.isButtonLogModeKnown()) { int buttonMode = sb.getButtonMode(); int logTriggers = sb.getLogTriggers(); @@ -342,6 +387,95 @@ public void refresh() { updateCounters(); } + /** Byte 233 and the audio flags as the driver holds them */ + private void refreshAudio(ShimmerBluetooth sb) { + boolean recordsAudio = MicrophoneSettings.recordsAudio(sb); + boolean hasSoundLevel = MicrophoneSettings.hasSoundLevel(sb); + mComboAudioMode.setEnabled(recordsAudio); + mChkSoundLevel.setEnabled(hasSoundLevel); + if(!recordsAudio) { + mLblAudio.setText("This unit does not record audio: LogAndStream_Shimmer3R v1.01.026 or later does."); + mLblAudioStatus.setText(" "); + return; + } + int mode = sb.getAudioMode(); + if(mode>=0 && mode + *
  • A unit records audio on LogAndStream_Shimmer3R v1.01.026 or later, or + * on a v1.01.025 development build that answered GET_AUDIO_STATUS at + * connect ({@link ShimmerDevice#isAudioSupported()}).
  • + *
  • Only v1.01.026 or later has the sound level channel.
  • + *
  • Raw audio records speech, so a raw mode is written only where the user + * agreed to it, or where the unit already keeps raw audio. The driver's own + * rule ({@link ShimmerObject#getAudioModeToWrite()}) otherwise writes the + * mode without the raw audio.
  • + * + */ +public final class MicrophoneSettings { + + private MicrophoneSettings() { + } + + /** The driver's names for the four audio modes, Off first, indexed by mode */ + public static List modeNames() { + return Collections.unmodifiableList(Arrays.asList(Configuration.Shimmer3.ListofAudioMode)); + } + + /** Whether the unit records audio from its microphone */ + public static boolean recordsAudio(ShimmerDevice device) { + return device != null && device.isAudioSupported(); + } + + /** Whether the unit's firmware has the sound level channel: v1.01.026 or later */ + public static boolean hasSoundLevel(ShimmerDevice device) { + return device != null + && device.isVerCompatibleWithAnyOf(Configuration.Shimmer3.CompatibilityInfoForMaps.listOfCompatibleVersionInfoSoundLevel); + } + + /** Whether the sound level is turned on in the driver's copy of the configuration */ + public static boolean isSoundLevelOn(ShimmerDevice device) { + return hasSoundLevel(device) && device.isSensorEnabled(Configuration.Shimmer3.SENSOR_ID.SHIMMER_SOUND_LEVEL); + } + + /** + * The audio mode in byte 233 as last read from the unit, whatever has been + * set on the driver since; Off before the first read. + */ + public static int modeAsRead(ShimmerDevice device) { + AbstractSensor sensor = device == null ? null : device.getSensorClass(AbstractSensor.SENSORS.SOUND_LEVEL); + if (!(sensor instanceof SensorSoundLevel)) { + return Configuration.Shimmer3.AUDIO_MODE_OFF; + } + return ((SensorSoundLevel) sensor).getAudioModeAndGain() & 0x03; + } + + /** Whether writing {@code mode} asks first: it keeps raw audio, and the unit's own mode does not */ + public static boolean asksFirst(int mode, int modeAsRead) { + return ShimmerObject.isRawAudioMode(mode) && !ShimmerObject.isRawAudioMode(modeAsRead); + } + + /** Whether the driver may write raw audio for this write: the mode keeps it, and the user agreed or the unit keeps it already */ + static boolean rawAudioAllowed(int mode, int modeAsRead, boolean agreed) { + return ShimmerObject.isRawAudioMode(mode) && (agreed || ShimmerObject.isRawAudioMode(modeAsRead)); + } + + /** + * Sets the audio mode and the sound level on the driver's copy of the + * configuration, then writes the whole configuration and reads it back, + * and asks for the channel list again (an inquiry), since the sound level + * adds or removes a channel. The firmware corrects what it does not keep, + * so the read-back is what the unit holds. The sound level is left as it is + * on firmware without it. + * + * @param agreed whether the user agreed to raw audio, where {@link #asksFirst} asked + */ + public static void write(final ShimmerBluetooth shimmer, final int mode, final boolean soundLevel, boolean agreed) { + withRawAudioAllowed(rawAudioAllowed(mode, modeAsRead(shimmer), agreed), new Runnable() { + public void run() { + set(shimmer, mode, soundLevel); + shimmer.writeConfigBytes(true); + } + }); + if (hasSoundLevel(shimmer)) { + shimmer.inquiry(); + } + } + + /** Byte 233 as {@link #write} would send it, without sending it */ + public static int byteToWrite(final ShimmerBluetooth shimmer, final int mode, final boolean soundLevel, boolean agreed) { + final byte[][] config = new byte[1][]; + withRawAudioAllowed(rawAudioAllowed(mode, modeAsRead(shimmer), agreed), new Runnable() { + public void run() { + set(shimmer, mode, soundLevel); + config[0] = shimmer.generateConfigBytesForWritingToShimmer(); + } + }); + ConfigByteLayout layout = shimmer.getConfigByteLayout(); + if (!(layout instanceof ConfigByteLayoutShimmer3) || ((ConfigByteLayoutShimmer3) layout).idxAudioConfig <= 0) { + return -1; + } + return config[0][((ConfigByteLayoutShimmer3) layout).idxAudioConfig] & 0xFF; + } + + private static void set(ShimmerObject shimmer, int mode, boolean soundLevel) { + shimmer.setAudioMode(mode); + if (hasSoundLevel(shimmer)) { + shimmer.setSensorEnabledState(Configuration.Shimmer3.SENSOR_ID.SHIMMER_SOUND_LEVEL, soundLevel); + } + } + + /** The driver's raw audio switch is for the whole process, so it is set for this one write and put back */ + private static void withRawAudioAllowed(boolean allowed, Runnable write) { + boolean was = ShimmerObject.isRawAudioAllowed(); + ShimmerObject.setRawAudioAllowed(allowed); + try { + write.run(); + } finally { + ShimmerObject.setRawAudioAllowed(was); + } + } + + /** What the speech question says */ + public static String speechQuestion(String modeName) { + return "" + modeName + " keeps the microphone's raw audio on the SD card, and raw audio records speech.
    " + + "Everyone who may be recorded should know, and agree, before this unit logs.

    " + + "Write " + modeName + "?"; + } + + /** The status's two audio flags, as the window shows them */ + public static String audioFlags(boolean recording, boolean fault) { + return "recording audio " + (recording ? "yes" : "no") + ", audio fault " + (fault ? "yes" : "no"); + } + +} diff --git a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java index 84fdd94b6..4a39561d8 100644 --- a/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java +++ b/ShimmerPCBasicExamples/src/test/java/com/shimmerresearch/capture/CaptureRulesTest.java @@ -14,13 +14,17 @@ import org.junit.rules.TemporaryFolder; import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_STATE; +import com.shimmerresearch.driver.Configuration; import com.shimmerresearch.driver.Configuration.COMMUNICATION_TYPE; import com.shimmerresearch.driver.ObjectCluster; +import com.shimmerresearch.driver.ShimmerObject; 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; +import com.shimmerresearch.sensors.soundlevel.SensorSoundLevel; +import com.shimmerresearch.simpleexamples.MicrophoneSettings; /** * The rules shimmer-host-core's bindings/CAPTURE.md sets every Capture app, with the inputs and @@ -291,4 +295,145 @@ public void theDriversStatesAreCaptureMdsStates() { assertEquals("DISCONNECTED", CaptureDevice.captureState(BT_STATE.DISCONNECTED)); } + // ------------------------------------------------------------------ + // The microphone (DEV-1478): CAPTURE.md's "Event markers and audio recording" + // ------------------------------------------------------------------ + + /** LogAndStream_Shimmer3R v1.01.026, the first release with the sound level and the audio flags */ + private static final ShimmerVerObject S3R_026 = new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 26); + private static final ShimmerVerObject S3R_025 = new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25); + private static final int OFF = Configuration.Shimmer3.AUDIO_MODE_OFF; + private static final int FINGERPRINT = Configuration.Shimmer3.AUDIO_MODE_FINGERPRINT; + private static final int FINGERPRINT_AND_RAW = Configuration.Shimmer3.AUDIO_MODE_FINGERPRINT_AND_RAW; + private static final int RAW = Configuration.Shimmer3.AUDIO_MODE_RAW; + private static final int SOUND_LEVEL_BIT = 0x10; + + /** A Shimmer3R whose configuration was read with {@code audioConfig} in byte 233 */ + private static ShimmerPC readFrom(ShimmerVerObject version, int audioConfig) { + ShimmerPC source = new ShimmerPC("COM98"); + source.setShimmerVersionObjectAndCreateSensorMap(version); + byte[] config = source.generateConfigBytesForWritingToShimmer().clone(); + config[233] = (byte) audioConfig; + ShimmerPC shimmer = new ShimmerPC("COM32"); + shimmer.setShimmerVersionObjectAndCreateSensorMap(version); + shimmer.configBytesParse(config, COMMUNICATION_TYPE.BLUETOOTH); + return shimmer; + } + + @Test + public void theAudioRecordingSettingIsTheDriversFourModesOffFirst() { + assertEquals(Arrays.asList("Off", "Fingerprint only", "Fingerprint and raw audio", "Raw audio only"), MicrophoneSettings.modeNames()); + assertEquals("Fingerprint only", MicrophoneSettings.modeNames().get(FINGERPRINT)); + assertEquals("Raw audio only", MicrophoneSettings.modeNames().get(RAW)); + } + + @Test + public void writeAsksFirstWhereTheNewModeKeepsRawAudioAndTheUnitsOwnDoesNot() { + assertTrue(MicrophoneSettings.asksFirst(RAW, OFF)); + assertTrue(MicrophoneSettings.asksFirst(RAW, FINGERPRINT)); + assertTrue(MicrophoneSettings.asksFirst(FINGERPRINT_AND_RAW, FINGERPRINT)); + assertFalse("the unit records speech already", MicrophoneSettings.asksFirst(RAW, FINGERPRINT_AND_RAW)); + assertFalse("the unit records speech already", MicrophoneSettings.asksFirst(FINGERPRINT_AND_RAW, RAW)); + assertFalse(MicrophoneSettings.asksFirst(FINGERPRINT, RAW)); + assertFalse(MicrophoneSettings.asksFirst(OFF, OFF)); + assertFalse(MicrophoneSettings.asksFirst(FINGERPRINT, OFF)); + } + + @Test + public void aRawModeAgreedToIsWritten() { + assertEquals(RAW, MicrophoneSettings.byteToWrite(readFrom(S3R_026, FINGERPRINT), RAW, false, true)); + assertEquals(FINGERPRINT_AND_RAW, MicrophoneSettings.byteToWrite(readFrom(S3R_026, OFF), FINGERPRINT_AND_RAW, false, true)); + } + + @Test + public void aRawModeNotAgreedToIsWrittenWithoutTheRawAudio() { + assertEquals(OFF, MicrophoneSettings.byteToWrite(readFrom(S3R_026, FINGERPRINT), RAW, false, false)); + assertEquals(FINGERPRINT, MicrophoneSettings.byteToWrite(readFrom(S3R_026, OFF), FINGERPRINT_AND_RAW, false, false)); + } + + @Test + public void aUnitThatKeepsRawAudioAlreadyIsNotAskedAndKeepsIt() { + assertEquals(RAW, MicrophoneSettings.byteToWrite(readFrom(S3R_026, FINGERPRINT_AND_RAW), RAW, false, false)); + assertEquals(FINGERPRINT_AND_RAW, MicrophoneSettings.byteToWrite(readFrom(S3R_026, FINGERPRINT_AND_RAW), FINGERPRINT_AND_RAW, false, false)); + } + + @Test + public void theDriversRawAudioSwitchIsPutBackAfterAWrite() { + boolean was = ShimmerObject.isRawAudioAllowed(); + ShimmerObject.setRawAudioAllowed(false); + try { + MicrophoneSettings.byteToWrite(readFrom(S3R_026, OFF), RAW, false, true); + assertFalse(ShimmerObject.isRawAudioAllowed()); + } finally { + ShimmerObject.setRawAudioAllowed(was); + } + } + + @Test + public void theSoundLevelIsBit4FromV1_01_026() { + assertEquals(FINGERPRINT | SOUND_LEVEL_BIT, MicrophoneSettings.byteToWrite(readFrom(S3R_026, FINGERPRINT), FINGERPRINT, true, false)); + assertEquals(FINGERPRINT, MicrophoneSettings.byteToWrite(readFrom(S3R_026, FINGERPRINT | SOUND_LEVEL_BIT), FINGERPRINT, false, false)); + assertEquals("v1.01.025 has no sound level channel", FINGERPRINT, + MicrophoneSettings.byteToWrite(readFrom(S3R_025, FINGERPRINT), FINGERPRINT, true, false)); + } + + @Test + public void theUnitsOwnModeIsTheOneReadWhateverIsSetSince() { + ShimmerPC shimmer = readFrom(S3R_026, FINGERPRINT_AND_RAW | SOUND_LEVEL_BIT); + assertEquals(FINGERPRINT_AND_RAW, MicrophoneSettings.modeAsRead(shimmer)); + assertTrue(MicrophoneSettings.isSoundLevelOn(shimmer)); + shimmer.setAudioMode(OFF); + assertEquals(FINGERPRINT_AND_RAW, MicrophoneSettings.modeAsRead(shimmer)); + } + + @Test + public void whichUnitsRecordAudioAndHaveTheSoundLevel() { + ShimmerPC s3r026 = readFrom(S3R_026, OFF); + assertTrue(MicrophoneSettings.recordsAudio(s3r026)); + assertTrue(MicrophoneSettings.hasSoundLevel(s3r026)); + ShimmerPC s3r025 = readFrom(S3R_025, OFF); + assertFalse("v1.01.025 records audio only once it answers GET_AUDIO_STATUS", MicrophoneSettings.recordsAudio(s3r025)); + assertFalse(MicrophoneSettings.hasSoundLevel(s3r025)); + ShimmerPC s3 = new ShimmerPC("COM97"); + s3.setShimmerVersionObjectAndCreateSensorMap(new ShimmerVerObject(HW_ID.SHIMMER_3, FW_ID.LOGANDSTREAM, 1, 1, 26)); + assertFalse(MicrophoneSettings.recordsAudio(s3)); + assertFalse(MicrophoneSettings.hasSoundLevel(s3)); + assertFalse(MicrophoneSettings.recordsAudio(null)); + } + + @Test + public void theDevicePanelShowsTheAudioFlagsAndWhatTheFirmwareHas() { + assertEquals("recording audio yes, audio fault no", MicrophoneSettings.audioFlags(true, false)); + assertEquals("recording audio no, audio fault yes", MicrophoneSettings.audioFlags(false, true)); + assertEquals("event markers not asked yet, audio recording no", CaptureDevice.features(null, false)); + assertEquals("event markers yes, audio recording yes", CaptureDevice.features(Boolean.TRUE, true)); + assertEquals("event markers no, audio recording no", CaptureDevice.features(Boolean.FALSE, false)); + } + + @Test + public void theSoundLevelIsAColumnOfTheRecordingWithNaNWhereThereIsNoLevel() throws Exception { + File folder = tmp.newFolder("sound"); + ObjectCluster first = sample(1420786, 1790960000331.4); + first.addData("Sound_Level", CHANNEL_TYPE.UNCAL, "no_units", -32768); + first.addData("Sound_Level", CHANNEL_TYPE.CAL, Configuration.CHANNEL_UNITS.DECIBELS_A, SensorSoundLevel.calibrateSoundLevel(-32768)); + ObjectCluster second = sample(1421426, 1790960000351.0); + second.addData("Sound_Level", CHANNEL_TYPE.UNCAL, "no_units", 5432); + second.addData("Sound_Level", CHANNEL_TYPE.CAL, Configuration.CHANNEL_UNITS.DECIBELS_A, SensorSoundLevel.calibrateSoundLevel(5432)); + CsvRecording r = new CsvRecording(folder, "Shimmer3R", "E747AA7D2F31", first, 1792999200000L); + r.append(first, 1790960000331.4); + r.append(second, 1790960000351.0); + r.close(); + String[] rows = new String(Files.readAllBytes(r.getFile().toPath()), StandardCharsets.UTF_8).split("\r\n", -1); + List names = Arrays.asList(rows[0].split(",")); + int cal = names.indexOf("Sound_Level_CAL"); + int raw = names.indexOf("Sound_Level_RAW"); + assertTrue(names.toString(), cal > 0 && raw == cal + 1); + assertEquals(Configuration.CHANNEL_UNITS.DECIBELS_A, rows[1].split(",")[cal]); + assertEquals("NaN", rows[2].split(",")[cal]); + assertEquals("-32768", rows[2].split(",")[raw]); + assertEquals("54.32", rows[3].split(",")[cal]); + assertEquals("5432", rows[3].split(",")[raw]); + assertEquals("Other", Panels.of("Sound_Level")); + } + }