'use strict'

// Tractor Beam / Zumo
const DIR_R = 7
const DIR_L = 8
const PWM_R = 9
const PWM_L = 10

function success (message) {
  console.log(message)
}

function error (message) {
  console.error(message)
}

module.exports = class TractorBeam {
  connect () {
    firmata.connect(function () {
      console.log('connected')
    }, error)
  }

  setSpeed (dir, pwm, speed) {
    const FORWARD = firmata.LOW
    const REVERSE = firmata.HIGH

    let direction = FORWARD
    if (speed < 0) {
      speed = 255 + speed
      direction = REVERSE
    }
    firmata.digitalWrite(dir, direction, success, error)
    firmata.analogWrite(pwm, speed, success, error)
  }

  setLeftSpeed (speed) {
    this.setSpeed(DIR_L, PWM_L, speed)
  }

  setRightSpeed (speed) {
    this.setSpeed(DIR_R, PWM_R, speed)
  }

  setSpeeds (speeds) {
    this.setLeftSpeed(speeds[0])
    this.setRightSpeed(speeds[1])

    if (this._safetyTimeout) {
      clearTimeout(this._safetyTimeout)
      this._safetyTimeout = null
    }
    this._safetyTimeout = setTimeout(function () {
      this._safetyTimeout = null
      this.setLeftSpeed(0)
      this.setRightSpeed(0)
    }.bind(this), 500)
  }
}

@@ -7,16 +7,43 @@
 trict'%0A%0A
+const TIMEOUT = 500 // ms%0A%0A
 // Tract
@@ -945,24 +945,16 @@
 Timeout)
- %7B%0A     
  clearTi
@@ -984,47 +984,8 @@
 ut)%0A
-      this._safetyTimeout = null%0A    %7D%0A
     
@@ -1035,41 +1035,8 @@
 ) %7B%0A
-      this._safetyTimeout = null%0A
     
@@ -1104,19 +1104,23 @@
 (this), 
-500
+TIMEOUT
 )%0A  %7D%0A%7D%0A

simplify timeout logic