#include "common.h"
#include "gpio_init.h"
#include "ship0301_control.h"

void ship0301_stop() {
    pwmWrite(PWM_PIN_SPEED,75);
    pwmWrite(PWM_PIN_CHANGE,75);
}

void ship0301_mode_lift_flont(unsigned char gval) {
	int b=0;
   if (gval < 50) {
		pwmWrite(PWM_PIN_SPEED, 75);
	}
	else if (gval <= 60) {
		pwmWrite(PWM_PIN_SPEED, 79);
	}else if (gval <= 70) {
		pwmWrite(PWM_PIN_SPEED, 80);
	}else if(gval >70){
		int flont_speed = 80+(gval-70)/10+b;
		if(flont_speed>95) flont_speed = 95;
		pwmWrite(PWM_PIN_SPEED, flont_speed);
	}
}

void ship0301_mode_lift_back(unsigned char gval) {
	int b=0;
	if (gval < 50) {
		pwmWrite(PWM_PIN_SPEED, 75);
	} else if (gval <= 60) {
		pwmWrite(PWM_PIN_SPEED, 71);
	}else if (gval <= 70) {
		pwmWrite(PWM_PIN_SPEED, 70);
	} else if(gval >70){
		int back_speed = 70 - (gval-70)/10-b;
		if(back_speed<55) back_speed =55;
		pwmWrite(PWM_PIN_SPEED, back_speed);
	}  
}

void ship0301_mode_right_back(unsigned char gval) {
	int b=0;
   if (gval < 50) {
		pwmWrite(PWM_PIN_CHANGE, 75);
	}else if (gval <= 60) {
		pwmWrite(PWM_PIN_CHANGE, 79);
	}else if (gval <= 70) {
		pwmWrite(PWM_PIN_CHANGE, 80);
	}else if(gval >70){
		int flont_speed = 80+(gval-70)/10+b;
		if(flont_speed>95) flont_speed = 95;
		pwmWrite(PWM_PIN_CHANGE, flont_speed);
	}
}

void ship0301_mode_right_flont(unsigned char gval) {
	int b=0;
	if (gval < 50) {
		pwmWrite(PWM_PIN_CHANGE, 75);
	}else if (gval <= 60) {
		pwmWrite(PWM_PIN_CHANGE, 71);
	} else if (gval <= 70) {
		pwmWrite(PWM_PIN_CHANGE, 70);
	} else if(gval >70){
		int back_speed = 70 - (gval-70)/10-b;
		if(back_speed<55) back_speed =55;
		pwmWrite(PWM_PIN_CHANGE, back_speed);
	}
}


void  ship0301_change(unsigned char *buf) {
    unsigned char mode = buf[1];
    unsigned char val = buf[2];
	static int modecount_ship0301;
    if(mode == 1 ) {
        //mode_lift_flont(val);
        ship0301_mode_right_flont(val);
		modecount_ship0301=0;
    }else if(mode == 2 ) {
        //mode_lift_back(val);
        ship0301_mode_right_back(val);
		modecount_ship0301=1;
    }
	
	if((mode == 1||mode ==2)&&val == 0) modecount_ship0301=0;

	if(mode == 3) {
        if(modecount_ship0301 == 0) ship0301_mode_lift_back(val+15);
        if(modecount_ship0301 == 1) ship0301_mode_lift_flont(val+15);
    }else if(mode == 4) {
        if(modecount_ship0301 == 0) ship0301_mode_lift_flont(val+15);
        if(modecount_ship0301 == 1) ship0301_mode_lift_back(val+15);
    }
    
}