-
Notifications
You must be signed in to change notification settings - Fork 53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Initial Code Simulation Support: WebSocket Client #1031
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
3cc003d
Starting WS connection
HunterBarclay 26d8c33
Can now receive ws messages, need to parse
HunterBarclay c21adb0
Merge branch 'dev' into barclah/code-sim
HunterBarclay 7fe3cb9
Merge branch 'dev' into barclah/code-sim
HunterBarclay a491e38
Non-deterministic behaviour because of course
HunterBarclay 1b59d94
Working on View panle
HunterBarclay 52e5a16
Discovering some short comings with the WPILib WS sim
HunterBarclay dd28d7a
CAN Motors and Encoders giving ok ish data. SparkMaxes aren't support…
HunterBarclay eb02777
Slowly discovering this may not be the solution
HunterBarclay c0d38ad
Added modification
HunterBarclay 5d61696
Added sample
HunterBarclay d6070d6
This actually appears to be a plausible path
HunterBarclay 71de3f9
Added javadocs to SyntheSimJava, READMEs all around, and now JavaSamp…
HunterBarclay b9db094
Added Cpp sampel
HunterBarclay b3230d5
Merge branch 'dev' into barclah/code-sim
HunterBarclay fec36d8
Linting and build errors
HunterBarclay d5b8a8e
Formatted
HunterBarclay 4aa159e
Added lazy to satisfy linter
HunterBarclay 717fe10
Formatted and removed comments
HunterBarclay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
233 changes: 233 additions & 0 deletions
233
fission/src/systems/simulation/wpilib_brain/WPILibBrain.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,233 @@ | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
import Mechanism from "@/systems/physics/Mechanism" | ||
import Brain from "../Brain" | ||
|
||
import WPILibWSWorker from "./WPILibWSWorker?worker" | ||
|
||
const worker = new WPILibWSWorker() | ||
|
||
const PWM_SPEED = "<speed" | ||
const PWM_POSITION = "<position" | ||
const CANMOTOR_DUTY_CYCLE = "<dutyCycle" | ||
const CANMOTOR_SUPPLY_VOLTAGE = ">supplyVoltage" | ||
const CANENCODER_RAW_INPUT_POSITION = ">rawPositionInput" | ||
|
||
export type SimType = "PWM" | "CANMotor" | "Solenoid" | "SimDevice" | "CANEncoder" | ||
|
||
enum FieldType { | ||
Read = 0, | ||
Write = 1, | ||
Both = 2, | ||
Unknown = -1, | ||
} | ||
|
||
function GetFieldType(field: string): FieldType { | ||
if (field.length < 2) { | ||
return FieldType.Unknown | ||
} | ||
|
||
switch (field.charAt(0)) { | ||
case "<": | ||
return field.charAt(1) == ">" ? FieldType.Both : FieldType.Read | ||
case ">": | ||
return FieldType.Write | ||
default: | ||
return FieldType.Unknown | ||
} | ||
} | ||
|
||
export const simMap = new Map<SimType, Map<string, any>>() | ||
|
||
export class SimGeneric { | ||
private constructor() {} | ||
|
||
public static Get<T>(simType: SimType, device: string, field: string, defaultValue?: T): T | undefined { | ||
const fieldType = GetFieldType(field) | ||
if (fieldType != FieldType.Read && fieldType != FieldType.Both) { | ||
console.warn(`Field '${field}' is not a read or both field type`) | ||
return undefined | ||
} | ||
|
||
const map = simMap.get(simType) | ||
if (!map) { | ||
console.warn(`No '${simType}' devices found`) | ||
return undefined | ||
} | ||
|
||
const data = map.get(device) | ||
if (!data) { | ||
console.warn(`No '${simType}' device '${device}' found`) | ||
return undefined | ||
} | ||
|
||
return (data[field] as T | undefined) ?? defaultValue | ||
} | ||
|
||
public static Set<T>(simType: SimType, device: string, field: string, value: T): boolean { | ||
const fieldType = GetFieldType(field) | ||
if (fieldType != FieldType.Write && fieldType != FieldType.Both) { | ||
console.warn(`Field '${field}' is not a write or both field type`) | ||
return false | ||
} | ||
|
||
const map = simMap.get(simType) | ||
if (!map) { | ||
console.warn(`No '${simType}' devices found`) | ||
return false | ||
} | ||
|
||
const data = map.get(device) | ||
if (!data) { | ||
console.warn(`No '${simType}' device '${device}' found`) | ||
return false | ||
} | ||
|
||
const selectedData: any = {} | ||
selectedData[field] = value | ||
|
||
data[field] = value | ||
worker.postMessage({ | ||
command: "update", | ||
data: { | ||
type: simType, | ||
device: device, | ||
data: selectedData, | ||
}, | ||
}) | ||
|
||
window.dispatchEvent(new SimMapUpdateEvent(true)) | ||
return true | ||
} | ||
} | ||
|
||
export class SimPWM { | ||
private constructor() {} | ||
|
||
public static GetSpeed(device: string): number | undefined { | ||
return SimGeneric.Get("PWM", device, PWM_SPEED, 0.0) | ||
} | ||
|
||
public static GetPosition(device: string): number | undefined { | ||
return SimGeneric.Get("PWM", device, PWM_POSITION, 0.0) | ||
} | ||
} | ||
|
||
export class SimCANMotor { | ||
private constructor() {} | ||
|
||
public static GetDutyCycle(device: string): number | undefined { | ||
return SimGeneric.Get("CANMotor", device, CANMOTOR_DUTY_CYCLE, 0.0) | ||
} | ||
|
||
public static SetSupplyVoltage(device: string, voltage: number): boolean { | ||
return SimGeneric.Set("CANMotor", device, CANMOTOR_SUPPLY_VOLTAGE, voltage) | ||
} | ||
} | ||
|
||
export class SimCANEncoder { | ||
private constructor() {} | ||
|
||
public static SetRawInputPosition(device: string, rawInputPosition: number): boolean { | ||
return SimGeneric.Set("CANEncoder", device, CANENCODER_RAW_INPUT_POSITION, rawInputPosition) | ||
} | ||
} | ||
|
||
worker.addEventListener("message", (eventData: MessageEvent) => { | ||
let data: any | undefined | ||
try { | ||
if (typeof eventData.data == "object") { | ||
data = eventData.data | ||
} else { | ||
data = JSON.parse(eventData.data) | ||
} | ||
} catch (e) { | ||
console.warn(`Failed to parse data:\n${JSON.stringify(eventData.data)}`) | ||
} | ||
|
||
if (!data || !data.type) { | ||
console.log("No data, bailing out") | ||
return | ||
} | ||
|
||
// console.debug(data) | ||
|
||
const device = data.device | ||
const updateData = data.data | ||
|
||
switch (data.type) { | ||
case "PWM": | ||
console.debug("pwm") | ||
UpdateSimMap("PWM", device, updateData) | ||
break | ||
case "Solenoid": | ||
console.debug("solenoid") | ||
UpdateSimMap("Solenoid", device, updateData) | ||
break | ||
case "SimDevice": | ||
console.debug("simdevice") | ||
UpdateSimMap("SimDevice", device, updateData) | ||
break | ||
case "CANMotor": | ||
console.debug("canmotor") | ||
UpdateSimMap("CANMotor", device, updateData) | ||
break | ||
case "CANEncoder": | ||
console.debug("canencoder") | ||
UpdateSimMap("CANEncoder", device, updateData) | ||
break | ||
default: | ||
// console.debug(`Unrecognized Message:\n${data}`) | ||
break | ||
} | ||
}) | ||
|
||
function UpdateSimMap(type: SimType, device: string, updateData: any) { | ||
let typeMap = simMap.get(type) | ||
if (!typeMap) { | ||
typeMap = new Map<string, any>() | ||
simMap.set(type, typeMap) | ||
} | ||
|
||
let currentData = typeMap.get(device) | ||
if (!currentData) { | ||
currentData = {} | ||
typeMap.set(device, currentData) | ||
} | ||
Object.entries(updateData).forEach(kvp => (currentData[kvp[0]] = kvp[1])) | ||
|
||
window.dispatchEvent(new SimMapUpdateEvent(false)) | ||
} | ||
|
||
class WPILibBrain extends Brain { | ||
constructor(mech: Mechanism) { | ||
super(mech) | ||
} | ||
|
||
public Update(_: number): void {} | ||
|
||
public Enable(): void { | ||
worker.postMessage({ command: "connect" }) | ||
} | ||
|
||
public Disable(): void { | ||
worker.postMessage({ command: "disconnect" }) | ||
} | ||
} | ||
|
||
export class SimMapUpdateEvent extends Event { | ||
public static readonly TYPE: string = "ws/sim-map-update" | ||
|
||
private _internalUpdate: boolean | ||
|
||
public get internalUpdate(): boolean { | ||
return this._internalUpdate | ||
} | ||
|
||
public constructor(internalUpdate: boolean) { | ||
super(SimMapUpdateEvent.TYPE) | ||
|
||
this._internalUpdate = internalUpdate | ||
} | ||
} | ||
|
||
export default WPILibBrain |
65 changes: 65 additions & 0 deletions
65
fission/src/systems/simulation/wpilib_brain/WPILibWSWorker.ts
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note: If you click WS test twice you run into a warning (the connection is not being closed I believe) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import { Mutex } from "async-mutex" | ||
|
||
let socket: WebSocket | undefined = undefined | ||
|
||
const connectMutex = new Mutex() | ||
|
||
async function tryConnect(port: number | undefined): Promise<void> { | ||
await connectMutex | ||
.runExclusive(() => { | ||
if ((socket?.readyState ?? WebSocket.CLOSED) == WebSocket.OPEN) { | ||
return | ||
} | ||
|
||
socket = new WebSocket(`ws://localhost:${port ?? 3300}/wpilibws`) | ||
|
||
socket.addEventListener("open", () => { | ||
console.log("WS Opened") | ||
self.postMessage({ status: "open" }) | ||
}) | ||
socket.addEventListener("error", () => { | ||
console.log("WS Could not open") | ||
self.postMessage({ status: "error" }) | ||
}) | ||
|
||
socket.addEventListener("message", onMessage) | ||
}) | ||
.then(() => console.debug("Mutex released")) | ||
} | ||
|
||
async function tryDisconnect(): Promise<void> { | ||
await connectMutex.runExclusive(() => { | ||
if (!socket) { | ||
return | ||
} | ||
|
||
socket?.close() | ||
socket = undefined | ||
}) | ||
} | ||
|
||
function onMessage(event: MessageEvent) { | ||
// console.log(`${JSON.stringify(JSON.parse(event.data), null, '\t')}`) | ||
self.postMessage(event.data) | ||
} | ||
|
||
self.addEventListener("message", e => { | ||
switch (e.data.command) { | ||
case "connect": | ||
tryConnect(e.data.port) | ||
break | ||
case "disconnect": | ||
tryDisconnect() | ||
break | ||
case "update": | ||
if (socket) { | ||
socket.send(JSON.stringify(e.data.data)) | ||
} | ||
break | ||
default: | ||
console.warn(`Unrecognized command '${e.data.command}'`) | ||
break | ||
} | ||
}) | ||
|
||
console.log("Worker started") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should simMap be a static field on SimGeneric, since the latter encapsulates former?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@PepperLola How ever you two end up structuring everything will determine this.