<commit_before>#!/usr/bin/python
import time, threading, json, logging, tornado.websocket, modules.calc, math, modules.utils, modules.log, socket, sys
from modules.server import ServerThread
from modules.location import Location
from modules.calc import direction_to_point
from modules.control_thread import StoppableThread

# Variables and constants
data = {'category': 'data', 'timestamp': 0, 'location': Location(0, 0),
        'heading': 0, 'speed': 0, 'wind_dir': 0, 'roll': 0, 'pitch': 0,
        'yaw': 0}

target_locations = []
boundary_locations = []
location_pointer = 0

# Specifies the default values
values = {'event': 'default', 'debug': False, 'port': 80, 'transmission_delay': 5, 'eval_delay': 5, 'current_desired_heading': 0,
          'direction': 0, 'absolute_wind_direction': 0, 'max_turn_rate_angle': 70, 'max_rudder_angle': 40, 'max_winch_angle': 70,
          'tack_angle': 45, 'gybe_angle': 20}

## ----------------------------------------------------------
    
class DataThread(StoppableThread):

    """ Transmits the data object to the server thread
    """

    server_thread = None
    rudder_sock = None
    winch_sock = None

    def __init__(self, *args, **kwargs):
        super(DataThread, self).__init__(*args, **kwargs)

        global server_thread
        server_thread = ServerThread(name='Server', kwargs={'port': values['port'], 'target_locations': target_locations, 'boundary_locations': boundary_locations})
        server_thread.start()

        global rudder_sock
        try:
            rudder_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            rudder_sock.connect(("localhost", 9107))
        except socket.error:
            # Connection refused error
            logging.critical("Could not connect to servo socket")

        global winch_sock
        try:
            winch_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            winch_sock.connect(("localhost", 9108))
        except socket.error:
            # Connection refused error
            logging.critical("Could not connect to servo socket")


        # Set up logging to the web server console
        logging.getLogger().addHandler(modules.log.WebSocketLogger(self))

    def set_rudder_angle(self, angle):
        try:
            rudder_sock.send(str(angle).encode('utf-8'))
        except socket.error:
            # Broken Pipe Error
            logging.error('The rudder socket is broken!')

    def set_winch_angle(self, angle):
        try:
            winch_sock.send(str(angle).encode('utf-8'))
        except socket.error:
            # Broken Pipe Error
            logging.error('The winch socket is broken!')

    def send_data(self, data):

        # do not log any data here, doing so would create an infinite loop
        try:
            server_thread.send_data(data)
        except tornado.websocket.WebSocketClosedError:
            print('Could not send data because the socket is closed.')

    def run(self):
        
        logging.info('Starting the data thread!')
        
        # Connect to the GPS socket
        try:
            gps_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            gps_sock.connect(("localhost", 8907))
        except socket.error:
            # Connection refused error
            logging.critical("Could not connect to GPS socket")

        # Connect to the wind sensor socket
        try:
            wind_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            wind_sock.connect(("localhost", 8894))
        except socket.error:
            logging.critical("Could not connect to wind sensor socket")
        
        while True:

            if self.stopped():
                # Stop the server thread
                server_thread.stop()
                break
            
            # Query and update the GPS data
            try:
                gps_sock.send(str(0).encode('utf-8'))
                gps_parsed = json.loads(gps_sock.recv(128).decode('utf-8').strip('\x00'))

                # Update the data object
                data.update(gps_parsed)

                # Add the location as an embeded data structure
                data['location'] = Location(gps_parsed['latitude'], gps_parsed['longitude'])

                data['heading'] = 180
                
            except (AttributeError, ValueError, socket.error) as e:
                logging.error('The GPS socket is broken or sent malformed data!')
 
            # Query and update the wind sensor data
            try:
                wind_sock.send(str(0).encode('utf-8'))
                wind_parsed = json.loads(wind_sock.recv(1024).decode('utf-8'))
                data['wind_dir'] = wind_parsed
            except (ValueError, socket.error) as e:
                # Broken pipe error
                logging.error('The wind sensor socket is broken!')

            # Send data to the server
            server_thread.send_data(modules.utils.getJSON(data))
            logging.debug('Data sent to the server %s' % json.dumps(json.loads(modules.utils.getJSON(data))))

            # Wait in the loop
            time.sleep(float(values['transmission_delay']))


## ----------------------------------------------------------

class LogicThread(StoppableThread):

    preferred_tack = 0 # -1 means left tack and 1 means right tack; 0 not on a tack
    preferred_gybe = 0 # -1 means left-of-wind gybe and 1 means right-of-wind gybe; 0 not on a gybe
    
    def run(self):
        logging.info("Beginning autonomous navigation routines....")
        logging.warn("The angle is: %d" % data['wind_dir'])


        if (values['event'] == 'default'):
            self.run_default()

        elif (values['event'] == 'station_keeping')
            self.run_station_keeping()



    def station_keeping(self):
        while True:

            if self.stopped():
                break    
    
    def run_default(self):
        while True:
<commit_msg>Minor logging changes<commit_after>#!/usr/bin/python
import time, threading, json, logging, tornado.websocket, modules.calc, math, modules.utils, modules.log, socket, sys
from modules.server import ServerThread
from modules.location import Location
from modules.calc import direction_to_point
from modules.control_thread import StoppableThread

# Variables and constants
data = {'category': 'data', 'timestamp': 0, 'location': Location(0, 0),
        'heading': 0, 'speed': 0, 'wind_dir': 0, 'roll': 0, 'pitch': 0,
        'yaw': 0}

target_locations = []
boundary_locations = []
location_pointer = 0

# Specifies the default values
values = {'event': 'default', 'debug': False, 'port': 80, 'transmission_delay': 5, 'eval_delay': 5, 'current_desired_heading': 0,
          'direction': 0, 'absolute_wind_direction': 0, 'max_turn_rate_angle': 70, 'max_rudder_angle': 40, 'max_winch_angle': 70,
          'tack_angle': 45, 'gybe_angle': 20}

## ----------------------------------------------------------
    
class DataThread(StoppableThread):

    """ Transmits the data object to the server thread
    """

    server_thread = None
    rudder_sock = None
    winch_sock = None

    def __init__(self, *args, **kwargs):
        super(DataThread, self).__init__(*args, **kwargs)

        global server_thread
        server_thread = ServerThread(name='Server', kwargs={'port': values['port'], 'target_locations': target_locations, 'boundary_locations': boundary_locations})
        server_thread.start()

        global rudder_sock
        try:
            rudder_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            rudder_sock.connect(("localhost", 9107))
        except socket.error:
            # Connection refused error
            logging.critical("Could not connect to servo socket")

        global winch_sock
        try:
            winch_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            winch_sock.connect(("localhost", 9108))
        except socket.error:
            # Connection refused error
            logging.critical("Could not connect to servo socket")


        # Set up logging to the web server console
        logging.getLogger().addHandler(modules.log.WebSocketLogger(self))

    def set_rudder_angle(self, angle):
        try:
            rudder_sock.send(str(angle).encode('utf-8'))
        except socket.error:
            # Broken Pipe Error
            logging.error('The rudder socket is broken!')

    def set_winch_angle(self, angle):
        try:
            winch_sock.send(str(angle).encode('utf-8'))
        except socket.error:
            # Broken Pipe Error
            logging.error('The winch socket is broken!')

    def send_data(self, data):

        # do not log any data here, doing so would create an infinite loop
        try:
            server_thread.send_data(data)
        except tornado.websocket.WebSocketClosedError:
            print('Could not send data because the socket is closed.')

    def run(self):
        
        logging.info('Starting the data thread!')
        
        # Connect to the GPS socket
        try:
            gps_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            gps_sock.connect(("localhost", 8907))
        except socket.error:
            # Connection refused error
            logging.critical("Could not connect to GPS socket")

        # Connect to the wind sensor socket
        try:
            wind_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            wind_sock.connect(("localhost", 8894))
        except socket.error:
            logging.critical("Could not connect to wind sensor socket")
        
        while True:

            if self.stopped():
                # Stop the server thread
                server_thread.stop()
                break
            
            # Query and update the GPS data
            try:
                gps_sock.send(str(0).encode('utf-8'))
                gps_parsed = json.loads(gps_sock.recv(128).decode('utf-8').strip('\x00'))

                # Update the data object
                data.update(gps_parsed)

                # Add the location as an embeded data structure
                data['location'] = Location(gps_parsed['latitude'], gps_parsed['longitude'])

                data['heading'] = 180
                
            except (AttributeError, ValueError, socket.error) as e:
                logging.error('The GPS socket is broken or sent malformed data!')
 
            # Query and update the wind sensor data
            try:
                wind_sock.send(str(0).encode('utf-8'))
                wind_parsed = json.loads(wind_sock.recv(1024).decode('utf-8'))
                data['wind_dir'] = wind_parsed
            except (ValueError, socket.error) as e:
                # Broken pipe error
                logging.error('The wind sensor socket is broken!')

            # Send data to the server
            server_thread.send_data(modules.utils.getJSON(data))
            logging.debug('Data sent to the server %s' % json.dumps(json.loads(modules.utils.getJSON(data))))

            # Wait in the loop
            time.sleep(float(values['transmission_delay']))


## ----------------------------------------------------------

class LogicThread(StoppableThread):

    preferred_tack = 0 # -1 means left tack and 1 means right tack; 0 not on a tack
    preferred_gybe = 0 # -1 means left-of-wind gybe and 1 means right-of-wind gybe; 0 not on a gybe
    
    def run(self):
        logging.info("Beginning autonomous navigation routines....")
        logging.warn("The angle is: %d" % data['wind_dir'])

        if (values['event'] == 'default'):
            logging.info("Starting the default event!")
            self.run_default()

        elif (values['event'] == 'station_keeping'):
            logging.info("Starting the station keeping event!")
            self.run_station_keeping()

    def station_keeping(self):
        while True:

            if self.stopped():
                break    
    
    def run_default(self):
        while True:

{'fraction_non_alphanumeric': 0.12271518777002326, 'fraction_numerical': 0.011797939514788967, 'mean_word_length': 2.1208192896033187, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '761225', 'n_tokens_mistral': 3436, 'n_tokens_neox': 3200, 'n_words': 887}