Skip to content

Commit

Permalink
fix race in motor driver promise
Browse files Browse the repository at this point in the history
  • Loading branch information
cubicap committed Jul 10, 2024
1 parent 6a51b22 commit eccff0b
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions main/espFeatures/motorFeature.h
Original file line number Diff line number Diff line change
Expand Up @@ -169,18 +169,35 @@ class MotorProtoBuilder : public jac::ProtoBuilder::Opaque<JSDCMotor>, public ja
throw jac::Exception::create(jac::Exception::Type::InternalError, "Motor is already moving");
}

std::optional<jac::Promise> pms;

if (args.size() == 0) {
motor.motor->moveInfinite();

auto [ promise, resolve, reject ] = jac::Promise::create(ctx);
motor.pendingPromise = PromiseFunctions{resolve, reject};
pms = promise;
}
else {
jac::Object duration = args[0].to<jac::Object>();

if (duration.hasProperty("distance")) {
bool hasDistance = duration.hasProperty("distance");
bool hasTime = duration.hasProperty("time");

if (hasDistance && hasTime) {
throw jac::Exception::create(jac::Exception::Type::TypeError, "Cannot specify both distance and time");
}

auto [ promise, resolve, reject ] = jac::Promise::create(ctx);
motor.pendingPromise = PromiseFunctions{resolve, reject};
pms = promise;

if (hasDistance) {
double distance = duration.get("distance").to<double>();
int64_t ticks = motor.encTicks * distance / (motor.circumference);
motor.motor->moveDistance(ticks);
}
else if (duration.hasProperty("time")) {
else if (hasTime) {
int64_t time = duration.get("time").to<int64_t>();
motor.motor->moveTime(time);
}
Expand All @@ -189,10 +206,7 @@ class MotorProtoBuilder : public jac::ProtoBuilder::Opaque<JSDCMotor>, public ja
}
}

auto [ promise, resolve, reject ] = jac::Promise::create(ctx);
motor.pendingPromise = PromiseFunctions{resolve, reject};

return promise;
return pms.value();
}), jac::PropFlags::Enumerable);

proto.defineProperty("stop", ff.newFunctionThisVariadic([](jac::ContextRef ctx, jac::ValueWeak thisVal, std::vector<jac::ValueWeak> args) {
Expand Down Expand Up @@ -262,12 +276,11 @@ class MotorFeature : public Next {
#endif



MotorFeature() {
MotorClass::init("Motor");
}

#if not defined(CONFIG_IDF_TARGET_ESP32C3)
#if !defined(CONFIG_IDF_TARGET_ESP32C3)
~MotorFeature() {
for(auto& motor : _motors) {
auto& jsdcMotor = *MotorProtoBuilder<MotorFeature<Next>>::getOpaque(this->context(), motor);
Expand Down

0 comments on commit eccff0b

Please sign in to comment.