CIS441 Proj MS 2b

Dependencies:   TextLCD MQTT

AccCar.cpp

Committer:
kchen7
Date:
2019-12-13
Revision:
16:cb7cbf2cc23b
Parent:
8:c40e805eecba

File content as of revision 16:cb7cbf2cc23b:

#include "AccCar.h"
#include <stdlib.h>
#include <algorithm>

#define TICK 1000
#define MONITOR_DIST 17
#define SAFETY_GAP 2

AccCar::AccCar(int id, Road* road, int flag) {
    this->id = id;
    this->road = road;
    this->flag = flag;
    
    waited = false;
        
    this->thread = NULL;
}

void AccCar::set_forward_car(AccCar* car) {
    this->forward_car = car;   
}

void AccCar::set_target_speed(int speed) {
    this->target_speed = speed;
    this->speed = speed;   
}

void AccCar::update() {
    do {
        ThisThread::sleep_for(TICK);
        road->go_flags.wait_all(flag);
        cycle++;
                
        position = position + speed;
        
        if (cycle % 5 == 0) {
            target_speed = rand() % 11 + 5;
        }
        
        if (forward_car != NULL && forward_car->position > -1) {
            if (forward_car->position - position < MONITOR_DIST) {
                road->done_flags.wait_all(forward_car->flag, osWaitForever, false);
                
                int diff = forward_car->position - position;
                int maxSafeSpeed = diff - SAFETY_GAP;
                
                speed = std::min(maxSafeSpeed, target_speed);
            } else {
                speed = target_speed;   
            }
        } else {
            speed = target_speed;
        }

        road->done_flags.set(flag);   
    } while( position < 100 );
}

void AccCar::reset() {
    road->done_flags.clear(flag);
    
    if (thread != NULL) {
        thread->terminate();   
    }
    
    thread = new Thread();
    thread->start( callback(this, &AccCar::update) );
    
    this->position = 0;
    this->cycle = 0;
}