Skip to content

Commit

Permalink
Add displaying device name in UI when connected
Browse files Browse the repository at this point in the history
  • Loading branch information
simon-wh committed Aug 6, 2020
1 parent 1deb0b9 commit 26e8b68
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 23 deletions.
5 changes: 3 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 22 additions & 6 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ use std::sync::{Arc, RwLock};
use std::thread;
use std::thread::{sleep, JoinHandle};
use std::time::Duration;
use wooting_analog_midi::{Channel, MidiService, NoteID, WootingAnalogResult, REFRESH_RATE};
use wooting_analog_midi::{
Channel, DeviceInfo, MidiService, NoteID, WootingAnalogResult, REFRESH_RATE,
};
mod settings;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -112,8 +114,15 @@ impl App {
self.thread_pool.push(thread::spawn(move || {
let mut iter_count: u32 = 0;
if has_devices {
let devices = midi_service_inner
.read()
.unwrap()
.get_connected_devices()
.context("Failed to get connected devices")
.map_err(output_err)
.unwrap_or(vec![]);
if let Err(e) = tx_inner
.send(AppEvent::FoundDevices)
.send(AppEvent::FoundDevices(devices))
.context("Error when sending FoundDevices event!")
{
output_err(e);
Expand Down Expand Up @@ -152,8 +161,15 @@ impl App {
if !errored {
if !has_devices {
has_devices = true;
let devices = midi_service_inner
.read()
.unwrap()
.get_connected_devices()
.context("Failed to get connected devices")
.map_err(output_err)
.unwrap_or(vec![]);
if let Err(e) = tx_inner
.send(AppEvent::FoundDevices)
.send(AppEvent::FoundDevices(devices))
.context("Error when sending FoundDevices event!")
{
output_err(e);
Expand Down Expand Up @@ -301,7 +317,7 @@ pub enum ChannelMessage {
pub enum AppEvent {
MidiUpdate(MidiUpdate),
NoDevices,
FoundDevices,
FoundDevices(Vec<DeviceInfo>),
}

fn emit_event(handle: &mut tauri::WebviewMut, event_name: &str, param: Option<String>) {
Expand Down Expand Up @@ -347,8 +363,8 @@ fn main() {
emit_event(&mut handle, "midi-update", Some(serde_json::to_string(&update).unwrap()));

},
AppEvent::FoundDevices => {
emit_event(&mut handle, "found-devices", None);
AppEvent::FoundDevices(devices) => {
emit_event(&mut handle, "found-devices", Some(serde_json::to_string(&devices).unwrap()));
},
AppEvent::NoDevices => {
emit_event(&mut handle, "no-devices", None);
Expand Down
22 changes: 15 additions & 7 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import React, { useEffect, useState } from "react";
import "./App.css";
import { MidiDataEntry } from "./components/PianoDisplay";
import styled from "styled-components";
import { AppSettings, PortOptions, backend, MidiUpdate } from "./backend";
import {
AppSettings,
PortOptions,
backend,
MidiUpdate,
DeviceList,
} from "./backend";
import { Piano } from "./components/Piano";

const Row = styled.div`
Expand All @@ -19,20 +25,22 @@ function App() {
});
const [portOptions, setPortOptions] = useState<PortOptions>([]);
const [selectedChannel, setSelectedChannel] = useState<number>(0);
const [hasDevices, setHasDevices] = useState<boolean>(backend.hasDevices);
const [connectedDevices, setConnectedDevices] = useState<DeviceList>(
backend.connectedDeviceList
);

function settingsChanged(settings: AppSettings) {
setAppSettings(settings);
backend.updateSettings(settings);
}

useEffect(() => {
backend.on("found-devices", () => {
setHasDevices(true);
backend.on("found-devices", (devices: DeviceList) => {
setConnectedDevices(devices);
});

backend.on("no-devices", () => {
setHasDevices(false);
setConnectedDevices([]);
});

return () => {
Expand Down Expand Up @@ -119,8 +127,8 @@ function App() {
<header className="App-header">
<Row>
<p>
{hasDevices
? "Devices are connected, you're all set!"
{connectedDevices.length > 0
? `Device ${connectedDevices[0].device_name} are connected, you're all set!`
: "No compatible devices could be found!"}
</p>
</Row>
Expand Down
32 changes: 31 additions & 1 deletion src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,32 @@ type PortOption = [number, string, boolean];

export type PortOptions = PortOption[];

export enum DeviceType {
/// Device is of type Keyboard
Keyboard = 1,
/// Device is of type Keypad
Keypad = 2,
/// Device
Other = 3,
}

export interface DeviceInfo {
/// Device Vendor ID `vid`
vendor_id: number;
/// Device Product ID `pid`
product_id: number;
/// Device Manufacturer name
manufacturer_name: String;
/// Device name
device_name: String;
/// Unique device ID
device_id: number;
/// Hardware type of the Device
device_type: DeviceType;
}

export type DeviceList = DeviceInfo[];

export interface AppSettings {
keymapping: { [channel: string]: [HIDCodes, number][] };
}
Expand Down Expand Up @@ -43,6 +69,7 @@ export class Backend extends EventEmitter {
private lastMidi: MidiUpdate;
public hasDevices: boolean;
public hasInitComplete: boolean;
public connectedDeviceList: DeviceList;

constructor() {
super();
Expand All @@ -56,15 +83,18 @@ export class Backend extends EventEmitter {
this.lastMidi = JSON.parse(res.payload);
});
this.hasDevices = false;
this.connectedDeviceList = [];
listen<string>("found-devices", (res) => {
console.log("Found devices");
this.connectedDeviceList = JSON.parse(res.payload) as DeviceList;
this.hasDevices = true;
this.emit("found-devices");
this.emit("found-devices", this.connectedDeviceList);
});

listen<string>("no-devices", (res) => {
console.log("No devices");
this.hasDevices = false;
this.connectedDeviceList = [];
this.emit("no-devices");
});

Expand Down
9 changes: 5 additions & 4 deletions wooting-analog-midi/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion wooting-analog-midi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2018"
[dependencies]
midir = "0.6"
# wooting-analog-wrapper = { path="../../wooting-analog-sdk/wooting-analog-wrapper" }
wooting-analog-wrapper = { git = "https://github.com/WootingKb/wooting-analog-sdk", branch = "release/v0.5" }
wooting-analog-wrapper = { git = "https://github.com/WootingKb/wooting-analog-sdk", branch = "feature/serde-derive" }
# ctrlc = { version = "3", features = ["termination"] }
log = "0.4"
lazy_static = "1.4"
Expand Down
7 changes: 5 additions & 2 deletions wooting-analog-midi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ extern crate anyhow;
#[allow(unused_imports)]
use log::{error, info};
use sdk::SDKResult;
pub use sdk::WootingAnalogResult;
pub use sdk::{DeviceInfo, FromPrimitive, HIDCodes, ToPrimitive};
pub use sdk::{DeviceInfo, FromPrimitive, HIDCodes, ToPrimitive, WootingAnalogResult};
use wooting_analog_wrapper as sdk;

use anyhow::{Context, Result};
Expand Down Expand Up @@ -306,6 +305,10 @@ impl MidiService {
Ok(device_num)
}

pub fn get_connected_devices(&self) -> Result<Vec<DeviceInfo>> {
return Ok(sdk::get_connected_devices_info(DEVICE_BUFFER_MAX).0?);
}

pub fn select_port(&mut self, option: usize) -> Result<()> {
//TODO: Deal with the case where the port list has changed since the `port_options` was generated
if let Some(options) = &self.port_options {
Expand Down

0 comments on commit 26e8b68

Please sign in to comment.