Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions src/config.gd
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
## and user modifications to the configuration panel calls its corresponding set_value.
extends Node

## Emitted with the config id as argument on configuration change.
signal modified

# -------------------------------------------------------------------
# Private variables and functions
# -------------------------------------------------------------------
Expand All @@ -37,7 +40,8 @@ var _defaults: Dictionary[String, Dictionary] = {
"type": "float",
"default": 0.62,
"min": 0.40,
"max": 0.80
"max": 0.80,
"step": 0.01,
},
"player.pushrim_diameter":
{
Expand All @@ -47,7 +51,8 @@ var _defaults: Dictionary[String, Dictionary] = {
"type": "float",
"default": 0.54,
"min": 0.40,
"max": 0.80
"max": 0.80,
"step": 0.01,
},
"player.camera.fov":
{
Expand Down Expand Up @@ -101,9 +106,11 @@ var _defaults: Dictionary[String, Dictionary] = {
"overlays": {"order": 3, "label": "OVERLAYS"},
"overlays.speed_indicator.enabled":
{"order": 3.01, "label": "Speed indicator", "type": "bool", "default": true},
"overlays.debug.enabled": {"order": 3.02, "label": "Debug", "type": "bool", "default": false},
"overlays.debug.enabled": {"order": 3.15, "label": "Debug", "type": "bool", "default": false},
"overlays.biofeedback_kinematics.enabled":
{"order": 3.02, "label": "Biofeedback: Kinematics", "type": "bool", "default": false},
"overlays.biofeedback_push_pattern.enabled":
{"order": 3.03, "label": "Biofeedback Push pattern", "type": "bool", "default": false},
{"order": 3.03, "label": "Push Pattern", "type": "bool", "default": false},
"overlays.contact_angle_start":
{
"order": 3.04,
Expand All @@ -125,7 +132,25 @@ var _defaults: Dictionary[String, Dictionary] = {
"max": 140.0
},
"overlays.biofeedback_push_frequency.enabled":
{"order": 3.06, "label": "Biofeedback Push Frequency", "type": "bool", "default": false},
{"order": 3.06, "label": "Push Frequency", "type": "bool", "default": false},
"overlays.biofeedback_pushrim_kinetics.enabled":
{"order": 3.07, "label": "Biofeedback: Pushrim Kinetics", "type": "bool", "default": false},
"overlays.biofeedback_pushrim_kinetics.target_force":
{
"order": 3.08,
"label": "Target Force",
"type": "float",
"default": 50.0,
"min": 25.0,
"max": 125.0
},
"overlays.biofeedback_pushrim_kinetics.wheel_ip":
{
"order": 3.09,
"label": "Wheel IP ('xx.xx.xx.xx' or 'dummy')",
"type": "string",
"default": "dummy"
},
"devices": {"order": 4, "label": "DEVICE SETTINGS"},
"devices.screens": {"order": 4.1, "label": "Screens"},
"devices.screens.single_screen": {"order": 4.2, "label": "Single screen"},
Expand Down Expand Up @@ -174,7 +199,7 @@ var _defaults: Dictionary[String, Dictionary] = {
"devices.python_bridge.enabled":
{"order": 4.8, "label": "Python Bridge", "type": "bool", "default": false},
"devices.python_bridge.python_path":
{"order": 4.81, "label": "Python app path", "type": "file", "default": ""},
{"order": 4.81, "label": "Python or conda path", "type": "file", "default": ""},
"devices.python_bridge.script_path":
{"order": 4.82, "label": "Python script path", "type": "file", "default": ""},
"devices.data_logging": {"order": 4.9, "label": "DATA LOGGING"},
Expand Down Expand Up @@ -353,6 +378,8 @@ func set_value(key: String, value):
# Tell everyone that config has been modified
for caller_id in _modified:
_modified[caller_id][key] = true
# Send the modified signal for other modules to react to it
modified.emit(key)


## Has value been changed since last call with a given caller_id?
Expand Down
18 changes: 9 additions & 9 deletions src/devices/data_logging/data_logging.gd
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func _scene_signal_received(scene_name):
# If a trial was in progress (i.e. previous scene is not blank), end it
if scenes["current"] != "":
if logging["current"] == true and Globals.main.has_node("PythonBridge"):
Globals.main.get_node("PythonBridge").send("end_trial", data, "once")
Globals.main.get_node("PythonBridge").run("end_trial", data)
player_trajectory["position"] = NAN
player_trajectory["rotation"] = NAN

Expand All @@ -39,7 +39,7 @@ func _scene_signal_received(scene_name):
and scene_name != ""
and Globals.main.has_node("PythonBridge")
):
Globals.main.get_node("PythonBridge").send("create_trial", data, "once")
Globals.main.get_node("PythonBridge").run("create_trial", data)


# called everytime a signal is received from player.gd to save it
Expand All @@ -60,7 +60,7 @@ func _python_signal_received(connection):

if Config.get_value("devices.data_logging.enabled"):
update_logging()
Globals.main.get_node("PythonBridge").send(connection_command, data, "once")
Globals.main.get_node("PythonBridge").run(connection_command, data)


# Update logging on/off variables
Expand All @@ -85,8 +85,8 @@ func update_data():

func _ready() -> void:
update_logging()
if SignalBus.python_connected.is_connected(_python_signal_received) == false:
SignalBus.python_connected.connect(_python_signal_received)
if SignalBus.python_bridge_connected.is_connected(_python_signal_received) == false:
SignalBus.python_bridge_connected.connect(_python_signal_received)
if Config.get_value("devices.data_logging.player_trajectory") == true:
SignalBus.player_trajectory.connect(_player_signal_received)

Expand All @@ -111,18 +111,18 @@ func _process(_delta: float) -> void:
if logging["current"] == true:
# Start logging if this is the first frame for which current_logging is enabled
if logging["past"] == false:
Globals.main.get_node("PythonBridge").send("start_logging", data, "once")
Globals.main.get_node("PythonBridge").run("start_logging", data)
# If a scene was already initiated before logging, start a trial and update scene
if scenes["current"] != "":
Globals.main.get_node("PythonBridge").send("create_trial", data, "once")
Globals.main.get_node("PythonBridge").run("create_trial", data)

# If any scene is running, send player data at each frame
if scenes["current"] != "":
Globals.main.get_node("PythonBridge").send("data_logging", data, "once")
Globals.main.get_node("PythonBridge").run("data_logging", data)

# Otherwise, if logging is not currently on but was in the previous frame, end the process
elif logging["past"] == true:
Globals.main.get_node("PythonBridge").send("end_trial", data, "once")
Globals.main.get_node("PythonBridge").run("end_trial", data)
player_trajectory["position"] = NAN
player_trajectory["rotation"] = NAN

Expand Down
113 changes: 53 additions & 60 deletions src/devices/python_bridge/python_bridge.gd
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ extends Node3D
@export var udp_send_port: int = 4243 # Python port
@export var udp_receive_port: int = 4242 # Godot port

var queue_requests_by_id = {} # Queue storing received request data per id
var _udp_receiver = PacketPeerUDP.new()
var _udp_sender = PacketPeerUDP.new()
var _udp_receiver_connected = false
var _signal_counter: int = 0


func _ready():
# Launch Python app
var python_app_path: String = Config.get_value("devices.python_bridge.python_path")
var python_script_path: String = Config.get_value("devices.python_bridge.script_path")
var conda_environment: String = "wheelsims"

if python_app_path == "":
print("Cannot launch Python because Python app path is unset.")
Expand All @@ -33,98 +33,91 @@ func _ready():
print("Cannot launch Python because Python app script is unset.")
return

OS.create_process(python_app_path, [python_script_path], true)
var parameters: Array[String]
if conda_environment == "": # Bare Python environment
parameters = [python_script_path]
else:
parameters = [
"run", "-n", conda_environment, "--no-capture-output", "python", python_script_path
]

if OS.get_name() == "macOS":
print("Launching a terminal window for Python Bridge...")
var cmd: String = 'tell app "Terminal" to do script "' + python_app_path + " "
for parameter in parameters:
cmd += parameter
cmd += '"'
OS.create_process("/usr/bin/osascript", ["-e", cmd])
else:
print(python_app_path, parameters)
OS.create_process(python_app_path, parameters, true)

# Set UDP receiver and UDP sender
_udp_receiver.bind(udp_receive_port)
_udp_sender.connect_to_host(udp_send_ip, udp_send_port)

# Waiting ping request from Python bridge
while _udp_receiver.get_available_packet_count() == 0:
await get_tree().create_timer(1.0).timeout
_udp_receiver_connected = true
if Config.get_value("devices.data_logging.enabled") == true:
SignalBus.python_connected.emit(_udp_receiver_connected)


func _process(_delta):
if Globals.main:
if not Config.get_value("devices.python_bridge.enabled"):
queue_free()
if _udp_receiver_connected:
_process_received_packets()

if Config.get_value("devices.data_logging.enabled") == true:
SignalBus.python_connected.emit(_udp_receiver_connected)


## Receive and save JSON data from Python bridge in requests queues
func _process_received_packets():
while _udp_receiver.get_available_packet_count() > 0: # We received something
var data = _udp_receiver.get_packet()
var json_string = data.get_string_from_utf8()
var json = JSON.new()
json.parse(json_string)
var data_dict: Dictionary = json.get_data()

for id in queue_requests_by_id:
queue_requests_by_id[id].append(json.get_data())
if data_dict["id"] == "ready":
# This is the only "return value" not associated to a call from
# Godot. Therefore there is no signal to emit or value to return.
SignalBus.python_bridge_connected.emit(true)
_signal_counter += 1
return

emit_signal(data_dict["id"], data_dict["value"])
remove_user_signal(data_dict["id"])

## Receive data from Python.

## Run a Python command
##
## To use:
## result = await python_bridge.run(python_command, kwargs)
##
## Parameters
## ----------
## id
## Name of the receive queue. If the receive queue does not exist yet, it is created. Each
## received data is appended to every receive queue, which ensures that calling receive() with
## a unique queue gives access to every received packets.
## command
## Python command, as defined in the COMMAND_DICT dictionary of main.py
## kwargs
## Optional. Arguments of the command, in the form {"argname": value, ...}
##
## Returns
## -------
## Dictionary
## If no data is available, returns an empty dictionary.
## If data is available, returns a dictionary with keys "command", which is the name of the
## python command that sent this data, and "data", which is a dictionary with the actual
## data.
func receive(id: String) -> Dictionary:
if id not in queue_requests_by_id:
queue_requests_by_id[id] = []
return {}
if queue_requests_by_id[id].size() > 0:
var last_data = queue_requests_by_id[id].pop_at(-1)
return last_data
return {}


## Run a Python command.
##
## Parameters
## ----------
## command
## One of the available commands in the python_bridge.py's COMMAND_MAPPING
## args
## A dictionary containing any information required by the command
## run_mode
## "once" to launch the command once, "start" to run it continuously, and "stop" to
## stop from running it continuously.
func send(command: String, args: Dictionary, run_mode: String):
var request = {"command": command, "args": args, "run_mode": run_mode}
## signal
## A signal to await. The result of the Python function is returned with the
## signal.
func run(command: String, kwargs: Dictionary = {}) -> Signal:
var id: String = command + "_" + str(Time.get_ticks_usec()) + "_" + str(_signal_counter)
_signal_counter += 1
if _signal_counter >= 1000000:
_signal_counter = 1

var request = {"command": command, "kwargs": kwargs, "id": id}
_udp_sender.put_packet(JSON.stringify(request).to_utf8_buffer())
add_user_signal(id)
return Signal(self, id) # Reference to the created signal


## Debug overlay
func get_debug_text() -> String:
var text = ""
text += "Python "
if not _udp_receiver_connected:
text += "not "
text += "connected.\n"
var text = "Received " + str(_signal_counter) + " UDP packets."
return text


## Close the python app when the node exits the scene tree
func _exit_tree():
SignalBus.python_connected.emit(null)
send("close", {}, "once")
SignalBus.python_bridge_connected.emit()
await run("close")
# Delay to allow other overlays/devices to shut down before this device
await get_tree().create_timer(0.1).timeout
9 changes: 5 additions & 4 deletions src/main.tscn
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,20 @@
[ext_resource type="Script" uid="uid://db602oks11677" path="res://config.gd" id="3_h2yge"]
[ext_resource type="PackedScene" uid="uid://xwtfx6p27vlm" path="res://devices/motorized_rollers/motorized_rollers.tscn" id="4_5vw27"]
[ext_resource type="PackedScene" uid="uid://f24s3bar65fp" path="res://overlays/debug/debug.tscn" id="4_272bh"]
[ext_resource type="PackedScene" uid="uid://bm1b5ewq26kcl" path="res://overlays/biofeedback_push_pattern/biofeedback_push_pattern.tscn" id="4_dg77c"]
[ext_resource type="PackedScene" uid="uid://ck2thoxwmsujy" path="res://devices/d_box/d_box.tscn" id="5_5vw27"]
[ext_resource type="PackedScene" uid="uid://c5tbnk1yth8r8" path="res://overlays/biofeedback_push_frequency/biofeedback_push_frequency.tscn" id="5_ycdy4"]
[ext_resource type="PackedScene" uid="uid://dkk1u1dxvshbj" path="res://overlays/biofeedback_kinematics/biofeedback_kinematics.tscn" id="5_w48qg"]
[ext_resource type="PackedScene" uid="uid://utxy2vmv4wo7" path="res://devices/optitrack/optitrack.tscn" id="6_kek77"]
[ext_resource type="PackedScene" uid="uid://ccudr43mvulkw" path="res://overlays/biofeedback_pushrim_kinetics/biofeedback_pushrim_kinetics.tscn" id="6_vivmo"]
[ext_resource type="PackedScene" uid="uid://k18bpclv0qnw" path="res://devices/screens/single_screen.tscn" id="8_efxa6"]
[ext_resource type="PackedScene" uid="uid://bvnocfmlki4nf" path="res://devices/screens/front_floor_screens.tscn" id="9_dg77c"]
[ext_resource type="PackedScene" uid="uid://x4hefxmnqe41" path="res://devices/python_bridge/python_bridge.tscn" id="10_dg77c"]

[node name="main" type="Node" unique_id=502567777]
script = ExtResource("1_0xm2m")
available_overlays = Dictionary[String, PackedScene]({
"overlays.biofeedback_push_frequency.enabled": ExtResource("5_ycdy4"),
"overlays.biofeedback_push_pattern.enabled": ExtResource("4_dg77c"),
"": null,
"overlays.biofeedback_kinematics.enabled": ExtResource("5_w48qg"),
"overlays.biofeedback_pushrim_kinetics.enabled": ExtResource("6_vivmo"),
"overlays.debug.enabled": ExtResource("4_272bh"),
"overlays.speed_indicator.enabled": ExtResource("2_efxa6")
})
Expand Down
50 changes: 50 additions & 0 deletions src/overlays/biofeedback_kinematics/biofeedback_kinematics.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
extends Node2D

var python_bridge: Node

## Results from wheelsims_analysis/biofeedback_kinematics, updated regularly
var analysis_results: Dictionary


func _ready() -> void:
await SignalBus.python_bridge_connected
python_bridge = Globals.main.get_node("PythonBridge")
# await python_bridge.run("biofeedback_kinematics_connect", {})
update_loop()


func update_loop() -> void:
while true:
var temp

temp = await (
python_bridge
. run(
"biofeedback_kinematics",
{
"coordinates_left_wheel_center":
Config.get_value("coordinates.left_wheel_center"),
"coordinates_right_wheel_center":
Config.get_value("coordinates.right_wheel_center"),
"coordinates_left_hand": Config.get_value("coordinates.left_hand"),
"coordinates_right_hand": Config.get_value("coordinates.right_hand"),
"wheel_diameter": Config.get_value("player.pushrim_diameter"),
}
)
)
if temp != null:
analysis_results = temp

# set local variable analysis_results of every decendent node that has
# such variable.
propagate_call("set", ["analysis_results", analysis_results])


func _process(_delta) -> void:
$BiofeedbackPushPattern.visible = Config.get_value("overlays.biofeedback_push_pattern.enabled")
$BiofeedbackPushFrequency.visible = Config.get_value(
"overlays.biofeedback_push_frequency.enabled"
)

if not Config.get_value("overlays.biofeedback_kinematics.enabled"):
queue_free()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://cgmtlqtd2o0ny
Loading
Loading