Statistics
| Branch: | Tag: | Revision:

amiro-os / devices / DiWheelDrive / userthread.cpp @ e404e6c0

History | View | Annotate | Download (29.252 KB)

1 58fe0e0b Thomas Schöpping
#include "global.hpp"
2 10bf9cc0 galberding
#include <cmath>
3 8dced1c9 galberding
#include "linefollow.hpp"
4 d4c6efa9 galberding
#include "userthread.hpp"
5 e404e6c0 galberding
#include "amiro_map.hpp"
6
7 58fe0e0b Thomas Schöpping
using namespace amiro;
8
9
extern Global global;
10
11
// a buffer for the z-value of the accelerometer
12
int16_t accel_z;
13 5d138bca galberding
bool running = false;
14 58fe0e0b Thomas Schöpping
15
16 181f2892 galberding
/**
17
 * Set speed.
18 8dced1c9 galberding
 *
19 181f2892 galberding
 * @param rpmSpeed speed for left and right wheel in rounds/min
20
 */
21 c9fa414d galberding
void UserThread::setRpmSpeedFuzzy(const int (&rpmSpeed)[2]) {
22 5d138bca galberding
  global.motorcontrol.setTargetRPM(rpmSpeed[constants::DiWheelDrive::LEFT_WHEEL] * 1000000, rpmSpeed[constants::DiWheelDrive::RIGHT_WHEEL] * 1000000);
23 58fe0e0b Thomas Schöpping
}
24
25 c9fa414d galberding
void UserThread::setRpmSpeed(const int (&rpmSpeed)[2]) {
26
  global.motorcontrol.setTargetRPM(rpmSpeed[constants::DiWheelDrive::LEFT_WHEEL], rpmSpeed[constants::DiWheelDrive::RIGHT_WHEEL]);
27
}
28
29 181f2892 galberding
void UserThread::lightOneLed(Color color, int idx){
30 5d138bca galberding
  global.robot.setLightColor(idx, Color(color));
31
}
32 58fe0e0b Thomas Schöpping
33 181f2892 galberding
void UserThread::lightAllLeds(Color color){
34 5d138bca galberding
  int led = 0;
35
  for(led=0; led<8; led++){
36
        lightOneLed(color, led);
37
      }
38 58fe0e0b Thomas Schöpping
}
39
40 181f2892 galberding
void UserThread::showChargingState(){
41
  uint8_t numLeds = global.robot.getPowerStatus().state_of_charge / 12;
42
  Color color = Color::GREEN;
43
  if (numLeds <= 2){
44
    color = Color::RED;
45
  }else if(numLeds <= 6){
46
    color = Color::YELLOW;
47
  }
48
  for (int i=0; i<numLeds; i++){
49
    lightOneLed(color, i);
50
    this->sleep(300);
51 9c46b728 galberding
  }
52 181f2892 galberding
  this->sleep(1000);
53
  lightAllLeds(Color::BLACK);
54 9c46b728 galberding
}
55
56 10bf9cc0 galberding
void UserThread::chargeAsLED(){
57
  uint8_t numLeds = global.robot.getPowerStatus().state_of_charge / 12;
58
  Color color = Color::GREEN;
59
  if (numLeds <= 2){
60
    color = Color::RED;
61
  }else if(numLeds <= 6){
62
    color = Color::YELLOW;
63
  }
64
  for (int i=0; i<numLeds; i++){
65
    lightOneLed(color, i);
66
    // this->sleep(300);
67
  }
68
  // this->sleep(1000);
69
  // lightAllLeds(Color::BLACK);
70
}
71
72
// ----------------------------------------------------------------
73
74
void UserThread::getProxySectorVals(uint16_t (&proxVals)[8], uint16_t (&sProx)[8]){
75
  for (int i=0; i<8; i++){
76
    sProx[i] = (proxVals[i] < proxVals[(i+1) % 8]) ? proxVals[i] : proxVals[(i+1) % 8];
77
    // chprintf((BaseSequentialStream*)&global.sercanmux1, "%d: %d, ", i, sProx[i]);
78 8dced1c9 galberding
79 10bf9cc0 galberding
  }
80
    // chprintf((BaseSequentialStream*)&global.sercanmux1, "\n");
81
82
}
83
84
85
void UserThread::getMaxFrontSectorVal(uint16_t (&sProx)[8], int32_t &sPMax){
86
  for (int i=2; i<5; i++){
87
    sPMax = (sPMax < sProx[i]) ? sProx[i] : sPMax;
88
  }
89
}
90
91
void UserThread::proxSectorSpeedCorrection(int (&rpmSpeed)[2], uint16_t (&proxVals)[8]){
92
  int i;
93
  uint16_t sProx[8];
94
  int32_t sPMax = 0;
95
  getProxySectorVals(proxVals, sProx);
96
  getMaxFrontSectorVal(sProx, sPMax);
97 8dced1c9 galberding
98 10bf9cc0 galberding
  int32_t speedL = rpmSpeed[0] - (sPMax * pCtrl.pFactor);
99
  int32_t speedR = rpmSpeed[1] - (sPMax * pCtrl.pFactor);
100
101
102
103
  if(sPMax > pCtrl.threshMid){
104
      rpmSpeed[0] = 0;
105
      rpmSpeed[1] = 0;
106
      pCtrl.staticCont++;
107
  }else if((speedL > 0) || (speedR > 0)){
108
    pCtrl.staticCont = 0;
109
    rpmSpeed[0] = speedL;
110
    rpmSpeed[1] = speedR;
111
  }else{
112
    rpmSpeed[0] = 4000000 + (rpmSpeed[0] - global.rpmForward[0] * 1000000);
113
    rpmSpeed[1] = 4000000 + (rpmSpeed[1] - global.rpmForward[0] * 1000000);
114
  }
115
116
  for(i=4; i<5; i++){
117
    if ((proxVals[i] > pCtrl.threshMid) && (proxVals[i+1] > pCtrl.threshLow)){
118
      rpmSpeed[0] = -5000000 ;
119
      rpmSpeed[1] = -5000000 ;
120
      // pCtrl.staticCont++;
121
      break;
122
    }
123
  }
124
  chargeAsLED();
125 8dced1c9 galberding
126 10bf9cc0 galberding
  // chprintf((BaseSequentialStream*)&global.sercanmux1, "Max: %d factor: %d, Panel: %d SpeedL: %d SpeedR: %d ActualL: %d ActualR: %d\n",sPMax,  pCtrl.pFactor,  sPMax * pCtrl.pFactor, speedL, speedR, rpmSpeed[0], rpmSpeed[1]);
127
128
129
}
130
// -------------------------------------------------------------------
131
132
133
void UserThread::preventCollision( int (&rpmSpeed)[2], uint16_t (&proxVals)[8]) {
134
135
  if((proxVals[3] > pCtrl.threshLow) || (proxVals[4] > pCtrl.threshLow)){
136
      rpmSpeed[0] = rpmSpeed[0] / 2;
137
      rpmSpeed[1] = rpmSpeed[1] / 2;
138
  }
139
140
  if((proxVals[3] > pCtrl.threshMid) || (proxVals[4] > pCtrl.threshMid)){
141 d4c6efa9 galberding
      rpmSpeed[0] = rpmSpeed[0] / 3;
142
      rpmSpeed[1] = rpmSpeed[1] / 3;
143 10bf9cc0 galberding
  }
144
145
  if((proxVals[3] > pCtrl.threshHigh) || (proxVals[4] > pCtrl.threshHigh)){
146
      rpmSpeed[0] = 0;
147
      rpmSpeed[1] = 0;
148
      utCount.ringProxCount++;
149
  }else{
150
    utCount.ringProxCount = 0;
151
  }
152 8dced1c9 galberding
153 10bf9cc0 galberding
}
154
155
156 9c46b728 galberding
/**
157
 * Blocks as long as the position changes.
158
 */
159 181f2892 galberding
void UserThread::checkForMotion(){
160 8dced1c9 galberding
  bool motion = true;
161 9c46b728 galberding
  int led = 0;
162
  types::position oldPos = global.odometry.getPosition();
163
  while(motion){
164 8dced1c9 galberding
    this->sleep(200);
165 9c46b728 galberding
    types::position tmp = global.odometry.getPosition();
166 8dced1c9 galberding
    motion = oldPos.x != tmp.x; //abs(oldPos.x - tmp.x)+ abs(oldPos.y - tmp.y)+abs(oldPos.z - tmp.z);
167 9c46b728 galberding
    oldPos = tmp;
168 8dced1c9 galberding
    global.robot.setLightColor((led + 1) % 8, Color(Color::YELLOW));
169
    global.robot.setLightColor(led % 8, Color(Color::BLACK));
170
    led++;
171 9c46b728 galberding
  }
172 10bf9cc0 galberding
  lightAllLeds(Color::BLACK);
173 9c46b728 galberding
}
174
175 fbcb25cc galberding
bool UserThread::checkFrontalObject(){
176 10bf9cc0 galberding
  uint32_t thresh = pCtrl.threshMid;
177 fbcb25cc galberding
  uint32_t prox;
178
  for(int i=0; i<8; i++){
179
    prox = global.robot.getProximityRingValue(i);
180
    if((i == 3) || (i == 4)){
181
      if(prox < thresh){
182
        return false;
183
      }
184
    }else{
185
      if(prox > thresh){
186
        return false;
187
      }
188
    }
189
  }
190
  return true;
191
}
192
193 181f2892 galberding
bool UserThread::checkPinVoltage(){
194 8dced1c9 galberding
  return global.ltc4412.isPluggedIn();
195 181f2892 galberding
}
196 9c46b728 galberding
197 181f2892 galberding
bool UserThread::checkPinEnabled(){
198
  return global.ltc4412.isEnabled();
199
}
200
201
int UserThread::checkDockingSuccess(){
202
  // setRpmSpeed(stop);
203
  checkForMotion();
204 9c46b728 galberding
  int success = 0;
205 10bf9cc0 galberding
  // global.odometry.resetPosition();
206 9c46b728 galberding
  types::position start = global.startPos = global.odometry.getPosition();
207 27d4e1fa galberding
  global.motorcontrol.setMotorEnable(false);
208
  this->sleep(1000);
209 181f2892 galberding
  types::position stop_ = global.endPos = global.odometry.getPosition();
210 8dced1c9 galberding
211 9c46b728 galberding
  // Amiro moved, docking was not successful
212 10bf9cc0 galberding
  // if ((start.x + stop_.x)  || (start.y + stop_.y)){
213 84b4c632 galberding
  if (abs(start.x - stop_.x) > 200 /* || (start.y + stop_.y) */){
214 181f2892 galberding
    lightAllLeds(Color::RED);
215
    // Enable Motor again if docking was not successful
216 27d4e1fa galberding
    global.motorcontrol.setMotorEnable(true);
217 9c46b728 galberding
    success = 0;
218
  }else{
219 181f2892 galberding
    lightAllLeds(Color::GREEN);
220 9c46b728 galberding
    success = 1;
221
  }
222 8dced1c9 galberding
223 61544eee galberding
  // this->sleep(500);
224 181f2892 galberding
  lightAllLeds(Color::BLACK);
225 9c46b728 galberding
  return success;
226
}
227
228 c9fa414d galberding
int UserThread::getProxyRingSum(){
229
  int prox_sum = 0;
230 e2002d0e galberding
  for(int i=0; i<8;i++){
231
    prox_sum += global.robot.getProximityRingValue(i);;
232
  }
233
  return prox_sum;
234
}
235
236 b24df8ad galberding
int32_t UserThread::meanDeviation(uint16_t a, uint16_t b){
237
  int32_t diff = a - b;
238 8dced1c9 galberding
  int32_t res = 0;
239 b24df8ad galberding
  devCor.proxbuf[devCor.pCount] = (diff*100)/((a+b)/2);
240
  for (int i = 0; i< PROX_DEVIATION_MEAN_WINDOW; i++){
241
    res += devCor.proxbuf[i];
242
  }
243
  devCor.pCount++;
244
  devCor.pCount = devCor.pCount % PROX_DEVIATION_MEAN_WINDOW;
245
246
  devCor.currentDeviation =  res / PROX_DEVIATION_MEAN_WINDOW;
247
  return devCor.currentDeviation;
248
}
249
250 e404e6c0 galberding
void setAttributes(uint8_t (&map)[MAX_NODES][NODE_ATTRIBUTES],
251
                          uint8_t id, uint8_t l, uint8_t r, uint8_t att) {
252
  map[id][0] = l;
253
  map[id][1] = r;
254
  map[id][2] = att;
255
}
256 e2002d0e galberding
257 58fe0e0b Thomas Schöpping
UserThread::UserThread() :
258
  chibios_rt::BaseStaticThread<USER_THREAD_STACK_SIZE>()
259
{
260
}
261
262
UserThread::~UserThread()
263
{
264
}
265
266
msg_t
267
UserThread::main()
268
{
269 5d138bca galberding
  /*
270
   * SETUP
271
   */
272 181f2892 galberding
  // User thread state:
273
274 5d138bca galberding
  for (uint8_t led = 0; led < 8; ++led) {
275
    global.robot.setLightColor(led, Color(Color::BLACK));
276
  }
277
  running = false;
278 10bf9cc0 galberding
  LineFollowStrategy lStrategy = LineFollowStrategy::EDGE_RIGHT;
279 5d138bca galberding
  LineFollow lf(&global);
280 e404e6c0 galberding
  AmiroMap map(&global);
281 5d138bca galberding
  /*
282
   * LOOP
283
   */
284
  while (!this->shouldTerminate())
285
  {
286 181f2892 galberding
    /*
287
    * read accelerometer z-value
288
    */
289
    accel_z = global.lis331dlh.getAccelerationForce(LIS331DLH::AXIS_Z);
290 8dced1c9 galberding
291
    if (accel_z < -900 /*-0.9g*/) {
292 181f2892 galberding
      // Start line following when AMiRo is rotated
293 10bf9cc0 galberding
      if(currentState == states::INACTIVE){
294 fbcb25cc galberding
        newState = states::FOLLOW_LINE;
295 181f2892 galberding
      }else{
296 fbcb25cc galberding
        newState = states::IDLE;
297 181f2892 galberding
      }
298
      lightAllLeds(Color::GREEN);
299
      this->sleep(1000);
300
      lightAllLeds(Color::BLACK);
301 c76baf23 Georg Alberding
302 d607fcef galberding
    // If message was received handle it here:
303
    } else if(global.msgReceived){
304
      global.msgReceived = false;
305 181f2892 galberding
      // running = true;
306 d607fcef galberding
      switch(global.lfStrategy){
307 e404e6c0 galberding
      case msg_content::MSG_START:
308
        newState = states::CALIBRATION_CHECK;
309 10bf9cc0 galberding
        break;
310 e404e6c0 galberding
      case msg_content::MSG_STOP:
311
        newState = states::IDLE;
312 10bf9cc0 galberding
        break;
313 e404e6c0 galberding
      case msg_content::MSG_EDGE_RIGHT:
314
        // newState = states::FOLLOW_LINE;
315
        lStrategy = LineFollowStrategy::EDGE_RIGHT;
316 10bf9cc0 galberding
        break;
317 e404e6c0 galberding
      case  msg_content::MSG_EDGE_LEFT:
318
        // newState = states::FOLLOW_LINE;
319
        lStrategy = LineFollowStrategy::EDGE_LEFT;
320 10bf9cc0 galberding
        break;
321 e404e6c0 galberding
      case msg_content::MSG_FUZZY:
322
        // newState = states::FOLLOW_LINE;
323
        lStrategy = LineFollowStrategy::FUZZY;
324 10bf9cc0 galberding
        break;
325 e404e6c0 galberding
      case msg_content::MSG_DOCK:
326
        newState = states::DETECT_STATION;
327 10bf9cc0 galberding
        break;
328 e404e6c0 galberding
      case msg_content::MSG_UNDOCK:
329
        newState = states::RELEASE;
330
        break;
331
      case msg_content::MSG_CHARGE:
332
        newState = states::CHARGING;
333 10bf9cc0 galberding
        break;
334 e404e6c0 galberding
      case msg_content::MSG_RESET_ODOMETRY:
335
        global.odometry.resetPosition();
336 10bf9cc0 galberding
        break;
337 e404e6c0 galberding
      case msg_content::MSG_CALIBRATE_BLACK:
338
        proxCalib.calibrateBlack = true;
339
        // global.odometry.resetPosition();
340
        newState = states::CALIBRATION;
341 10bf9cc0 galberding
        break;
342 e404e6c0 galberding
      case msg_content::MSG_CALIBRATE_WHITE:
343
        proxCalib.calibrateBlack = false;
344
        newState = states::CALIBRATION;
345 10bf9cc0 galberding
        break;
346 e404e6c0 galberding
      case msg_content::MSG_TEST_MAP_STATE:
347
        newState = states::TEST_MAP_STATE;
348 10bf9cc0 galberding
        break;
349 e404e6c0 galberding
350
      default:
351
        newState = states::IDLE;
352 10bf9cc0 galberding
        break;
353 d607fcef galberding
      }
354 5d138bca galberding
    }
355 10bf9cc0 galberding
    // newState = currentState;
356 d607fcef galberding
357 8dced1c9 galberding
    // Get sensor data
358 fbcb25cc galberding
    // uint16_t WL = global.vcnl4020[constants::DiWheelDrive::PROX_WHEEL_LEFT].getProximityScaledWoOffset();
359
    // uint16_t WR = global.vcnl4020[constants::DiWheelDrive::PROX_WHEEL_RIGHT].getProximityScaledWoOffset();
360 019224ff galberding
    for(int i=0; i<8;i++){
361
      rProx[i] = global.robot.getProximityRingValue(i);
362
    }
363 b24df8ad galberding
364
    // Continously update devication values
365
    meanDeviation(rProx[0] & 0xFFF0, rProx[7] & 0xFFF0);
366 181f2892 galberding
    // int FL = global.vcnl4020[constants::DiWheelDrive::PROX_FRONT_LEFT].getProximityScaledWoOffset();
367
    // int FR = global.vcnl4020[constants::DiWheelDrive::PROX_FRONT_RIGHT].getProximityScaledWoOffset();
368 10bf9cc0 galberding
    switch(currentState){
369
      case states::INACTIVE:
370
        // Dummy state to deactivate every interaction
371
      break;
372
      // ---------------------------------------
373
      case states::CALIBRATION_CHECK:
374
        // global.robot.calibrate();
375
        if(global.linePID.BThresh >= global.linePID.WThresh){
376
          newState = states::CALIBRATION_ERROR;
377
        }else{
378
          newState = states::FOLLOW_LINE;
379
        }
380
      break;
381
      // ---------------------------------------
382
      case states::CALIBRATION:
383
        /* Calibrate the global thresholds for black or white.
384
            This values will be used by the line follow object
385
        */
386
387
        proxCalib.buf = 0;
388
        if(proxCalib.calibrateBlack){
389
          chprintf((BaseSequentialStream*)&global.sercanmux1, "Black Calibration, Place AMiRo on black Surface!\n");
390
          global.robot.calibrate();
391
        }
392
        for(int i=0; i <= proxCalib.meanWindow; i++){
393 8dced1c9 galberding
          proxCalib.buf += global.vcnl4020[constants::DiWheelDrive::PROX_FRONT_LEFT].getProximityScaledWoOffset()
394
                          + global.vcnl4020[constants::DiWheelDrive::PROX_FRONT_RIGHT].getProximityScaledWoOffset();
395 10bf9cc0 galberding
          this->sleep(CAN::UPDATE_PERIOD);
396
        }
397
        proxCalib.buf = proxCalib.buf / (2*proxCalib.meanWindow);
398 8dced1c9 galberding
399 10bf9cc0 galberding
        if(proxCalib.calibrateBlack){
400
          global.linePID.BThresh = proxCalib.buf;
401
        }else  {
402
          global.linePID.WThresh  = proxCalib.buf;
403
        }
404
          chprintf((BaseSequentialStream*)&global.sercanmux1, "Black: %d, White: %d!\n", global.linePID.BThresh, global.linePID.WThresh);
405
406
        newState = states::IDLE;
407
      break;
408
      // ---------------------------------------
409 181f2892 galberding
      case states::IDLE:
410 27d4e1fa galberding
        global.motorcontrol.setMotorEnable(true);
411 181f2892 galberding
        setRpmSpeed(stop);
412
        if(/* checkPinVoltage() && */ checkPinEnabled()){
413
          global.robot.requestCharging(0);
414
        }
415 10bf9cc0 galberding
        // pCtrl.pFactor = 0;
416
        pCtrl.staticCont = 0;
417 fbcb25cc galberding
        utCount.whiteCount = 0;
418 10bf9cc0 galberding
        utCount.ringProxCount = 0;
419 27d4e1fa galberding
        utCount.errorCount = 0;
420 10bf9cc0 galberding
        newState = states::INACTIVE;
421
      break;
422 181f2892 galberding
      // ---------------------------------------
423
      case states::FOLLOW_LINE:
424
      // Set correct forward speed to every strategy
425
        if (global.forwardSpeed != global.rpmForward[0]){
426
          global.forwardSpeed = global.rpmForward[0];
427
        }
428 8dced1c9 galberding
429 181f2892 galberding
        if(lf.getStrategy() != lStrategy){
430 9c46b728 galberding
          lf.setStrategy(lStrategy);
431
        }
432 5d138bca galberding
433 181f2892 galberding
        if(lf.followLine(rpmSpeed)){
434 fbcb25cc galberding
          utCount.whiteCount++;
435 10bf9cc0 galberding
          if(utCount.whiteCount >= WHITE_DETETION_TIMEOUT){
436
            setRpmSpeed(stop);
437
            utCount.whiteCount = 0;
438
            newState = states::WHITE_DETECTION_ERROR;
439 9c46b728 galberding
          }
440 181f2892 galberding
        }else{
441 fbcb25cc galberding
          utCount.whiteCount = 0;
442 9c46b728 galberding
        }
443 e2002d0e galberding
444 10bf9cc0 galberding
        preventCollision(rpmSpeed, rProx);
445
        // proxSectorSpeedCorrection(rpmSpeed, rProx);
446 61544eee galberding
447 10bf9cc0 galberding
        if(utCount.ringProxCount > RING_PROX_DETECTION_TIMEOUT){
448
          utCount.ringProxCount = 0;
449 8dced1c9 galberding
450 d4c6efa9 galberding
451
          checkForMotion();
452
          // Check if only front sensors are active
453
          if (checkFrontalObject()) {
454
            // global.distcontrol.setTargetPosition(0, 2792526, ROTATION_DURATION);
455
            // // BaseThread::sleep(8000);
456
            // checkForMotion();
457
            this->utCount.whiteCount = 0;
458
            newState = states::TURN;
459
            // lf.promptStrategyChange(LineFollowStrategy::EDGE_LEFT);
460
          } else {
461
            newState = states::PROXY_DETECTION_ERROR;
462
          }
463 61544eee galberding
        }
464
465 c9fa414d galberding
        if (lf.getStrategy() == LineFollowStrategy::FUZZY){
466
          setRpmSpeedFuzzy(rpmSpeed);
467
        }else{
468
469
          setRpmSpeed(rpmSpeed);
470
        }
471 8dced1c9 galberding
472 10bf9cc0 galberding
      break;
473 181f2892 galberding
      // ---------------------------------------
474 d4c6efa9 galberding
    case states::TURN:{
475
        // Check the line strategy in order to continue driving on the right side
476
      int factor = SPEED_CONVERSION_FACTOR;
477
      int frontL = global.vcnl4020[constants::DiWheelDrive::PROX_FRONT_LEFT].getProximityScaledWoOffset();
478
      int frontR = global.vcnl4020[constants::DiWheelDrive::PROX_FRONT_RIGHT].getProximityScaledWoOffset();
479 8dced1c9 galberding
      int blackSensor = 0;
480 d4c6efa9 galberding
      if (lf.getStrategy() == LineFollowStrategy::EDGE_RIGHT) {
481
        factor = -factor;
482 8dced1c9 galberding
        blackSensor = frontL;
483
      }else{
484
        blackSensor = frontR;
485 d4c6efa9 galberding
      }
486 8dced1c9 galberding
487 d4c6efa9 galberding
      rpmSpeed[0] = factor * CHARGING_SPEED;
488
      rpmSpeed[1] = -factor * CHARGING_SPEED;
489
      setRpmSpeed(rpmSpeed);
490 8dced1c9 galberding
491
      if ((blackSensor >= global.linePID.WThresh )){
492 d4c6efa9 galberding
        utCount.whiteCount = 1;
493 8dced1c9 galberding
      }else {
494
        if((utCount.whiteCount == 1) && (blackSensor <= global.linePID.BThresh)){
495 d4c6efa9 galberding
          utCount.whiteCount = 0;
496 fbcb25cc galberding
          newState = states::FOLLOW_LINE;
497 d4c6efa9 galberding
          setRpmSpeed(stop);
498 fbcb25cc galberding
        }
499 d4c6efa9 galberding
      }
500 10bf9cc0 galberding
      break;
501 d4c6efa9 galberding
    }
502 fbcb25cc galberding
      // ---------------------------------------
503 e404e6c0 galberding
    case states::DETECT_STATION:
504 8dced1c9 galberding
505 61544eee galberding
        if (global.forwardSpeed != DETECTION_SPEED){
506
          global.forwardSpeed = DETECTION_SPEED;
507
        }
508 181f2892 galberding
        if(lf.getStrategy() != LineFollowStrategy::EDGE_RIGHT){
509
          lf.setStrategy(LineFollowStrategy::EDGE_RIGHT);
510
        }
511 8dced1c9 galberding
512 181f2892 galberding
        lf.followLine(rpmSpeed);
513
        setRpmSpeed(rpmSpeed);
514
        // // Detect marker before docking station
515 019224ff galberding
        // if ((WL+WR) < PROXY_WHEEL_THRESH){
516 8dced1c9 galberding
        // Use proxy ring
517 019224ff galberding
        if ((rProx[3]+rProx[4]) > RING_PROX_FRONT_THRESH){
518
519 d607fcef galberding
          setRpmSpeed(stop);
520 181f2892 galberding
          checkForMotion();
521 8dced1c9 galberding
          // 180° Rotation
522 181f2892 galberding
          global.distcontrol.setTargetPosition(0, ROTATION_180, ROTATION_DURATION);
523
          // BaseThread::sleep(8000);
524
          checkForMotion();
525
          newState = states::CORRECT_POSITIONING;
526 9c46b728 galberding
        }
527 10bf9cc0 galberding
      break;
528 181f2892 galberding
      // ---------------------------------------
529 e404e6c0 galberding
    case states::CORRECT_POSITIONING:
530 019224ff galberding
        if (global.forwardSpeed != CHARGING_SPEED){
531
          global.forwardSpeed = CHARGING_SPEED;
532
        }
533 181f2892 galberding
        if(lf.getStrategy() != LineFollowStrategy::EDGE_LEFT){
534
          lf.promptStrategyChange(LineFollowStrategy::EDGE_LEFT);
535 9c46b728 galberding
        }
536 181f2892 galberding
        lf.followLine(rpmSpeed);
537
        setRpmSpeed(rpmSpeed);
538 9c46b728 galberding
539 10bf9cc0 galberding
        utCount.stateTime++;
540
        if (utCount.stateTime >= DOCKING_CORRECTION_TIMEOUT){
541
          utCount.stateTime = 0;
542 181f2892 galberding
          newState = states::REVERSE;
543
          setRpmSpeed(stop);
544
          checkForMotion();
545
        }
546 10bf9cc0 galberding
      break;
547 181f2892 galberding
      // ---------------------------------------
548 e404e6c0 galberding
    case states::REVERSE:
549 181f2892 galberding
        if(lf.getStrategy() != LineFollowStrategy::REVERSE){
550
          lf.setStrategy(LineFollowStrategy::REVERSE);
551
        }
552
        lf.followLine(rpmSpeed);
553
        setRpmSpeed(rpmSpeed);
554 b24df8ad galberding
        // utCount.stateTime++;
555 58fe0e0b Thomas Schöpping
556 b24df8ad galberding
        // Docking is only successful if Deviation is in range and sensors are at their max values.
557 d4c6efa9 galberding
        if((rProx[0] >= PROX_MAX_VAL)
558
           && (rProx[7] >= PROX_MAX_VAL)
559
           && ((devCor.currentDeviation > -MAX_DEVIATION_FACTOR) && (devCor.currentDeviation < MAX_DEVIATION_FACTOR) )){
560 61544eee galberding
          // setRpmSpeed(stop);
561
          // checkForMotion();
562 10bf9cc0 galberding
          utCount.stateTime = 0;
563 27d4e1fa galberding
          newState = states::PUSH_BACK;
564 b24df8ad galberding
        }else if ((devCor.currentDeviation <= -MAX_DEVIATION_FACTOR) && ((rProx[0] > DEVIATION_DIST_THRESH) || (rProx[7] > DEVIATION_DIST_THRESH))){
565 8dced1c9 galberding
          // Case R
566 b24df8ad galberding
          utCount.stateTime = 0;
567
          setRpmSpeed(stop);
568
          devCor.RCase = true;
569
          lightAllLeds(Color::YELLOW);
570
          newState = states::DEVIATION_CORRECTION;
571
        }else if ((devCor.currentDeviation >= MAX_DEVIATION_FACTOR) && ((rProx[0] > DEVIATION_DIST_THRESH) || (rProx[7] > DEVIATION_DIST_THRESH))){
572 8dced1c9 galberding
          // Case L
573 b24df8ad galberding
          utCount.stateTime = 0;
574
          setRpmSpeed(stop);
575
          devCor.RCase = false;
576
          lightAllLeds(Color::WHITE);
577
          newState = states::DEVIATION_CORRECTION;
578 10bf9cc0 galberding
        }else if (utCount.stateTime >= REVERSE_DOCKING_TIMEOUT){
579
          setRpmSpeed(stop);
580
          utCount.stateTime = 0;
581
          utCount.errorCount++;
582
          if (utCount.errorCount >= DOCKING_ERROR_THRESH){
583
            newState = states::DOCKING_ERROR;
584
          }else{
585
            newState = states::CORRECT_POSITIONING;
586
          }
587 27d4e1fa galberding
        }
588 10bf9cc0 galberding
589 84b4c632 galberding
        // if((devCor.currentDeviation <= -10)){
590
        //   rpmSpeed[0] -= 2000000;
591
        // }else if(devCor.currentDeviation >= 10){
592
        //   rpmSpeed[1] -= 2000000;
593
        // }
594
        // setRpmSpeed(rpmSpeed);
595 10bf9cc0 galberding
      break;
596 27d4e1fa galberding
      // ---------------------------------------
597 e404e6c0 galberding
    case states::DEVIATION_CORRECTION:
598 b24df8ad galberding
        // if(lf.getStrategy() != LineFollowStrategy::REVERSE){
599
        //   lf.setStrategy(LineFollowStrategy::REVERSE);
600
        // }
601
        // lf.followLine(rpmSpeed);
602
        // setRpmSpeed(rpmSpeed);
603
        if(utCount.stateTime < DEVIATION_CORRECTION_DURATION / 2 ){
604
          if(devCor.RCase){
605
            rpmSpeed[0] = 0;
606
            rpmSpeed[1] = DEVIATION_CORRECTION_SPEED;
607
          }else {
608
            rpmSpeed[0] = DEVIATION_CORRECTION_SPEED;
609
            rpmSpeed[1] = 0;
610
          }
611
          setRpmSpeed(rpmSpeed);
612 84b4c632 galberding
        }else if (((utCount.stateTime >= DEVIATION_CORRECTION_DURATION / 2) && (utCount.stateTime < DEVIATION_CORRECTION_DURATION +10)) ){
613 b24df8ad galberding
          if(devCor.RCase){
614
            rpmSpeed[0] = DEVIATION_CORRECTION_SPEED;
615
            rpmSpeed[1] = 0;
616
          }else {
617
            rpmSpeed[0] = 0;
618
            rpmSpeed[1] = DEVIATION_CORRECTION_SPEED;
619
          }
620
          setRpmSpeed(rpmSpeed);
621 84b4c632 galberding
          if(((devCor.currentDeviation >= -5) && (devCor.currentDeviation <= 5))){
622
            utCount.stateTime = 0;
623
            newState = states::REVERSE;
624
            setRpmSpeed(stop);
625
          }
626 b24df8ad galberding
        }else{
627
          utCount.stateTime = 0;
628
          newState = states::REVERSE;
629
          setRpmSpeed(stop);
630
        }
631
632
        utCount.stateTime++;
633
634
635
        // if (utCount.stateTime > PUSH_BACK_TIMEOUT){
636
        //   utCount.stateTime = 0;
637
        //   newState = states::CHECK_POSITIONING;
638
        // }
639
      break;
640
      // ---------------------------------------
641 e404e6c0 galberding
    case states::PUSH_BACK:
642 27d4e1fa galberding
        if(lf.getStrategy() != LineFollowStrategy::REVERSE){
643
          lf.setStrategy(LineFollowStrategy::REVERSE);
644
        }
645
        lf.followLine(rpmSpeed);
646
        setRpmSpeed(rpmSpeed);
647
648 10bf9cc0 galberding
        utCount.stateTime++;
649
        if (utCount.stateTime > PUSH_BACK_TIMEOUT){
650
          utCount.stateTime = 0;
651 181f2892 galberding
          newState = states::CHECK_POSITIONING;
652
        }
653 10bf9cc0 galberding
      break;
654 181f2892 galberding
      // ---------------------------------------
655 e404e6c0 galberding
    case states::CHECK_POSITIONING:
656 61544eee galberding
        setRpmSpeed(stop);
657
        checkForMotion();
658 27d4e1fa galberding
        if(checkDockingSuccess()){
659
          newState = states::CHECK_VOLTAGE;
660
        }else{
661
          utCount.errorCount++;
662
          newState = states::CORRECT_POSITIONING;
663 10bf9cc0 galberding
          if (utCount.errorCount >= DOCKING_ERROR_THRESH){
664
              newState = states::DOCKING_ERROR;
665 27d4e1fa galberding
            }
666
        }
667 10bf9cc0 galberding
      break;
668 181f2892 galberding
      // ---------------------------------------
669 e404e6c0 galberding
    case states::CHECK_VOLTAGE:
670 ba75ee1d galberding
        if(!checkPinEnabled()){
671
          global.robot.requestCharging(1);
672
        } else {
673
          if(checkPinVoltage()){
674 8dced1c9 galberding
            // Pins are under voltage -> correctly docked
675
676 ba75ee1d galberding
            newState = states::CHARGING;
677
          }else{
678 27d4e1fa galberding
            utCount.errorCount++;
679 ba75ee1d galberding
            // No voltage on pins -> falsely docked
680
            // deactivate pins
681 27d4e1fa galberding
            global.motorcontrol.setMotorEnable(true);
682 ba75ee1d galberding
            global.robot.requestCharging(0);
683 27d4e1fa galberding
            // TODO: Soft release when docking falsely
684 61544eee galberding
            if((rProx[0] >= PROX_MAX_VAL) && (rProx[7] >= PROX_MAX_VAL)){
685
              newState = states::RELEASE_TO_CORRECT;
686
            } else {
687 8dced1c9 galberding
              newState = states::RELEASE_TO_CORRECT; //states::CORRECT_POSITIONING;
688 27d4e1fa galberding
            }
689
690
            if (utCount.errorCount > DOCKING_ERROR_THRESH){
691 10bf9cc0 galberding
              newState = states::DOCKING_ERROR;
692 61544eee galberding
            }
693 ba75ee1d galberding
          }
694
        }
695 10bf9cc0 galberding
      break;
696 019224ff galberding
      // ---------------------------------------
697 e404e6c0 galberding
    case states::RELEASE_TO_CORRECT:
698 8dced1c9 galberding
699 019224ff galberding
        global.distcontrol.setTargetPosition(0, ROTATION_20, ROTATION_DURATION);
700
        checkForMotion();
701
        // move 1cm forward
702
        global.distcontrol.setTargetPosition(5000, 0, ROTATION_DURATION);
703
        checkForMotion();
704
        // rotate back
705
        global.distcontrol.setTargetPosition(0, -2*ROTATION_20, ROTATION_DURATION);
706
        checkForMotion();
707
708 10bf9cc0 galberding
        global.distcontrol.setTargetPosition(1500, 0, ROTATION_DURATION);
709 019224ff galberding
        checkForMotion();
710
        newState = states::CORRECT_POSITIONING;
711 10bf9cc0 galberding
      break;
712 27d4e1fa galberding
      // ---------------------------------------
713 e404e6c0 galberding
    case states::CHARGING:
714 27d4e1fa galberding
        global.motorcontrol.setMotorEnable(false);
715 10bf9cc0 galberding
        utCount.errorCount = 0;
716 181f2892 galberding
        // Formulate Request to enable charging
717
        if(/* checkPinVoltage() && */ !checkPinEnabled()){
718
          global.robot.requestCharging(1);
719
        }
720
        if(checkPinEnabled()){
721
          showChargingState();
722
        }
723 10bf9cc0 galberding
      break;
724 181f2892 galberding
      // ---------------------------------------
725 e404e6c0 galberding
    case states::RELEASE:
726 61544eee galberding
      if (global.forwardSpeed != DETECTION_SPEED){
727
          global.rpmForward[0] = DETECTION_SPEED;
728
        }
729 181f2892 galberding
        if(/* checkPinVoltage() && */ checkPinEnabled()){
730
          global.robot.requestCharging(0);
731
        }else{
732 27d4e1fa galberding
          global.motorcontrol.setMotorEnable(true);
733 8dced1c9 galberding
          // TODO: Use controlled
734 181f2892 galberding
          //Rotate -20° to free from magnet
735
          global.distcontrol.setTargetPosition(0, ROTATION_20, ROTATION_DURATION);
736 61544eee galberding
          checkForMotion();
737
          // move 1cm forward
738
          global.distcontrol.setTargetPosition(5000, 0, ROTATION_DURATION);
739
          checkForMotion();
740
          // rotate back
741 10bf9cc0 galberding
          // global.distcontrol.setTargetPosition(0, -ROTATION_20, ROTATION_DURATION);
742
          // checkForMotion();
743 019224ff galberding
744 61544eee galberding
          // global.distcontrol.setTargetPosition(5000, 0, ROTATION_DURATION);
745
          // checkForMotion();
746 181f2892 galberding
          lStrategy = LineFollowStrategy::EDGE_RIGHT;
747
          newState = states::FOLLOW_LINE;
748 61544eee galberding
            // whiteBuf = -100;
749
          // lf.followLine(rpmSpeed);
750
          // setRpmSpeed(rpmSpeed);
751 181f2892 galberding
        }
752 61544eee galberding
        // lightAllLeds(Color::BLACK);
753 10bf9cc0 galberding
      break;
754
      // ---------------------------------------
755 e404e6c0 galberding
    case states::DOCKING_ERROR:
756
      newState = states::RELEASE;
757 10bf9cc0 galberding
      break;
758
      // ---------------------------------------
759 e404e6c0 galberding
    case states::REVERSE_TIMEOUT_ERROR:
760
      newState = states::IDLE;
761 10bf9cc0 galberding
      break;
762
      // ---------------------------------------
763 e404e6c0 galberding
    case states::CALIBRATION_ERROR:
764
      newState = states::IDLE;
765 10bf9cc0 galberding
      break;
766
      // ---------------------------------------
767 e404e6c0 galberding
    case states::WHITE_DETECTION_ERROR:
768
      newState = states::IDLE;
769 10bf9cc0 galberding
      break;
770
      // ---------------------------------------
771 e404e6c0 galberding
    case states::PROXY_DETECTION_ERROR:
772
      newState = states::IDLE;
773 10bf9cc0 galberding
      break;
774
      // ---------------------------------------
775 e404e6c0 galberding
    case states::NO_CHARGING_POWER_ERROR:
776
      newState = states::IDLE;
777 10bf9cc0 galberding
      break;
778
      // ---------------------------------------
779 e404e6c0 galberding
    case states::UNKNOWN_STATE_ERROR:
780 10bf9cc0 galberding
        newState = states::IDLE;
781
      break;
782
      // ---------------------------------------
783 e404e6c0 galberding
    case states::TEST_MAP_STATE:{
784
      /* Test suit for amiro map */
785
786
787
      setAttributes(global.testmap, 0, 1, 2, 1);
788
      setAttributes(global.testmap, 1, 2, 2, 0);
789
      setAttributes(global.testmap, 2, 1, 0, 0);
790
      setAttributes(global.testmap, 3, 0, 0, 0xff);
791
      // AmiroMap map = AmiroMap(&global);
792
793
    //   // --------------------------------------------------
794
795
      global.tcase = 0;
796
      map.initialize();
797
      global.testres[global.tcase] = map.get_state()->valid;
798
799
        global.tcase++; // 1
800
      setAttributes(global.testmap, 0, 1, 2, 0xff);
801
      map.initialize();
802
      global.testres[global.tcase] = !map.get_state()->valid;
803
804
      global.tcase++; // 2
805
      setAttributes(global.testmap, 0, 1, 2, 0);
806
      setAttributes(global.testmap, 2, 1, 0, 1);
807
      map.initialize();
808
      global.testres[global.tcase] = map.get_state()->current == 2;
809
810
      global.tcase++; // 3
811
      setAttributes(global.testmap, 3, 0, 0, 0);
812
      setAttributes(global.testmap, 4, 0, 0, 0xff);
813
      map.initialize();
814
      global.testres[global.tcase] = !map.get_state()->valid;
815
816
      int failed = 0;
817
      int passed = 0;
818
      for (int i = 0; i <= global.tcase; i++) {
819
        if (global.testres[i]) {
820
          passed++;
821
          chprintf((BaseSequentialStream *)&global.sercanmux1,
822
                   "Test %d Passed!\n", i);
823
        } else {
824
          failed++;
825
          chprintf((BaseSequentialStream *)&global.sercanmux1,
826
                   "Test %d Failed\n", i);
827
        }
828 27d4e1fa galberding
      }
829 e404e6c0 galberding
      chprintf((BaseSequentialStream *)&global.sercanmux1,
830
               "Total: %d, Passed: %d, Failed: %d\n", global.tcase + 1, passed,
831
               failed);
832
833
      newState = states::IDLE;
834
      break;
835
    }
836
      // --------------------------------------------------
837
    default:
838
      newState = states::UNKNOWN_STATE_ERROR;
839
      break;
840
    }
841
842
    if (currentState != newState){
843
      chprintf((BaseSequentialStream*)&global.sercanmux1, "Transmit state %d\n", newState);
844
      global.robot.transmitState(newState);
845
    //   if (newState == states::IDLE)
846
    //     {global.stateTracker[states::IDLE] += 1;}
847
    //   else if (newState == states::FOLLOW_LINE)
848
    //     {global.stateTracker[states::FOLLOW_LINE] += 1;}
849
    //   else if (newState == states::DETECT_STATION)
850
    //     {global.stateTracker[states::DETECT_STATION] += 1;}
851
    //   else if (newState == states::REVERSE)
852
    //     {global.stateTracker[states::REVERSE] += 1;}
853
    //   else if (newState == states::PUSH_BACK)
854
    //     {global.stateTracker[states::PUSH_BACK] += 1;}
855
    //   else if (newState == states::CHECK_POSITIONING)
856
    //     {global.stateTracker[states::CHECK_POSITIONING] += 1;}
857
    //   else if (newState == states::CHECK_VOLTAGE)
858
    //     {global.stateTracker[states::CHECK_VOLTAGE] += 1;}
859
    //   else if (newState == states::CHARGING)
860
    //     {global.stateTracker[states::CHARGING] += 1;}
861
    //   else if (newState == states::RELEASE)
862
    //     {global.stateTracker[states::RELEASE] += 1;}
863
    //   else if (newState == states::RELEASE_TO_CORRECT)
864
    //     {global.stateTracker[states::RELEASE_TO_CORRECT] += 1;}
865
    //   else if (newState == states::CORRECT_POSITIONING)
866
    //     {global.stateTracker[states::CORRECT_POSITIONING] += 1;}
867
    //   else if (newState == states::TURN)
868
    //     {global.stateTracker[states::TURN] += 1;}
869
    //   else if (newState == states::INACTIVE)
870
    //     {global.stateTracker[states::INACTIVE] += 1;}
871
    //   else if (newState == states::CALIBRATION)
872
    //     {global.stateTracker[states::CALIBRATION] += 1;}
873
    //   else if (newState == states::CALIBRATION_CHECK)
874
    //     {global.stateTracker[states::CALIBRATION_CHECK] += 1;}
875
    //   else if (newState == states::DEVIATION_CORRECTION)
876
    //     {global.stateTracker[states::DEVIATION_CORRECTION] += 1;}
877
    //   else if (newState == states::DOCKING_ERROR)
878
    //     {global.stateTracker[16+(-states::DOCKING_ERROR)] += 1;}
879
    //   else if (newState == states::REVERSE_TIMEOUT_ERROR)
880
    //     {global.stateTracker[16+(-states::REVERSE_TIMEOUT_ERROR)] += 1;}
881
    //   else if (newState == states::CALIBRATION_ERROR)
882
    //     {global.stateTracker[16+(-states::CALIBRATION_ERROR)] += 1;}
883
    //   else if (newState == states::WHITE_DETECTION_ERROR)
884
    //     {global.stateTracker[16+(-states::WHITE_DETECTION_ERROR)] += 1;}
885
    //   else if (newState == states::PROXY_DETECTION_ERROR)
886
    //     {global.stateTracker[16+(-states::PROXY_DETECTION_ERROR)] += 1;}
887
    //   else if (newState == states::NO_CHARGING_POWER_ERROR)
888
    //     {global.stateTracker[16+(-states::NO_CHARGING_POWER_ERROR)] += 1;}
889
    //   else if (newState == states::UNKNOWN_STATE_ERROR)
890
    //     {global.stateTracker[16+(-states::UNKNOWN_STATE_ERROR)] += 1;}
891
    }
892
    prevState = currentState;
893
    currentState = newState;
894
895 5d138bca galberding
    this->sleep(CAN::UPDATE_PERIOD);
896
  }
897 58fe0e0b Thomas Schöpping
898
  return RDY_OK;
899
}