/**************************************************************************
Function Name   - auto_track 
Parameters      - p_rotor --a pointer to a rotor structure.

Responsibility  - Bring a rotor's actual bearing in line with the data
                  form the satellite tracking software running on a 
                  separate PC.

                  Since this function operates on a rotor structure it can
                  be used for both the axmith and elevation rotors by passing
                  in pointers to each in separate calls.
                
Notes           -
Returns         - Nothing
Status          - Testing in progress
Author          - Bill (N9CX)
**************************************************************************/
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <avr/eeprom.h>

#include "sw_timers.h"
#include "uart_getchar.h"
#include "switches.h"
#include "main.h"
#define LOCAL
#include "auto_track.h"
#include "rotor.h"

#define AZ_TOLERANCE 5

extern FILE uart_out;

char parse_rx_buffer(void);
char novacomm1_parser(char *cptr, int);

void auto_track(struct rotor *p_rotor){

    if(p_rotor->wait) return;

    int tmp;

    tmp = p_rotor->bearing - p_rotor->auto_bearing;
    if(p_rotor->moving){
        delta_bearing = tmp;
    }
    else if(tmp >= AZ_TOLERANCE || tmp <= -AZ_TOLERANCE){
        delta_bearing = tmp;
    }
    else delta_bearing = 0;

    if(delta_bearing > 0){
        if(!p_rotor->moving && p_rotor->limit != CCW){
            p_rotor->pulse_timer = PULSE_TIMEOUT;
            p_rotor->limit = FALSE;
            p_rotor->pwr_ctl(p_rotor, PWR_CCW);
        }
        // We are moving but in the proper direction?
        else if(p_rotor->cw) {
            //wrong direction
            p_rotor->pwr_ctl(p_rotor, PWR_OFF);
            //This is so we won't yank the antenna around
            p_rotor->wait = 400;
            // We will correct the direction when the "wait' expires
            // since the rotor will not be moving.
        }
    }
    else if (delta_bearing < 0){
        if(!p_rotor->moving && p_rotor->limit != CW){
            p_rotor->pulse_timer = PULSE_TIMEOUT;
            p_rotor->limit = FALSE;
            p_rotor->pwr_ctl(p_rotor, PWR_CW);
        }
        else {
            if(p_rotor->ccw) {
                //wrong direction
                p_rotor->pwr_ctl(p_rotor, PWR_OFF);
                p_rotor->wait = 400;
            }
        }
    }
    // distance is 0
    else if(p_rotor->moving){
        p_rotor->pwr_ctl(p_rotor, PWR_OFF);
        request_lcd_refresh = TRUE;
    }
    //Have we hit any hardware limit stops?
    if(p_rotor->limit && p_rotor->moving){
        p_rotor->pwr_ctl(p_rotor, PWR_OFF);
        request_lcd_refresh = TRUE;
        p_rotor->pulse_timer = PULSE_TIMEOUT;
        request_lcd_refresh = TRUE;
        mode = MANUAL;
    }
}

