mirror of
https://github.com/scottbez1/smartknob.git
synced 2025-09-26 23:09:27 +08:00
New detent configurations (magnetic and biased-to-center) and demo React app (#105)
Breaking change to protobuf messages to support new detent configurations - adds more flexibility compared to existing config parameters (e.g. min/max position rather than just number of positions). New magnetic detent mode allows for config to specify up to 5 nearest detent positions (with smooth scrolling in between them); the intent is a higher-level controller (e.g. connected demo app, see below) to dynamically update that list as the position changes, in order to support an unlimited number of magnetic detents. --- React demo app implements a mock video editor timeline, with the ability to interact with it via the SmartKnob connected over USB serial. (Currently uses a node backend to stream config/state to the frontend via websockets, but it would probably be possible to do everything on the frontend with webserial in the future?). The 3 demo input modes are: - Scroll: quickly smooth-scroll through the timeline, with magnetic detents at clip boundaries. Scroll speed is determined by zoom level (currently only controllable by mouse scroll wheel) - Frames: small detents (1.5 degrees) to move frame-by-frame through video - Speed/playback: "spring-loaded" speed control, biased to return to center (paused), with detents at powers of 2: 1x, 2x, 4x playback Currently the frontend app has some bugs, particularly with the current playback position when switching modes and zooming, but planning to merge anyway to get the other breaking changes into master along with the initial demo framework.
This commit is contained in:
parent
340eed936d
commit
9431ed3971
@ -22,7 +22,7 @@ DisplayTask::~DisplayTask() {
|
||||
void DisplayTask::run() {
|
||||
tft_.begin();
|
||||
tft_.invertDisplay(1);
|
||||
tft_.setRotation(0);
|
||||
tft_.setRotation(SK_DISPLAY_ROTATION);
|
||||
tft_.fillScreen(TFT_DARKGREEN);
|
||||
|
||||
ledcSetup(LEDC_CHANNEL_LCD_BACKLIGHT, 5000, 16);
|
||||
@ -54,8 +54,10 @@ void DisplayTask::run() {
|
||||
}
|
||||
|
||||
spr_.fillSprite(TFT_BLACK);
|
||||
if (state.config.num_positions > 1) {
|
||||
int32_t height = state.current_position * TFT_HEIGHT / (state.config.num_positions - 1);
|
||||
|
||||
int32_t num_positions = state.config.max_position - state.config.min_position + 1;
|
||||
if (num_positions > 1) {
|
||||
int32_t height = (state.current_position - state.config.min_position) * TFT_HEIGHT / (state.config.max_position - state.config.min_position);
|
||||
spr_.fillRect(0, TFT_HEIGHT - height, TFT_WIDTH, height, FILL_COLOR);
|
||||
}
|
||||
|
||||
@ -80,8 +82,8 @@ void DisplayTask::run() {
|
||||
|
||||
float left_bound = PI / 2;
|
||||
|
||||
if (state.config.num_positions > 0) {
|
||||
float range_radians = (state.config.num_positions - 1) * state.config.position_width_radians;
|
||||
if (num_positions > 0) {
|
||||
float range_radians = (state.config.max_position - state.config.min_position) * state.config.position_width_radians;
|
||||
left_bound = PI / 2 + range_radians / 2;
|
||||
float right_bound = PI / 2 - range_radians / 2;
|
||||
spr_.drawLine(TFT_WIDTH/2 + RADIUS * cosf(left_bound), TFT_HEIGHT/2 - RADIUS * sinf(left_bound), TFT_WIDTH/2 + (RADIUS - 10) * cosf(left_bound), TFT_HEIGHT/2 - (RADIUS - 10) * sinf(left_bound), TFT_WHITE);
|
||||
@ -92,18 +94,18 @@ void DisplayTask::run() {
|
||||
}
|
||||
|
||||
float adjusted_sub_position = state.sub_position_unit * state.config.position_width_radians;
|
||||
if (state.config.num_positions > 0) {
|
||||
if (state.current_position == 0 && state.sub_position_unit < 0) {
|
||||
if (num_positions > 0) {
|
||||
if (state.current_position == state.config.min_position && state.sub_position_unit < 0) {
|
||||
adjusted_sub_position = -logf(1 - state.sub_position_unit * state.config.position_width_radians / 5 / PI * 180) * 5 * PI / 180;
|
||||
} else if (state.current_position == state.config.num_positions - 1 && state.sub_position_unit > 0) {
|
||||
} else if (state.current_position == state.config.max_position && state.sub_position_unit > 0) {
|
||||
adjusted_sub_position = logf(1 + state.sub_position_unit * state.config.position_width_radians / 5 / PI * 180) * 5 * PI / 180;
|
||||
}
|
||||
}
|
||||
|
||||
float raw_angle = left_bound - state.current_position * state.config.position_width_radians;
|
||||
float raw_angle = left_bound - (state.current_position - state.config.min_position) * state.config.position_width_radians;
|
||||
float adjusted_angle = raw_angle - adjusted_sub_position;
|
||||
|
||||
if (state.config.num_positions > 0 && ((state.current_position == 0 && state.sub_position_unit < 0) || (state.current_position == state.config.num_positions - 1 && state.sub_position_unit > 0))) {
|
||||
if (num_positions > 0 && ((state.current_position == state.config.min_position && state.sub_position_unit < 0) || (state.current_position == state.config.max_position && state.sub_position_unit > 0))) {
|
||||
|
||||
spr_.fillCircle(TFT_WIDTH/2 + (RADIUS - 10) * cosf(raw_angle), TFT_HEIGHT/2 - (RADIUS - 10) * sinf(raw_angle), 5, DOT_COLOR);
|
||||
if (raw_angle < adjusted_angle) {
|
||||
|
@ -13,8 +13,6 @@
|
||||
#include "interface_task.h"
|
||||
#include "util.h"
|
||||
|
||||
#define COUNT_OF(A) (sizeof(A) / sizeof(A[0]))
|
||||
|
||||
#if SK_LEDS
|
||||
CRGB leds[NUM_LEDS];
|
||||
#endif
|
||||
@ -28,94 +26,160 @@ Adafruit_VEML7700 veml = Adafruit_VEML7700();
|
||||
#endif
|
||||
|
||||
static PB_SmartKnobConfig configs[] = {
|
||||
// int32_t num_positions;
|
||||
// int32_t position;
|
||||
// int32_t min_position;
|
||||
// int32_t max_position;
|
||||
// float position_width_radians;
|
||||
// float detent_strength_unit;
|
||||
// float endstop_strength_unit;
|
||||
// float snap_point;
|
||||
// char text[51];
|
||||
// pb_size_t detent_positions_count;
|
||||
// int32_t detent_positions[5];
|
||||
// float snap_point_bias;
|
||||
|
||||
{
|
||||
0,
|
||||
0,
|
||||
-1, // max position < min position indicates no bounds
|
||||
10 * PI / 180,
|
||||
0,
|
||||
1,
|
||||
1.1,
|
||||
"Unbounded\nNo detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
11,
|
||||
0,
|
||||
0,
|
||||
10,
|
||||
10 * PI / 180,
|
||||
0,
|
||||
1,
|
||||
1.1,
|
||||
"Bounded 0-10\nNo detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
73,
|
||||
0,
|
||||
0,
|
||||
72,
|
||||
10 * PI / 180,
|
||||
0,
|
||||
1,
|
||||
1.1,
|
||||
"Multi-rev\nNo detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
60 * PI / 180,
|
||||
1,
|
||||
1,
|
||||
0.55, // Note the snap point is slightly past the midpoint (0.5); compare to normal detents which use a snap point *past* the next value (i.e. > 1)
|
||||
"On/off\nStrong detent",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
60 * PI / 180,
|
||||
0.01,
|
||||
0.6,
|
||||
1.1,
|
||||
"Return-to-center",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
256,
|
||||
127,
|
||||
0,
|
||||
255,
|
||||
1 * PI / 180,
|
||||
0,
|
||||
1,
|
||||
1.1,
|
||||
"Fine values\nNo detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
256,
|
||||
127,
|
||||
0,
|
||||
255,
|
||||
1 * PI / 180,
|
||||
1,
|
||||
1,
|
||||
1.1,
|
||||
"Fine values\nWith detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
32,
|
||||
0,
|
||||
0,
|
||||
31,
|
||||
8.225806452 * PI / 180,
|
||||
2,
|
||||
1,
|
||||
1.1,
|
||||
"Coarse values\nStrong detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
32,
|
||||
0,
|
||||
0,
|
||||
31,
|
||||
8.225806452 * PI / 180,
|
||||
0.2,
|
||||
1,
|
||||
1.1,
|
||||
"Coarse values\nWeak detents",
|
||||
0,
|
||||
{},
|
||||
0,
|
||||
},
|
||||
{
|
||||
0,
|
||||
0,
|
||||
31,
|
||||
7 * PI / 180,
|
||||
2.5,
|
||||
1,
|
||||
0.7,
|
||||
"Magnetic detents",
|
||||
4,
|
||||
{2, 10, 21, 22},
|
||||
0,
|
||||
},
|
||||
{
|
||||
0,
|
||||
-6,
|
||||
6,
|
||||
60 * PI / 180,
|
||||
1,
|
||||
1,
|
||||
0.55,
|
||||
"Return-to-center\nwith detents",
|
||||
0,
|
||||
{},
|
||||
0.4
|
||||
},
|
||||
};
|
||||
|
||||
@ -271,13 +335,22 @@ void InterfaceTask::updateHardware() {
|
||||
press_value_unit = 1. * (value - lower) / (upper - lower);
|
||||
|
||||
static bool pressed;
|
||||
static uint8_t press_count;
|
||||
if (!pressed && press_value_unit > 0.75) {
|
||||
motor_task_.playHaptic(true);
|
||||
pressed = true;
|
||||
changeConfig(true);
|
||||
press_count++;
|
||||
if (press_count > 2) {
|
||||
motor_task_.playHaptic(true);
|
||||
pressed = true;
|
||||
changeConfig(true);
|
||||
}
|
||||
} else if (pressed && press_value_unit < 0.25) {
|
||||
motor_task_.playHaptic(false);
|
||||
pressed = false;
|
||||
press_count++;
|
||||
if (press_count > 2) {
|
||||
motor_task_.playHaptic(false);
|
||||
pressed = false;
|
||||
}
|
||||
} else {
|
||||
press_count = 0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
@ -13,7 +13,7 @@
|
||||
// ####
|
||||
// Hardware-specific motor calibration constants.
|
||||
// Run calibration once at startup, then update these constants with the calibration results.
|
||||
static const float ZERO_ELECTRICAL_OFFSET = 2.77;
|
||||
static const float ZERO_ELECTRICAL_OFFSET = 7.61;
|
||||
static const Direction FOC_DIRECTION = Direction::CW;
|
||||
static const int MOTOR_POLE_PAIRS = 7;
|
||||
// ####
|
||||
@ -85,8 +85,9 @@ void MotorTask::run() {
|
||||
|
||||
float current_detent_center = motor.shaft_angle;
|
||||
PB_SmartKnobConfig config = {
|
||||
.num_positions = 2,
|
||||
.position = 0,
|
||||
.min_position = 0,
|
||||
.max_position = 1,
|
||||
.position_width_radians = 60 * _PI / 180,
|
||||
.detent_strength_unit = 0,
|
||||
};
|
||||
@ -95,8 +96,6 @@ void MotorTask::run() {
|
||||
uint32_t last_idle_start = 0;
|
||||
uint32_t last_publish = 0;
|
||||
|
||||
PB_SmartKnobConfig latest_config = config;
|
||||
|
||||
while (1) {
|
||||
motor.loopFOC();
|
||||
|
||||
@ -108,14 +107,46 @@ void MotorTask::run() {
|
||||
calibrate();
|
||||
break;
|
||||
case CommandType::CONFIG: {
|
||||
// Check new config for validity
|
||||
if (command.data.config.detent_strength_unit < 0) {
|
||||
log("Ignoring invalid config: detent_strength_unit cannot be negative");
|
||||
break;
|
||||
}
|
||||
if (command.data.config.endstop_strength_unit < 0) {
|
||||
log("Ignoring invalid config: endstop_strength_unit cannot be negative");
|
||||
break;
|
||||
}
|
||||
if (command.data.config.snap_point < 0.5) {
|
||||
log("Ignoring invalid config: snap_point must be >= 0.5 for stability");
|
||||
break;
|
||||
}
|
||||
if (command.data.config.detent_positions_count > COUNT_OF(command.data.config.detent_positions)) {
|
||||
log("Ignoring invalid config: detent_positions_count is too large");
|
||||
break;
|
||||
}
|
||||
if (command.data.config.snap_point_bias < 0) {
|
||||
log("Ignoring invalid config: snap_point_bias cannot be negative or there is risk of instability");
|
||||
break;
|
||||
}
|
||||
|
||||
// Change haptic input mode
|
||||
config = command.data.config;
|
||||
latest_config = config;
|
||||
PB_SmartKnobConfig newConfig = command.data.config;
|
||||
if (newConfig.position == INT32_MIN) {
|
||||
// INT32_MIN indicates no change to position, so restore from latest_config
|
||||
log("maintaining position");
|
||||
newConfig.position = config.position;
|
||||
}
|
||||
if (newConfig.position != config.position
|
||||
|| newConfig.position_width_radians != config.position_width_radians) {
|
||||
// Only adjust the detent center if the position or width has changed
|
||||
log("adjusting detent center");
|
||||
current_detent_center = motor.shaft_angle;
|
||||
#if SK_INVERT_ROTATION
|
||||
current_detent_center = -motor.shaft_angle;
|
||||
#endif
|
||||
}
|
||||
config = newConfig;
|
||||
log("Got new config");
|
||||
current_detent_center = motor.shaft_angle;
|
||||
#if SK_INVERT_ROTATION
|
||||
current_detent_center = -motor.shaft_angle;
|
||||
#endif
|
||||
|
||||
// Update derivative factor of torque controller based on detent width.
|
||||
// If the D factor is large on coarse detents, the motor ends up making noise because the P&D factors amplify the noise from the sensor.
|
||||
@ -130,7 +161,9 @@ void MotorTask::run() {
|
||||
const float derivative_position_width_lower = radians(3);
|
||||
const float derivative_position_width_upper = radians(8);
|
||||
const float raw = derivative_lower_strength + (derivative_upper_strength - derivative_lower_strength)/(derivative_position_width_upper - derivative_position_width_lower)*(config.position_width_radians - derivative_position_width_lower);
|
||||
motor.PID_velocity.D = CLAMP(
|
||||
// When there are intermittent detents (set via detent_positions), disable derivative factor as this adds extra "clicks" when nearing
|
||||
// a detent.
|
||||
motor.PID_velocity.D = config.detent_positions_count > 0 ? 0 : CLAMP(
|
||||
raw,
|
||||
min(derivative_lower_strength, derivative_upper_strength),
|
||||
max(derivative_lower_strength, derivative_upper_strength)
|
||||
@ -175,11 +208,18 @@ void MotorTask::run() {
|
||||
#if SK_INVERT_ROTATION
|
||||
angle_to_detent_center = -motor.shaft_angle - current_detent_center;
|
||||
#endif
|
||||
if (angle_to_detent_center > config.position_width_radians * config.snap_point && (config.num_positions <= 0 || config.position > 0)) {
|
||||
|
||||
float snap_point_radians = config.position_width_radians * config.snap_point;
|
||||
float bias_radians = config.position_width_radians * config.snap_point_bias;
|
||||
float snap_point_radians_decrease = snap_point_radians + (config.position <= 0 ? bias_radians : -bias_radians);
|
||||
float snap_point_radians_increase = -snap_point_radians + (config.position >= 0 ? -bias_radians : bias_radians);
|
||||
|
||||
int32_t num_positions = config.max_position - config.min_position + 1;
|
||||
if (angle_to_detent_center > snap_point_radians_decrease && (num_positions <= 0 || config.position > config.min_position)) {
|
||||
current_detent_center += config.position_width_radians;
|
||||
angle_to_detent_center -= config.position_width_radians;
|
||||
config.position--;
|
||||
} else if (angle_to_detent_center < -config.position_width_radians * config.snap_point && (config.num_positions <= 0 || config.position < config.num_positions - 1)) {
|
||||
} else if (angle_to_detent_center < snap_point_radians_increase && (num_positions <= 0 || config.position < config.max_position)) {
|
||||
current_detent_center -= config.position_width_radians;
|
||||
angle_to_detent_center += config.position_width_radians;
|
||||
config.position++;
|
||||
@ -190,7 +230,7 @@ void MotorTask::run() {
|
||||
fmaxf(-config.position_width_radians*DEAD_ZONE_DETENT_PERCENT, -DEAD_ZONE_RAD),
|
||||
fminf(config.position_width_radians*DEAD_ZONE_DETENT_PERCENT, DEAD_ZONE_RAD));
|
||||
|
||||
bool out_of_bounds = config.num_positions > 0 && ((angle_to_detent_center > 0 && config.position == 0) || (angle_to_detent_center < 0 && config.position == config.num_positions - 1));
|
||||
bool out_of_bounds = num_positions > 0 && ((angle_to_detent_center > 0 && config.position == config.min_position) || (angle_to_detent_center < 0 && config.position == config.max_position));
|
||||
motor.PID_velocity.limit = 10; //out_of_bounds ? 10 : 3;
|
||||
motor.PID_velocity.P = out_of_bounds ? config.endstop_strength_unit * 4 : config.detent_strength_unit * 4;
|
||||
|
||||
@ -200,7 +240,20 @@ void MotorTask::run() {
|
||||
// Don't apply torque if velocity is too high (helps avoid positive feedback loop/runaway)
|
||||
motor.move(0);
|
||||
} else {
|
||||
float torque = motor.PID_velocity(-angle_to_detent_center + dead_zone_adjustment);
|
||||
float input = -angle_to_detent_center + dead_zone_adjustment;
|
||||
if (!out_of_bounds && config.detent_positions_count > 0) {
|
||||
bool in_detent = false;
|
||||
for (uint8_t i = 0; i < config.detent_positions_count; i++) {
|
||||
if (config.detent_positions[i] == config.position) {
|
||||
in_detent = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!in_detent) {
|
||||
input = 0;
|
||||
}
|
||||
}
|
||||
float torque = motor.PID_velocity(input);
|
||||
#if SK_INVERT_ROTATION
|
||||
torque = -torque;
|
||||
#endif
|
||||
|
@ -23,13 +23,17 @@ typedef struct _PB_Log {
|
||||
} PB_Log;
|
||||
|
||||
typedef struct _PB_SmartKnobConfig {
|
||||
int32_t num_positions;
|
||||
int32_t position;
|
||||
int32_t min_position;
|
||||
int32_t max_position;
|
||||
float position_width_radians;
|
||||
float detent_strength_unit;
|
||||
float endstop_strength_unit;
|
||||
float snap_point;
|
||||
char text[51];
|
||||
pb_size_t detent_positions_count;
|
||||
int32_t detent_positions[5];
|
||||
float snap_point_bias;
|
||||
} PB_SmartKnobConfig;
|
||||
|
||||
typedef struct _PB_SmartKnobState {
|
||||
@ -70,26 +74,29 @@ extern "C" {
|
||||
#define PB_Log_init_default {""}
|
||||
#define PB_SmartKnobState_init_default {0, 0, false, PB_SmartKnobConfig_init_default}
|
||||
#define PB_ToSmartknob_init_default {0, 0, {PB_RequestState_init_default}}
|
||||
#define PB_SmartKnobConfig_init_default {0, 0, 0, 0, 0, 0, ""}
|
||||
#define PB_SmartKnobConfig_init_default {0, 0, 0, 0, 0, 0, 0, "", 0, {0, 0, 0, 0, 0}, 0}
|
||||
#define PB_RequestState_init_default {0}
|
||||
#define PB_FromSmartKnob_init_zero {0, {PB_Ack_init_zero}}
|
||||
#define PB_Ack_init_zero {0}
|
||||
#define PB_Log_init_zero {""}
|
||||
#define PB_SmartKnobState_init_zero {0, 0, false, PB_SmartKnobConfig_init_zero}
|
||||
#define PB_ToSmartknob_init_zero {0, 0, {PB_RequestState_init_zero}}
|
||||
#define PB_SmartKnobConfig_init_zero {0, 0, 0, 0, 0, 0, ""}
|
||||
#define PB_SmartKnobConfig_init_zero {0, 0, 0, 0, 0, 0, 0, "", 0, {0, 0, 0, 0, 0}, 0}
|
||||
#define PB_RequestState_init_zero {0}
|
||||
|
||||
/* Field tags (for use in manual encoding/decoding) */
|
||||
#define PB_Ack_nonce_tag 1
|
||||
#define PB_Log_msg_tag 1
|
||||
#define PB_SmartKnobConfig_num_positions_tag 1
|
||||
#define PB_SmartKnobConfig_position_tag 2
|
||||
#define PB_SmartKnobConfig_position_width_radians_tag 3
|
||||
#define PB_SmartKnobConfig_detent_strength_unit_tag 4
|
||||
#define PB_SmartKnobConfig_endstop_strength_unit_tag 5
|
||||
#define PB_SmartKnobConfig_snap_point_tag 6
|
||||
#define PB_SmartKnobConfig_text_tag 7
|
||||
#define PB_SmartKnobConfig_position_tag 1
|
||||
#define PB_SmartKnobConfig_min_position_tag 2
|
||||
#define PB_SmartKnobConfig_max_position_tag 3
|
||||
#define PB_SmartKnobConfig_position_width_radians_tag 4
|
||||
#define PB_SmartKnobConfig_detent_strength_unit_tag 5
|
||||
#define PB_SmartKnobConfig_endstop_strength_unit_tag 6
|
||||
#define PB_SmartKnobConfig_snap_point_tag 7
|
||||
#define PB_SmartKnobConfig_text_tag 8
|
||||
#define PB_SmartKnobConfig_detent_positions_tag 9
|
||||
#define PB_SmartKnobConfig_snap_point_bias_tag 10
|
||||
#define PB_SmartKnobState_current_position_tag 1
|
||||
#define PB_SmartKnobState_sub_position_unit_tag 2
|
||||
#define PB_SmartKnobState_config_tag 3
|
||||
@ -139,13 +146,16 @@ X(a, STATIC, ONEOF, MESSAGE, (payload,smartknob_config,payload.smartknob_c
|
||||
#define PB_ToSmartknob_payload_smartknob_config_MSGTYPE PB_SmartKnobConfig
|
||||
|
||||
#define PB_SmartKnobConfig_FIELDLIST(X, a) \
|
||||
X(a, STATIC, SINGULAR, INT32, num_positions, 1) \
|
||||
X(a, STATIC, SINGULAR, INT32, position, 2) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, position_width_radians, 3) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, detent_strength_unit, 4) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, endstop_strength_unit, 5) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, snap_point, 6) \
|
||||
X(a, STATIC, SINGULAR, STRING, text, 7)
|
||||
X(a, STATIC, SINGULAR, INT32, position, 1) \
|
||||
X(a, STATIC, SINGULAR, INT32, min_position, 2) \
|
||||
X(a, STATIC, SINGULAR, INT32, max_position, 3) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, position_width_radians, 4) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, detent_strength_unit, 5) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, endstop_strength_unit, 6) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, snap_point, 7) \
|
||||
X(a, STATIC, SINGULAR, STRING, text, 8) \
|
||||
X(a, STATIC, REPEATED, INT32, detent_positions, 9) \
|
||||
X(a, STATIC, SINGULAR, FLOAT, snap_point_bias, 10)
|
||||
#define PB_SmartKnobConfig_CALLBACK NULL
|
||||
#define PB_SmartKnobConfig_DEFAULT NULL
|
||||
|
||||
@ -176,9 +186,9 @@ extern const pb_msgdesc_t PB_RequestState_msg;
|
||||
#define PB_FromSmartKnob_size 261
|
||||
#define PB_Log_size 258
|
||||
#define PB_RequestState_size 0
|
||||
#define PB_SmartKnobConfig_size 94
|
||||
#define PB_SmartKnobState_size 112
|
||||
#define PB_ToSmartknob_size 102
|
||||
#define PB_SmartKnobConfig_size 165
|
||||
#define PB_SmartKnobState_size 184
|
||||
#define PB_ToSmartknob_size 174
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
|
@ -5,11 +5,15 @@
|
||||
bool config_eq(PB_SmartKnobConfig& first, PB_SmartKnobConfig& second) {
|
||||
return first.detent_strength_unit == second.detent_strength_unit
|
||||
&& first.endstop_strength_unit == second.endstop_strength_unit
|
||||
&& first.num_positions == second.num_positions
|
||||
&& first.position == second.position
|
||||
&& first.min_position == second.min_position
|
||||
&& first.max_position == second.max_position
|
||||
&& first.position_width_radians == second.position_width_radians
|
||||
&& first.snap_point == second.snap_point
|
||||
&& strcmp(first.text, second.text) == 0;
|
||||
&& strcmp(first.text, second.text) == 0
|
||||
&& first.detent_positions_count == second.detent_positions_count
|
||||
&& memcmp(first.detent_positions, second.detent_positions, first.detent_positions_count * sizeof(first.detent_positions[0]))
|
||||
&& first.snap_point_bias == second.snap_point_bias;
|
||||
}
|
||||
|
||||
bool state_eq(PB_SmartKnobState& first, PB_SmartKnobState& second) {
|
||||
|
@ -6,11 +6,18 @@ void SerialProtocolPlaintext::handleState(const PB_SmartKnobState& state) {
|
||||
bool substantial_change = (latest_state_.current_position != state.current_position)
|
||||
|| (latest_state_.config.detent_strength_unit != state.config.detent_strength_unit)
|
||||
|| (latest_state_.config.endstop_strength_unit != state.config.endstop_strength_unit)
|
||||
|| (latest_state_.config.num_positions != state.config.num_positions);
|
||||
|| (latest_state_.config.min_position != state.config.min_position)
|
||||
|| (latest_state_.config.max_position != state.config.max_position);
|
||||
latest_state_ = state;
|
||||
|
||||
if (substantial_change) {
|
||||
stream_.printf("STATE: %d/%d (detent strength: %0.2f, width: %0.0f deg, endstop strength: %0.2f)\n", state.current_position, state.config.num_positions - 1, state.config.detent_strength_unit, degrees(state.config.position_width_radians), state.config.endstop_strength_unit);
|
||||
stream_.printf("STATE: %d [%d, %d] (detent strength: %0.2f, width: %0.0f deg, endstop strength: %0.2f)\n",
|
||||
state.current_position,
|
||||
state.config.min_position,
|
||||
state.config.max_position,
|
||||
state.config.detent_strength_unit,
|
||||
degrees(state.config.position_width_radians),
|
||||
state.config.endstop_strength_unit);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,3 +5,5 @@ template <typename T> T CLAMP(const T& value, const T& low, const T& high)
|
||||
{
|
||||
return value < low ? low : (value > high ? high : value);
|
||||
}
|
||||
|
||||
#define COUNT_OF(A) (sizeof(A) / sizeof(A[0]))
|
||||
|
@ -50,14 +50,23 @@ lib_deps =
|
||||
|
||||
build_flags =
|
||||
${base_config.build_flags}
|
||||
; Display enabled: 1=enable, 0=disable
|
||||
-DSK_DISPLAY=1
|
||||
; Display orientation: 0=usb bottom, 2=usb top
|
||||
-DSK_DISPLAY_ROTATION=0
|
||||
; LEDs enabled: 1=enable, 0=disable
|
||||
-DSK_LEDS=1
|
||||
; Number of LEDs
|
||||
-DNUM_LEDS=8
|
||||
-DSENSOR_MT6701=1
|
||||
; Strain-gauge press input enabled: 1=enable, 0=disable
|
||||
-DSK_STRAIN=1
|
||||
; Invert direction of angle sensor (motor direction is detected relative to angle sensor as part of the calibration procedure)
|
||||
-DSK_INVERT_ROTATION=1
|
||||
; Ambient light sensor (VEML7700) enabled: 1=enable (display/LEDs match ambient brightness), 0=disable (100% brightness all the time)
|
||||
-DSK_ALS=1
|
||||
|
||||
; Pin configurations
|
||||
-DPIN_UH=26
|
||||
-DPIN_UL=25
|
||||
-DPIN_VH=27
|
||||
@ -79,6 +88,7 @@ build_flags =
|
||||
-DVALUE_OFFSET=30
|
||||
-DDRAW_ARC=0
|
||||
|
||||
; TFT_eSPI setup
|
||||
-DUSER_SETUP_LOADED=1
|
||||
-DGC9A01_DRIVER=1
|
||||
-DCGRAM_OFFSET=1
|
||||
@ -98,11 +108,11 @@ build_flags =
|
||||
; Reduce loop task stack size (only works on newer IDF Arduino core)
|
||||
; -DARDUINO_LOOP_STACK_SIZE=2048
|
||||
|
||||
; FastLED setup
|
||||
; Modify the default unusable pin mask to allow GPIO 7 (allowed to use on ESP32-PICO-V3-02)
|
||||
; Unusable bits: 6, 8, 9, 10, 20
|
||||
; (0ULL | _FL_BIT(6) | _FL_BIT(8) | _FL_BIT(9) | _FL_BIT(10) | _FL_BIT(20))
|
||||
-DFASTLED_UNUSABLE_PIN_MASK=0x100740LL
|
||||
|
||||
; 0~39 except from 24, 28~31 are valid
|
||||
; (0xFFFFFFFFFFULL & ~(0ULL | _FL_BIT(24) | _FL_BIT(28) | _FL_BIT(29) | _FL_BIT(30) | _FL_BIT(31)))
|
||||
-DSOC_GPIO_VALID_GPIO_MASK=0xFF0EFFFFFF
|
||||
|
@ -42,13 +42,16 @@ message ToSmartknob {
|
||||
}
|
||||
|
||||
message SmartKnobConfig {
|
||||
int32 num_positions = 1;
|
||||
int32 position = 2;
|
||||
float position_width_radians = 3;
|
||||
float detent_strength_unit = 4;
|
||||
float endstop_strength_unit = 5;
|
||||
float snap_point = 6;
|
||||
string text = 7 [(nanopb).max_length = 50];
|
||||
int32 position = 1;
|
||||
int32 min_position = 2;
|
||||
int32 max_position = 3;
|
||||
float position_width_radians = 4;
|
||||
float detent_strength_unit = 5;
|
||||
float endstop_strength_unit = 6;
|
||||
float snap_point = 7;
|
||||
string text = 8 [(nanopb).max_length = 50];
|
||||
repeated int32 detent_positions = 9 [(nanopb).max_count = 5];
|
||||
float snap_point_bias = 10;
|
||||
}
|
||||
|
||||
message RequestState {}
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Typescript SmartKnob protobuf interface library
|
||||
# Typescript SmartKnob protobuf interface library and examples
|
||||
|
||||
### Requirements (nvm is recommended)
|
||||
|
||||
@ -14,6 +14,7 @@ npm run build
|
||||
|
||||
### Example
|
||||
|
||||
A basic Node.js CLI example.
|
||||
Connect the SmartKnob via USB, then run the example:
|
||||
|
||||
```
|
||||
|
33340
software/js/package-lock.json
generated
33340
software/js/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -9,16 +9,20 @@
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build --workspaces --if-present",
|
||||
"example": "npm run -w example main"
|
||||
"demo": "concurrently \"npm -w demo-frontend start\" \"npm -w demo-backend start\"",
|
||||
"example": "npm -w example run main"
|
||||
},
|
||||
"author": "",
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
"packages/smartknobjs-proto",
|
||||
"packages/smartknobjs",
|
||||
"packages/demo-backend",
|
||||
"packages/demo-frontend",
|
||||
"packages/example"
|
||||
],
|
||||
"devDependencies": {
|
||||
"concurrently": "^7.6.0",
|
||||
"eslint-config-prettier": "^8.5.0"
|
||||
}
|
||||
}
|
||||
|
19
software/js/packages/demo-backend/.eslintrc
Normal file
19
software/js/packages/demo-backend/.eslintrc
Normal file
@ -0,0 +1,19 @@
|
||||
// .eslintrc
|
||||
{
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 12,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
|
||||
|
||||
"rules": {
|
||||
"@typescript-eslint/no-unused-vars": "error",
|
||||
"@typescript-eslint/consistent-type-definitions": ["error", "type"]
|
||||
},
|
||||
|
||||
"env": {
|
||||
"node": true
|
||||
}
|
||||
}
|
10
software/js/packages/demo-backend/.prettierrc
Normal file
10
software/js/packages/demo-backend/.prettierrc
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"tabWidth": 4,
|
||||
"useTabs": false,
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"bracketSpacing": false,
|
||||
"arrowParens": "always"
|
||||
}
|
32
software/js/packages/demo-backend/package.json
Normal file
32
software/js/packages/demo-backend/package.json
Normal file
@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "demo-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"format": "prettier --write \"**/*.+(js|ts|json)\"",
|
||||
"lint": "eslint --ext .js,.ts .",
|
||||
"start": "PORT=3001 ts-node src/index.ts"
|
||||
},
|
||||
"author": "",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"serialport": "^9.2.4",
|
||||
"smartknobjs": "^0.1.0",
|
||||
"socket.io": "^4.5.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.14",
|
||||
"@types/node": "^18.11.10",
|
||||
"@types/serialport": "^8.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^5.40.1",
|
||||
"@typescript-eslint/parser": "^5.40.1",
|
||||
"eslint": "^8.25.0",
|
||||
"nodemon": "^2.0.20",
|
||||
"prettier": "^2.4.1",
|
||||
"ts-node": "^10.2.1",
|
||||
"typescript": "^4.9.3"
|
||||
}
|
||||
}
|
75
software/js/packages/demo-backend/src/index.ts
Normal file
75
software/js/packages/demo-backend/src/index.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import SerialPort = require('serialport')
|
||||
import {SmartKnob} from 'smartknobjs'
|
||||
import {PB} from 'smartknobjs-proto'
|
||||
|
||||
import {Server, Socket} from 'socket.io'
|
||||
|
||||
const io = new Server(parseInt(process.env.PORT ?? '3001'))
|
||||
|
||||
const start = async () => {
|
||||
const ports = await SerialPort.list()
|
||||
|
||||
const matchingPorts = ports.filter((portInfo) => {
|
||||
// Implement a check for your device's vendor+product+serial
|
||||
// (this is more robust than the alternative of just hardcoding a "path" like "/dev/ttyUSB0")
|
||||
return (
|
||||
portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() &&
|
||||
portInfo.productId?.toLowerCase() === '7523'.toLowerCase()
|
||||
// && portInfo.serialNumber === 'DEADBEEF'
|
||||
)
|
||||
})
|
||||
|
||||
if (matchingPorts.length < 1) {
|
||||
console.error(`No smartknob usb serial port found! ${JSON.stringify(ports, undefined, 4)}`)
|
||||
return
|
||||
} else if (matchingPorts.length > 1) {
|
||||
console.error(`Multiple smartknob usb serial ports found: ${JSON.stringify(matchingPorts, undefined, 4)}`)
|
||||
return
|
||||
}
|
||||
|
||||
const portInfo = matchingPorts[0]
|
||||
console.info('Connecting to ', portInfo)
|
||||
|
||||
let lastLoggedState: PB.ISmartKnobState | undefined
|
||||
const smartknob = new SmartKnob(portInfo.path, (message: PB.FromSmartKnob) => {
|
||||
if (message.payload === 'log' && message.log) {
|
||||
console.log('LOG', message.log.msg)
|
||||
} else if (message.payload === 'smartknobState' && message.smartknobState) {
|
||||
const state = PB.SmartKnobState.toObject(message.smartknobState as PB.SmartKnobState, {defaults: true})
|
||||
io.emit('state', {pb: message.smartknobState})
|
||||
if (
|
||||
message.smartknobState.currentPosition !== lastLoggedState?.currentPosition ||
|
||||
Math.abs((message.smartknobState.subPositionUnit ?? 0) - (lastLoggedState?.subPositionUnit ?? 0)) > 1
|
||||
) {
|
||||
console.log(`State:\n${JSON.stringify(state, undefined, 4)}`)
|
||||
lastLoggedState = message.smartknobState
|
||||
}
|
||||
}
|
||||
})
|
||||
smartknob.sendConfig(
|
||||
PB.SmartKnobConfig.create({
|
||||
detentStrengthUnit: 1,
|
||||
endstopStrengthUnit: 1,
|
||||
position: 0,
|
||||
minPosition: -5,
|
||||
maxPosition: 5,
|
||||
positionWidthRadians: (10 * Math.PI) / 180,
|
||||
snapPoint: 1.1,
|
||||
text: 'From TS!',
|
||||
}),
|
||||
)
|
||||
|
||||
let currentSocket: Socket | null = null
|
||||
io.on('connection', (socket) => {
|
||||
if (currentSocket !== null) {
|
||||
currentSocket.disconnect(true)
|
||||
}
|
||||
currentSocket = socket
|
||||
socket.on('set_config', (config) => {
|
||||
console.log(config)
|
||||
smartknob.sendConfig(config)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
start()
|
105
software/js/packages/demo-backend/tsconfig.json
Normal file
105
software/js/packages/demo-backend/tsconfig.json
Normal file
@ -0,0 +1,105 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
|
||||
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "paths" :{
|
||||
// "*": ["./src/typings/*", "./*"]
|
||||
// },
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": ["src/typings"], /* Specify multiple folders that act like `./node_modules/@types`. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files */
|
||||
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
|
||||
|
||||
/* Emit */
|
||||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
|
||||
"noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
|
||||
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
|
||||
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
|
||||
// "noUnussedParameters": true, /* Raise an error when a function parameter isn't read */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
||||
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
19
software/js/packages/demo-frontend/.eslintrc
Normal file
19
software/js/packages/demo-frontend/.eslintrc
Normal file
@ -0,0 +1,19 @@
|
||||
// .eslintrc
|
||||
{
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 12,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
|
||||
|
||||
"rules": {
|
||||
"@typescript-eslint/no-unused-vars": "error",
|
||||
"@typescript-eslint/consistent-type-definitions": ["error", "type"]
|
||||
},
|
||||
|
||||
"env": {
|
||||
"node": true
|
||||
}
|
||||
}
|
23
software/js/packages/demo-frontend/.gitignore
vendored
Normal file
23
software/js/packages/demo-frontend/.gitignore
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
10
software/js/packages/demo-frontend/.prettierrc
Normal file
10
software/js/packages/demo-frontend/.prettierrc
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"tabWidth": 4,
|
||||
"useTabs": false,
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"bracketSpacing": false,
|
||||
"arrowParens": "always"
|
||||
}
|
46
software/js/packages/demo-frontend/README.md
Normal file
46
software/js/packages/demo-frontend/README.md
Normal file
@ -0,0 +1,46 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
54
software/js/packages/demo-frontend/package.json
Normal file
54
software/js/packages/demo-frontend/package.json
Normal file
@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "demo-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.10.5",
|
||||
"@emotion/styled": "^11.10.5",
|
||||
"@fontsource/roboto": "^4.5.8",
|
||||
"@mui/material": "^5.10.16",
|
||||
"@testing-library/jest-dom": "^5.16.5",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.18.4",
|
||||
"@types/react": "^18.0.25",
|
||||
"@types/react-dom": "^18.0.9",
|
||||
"lodash": "^4.17.21",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-scripts": "^5.0.1",
|
||||
"smartknobjs-proto": "^0.1.1",
|
||||
"socket.io-client": "^4.5.4",
|
||||
"typescript": "^4.9.3",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "PORT=3000 react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"proxy": "http://localhost:3001",
|
||||
"devDependencies": {
|
||||
"@types/lodash": "^4.14.191"
|
||||
}
|
||||
}
|
BIN
software/js/packages/demo-frontend/public/favicon.ico
Normal file
BIN
software/js/packages/demo-frontend/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.8 KiB |
43
software/js/packages/demo-frontend/public/index.html
Normal file
43
software/js/packages/demo-frontend/public/index.html
Normal file
@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
25
software/js/packages/demo-frontend/public/manifest.json
Normal file
25
software/js/packages/demo-frontend/public/manifest.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
3
software/js/packages/demo-frontend/public/robots.txt
Normal file
3
software/js/packages/demo-frontend/public/robots.txt
Normal file
@ -0,0 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
407
software/js/packages/demo-frontend/src/App.tsx
Normal file
407
software/js/packages/demo-frontend/src/App.tsx
Normal file
@ -0,0 +1,407 @@
|
||||
import React, {useEffect, useMemo, useRef, useState} from 'react'
|
||||
import io from 'socket.io-client'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Container from '@mui/material/Container'
|
||||
import ToggleButton from '@mui/material/ToggleButton'
|
||||
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'
|
||||
import {PB} from 'smartknobjs-proto'
|
||||
import {VideoInfo} from './types'
|
||||
import {Card, CardContent} from '@mui/material'
|
||||
import {exhaustiveCheck, findNClosest, INT32_MIN, lerp, NoUndefinedField} from './util'
|
||||
import {groupBy, parseInt} from 'lodash'
|
||||
|
||||
const socket = io()
|
||||
|
||||
const MIN_ZOOM = 0.01
|
||||
const MAX_ZOOM = 60
|
||||
|
||||
const PIXELS_PER_POSITION = 10
|
||||
|
||||
enum Mode {
|
||||
Scroll = 'Scroll',
|
||||
Frames = 'Frames',
|
||||
Speed = 'Speed',
|
||||
}
|
||||
|
||||
type State = {
|
||||
mode: Mode
|
||||
playbackSpeed: number
|
||||
currentFrame: number
|
||||
zoomTimelinePixelsPerFrame: number
|
||||
}
|
||||
|
||||
export type AppProps = {
|
||||
info: VideoInfo
|
||||
}
|
||||
export const App: React.FC<AppProps> = ({info}) => {
|
||||
const [isConnected, setIsConnected] = useState(socket.connected)
|
||||
const [state, setState] = useState<NoUndefinedField<PB.ISmartKnobState>>(
|
||||
PB.SmartKnobState.toObject(PB.SmartKnobState.create({config: PB.SmartKnobConfig.create()}), {
|
||||
defaults: true,
|
||||
}) as NoUndefinedField<PB.ISmartKnobState>,
|
||||
)
|
||||
const [derivedState, setDerivedState] = useState<State>({
|
||||
mode: Mode.Scroll,
|
||||
playbackSpeed: 0,
|
||||
currentFrame: 0,
|
||||
zoomTimelinePixelsPerFrame: 0.1,
|
||||
})
|
||||
|
||||
useMemo(() => {
|
||||
setDerivedState((cur) => {
|
||||
const modeText = state.config.text
|
||||
if (modeText === Mode.Scroll) {
|
||||
const rawFrame = Math.trunc(
|
||||
((state.currentPosition + state.subPositionUnit) * PIXELS_PER_POSITION) /
|
||||
cur.zoomTimelinePixelsPerFrame,
|
||||
)
|
||||
return {
|
||||
mode: Mode.Scroll,
|
||||
playbackSpeed: 0,
|
||||
currentFrame: Math.min(Math.max(rawFrame, 0), info.totalFrames - 1),
|
||||
zoomTimelinePixelsPerFrame: cur.zoomTimelinePixelsPerFrame,
|
||||
}
|
||||
} else if (modeText === Mode.Frames) {
|
||||
return {
|
||||
mode: Mode.Frames,
|
||||
playbackSpeed: 0,
|
||||
currentFrame: state.currentPosition ?? 0,
|
||||
zoomTimelinePixelsPerFrame: cur.zoomTimelinePixelsPerFrame,
|
||||
}
|
||||
} else if (modeText === Mode.Speed) {
|
||||
const normalizedWholeValue = state.currentPosition
|
||||
const normalizedFractional =
|
||||
Math.sign(state.subPositionUnit) *
|
||||
lerp(state.subPositionUnit * Math.sign(state.subPositionUnit), 0.1, 0.9, 0, 1)
|
||||
const normalized = normalizedWholeValue + normalizedFractional
|
||||
const speed = Math.sign(normalized) * Math.pow(2, Math.abs(normalized) - 1)
|
||||
return {
|
||||
mode: Mode.Speed,
|
||||
playbackSpeed: speed,
|
||||
currentFrame: cur.currentFrame,
|
||||
zoomTimelinePixelsPerFrame: cur.zoomTimelinePixelsPerFrame,
|
||||
}
|
||||
}
|
||||
return cur
|
||||
})
|
||||
}, [state.config.text, state.currentPosition, state.subPositionUnit])
|
||||
|
||||
const totalPositions = Math.ceil((info.totalFrames * derivedState.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION)
|
||||
const detentPositions = useMemo(() => {
|
||||
// Always include the first and last positions at detents
|
||||
const positionsToFrames = groupBy([0, ...info.boundaryFrames, info.totalFrames - 1], (frame) =>
|
||||
Math.round((frame * derivedState.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION),
|
||||
)
|
||||
console.log(JSON.stringify(positionsToFrames))
|
||||
return positionsToFrames
|
||||
}, [info.boundaryFrames, totalPositions, derivedState.zoomTimelinePixelsPerFrame])
|
||||
|
||||
// Continuous config updates for scrolling, to update detent positions
|
||||
useMemo(() => {
|
||||
if (derivedState.mode === Mode.Scroll) {
|
||||
const config = PB.SmartKnobConfig.create({
|
||||
position: INT32_MIN,
|
||||
minPosition: 0,
|
||||
maxPosition: totalPositions - 1,
|
||||
positionWidthRadians: (8 * Math.PI) / 180,
|
||||
detentStrengthUnit: 2.5,
|
||||
endstopStrengthUnit: 1,
|
||||
snapPoint: 0.7,
|
||||
text: Mode.Scroll,
|
||||
detentPositions: findNClosest(Object.keys(detentPositions).map(parseInt), state.currentPosition, 5),
|
||||
snapPointBias: 0,
|
||||
})
|
||||
socket.emit('set_config', config)
|
||||
}
|
||||
}, [derivedState.mode, derivedState.zoomTimelinePixelsPerFrame, detentPositions, state.currentPosition])
|
||||
|
||||
// For one-off config pushes, e.g. mode changes
|
||||
const pushConfig = (state: State) => {
|
||||
let config: PB.SmartKnobConfig
|
||||
if (state.mode === Mode.Scroll) {
|
||||
const position = Math.trunc((state.currentFrame * state.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION)
|
||||
config = PB.SmartKnobConfig.create({
|
||||
position,
|
||||
minPosition: 0,
|
||||
maxPosition: Math.trunc(
|
||||
((info.totalFrames - 1) * state.zoomTimelinePixelsPerFrame) / PIXELS_PER_POSITION,
|
||||
),
|
||||
positionWidthRadians: (8 * Math.PI) / 180,
|
||||
detentStrengthUnit: 2.5,
|
||||
endstopStrengthUnit: 1,
|
||||
snapPoint: 0.7,
|
||||
text: Mode.Scroll,
|
||||
detentPositions: findNClosest(Object.keys(detentPositions).map(parseInt), position, 5),
|
||||
snapPointBias: 0,
|
||||
})
|
||||
} else if (state.mode === Mode.Frames) {
|
||||
config = PB.SmartKnobConfig.create({
|
||||
position: state.currentFrame,
|
||||
minPosition: 0,
|
||||
maxPosition: info.totalFrames - 1,
|
||||
positionWidthRadians: (1.5 * Math.PI) / 180,
|
||||
detentStrengthUnit: 1,
|
||||
endstopStrengthUnit: 1,
|
||||
snapPoint: 1.1,
|
||||
text: Mode.Frames,
|
||||
detentPositions: [],
|
||||
snapPointBias: 0,
|
||||
})
|
||||
} else if (state.mode === Mode.Speed) {
|
||||
config = PB.SmartKnobConfig.create({
|
||||
position: state.playbackSpeed === 0 ? 0 : INT32_MIN,
|
||||
minPosition: state.currentFrame === 0 ? 0 : -6,
|
||||
maxPosition: state.currentFrame === info.totalFrames - 1 ? 0 : 6,
|
||||
positionWidthRadians: (60 * Math.PI) / 180,
|
||||
detentStrengthUnit: 1,
|
||||
endstopStrengthUnit: 1,
|
||||
snapPoint: 0.55,
|
||||
text: Mode.Speed,
|
||||
detentPositions: [],
|
||||
snapPointBias: 0.4,
|
||||
})
|
||||
} else {
|
||||
throw exhaustiveCheck(state.mode)
|
||||
}
|
||||
socket.emit('set_config', config)
|
||||
}
|
||||
|
||||
const setCurrentFrame = (fn: (oldFrame: number) => number) => {
|
||||
setDerivedState((cur) => {
|
||||
const newState = {...cur}
|
||||
if (cur.mode === Mode.Speed) {
|
||||
newState.currentFrame = fn(cur.currentFrame)
|
||||
}
|
||||
return newState
|
||||
})
|
||||
}
|
||||
|
||||
// Timer for speed-based playback
|
||||
useEffect(() => {
|
||||
const refreshInterval = 20
|
||||
const fps = info.frameRate * derivedState.playbackSpeed
|
||||
if (derivedState.mode === Mode.Speed && fps !== 0) {
|
||||
const timer = setInterval(() => {
|
||||
setCurrentFrame((oldFrame) => {
|
||||
const newFrame = oldFrame + (fps * refreshInterval) / 1000
|
||||
|
||||
const oldFrameTrunc = Math.trunc(oldFrame)
|
||||
const newFrameTrunc = Math.trunc(newFrame)
|
||||
|
||||
if (newFrame < 0 || newFrame >= info.totalFrames) {
|
||||
const clampedNewFrame = Math.min(Math.max(newFrame, 0), info.totalFrames - 1)
|
||||
if (oldFrame !== clampedNewFrame) {
|
||||
// If we've hit a boundary, push a config to set the bounds
|
||||
pushConfig({
|
||||
mode: Mode.Speed,
|
||||
playbackSpeed: 0,
|
||||
currentFrame: Math.trunc(clampedNewFrame),
|
||||
zoomTimelinePixelsPerFrame: derivedState.zoomTimelinePixelsPerFrame,
|
||||
})
|
||||
}
|
||||
return clampedNewFrame
|
||||
} else {
|
||||
if (
|
||||
(oldFrameTrunc === 0 && newFrameTrunc > 0) ||
|
||||
(oldFrameTrunc === info.totalFrames - 1 && newFrameTrunc < info.totalFrames - 1)
|
||||
) {
|
||||
// If we've left a boundary condition, push a config to reset the bounds
|
||||
pushConfig({
|
||||
mode: derivedState.mode,
|
||||
playbackSpeed: 0,
|
||||
currentFrame: newFrameTrunc,
|
||||
zoomTimelinePixelsPerFrame: derivedState.zoomTimelinePixelsPerFrame,
|
||||
})
|
||||
}
|
||||
return newFrame
|
||||
}
|
||||
})
|
||||
}, refreshInterval)
|
||||
return () => clearInterval(timer)
|
||||
}
|
||||
}, [derivedState.mode, derivedState.playbackSpeed, info.totalFrames, info.frameRate])
|
||||
|
||||
// Socket.io subscription
|
||||
useEffect(() => {
|
||||
socket.on('connect', () => {
|
||||
setIsConnected(true)
|
||||
pushConfig(derivedState)
|
||||
})
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setIsConnected(false)
|
||||
})
|
||||
|
||||
socket.on('state', (input: {pb: PB.SmartKnobState}) => {
|
||||
const {pb: state} = input
|
||||
const stateObj = PB.SmartKnobState.toObject(state, {
|
||||
defaults: true,
|
||||
}) as NoUndefinedField<PB.ISmartKnobState>
|
||||
setState(stateObj)
|
||||
})
|
||||
return () => {
|
||||
socket.off('connect')
|
||||
socket.off('disconnect')
|
||||
socket.off('state')
|
||||
}
|
||||
}, [])
|
||||
return (
|
||||
<>
|
||||
<Container component="main" maxWidth="md">
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography component="h1" variant="h5">
|
||||
Video Playback Control Demo
|
||||
</Typography>
|
||||
{isConnected || (
|
||||
<Typography component="h6" variant="h6">
|
||||
[Not connected]
|
||||
</Typography>
|
||||
)}
|
||||
<ToggleButtonGroup
|
||||
color="primary"
|
||||
value={derivedState.mode}
|
||||
exclusive
|
||||
onChange={(e, value: Mode | null) => {
|
||||
if (value === null) {
|
||||
return
|
||||
}
|
||||
pushConfig({
|
||||
...derivedState,
|
||||
mode: value,
|
||||
})
|
||||
}}
|
||||
aria-label="Mode"
|
||||
>
|
||||
{Object.keys(Mode).map((mode) => (
|
||||
<ToggleButton value={mode} key={mode}>
|
||||
{mode}
|
||||
</ToggleButton>
|
||||
))}
|
||||
</ToggleButtonGroup>
|
||||
<Typography>
|
||||
Frame {Math.trunc(derivedState.currentFrame)} / {info.totalFrames - 1}
|
||||
<br />
|
||||
Speed {Math.trunc(derivedState.playbackSpeed * 10) / 10}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Timeline
|
||||
info={info}
|
||||
currentFrame={derivedState.currentFrame}
|
||||
zoomTimelinePixelsPerFrame={derivedState.zoomTimelinePixelsPerFrame}
|
||||
adjustZoom={(factor) => {
|
||||
setDerivedState((cur) => {
|
||||
const newZoom = Math.min(
|
||||
Math.max(cur.zoomTimelinePixelsPerFrame * factor, MIN_ZOOM),
|
||||
MAX_ZOOM,
|
||||
)
|
||||
console.log(factor, newZoom)
|
||||
return {
|
||||
...cur,
|
||||
zoomTimelinePixelsPerFrame: newZoom,
|
||||
}
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div>{JSON.stringify(detentPositions)}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export type TimelineProps = {
|
||||
info: VideoInfo
|
||||
currentFrame: number
|
||||
zoomTimelinePixelsPerFrame: number
|
||||
adjustZoom: (factor: number) => void
|
||||
}
|
||||
export const Timeline: React.FC<TimelineProps> = ({info, currentFrame, zoomTimelinePixelsPerFrame, adjustZoom}) => {
|
||||
const gradients = [
|
||||
'linear-gradient( 135deg, #FDEB71 10%, #F8D800 100%)',
|
||||
'linear-gradient( 135deg, #ABDCFF 10%, #0396FF 100%)',
|
||||
'linear-gradient( 135deg, #FEB692 10%, #EA5455 100%)',
|
||||
'linear-gradient( 135deg, #CE9FFC 10%, #7367F0 100%)',
|
||||
'linear-gradient( 135deg, #90F7EC 10%, #32CCBC 100%)',
|
||||
]
|
||||
|
||||
const timelineRef = useRef<HTMLDivElement>(null)
|
||||
const cursorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const handleWheel = (event: HTMLElementEventMap['wheel']) => {
|
||||
const delta = event.deltaY
|
||||
if (delta) {
|
||||
event.preventDefault()
|
||||
adjustZoom(1 - delta / 500)
|
||||
}
|
||||
}
|
||||
|
||||
timelineRef.current?.addEventListener('wheel', handleWheel)
|
||||
return () => {
|
||||
timelineRef.current?.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
cursorRef.current?.scrollIntoView()
|
||||
}, [currentFrame, zoomTimelinePixelsPerFrame])
|
||||
return (
|
||||
<div
|
||||
className="timeline-container"
|
||||
ref={timelineRef}
|
||||
style={{
|
||||
width: '100%',
|
||||
margin: '10px auto',
|
||||
overflowX: 'scroll',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="timeline"
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'inline-block',
|
||||
height: '80px',
|
||||
width: `${zoomTimelinePixelsPerFrame * info.totalFrames}px`,
|
||||
backgroundColor: '#dde',
|
||||
}}
|
||||
>
|
||||
{[...info.boundaryFrames, info.totalFrames].map((f, i, a) => {
|
||||
const lengthFrames = f - (a[i - 1] ?? 0)
|
||||
const widthPixels = zoomTimelinePixelsPerFrame * lengthFrames
|
||||
return (
|
||||
<div
|
||||
key={`clip-${f}`}
|
||||
className="video-clip"
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'inline-block',
|
||||
top: '10px',
|
||||
height: '60px',
|
||||
width: `${widthPixels}px`,
|
||||
backgroundImage: gradients[i % gradients.length],
|
||||
}}
|
||||
></div>
|
||||
)
|
||||
})}
|
||||
<div
|
||||
className="playback-cursor"
|
||||
ref={cursorRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
display: 'inline-block',
|
||||
left: `${zoomTimelinePixelsPerFrame * Math.trunc(currentFrame)}px`,
|
||||
width: `${Math.max(zoomTimelinePixelsPerFrame, 1)}px`,
|
||||
height: '100%',
|
||||
backgroundColor: 'rgba(255, 0, 0, 0.4)',
|
||||
borderLeft: '1px solid red',
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
34
software/js/packages/demo-frontend/src/index.tsx
Normal file
34
software/js/packages/demo-frontend/src/index.tsx
Normal file
@ -0,0 +1,34 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import {App} from './App'
|
||||
import reportWebVitals from './reportWebVitals'
|
||||
import '@fontsource/roboto/300.css'
|
||||
import '@fontsource/roboto/400.css'
|
||||
import '@fontsource/roboto/500.css'
|
||||
import '@fontsource/roboto/700.css'
|
||||
import CssBaseline from '@mui/material/CssBaseline'
|
||||
import {createTheme, ThemeProvider} from '@mui/material/styles'
|
||||
import {VideoInfo} from './types'
|
||||
|
||||
const theme = createTheme()
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
|
||||
|
||||
const info: VideoInfo = {
|
||||
totalFrames: 30 * 60 * 5,
|
||||
frameRate: 30,
|
||||
boundaryFrames: [312, 400, 1234, 1290, 3000, 4000],
|
||||
}
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<ThemeProvider theme={theme}>
|
||||
<CssBaseline />
|
||||
<App info={info} />
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals()
|
1
software/js/packages/demo-frontend/src/react-app-env.d.ts
vendored
Normal file
1
software/js/packages/demo-frontend/src/react-app-env.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
||||
/// <reference types="react-scripts" />
|
15
software/js/packages/demo-frontend/src/reportWebVitals.ts
Normal file
15
software/js/packages/demo-frontend/src/reportWebVitals.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
5
software/js/packages/demo-frontend/src/types.tsx
Normal file
5
software/js/packages/demo-frontend/src/types.tsx
Normal file
@ -0,0 +1,5 @@
|
||||
export type VideoInfo = {
|
||||
totalFrames: number
|
||||
frameRate: number
|
||||
boundaryFrames: number[]
|
||||
}
|
31
software/js/packages/demo-frontend/src/util.ts
Normal file
31
software/js/packages/demo-frontend/src/util.ts
Normal file
@ -0,0 +1,31 @@
|
||||
export const exhaustiveCheck = (x: never): never => {
|
||||
throw new Error("Didn't expect to get here", x)
|
||||
}
|
||||
|
||||
export const isSome = <T>(v: T | null | undefined): v is T => {
|
||||
return v !== null && v !== undefined
|
||||
}
|
||||
|
||||
export const lerp = (value: number, inMin: number, inMax: number, min: number, max: number): number => {
|
||||
// Map the input value from the input range to the output range
|
||||
value = ((value - inMin) / (inMax - inMin)) * (max - min) + min
|
||||
|
||||
// Clamp the mapped value between the minimum and maximum range
|
||||
return Math.min(Math.max(value, min), max)
|
||||
}
|
||||
|
||||
export type NoUndefinedField<T> = {
|
||||
[P in keyof T]-?: NoUndefinedField<NonNullable<T[P]>>
|
||||
}
|
||||
|
||||
export const INT32_MIN = -2147483648
|
||||
|
||||
export function findNClosest(numbers: number[], target: number, n: number): number[] {
|
||||
// First, we sort the numbers in ascending order based on their absolute difference
|
||||
// from the target number. This means that the numbers that are closest to the target
|
||||
// will come first in the sorted array.
|
||||
const sortedNumbers = numbers.sort((a, b) => Math.abs(a - target) - Math.abs(b - target))
|
||||
|
||||
// Next, we return the first N numbers from the sorted array as the N closest numbers.
|
||||
return sortedNumbers.slice(0, n)
|
||||
}
|
26
software/js/packages/demo-frontend/tsconfig.json
Normal file
26
software/js/packages/demo-frontend/tsconfig.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
@ -9,7 +9,8 @@ const main = async () => {
|
||||
// Implement a check for your device's vendor+product+serial
|
||||
// (this is more robust than the alternative of just hardcoding a "path" like "/dev/ttyUSB0")
|
||||
return (
|
||||
portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() && portInfo.productId?.toLowerCase() === '7523'.toLowerCase()
|
||||
portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() &&
|
||||
portInfo.productId?.toLowerCase() === '7523'.toLowerCase()
|
||||
// && portInfo.serialNumber === 'DEADBEEF'
|
||||
)
|
||||
})
|
||||
@ -48,8 +49,9 @@ const main = async () => {
|
||||
PB.SmartKnobConfig.create({
|
||||
detentStrengthUnit: 1,
|
||||
endstopStrengthUnit: 1,
|
||||
numPositions: 5,
|
||||
position: 0,
|
||||
minPosition: 0,
|
||||
maxPosition: 4,
|
||||
positionWidthRadians: (10 * Math.PI) / 180,
|
||||
snapPoint: 1.1,
|
||||
text: 'From TS!',
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "smartknobjs-proto",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"description": "SmartKnob Protobuf Generated Code",
|
||||
"main": "dist/smartknob_proto.js",
|
||||
"types": "dist/smartknob_proto.d.ts",
|
||||
|
@ -49,15 +49,7 @@ export class SmartKnob {
|
||||
this.port = null
|
||||
}
|
||||
|
||||
this.currentConfig = PB.SmartKnobConfig.create({
|
||||
detentStrengthUnit: 1,
|
||||
endstopStrengthUnit: 1,
|
||||
numPositions: 5,
|
||||
position: 0,
|
||||
positionWidthRadians: (10 * Math.PI) / 180,
|
||||
snapPoint: 1.1,
|
||||
text: 'From TS!',
|
||||
})
|
||||
this.currentConfig = PB.SmartKnobConfig.create({})
|
||||
|
||||
this.lastNonce = Math.floor(Math.random() * (2 ^ (32 - 1)))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user