<commit_before>//
// sim.cpp
//
// Program to read the contents of a GTC file
//
// $Id: sim.cpp 1354 2010-11-11 16:20:09Z js10 $
//
// Copyright (c) 2009 - 2010 Genome Research Ltd.
//
// Author: Jennifer Liddle <js10@sanger.ac.uk, jennifer@jsquared.co.uk>
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the Genome Research Ltd nor the names of its contributors
// may be used to endorse or promote products derived from software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. EVENT SHALL GENOME RESEARCH LTD. BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

#include <iostream>
#include <vector>
#include <map>
#include "stdlib.h"

#include "Sim.h"

using namespace std;

int main(int argc, char *argv[])
{
  // Simple executable to demonstrate use of the .sim class
  // Similar functionality to "simtools view"

        if (argc!=3) {
	  cout << "Usage: " << argv[0] << " [path to .sim file] "
	       << "[max intensities to display per sample]" << endl;
	  exit(1);
	}
	Sim *sim = new Sim();
	string m;
	cout << endl << "Reading SIM file: " << argv[1] << endl;
	try { sim->openInput(argv[1]); }
	catch (string m) { cout << m << endl; }

	int maxDisplay;
	maxDisplay = atoi(argv[2]);

	cout << "Magic:     " << sim->magic << endl;
	cout << "Version:   " << (int)sim->version << endl;
	cout << "Name Size: " << sim->sampleNameSize << endl;
	cout << "Samples:   " << sim->numSamples << endl;
	cout << "Probes:    " << sim->numProbes << endl;
	cout << "Channels:  " << (int)sim->numChannels << endl;
	cout << "Format:    " << (int)sim->numberFormat << endl;

	cout << endl;
	char *sampleName = new char[sim->sampleNameSize+1];

	uint16_t *intensity_int =
	  (uint16_t *) calloc(sim->sampleIntensityTotal, sizeof(uint16_t));
	float *intensity_float =
	  (float *) calloc(sim->sampleIntensityTotal, sizeof(float));

	unsigned int i;
	int j;
	int displayTotal = min(sim->sampleIntensityTotal, maxDisplay);
	for (i=0; i < sim->numSamples; i++) {
		if (sim->numberFormat == 0) {
		  sim->getNextRecord(sampleName, intensity_float);
		} else {
		  sim->getNextRecord(sampleName, intensity_int);
		}
		cout << sampleName << "\t: ";
		for (j=0; j<displayTotal; j++) {
		  if (sim->numberFormat == 0) {
		    cout << intensity_float[j] << " ";
		  } else {
		    cout << intensity_int[j] << " ";
		  }
		}
		cout << endl;
	}
	free(intensity_int);
	free(intensity_float);
	return 0;
}

<commit_msg>Report non-numeric values<commit_after>//
// sim.cpp
//
// Program to read the contents of a GTC file
//
// $Id: sim.cpp 1354 2010-11-11 16:20:09Z js10 $
//
// Copyright (c) 2009 - 2010 Genome Research Ltd.
//
// Author: Jennifer Liddle <js10@sanger.ac.uk, jennifer@jsquared.co.uk>
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the Genome Research Ltd nor the names of its contributors
// may be used to endorse or promote products derived from software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. EVENT SHALL GENOME RESEARCH LTD. BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

#include <iostream>
#include <vector>
#include <map>
#include "stdlib.h"
#include "Sim.h"

using namespace std;

int main(int argc, char *argv[])
{
  // Simple executable to demonstrate use of the .sim class
  // Similar functionality to "simtools view"

        if (argc!=3) {
	  cout << "Usage: " << argv[0] << " [path to .sim file] "
	       << "[max intensities to display per sample]" << endl;
	  exit(1);
	}
	Sim *sim = new Sim();
	string m;
	cout << endl << "Reading SIM file: " << argv[1] << endl;
	try { sim->openInput(argv[1]); }
	catch (string m) { cout << m << endl; }

	int maxDisplay;
	maxDisplay = atoi(argv[2]);

	cout << "Magic:     " << sim->magic << endl;
	cout << "Version:   " << (int)sim->version << endl;
	cout << "Name Size: " << sim->sampleNameSize << endl;
	cout << "Samples:   " << sim->numSamples << endl;
	cout << "Probes:    " << sim->numProbes << endl;
	cout << "Channels:  " << (int)sim->numChannels << endl;
	cout << "Format:    " << (int)sim->numberFormat << endl;

	cout << endl;
	char *sampleName = new char[sim->sampleNameSize+1];

	uint16_t *intensity_int =
	  (uint16_t *) calloc(sim->sampleIntensityTotal, sizeof(uint16_t));
	float *intensity_float =
	  (float *) calloc(sim->sampleIntensityTotal, sizeof(float));

	unsigned int i;
	int j;
	int displayTotal = min(sim->sampleIntensityTotal, maxDisplay);
	for (i=0; i < sim->numSamples; i++) {
		if (sim->numberFormat == 0) {
		  sim->getNextRecord(sampleName, intensity_float);
		} else {
		  sim->getNextRecord(sampleName, intensity_int);
		}
		cout << sampleName << "\t: ";
		for (j=0; j<displayTotal; j++) {
		  if (sim->numberFormat == 0) {
		    cout << intensity_float[j] << " ";
		  } else {
		    cout << intensity_int[j] << " ";
		  }
		}
		cout << endl;
	}
	sim -> reportNonNumeric();
	free(intensity_int);
	free(intensity_float);
	sim->close();
	delete sim;
	return 0;
}

<|endoftext|>


<commit_before>#include "InputSystem.hpp"
#include "WindowSystem.hpp"

using namespace crimild;

InputSystem::InputSystem( void )
	: System( "Input System" )
{
    auto self = this;

    registerMessageHandler< messages::WindowSystemDidCreateWindow >( [self]( messages::WindowSystemDidCreateWindow const &message ) {
        self->_window = message.video->getWindowHandler();

        Input::getInstance()->reset( GLFW_KEY_LAST, GLFW_MOUSE_BUTTON_LAST );

        glfwSetKeyCallback( self->_window, []( GLFWwindow* window, int key, int scancode, int action, int mods ) {
            if ( Console::getInstance()->isEnabled() ) {
                if ( action == GLFW_PRESS ) {
                    switch ( key ) {
                        case CRIMILD_INPUT_KEY_BACKSPACE:
                        case CRIMILD_INPUT_KEY_UP:
                        case CRIMILD_INPUT_KEY_DOWN:
                        case CRIMILD_INPUT_KEY_ENTER:
                            Console::getInstance()->handleInput( key, mods );
                            break;

                        default:
                            break;
                    }
                }

                if ( Console::getInstance()->isActive() ) {
                    return;
                }
            }

            if ( action == GLFW_PRESS || action == GLFW_REPEAT ) {
                MessageQueue::getInstance()->pushMessage( messaging::KeyPressed { key } );
            }
            else {
                MessageQueue::getInstance()->pushMessage( messaging::KeyReleased { key } );
            }
        });

        glfwSetCharCallback( self->_window, []( GLFWwindow *window, unsigned int codepoint ) {
            if ( Console::getInstance()->isEnabled() ) {
                Console::getInstance()->handleInput( codepoint, 0 );
            }
        });

        /*
        glfwSetCursorPosCallback( self->_window, []( GLFWwindow* window, double xpos, double ypos ) {
            int windowWidth, windowHeight;
            glfwGetWindowSize( window, &windowWidth, &windowHeight );

            MessageQueue::getInstance()->pushMessage( messaging::MouseMotion {
                ( float ) xpos,
                ( float ) ypos,
                ( float ) xpos / ( float ) windowWidth,
                ( float ) ypos / ( float ) windowHeight
            });
        });
        */

        glfwSetMouseButtonCallback( self->_window, []( GLFWwindow* window, int button, int action, int mods ) {
            double x, y;
            glfwGetCursorPos( window, &x, &y );

            if ( action == GLFW_PRESS ) {
                MessageQueue::getInstance()->pushMessage( messaging::MouseButtonDown { button } );
            }
            else {
                MessageQueue::getInstance()->pushMessage( messaging::MouseButtonUp { button } );
            }
        });

        glfwSetScrollCallback( self->_window, []( GLFWwindow* window, double xoffset, double yoffset ) {
            MessageQueue::getInstance()->pushMessage( messaging::MouseScroll { ( float ) xoffset, ( float ) yoffset } );
        });

        crimild::concurrency::sync_frame( std::bind( &InputSystem::update, self ) );
    });

    registerMessageHandler< messages::WindowSystemWillDestroyWindow >( [&]( messages::WindowSystemWillDestroyWindow const &message ) {
        _window = nullptr;
    });
}

InputSystem::~InputSystem( void )
{

}

bool InputSystem::start( void )
{
	if ( !System::start() ) {
		return false;
	}

    return true;
}

void InputSystem::update( void )
{
    CRIMILD_PROFILE( "Update Input" )

    if ( _window == nullptr ) {
        return;
    }

    switch ( Input::getInstance()->getMouseCursorMode() ) {
        case Input::MouseCursorMode::NORMAL:
            glfwSetInputMode( _window, GLFW_CURSOR, GLFW_CURSOR_NORMAL );
            break;

        case Input::MouseCursorMode::HIDDEN:
            glfwSetInputMode( _window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN );
            break;

        case Input::MouseCursorMode::GRAB:
            glfwSetInputMode( _window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );
            break;

        default:
            break;
    }

    // trigger MouseMotion in every update to handle cases
    // when the mouse is not moving and the delta pos should
    // be updated
    int windowWidth, windowHeight;
    double x, y;
    glfwGetWindowSize( _window, &windowWidth, &windowHeight );
    glfwGetCursorPos( _window, &x, &y );

    MessageQueue::getInstance()->pushMessage( messaging::MouseMotion {
        ( float ) x,
        ( float ) y,
        ( float ) x / ( float ) windowWidth,
        ( float ) y / ( float ) windowHeight
    });

	std::vector< float > axes;
	auto joyPresent = glfwJoystickPresent(GLFW_JOYSTICK_1);
	if (joyPresent == 1) {
		int axesCount;
		const float *axesData = glfwGetJoystickAxes( GLFW_JOYSTICK_1, &axesCount );
		for ( int i = 0; i < axesCount; i++ ) {
			axes.push_back( axesData[ i ] );
		}
	}
	Input::getInstance()->resetJoystickAxes( axes );

    crimild::concurrency::sync_frame( std::bind( &InputSystem::update, this ) );
}

void InputSystem::stop( void )
{
	System::stop();
}

<commit_msg>Fixed unknown key handling problem in Input<commit_after>#include "InputSystem.hpp"
#include "WindowSystem.hpp"

using namespace crimild;

InputSystem::InputSystem( void )
	: System( "Input System" )
{
    auto self = this;

    registerMessageHandler< messages::WindowSystemDidCreateWindow >( [self]( messages::WindowSystemDidCreateWindow const &message ) {
        self->_window = message.video->getWindowHandler();

        Input::getInstance()->reset( GLFW_KEY_LAST, GLFW_MOUSE_BUTTON_LAST );

        glfwSetKeyCallback( self->_window, []( GLFWwindow* window, int key, int scancode, int action, int mods ) {
			if ( key == GLFW_KEY_UNKNOWN ) {
				return;
			}

            if ( Console::getInstance()->isEnabled() ) {
                if ( action == GLFW_PRESS ) {
                    switch ( key ) {
                        case CRIMILD_INPUT_KEY_BACKSPACE:
                        case CRIMILD_INPUT_KEY_UP:
                        case CRIMILD_INPUT_KEY_DOWN:
                        case CRIMILD_INPUT_KEY_ENTER:
                            Console::getInstance()->handleInput( key, mods );
                            break;

                        default:
                            break;
                    }
                }

                if ( Console::getInstance()->isActive() ) {
                    return;
                }
            }

            if ( action == GLFW_PRESS || action == GLFW_REPEAT ) {
                MessageQueue::getInstance()->pushMessage( messaging::KeyPressed { key } );
            }
            else {
                MessageQueue::getInstance()->pushMessage( messaging::KeyReleased { key } );
            }
        });

        glfwSetCharCallback( self->_window, []( GLFWwindow *window, unsigned int codepoint ) {
            if ( Console::getInstance()->isEnabled() ) {
                Console::getInstance()->handleInput( codepoint, 0 );
            }
        });

        glfwSetMouseButtonCallback( self->_window, []( GLFWwindow* window, int button, int action, int mods ) {
            double x, y;
            glfwGetCursorPos( window, &x, &y );

            if ( action == GLFW_PRESS ) {
                MessageQueue::getInstance()->pushMessage( messaging::MouseButtonDown { button } );
            }
            else {
                MessageQueue::getInstance()->pushMessage( messaging::MouseButtonUp { button } );
            }
        });

        glfwSetScrollCallback( self->_window, []( GLFWwindow* window, double xoffset, double yoffset ) {
            MessageQueue::getInstance()->pushMessage( messaging::MouseScroll { ( float ) xoffset, ( float ) yoffset } );
        });

        crimild::concurrency::sync_frame( std::bind( &InputSystem::update, self ) );
    });

    registerMessageHandler< messages::WindowSystemWillDestroyWindow >( [&]( messages::WindowSystemWillDestroyWindow const &message ) {
        _window = nullptr;
    });
}

InputSystem::~InputSystem( void )
{

}

bool InputSystem::start( void )
{
	if ( !System::start() ) {
		return false;
	}

    return true;
}

void InputSystem::update( void )
{
    CRIMILD_PROFILE( "Update Input" )

    if ( _window == nullptr ) {
        return;
    }

    switch ( Input::getInstance()->getMouseCursorMode() ) {
        case Input::MouseCursorMode::NORMAL:
            glfwSetInputMode( _window, GLFW_CURSOR, GLFW_CURSOR_NORMAL );
            break;

        case Input::MouseCursorMode::HIDDEN:
            glfwSetInputMode( _window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN );
            break;

        case Input::MouseCursorMode::GRAB:
            glfwSetInputMode( _window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );
            break;

        default:
            break;
    }

    // trigger MouseMotion in every update to handle cases
    // when the mouse is not moving and the delta pos should
    // be updated
    int windowWidth, windowHeight;
    double x, y;
    glfwGetWindowSize( _window, &windowWidth, &windowHeight );
    glfwGetCursorPos( _window, &x, &y );

    MessageQueue::getInstance()->pushMessage( messaging::MouseMotion {
        ( float ) x,
        ( float ) y,
        ( float ) x / ( float ) windowWidth,
        ( float ) y / ( float ) windowHeight
    });

	std::vector< float > axes;
	auto joyPresent = glfwJoystickPresent(GLFW_JOYSTICK_1);
	if (joyPresent == 1) {
		int axesCount;
		const float *axesData = glfwGetJoystickAxes( GLFW_JOYSTICK_1, &axesCount );
		for ( int i = 0; i < axesCount; i++ ) {
			axes.push_back( axesData[ i ] );
		}
	}
	Input::getInstance()->resetJoystickAxes( axes );

    crimild::concurrency::sync_frame( std::bind( &InputSystem::update, this ) );
}

void InputSystem::stop( void )
{
	System::stop();
}

<|endoftext|>


<commit_before>#include <Arduino.h>
#include <Display.h>

#define PRINT true
//#define TESTMTS

// Pins in use
/**
 *  00 RX1 ..(CP2102)
 *  01 TX1 ..
 *  02                        * 23 ENC_B - Rotary B
 *  03                        * 22 ENC_A - Rotary A
 *  04                        * 21 Potentiometer
 *  05                        * 20 PWM - TFT:LITE <grey?>
 *  06 ENC_BTN <orange>       * 19 LED_GREEN <purple> 330ohm
 *  07 RX3 MTS <green>        * 18 LED_RED   <blue>   220ohm
 *  08 TX3 MTS <yellow>       * 17 TFT:RS  <blue>   D/C
 *  09 RX2 .. (GPS)           * 16 TFT:RST <green>  RST
 *  10 TX2 .. (GPS)           * 15 SPI:CS  <yellow> TCS
 *  11 SPI:DOUT <orange> SI   * 14 SPI:SCK <grey?>  SCK
 *  12 SPI:DIN  <red>    SO   * 13 LED_BOARD
 *
 *  [[ underside  ]]
 *
 *  ** not used **
 */
//

// UART Serial communications

// Host comms for data exchange with computer

//#define HWSERIAL      Serial2
//#define HWSERIAL_BAUD 57600

// Innovate MTS serial data
#include <Drive.h>
#define MTSSERIAL      Serial2

#define RECBUFF 64
byte mtsbuffer[RECBUFF];

// Keep a small buffer for reading bytes from MTSSERIAL
void maintainMTS(); // Feed available serial data to Drive packet buffer
#ifdef TESTMTS
void testMTS();
#endif // TESTMTS

Drive drive;
void maintainDrive(); // Detect newly arrived packets

#include <ADC.h>
// https://forum.pjrc.com/threads/25532-ADC-library-update-now-with-support-for-Teensy-3-1
#include "RingBuffer.h"
// and IntervalTimer
#include <IntervalTimer.h>

#define ADC_RESOLUTION 12
#define ADC_POT A7 // (21) ADC0_SE7B

ADC *adc = new ADC();
IntervalTimer timer0;
RingBuffer *buffer0 = new RingBuffer;
int startTimerValue0 = 0;
const int period0 = 10000; // us
// 50,000 is good for infrequent signals

void setupADC();
void timer0_callback();

// LED Arrangement
#include <Led.h>

Led *Leds; // = {13, 18, 19};
const int LED_BOARD = 0; // Pin 13 (on board)
const int LED_GREEN = 1; // 18 <purple> GREEN
const int LED_RED = 2; // 19 <blue> RED
int ledCount;

void maintainLeds();
void setupLeds();

#define TFT_LITE   20 // PWM backlight/brightness control

Display display = Display();

#include <Encoder.h>

// Encoder
#define ENC_A      22
#define ENC_B      23
#define ENC_BUTTON 06

// Note the 2000millis delay during constructor!
Encoder rotary(ENC_A, ENC_B);

void maintainRotary();

#include <Bounce2.h>
//#include <algorithm>

Bounce debouncer = Bounce();

void setupButton();
void maintainButton();

#include "TinyGPS.h"

// GPS updates

#define GPSSERIAL      Serial3
#define GPSSERIAL_BAUD 9600

TinyGPS gps;

void setupGps();
void maintainGps();

#define ANSI_ESCAPE 0x1B
#define ANSI_LEFT_BRACKET 0x5B
const uint8_t ERASE_DISPLAY[] = {ANSI_ESCAPE, ANSI_LEFT_BRACKET, '2', 'J'};

void setup() {
    setupLeds();
    setupButton();
    setupADC();
    display.setupVolts(buffer0, adc->getMaxValue(0));

    // Indicate startup with all Leds
    Leds[LED_BOARD].flash(9999);
    Leds[LED_RED].flash(9999);
    Leds[LED_GREEN].flash(10);

    Serial.begin(19200);  // USB, communication to PC or Mac

    display.setupBrightness(TFT_LITE);
    display.setupChannel(0, 8191); // Lambda
    // Aux1 => not connected
    // Aux2 => Injector Pulse Width
    display.setupChannel(1, MTS10BIT_MAX);
    // Aux3 => O2; up to ~1.2V
    display.setupChannel(2, 480);
    // Aux4 => AFM; up to ~4V
    display.setupChannel(3, MTS10BIT_MAX);

    // Waits until USB is connected
#if PRINT
    while(!Serial) {
        maintainLeds();
        delay(20);
    }
#endif // PRINT

    display.splash();

#if PRINT
    Serial.write(ERASE_DISPLAY, 4);

    Serial.println("Connected USB.");
#endif // PRINT

    MTSSERIAL.begin(MTSSERIAL_BAUD);
    while(!MTSSERIAL) {
        maintainLeds();
        delay(20);
    }
#if PRINT
    Serial.println("Connected MTS.");
#endif

    setupGps();

    Leds[LED_BOARD].off();
    Leds[LED_RED].off();
    Leds[LED_GREEN].off();
#ifdef TESTMTS
    testMTS();
#endif // TESTMTS
}

/**
 * Configure the Leds[] collection
 */
void setupLeds() {
    int pins[3] = {13, 18, 19};
    Leds = Led::forPins(pins);
    ledCount = sizeof(Leds);
}

/**
 * Configure debuouncer.
 * - 10 millis of debounce
 */
void setupButton() {
    // Pullup requires the button connect the pin to ground
    debouncer.attach(ENC_BUTTON, INPUT_PULLUP);
    debouncer.interval(10);
}

/**
 * Configure analog input.
 * - Use a timer to do DMA reads to a buffer
 */
void setupADC() {
    pinMode(ADC_POT, INPUT);
    adc->setReference(ADC_REF_3V3, ADC_0);
    adc->setAveraging(16);
    adc->setResolution(ADC_RESOLUTION);
    adc->setConversionSpeed(ADC_MED_SPEED);
    adc->setSamplingSpeed(ADC_MED_SPEED);
    startTimerValue0 = timer0.begin(timer0_callback, period0);
    delayMicroseconds(250);
    adc->enableInterrupts(ADC_0);
}

// This function will be called with the desired frequency
// start the measurement
void timer0_callback(void) {
    adc->startSingleRead(ADC_POT, ADC_0); // also: startSingleDifferential, analogSynchronizedRead, analogSynchronizedReadDifferential
}

// when the measurement finishes, this will be called
// first: see which pin finished and then save the measurement into the correct buffer
//uint8_t isrTick = 0;
void adc0_isr() {
//    if (isrTick++ % 2) {
//        Leds[LED_GREEN].on();
//    } else {
//        Leds[LED_GREEN].off();
//    }

    uint8_t pin = ADC::sc1a2channelADC0[ADC0_SC1A&ADC_SC1A_CHANNELS]; // the bits 0-4 of ADC0_SC1A have the channel

    // add value to correct buffer
    if(pin==ADC_POT) {
        buffer0->write(adc->readSingle());
        display.voltsReady(true);
    } else { // clear interrupt anyway
        adc->readSingle();
    }

    // restore ADC config if it was in use before being interrupted by the analog timer
    if (adc->adc0->adcWasInUse) {
        // restore ADC config, and restart conversion
        adc->adc0->loadConfig(&adc->adc0->adc_config);
        // avoid a conversion started by this isr to repeat itself
        adc->adc0->adcWasInUse = (uint8_t) false;
    }
}

void setupGps() {
    GPSSERIAL.begin(GPSSERIAL_BAUD);
}

/******* LOOP *******/

uint32_t lastLoop = millis();
void loop() {
    uint32_t now = millis();
    if (now - lastLoop > 10) {
        maintainMTS();
        maintainGps();
        maintainDrive();
        lastLoop = now;
    }
    maintainLeds();
    maintainRotary();
    maintainButton();
    display.maintain();
}

int32_t previousValue;

void maintainRotary() {
    int32_t value;
    value = rotary.read();
    if (value != previousValue) {
        int16_t delta = (int16_t) (previousValue - value);
        display.directionInput(delta);
        previousValue = value;
    }
}

bool wasPressed = false;
void maintainButton() {

    // Update the Bounce instance :
    debouncer.update();

    // Get the updated value :
    bool pressed = !debouncer.read();
    if (wasPressed != pressed) {
        display.pressInput(1, pressed);
        wasPressed = pressed;
        if (pressed) {
            Leds[LED_GREEN].on();
        } else {
            Leds[LED_GREEN].off();
        }
    }
}

// Each Led needs a `tick` to flash behaviour maintenance
void maintainLeds() {
    for (int i = 0; i < ledCount; i++) {
        Leds[i].tick();
    }
}

Packet *p;

// When a packets are available, push parts of it into the display
// TODO: feed values into drive statistics (avg/min/max/etc)
void maintainDrive() {
    while(Packet *p = drive.nextPacket()) {
        // Process the packet by sending it's values to display for processing
        display.setChannel(0, p->lambda);
        if (p->channelCount >= 2) {
            display.setChannel(1, p->channel[1]);
            display.setChannel(2, p->channel[2]);
            display.setChannel(3, p->channel[3]);
//            display.setChannel(4, p->channel[4]);
        }
    }
    display.setElapsed(drive.elapsedMillis());
}

// Push all available MTS bytes to the drive
// if that results in packets being decoded, they will be buffered in the Drive packetbuffer!
void maintainMTS() {
    while (MTSSERIAL.available()) {
        uint8_t m = (uint8_t) (MTSSERIAL.read() & 0xFF);
        drive.encode(m);
    }
}

#ifdef TESTMTS
int incoming[] = {0x27, 0x39, 0x00, 0xB2, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x7A, 0xB2, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x7A};
//                  --    --    --    HH    HH    a0    a0    a1    a1    a2    a2    a3    a3    HH    HH    a0    a0    a1    a1    a2    a2    a3    a3
void testMTS() {
    size_t intSize = sizeof(int);
//    Serial.print("sizeof(int) == "); Serial.println(intSize, DEC);
//    Serial.print("sizeof(uint8_t) == "); Serial.println(sizeof(uint8_t), DEC);
//    Serial.print("sizeof(uint16_t) == "); Serial.println(sizeof(uint16_t), DEC);
    Serial.print("sizeof(Packet) == "); Serial.println(sizeof(Packet), DEC);

//    Serial.println("MTS::Function >");
//    for (uint8_t f = MTS::Funtion::NORMAL; f <= MTS::Funtion::RESERVED; f++) {
//        Serial.print(f < 0b100 ? f < 0b10 ? "0b00" : "0b0" : "0b"); Serial.println(f, BIN);
//    }
//    Serial.println();

    // Feed predefined byte sequences to verify packet decoding
    for(int i = 0; i < sizeof(incoming) / intSize; i++) {
        uint8_t in = (uint8_t) (incoming[i] & 0xFF);
        Serial.print(i < 10 ? "[0" : "["); Serial.print(i); Serial.print("] ");
        Serial.print(in > 0xF ? "0x" : "0x0");
        Serial.print(in, HEX); Serial.print(" > ");

        drive.encode(in);

        if (Packet *p = drive.nextPacket()) {
            Serial.print("FOUND PACKET >> ");
            Serial.print(p->channelCount); Serial.println(" channels");
        }
    }
    Serial.println("Finished testMTS");
}
#endif // TESTMTS

long lat, lon;
unsigned long fix_age, time, date, speed, course;
unsigned long chars;
unsigned short sentences, failed_checksum;
int year;
byte month, day, hour, minutes, second, hundredths;

void maintainGps() {
    while (GPSSERIAL.available()) {
        int g = GPSSERIAL.read();
        if (gps.encode(g)) {
            // Packet decoded.
            // statistics
            gps.stats(&chars, &sentences, &failed_checksum);
            // retrieves +/- lat/long in 100000ths of a degree
            gps.get_position(&lat, &lon, &fix_age);
            // time in hhmmsscc, date in ddmmyy
//                gps.get_datetime(&date, &time, &fix_age);
            // returns speed in 100ths of a knot
            speed = gps.speed();
            // course in 100ths of a degree
            course = gps.course();
            // split open date/time components
            gps.crack_datetime(&year, &month, &day, &hour, &minutes, &second, &hundredths, &fix_age);

            display.setGPSData(lat, lon, course);
//            Serial.print(year); Serial.print("-"); Serial.print(month); Serial.print("-"); Serial.print(day);
//            Serial.print("T"); Serial.print(hour); Serial.print(":"); Serial.print(minutes); Serial.print(" $ ");
//            Serial.print(chars); Serial.print(":"); Serial.print(sentences); Serial.print(":"); Serial.print(failed_checksum);
//            Serial.print("> lat/long  = "); Serial.print(lat); Serial.print("/"); Serial.print(lon);
//            Serial.print(" course = "); Serial.print(course);
//            Serial.println();
        }
    }
}<commit_msg>Cleanup pin usage comments<commit_after>#include <Arduino.h>
#include <Display.h>

#define PRINT false
//#define TESTMTS
//#define QUERYMTS

// Pins in use
/**
 *  00 RX1 MTS <green>        * AGND
 *  01 TX1 MTS <yellow>       * 3v3 - RS232 Level Shift VCC <red>
 *  02                        * 23 ENC_B - Rotary B <orange>
 *  03 Buzzer <brown>         * 22 ENC_A - Rotary A <yellow>
 *  04                        * 21 Potentiometer <green>
 *  05                        * 20 PWM - TFT:LITE <grey>
 *  06 ENC_BTN <orange>       * 19 LED_RED   <blue>   330ohm
 *  07 RX3                    * 18 LED_GREEN <purple> 220ohm
 *  08 TX3                    * 17 TFT:RS  <blue>   D/C
 *  09 RX2 .. (GPS)           * 16 TFT:RST <green>  RST
 *  10 TX2 .. (GPS)           * 15 SPI:CS  <yellow> TCS
 *  11 SPI:DOUT <orange> SI   * 14 SPI:SCK <brown>  SCK
 *  12 SPI:DIN  <red>    SO   * 13 LED_BOARD
 *
 *  [[ underside  ]]
 *
 *  ** not used **
 */
//

// UART Serial communications

// Host comms for data exchange with computer

//#define HWSERIAL      Serial2
//#define HWSERIAL_BAUD 57600

// Innovate MTS serial data
#include <Drive.h>
#define MTSSERIAL      Serial2

#define RECBUFF 64
byte mtsbuffer[RECBUFF];

// Keep a small buffer for reading bytes from MTSSERIAL
void maintainMTS(); // Feed available serial data to Drive packet buffer
#ifdef TESTMTS
void testMTS();
#endif // TESTMTS

Drive drive;
void maintainDrive(); // Detect newly arrived packets

#include <ADC.h>
// https://forum.pjrc.com/threads/25532-ADC-library-update-now-with-support-for-Teensy-3-1

// and IntervalTimer
#include <IntervalTimer.h>

#define ADC_RESOLUTION 12
#define ADC_POT A7 // (21) ADC0_SE7B

ADC *adc = new ADC();
IntervalTimer timer0;
RingBuffer *buffer0 = new RingBuffer;
int startTimerValue0 = 0;
const int period0 = 10000; // us
// 50,000 is good for infrequent signals

void setupADC();
void timer0_callback();

// LED Arrangement
#include <Led.h>

Led *Leds; // = {13, 18, 19};
const int LED_BOARD = 0; // Pin 13 (on board)
const int LED_GREEN = 1; // 18 <purple> GREEN
const int LED_RED = 2; // 19 <blue> RED
int ledCount;

void maintainLeds();
void setupLeds();

#define TFT_LITE   20 // PWM backlight/brightness control

Display display = Display();

#include <Encoder.h>

// Encoder
#define ENC_A      22
#define ENC_B      23
#define ENC_BUTTON 06

// Note the 2000millis delay during constructor!
Encoder rotary(ENC_A, ENC_B);

void maintainRotary();

#include <Bounce2.h>
//#include <algorithm>

Bounce debouncer = Bounce();

void setupButton();
void maintainButton();

#include "TinyGPS.h"

// GPS updates

#define GPSSERIAL      Serial3
#define GPSSERIAL_BAUD 9600

TinyGPS gps;

void setupGps();
void maintainGps();

#define ANSI_ESCAPE 0x1B
#define ANSI_LEFT_BRACKET 0x5B
const uint8_t ERASE_DISPLAY[] = {ANSI_ESCAPE, ANSI_LEFT_BRACKET, '2', 'J'};

void setup() {
    setupLeds();
    setupButton();
    setupADC();
    display.setupVolts(buffer0, adc->getMaxValue(0));

    // Indicate startup with all Leds
    Leds[LED_BOARD].flash(9999);
    Leds[LED_RED].flash(9999);
    Leds[LED_GREEN].flash(10);

    Serial.begin(19200);  // USB, communication to PC or Mac

    display.setupBrightness(TFT_LITE);
    display.setupChannel(0, 8191); // Lambda
    // Aux1 => not connected
    // Aux2 => Injector Pulse Width
    display.setupChannel(1, MTS10BIT_MAX);
    // Aux3 => O2; up to ~1.2V
    display.setupChannel(2, 480);
    // Aux4 => AFM; up to ~4V
    display.setupChannel(3, MTS10BIT_MAX);

    // Waits until USB is connected
#if PRINT
    while(!Serial) {
        maintainLeds();
        delay(20);
    }
#endif // PRINT

    display.splash();

#if PRINT
    Serial.write(ERASE_DISPLAY, 4);

    Serial.println("Connected USB.");
#endif // PRINT

    MTSSERIAL.begin(MTSSERIAL_BAUD);
    while(!MTSSERIAL) {
        maintainLeds();
        delay(20);
    }
#if PRINT
    Serial.println("Connected MTS.");
#endif

    setupGps();

    Leds[LED_BOARD].off();
    Leds[LED_RED].off();
    Leds[LED_GREEN].off();
#ifdef TESTMTS
    testMTS();
#endif // TESTMTS
}

/**
 * Configure the Leds[] collection
 */
void setupLeds() {
    int pins[3] = {13, 18, 19};
    Leds = Led::forPins(pins);
    ledCount = sizeof(Leds);
}

/**
 * Configure debuouncer.
 * - 10 millis of debounce
 */
void setupButton() {
    // Pullup requires the button connect the pin to ground
    debouncer.attach(ENC_BUTTON, INPUT_PULLUP);
    debouncer.interval(10);
}

/**
 * Configure analog input.
 * - Use a timer to do DMA reads to a buffer
 */
void setupADC() {
    pinMode(ADC_POT, INPUT);
    adc->setReference(ADC_REF_3V3, ADC_0);
    adc->setAveraging(16);
    adc->setResolution(ADC_RESOLUTION);
    adc->setConversionSpeed(ADC_MED_SPEED);
    adc->setSamplingSpeed(ADC_MED_SPEED);
    startTimerValue0 = timer0.begin(timer0_callback, period0);
    delayMicroseconds(250);
    adc->enableInterrupts(ADC_0);
}

// This function will be called with the desired frequency
// start the measurement
void timer0_callback(void) {
    adc->startSingleRead(ADC_POT, ADC_0); // also: startSingleDifferential, analogSynchronizedRead, analogSynchronizedReadDifferential
}

// when the measurement finishes, this will be called
// first: see which pin finished and then save the measurement into the correct buffer
//uint8_t isrTick = 0;
void adc0_isr() {
//    if (isrTick++ % 2) {
//        Leds[LED_GREEN].on();
//    } else {
//        Leds[LED_GREEN].off();
//    }

    uint8_t pin = ADC::sc1a2channelADC0[ADC0_SC1A&ADC_SC1A_CHANNELS]; // the bits 0-4 of ADC0_SC1A have the channel

    // add value to correct buffer
    if(pin==ADC_POT) {
        buffer0->write(adc->readSingle());
        display.voltsReady(true);
    } else { // clear interrupt anyway
        adc->readSingle();
    }

    // restore ADC config if it was in use before being interrupted by the analog timer
    if (adc->adc0->adcWasInUse) {
        // restore ADC config, and restart conversion
        adc->adc0->loadConfig(&adc->adc0->adc_config);
        // avoid a conversion started by this isr to repeat itself
        adc->adc0->adcWasInUse = (uint8_t) false;
    }
}

void setupGps() {
    GPSSERIAL.begin(GPSSERIAL_BAUD);
}

/******* LOOP *******/

uint32_t lastLoop = millis();
void loop() {
    uint32_t now = millis();
    if (now - lastLoop > 10) {
        maintainMTS();
        maintainGps();
        maintainDrive();
        lastLoop = now;
    }
    maintainLeds();
    maintainRotary();
    maintainButton();
    display.maintain();
}

int32_t previousValue;

void maintainRotary() {
    int32_t value;
    value = rotary.read();
    if (value != previousValue) {
        int16_t delta = (int16_t) (previousValue - value);
        display.directionInput(delta);
        previousValue = value;
    }
}

bool wasPressed = false;
void maintainButton() {

    // Update the Bounce instance :
    debouncer.update();

    // Get the updated value :
    bool pressed = !debouncer.read();
    if (wasPressed != pressed) {
        display.pressInput(1, pressed);
        wasPressed = pressed;
        if (pressed) {
            Leds[LED_GREEN].on();
        } else {
            Leds[LED_GREEN].off();
        }
    }
}

// Each Led needs a `tick` to flash behaviour maintenance
void maintainLeds() {
    for (int i = 0; i < ledCount; i++) {
        Leds[i].tick();
    }
}

Packet *p;

// When a packets are available, push parts of it into the display
// TODO: feed values into drive statistics (avg/min/max/etc)
void maintainDrive() {
    while(Packet *p = drive.nextPacket()) {
        // Process the packet by sending it's values to display for processing
        display.setChannel(0, p->lambda);
        if (p->channelCount >= 2) {
            display.setChannel(1, p->channel[1]);
            display.setChannel(2, p->channel[2]);
            display.setChannel(3, p->channel[3]);
//            display.setChannel(4, p->channel[4]);
        }
    }
    display.setElapsed(drive.elapsedMillis());
}

// Push all available MTS bytes to the drive
// if that results in packets being decoded, they will be buffered in the Drive packetbuffer!
void maintainMTS() {
    while (MTSSERIAL.available()) {
        uint8_t m = (uint8_t) (MTSSERIAL.read() & 0xFF);
        drive.encode(m);
    }
}

#ifdef TESTMTS
int incoming[] = {0x27, 0x39, 0x00, 0xB2, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x7A, 0xB2, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x7A};
//                  --    --    --    HH    HH    a0    a0    a1    a1    a2    a2    a3    a3    HH    HH    a0    a0    a1    a1    a2    a2    a3    a3
void testMTS() {
    size_t intSize = sizeof(int);
//    Serial.print("sizeof(int) == "); Serial.println(intSize, DEC);
//    Serial.print("sizeof(uint8_t) == "); Serial.println(sizeof(uint8_t), DEC);
//    Serial.print("sizeof(uint16_t) == "); Serial.println(sizeof(uint16_t), DEC);
    Serial.print("sizeof(Packet) == "); Serial.println(sizeof(Packet), DEC);

//    Serial.println("MTS::Function >");
//    for (uint8_t f = MTS::Funtion::NORMAL; f <= MTS::Funtion::RESERVED; f++) {
//        Serial.print(f < 0b100 ? f < 0b10 ? "0b00" : "0b0" : "0b"); Serial.println(f, BIN);
//    }
//    Serial.println();

    // Feed predefined byte sequences to verify packet decoding
    for(int i = 0; i < sizeof(incoming) / intSize; i++) {
        uint8_t in = (uint8_t) (incoming[i] & 0xFF);
        Serial.print(i < 10 ? "[0" : "["); Serial.print(i); Serial.print("] ");
        Serial.print(in > 0xF ? "0x" : "0x0");
        Serial.print(in, HEX); Serial.print(" > ");

        drive.encode(in);

        if (Packet *p = drive.nextPacket()) {
            Serial.print("FOUND PACKET >> ");
            Serial.print(p->channelCount); Serial.println(" channels");
        }
    }
    Serial.println("Finished testMTS");
}
#endif // TESTMTS

long lat, lon;
unsigned long fix_age, time, date, speed, course;
unsigned long chars;
unsigned short sentences, failed_checksum;
int year;
byte month, day, hour, minutes, second, hundredths;

void maintainGps() {
    while (GPSSERIAL.available()) {
        int g = GPSSERIAL.read();
        if (gps.encode(g)) {
            // Packet decoded.
            // statistics
            gps.stats(&chars, &sentences, &failed_checksum);
            // retrieves +/- lat/long in 100000ths of a degree
            gps.get_position(&lat, &lon, &fix_age);
            // time in hhmmsscc, date in ddmmyy
//                gps.get_datetime(&date, &time, &fix_age);
            // returns speed in 100ths of a knot
            speed = gps.speed();
            // course in 100ths of a degree
            course = gps.course();
            // split open date/time components
            gps.crack_datetime(&year, &month, &day, &hour, &minutes, &second, &hundredths, &fix_age);

            display.setGPSData(lat, lon, course);
//            Serial.print(year); Serial.print("-"); Serial.print(month); Serial.print("-"); Serial.print(day);
//            Serial.print("T"); Serial.print(hour); Serial.print(":"); Serial.print(minutes); Serial.print(" $ ");
//            Serial.print(chars); Serial.print(":"); Serial.print(sentences); Serial.print(":"); Serial.print(failed_checksum);
//            Serial.print("> lat/long  = "); Serial.print(lat); Serial.print("/"); Serial.print(lon);
//            Serial.print(" course = "); Serial.print(course);
//            Serial.println();
        }
    }
}<|endoftext|>


<commit_before>#include"ics3/ics3.hpp"

#include"core.hpp"
#include"ics3/eeprom.hpp"
#include"ics3/parameter.hpp"
#include"ics3/id.hpp"

inline uint16_t getReceiveAngle(const std::vector<uint8_t>& rx) noexcept {
  return static_cast<uint16_t>((rx[4] << 7) | rx[5]);
}

ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate)
: core {Core::getReference(path, baudrate.get())}
{}

ics::Angle ics::ICS3::move(const ID& id, Angle angle) const {
  static std::vector<uint8_t> tx(3), rx(6);
  uint16_t send {angle.getRaw()};
  tx[0] = 0x80 | id.get();
  tx[1] = 0x7F & (send >> 7);
  tx[2] = 0x7F & send;
  core.communicate(tx, rx); // throw std::runtime_error
  angle.rawData = getReceiveAngle(rx); // need friend
  return angle;
}

ics::Angle ics::ICS3::free(const ID& id, Angle unit) const {
  static std::vector<uint8_t> tx(3), rx(6);
  tx[0] = 0x80 | id.get(); // tx[1] == tx[2] == 0
  core.communicate(tx, rx); // throw std::runtime_error
  unit.rawData = getReceiveAngle(rx); // need friend
  return unit;
}

ics::Parameter ics::ICS3::get(const ID& id, Parameter place) const {
  static std::vector<uint8_t> tx(2), rx(5);
  tx[0] = 0xA0 | id.get();
  tx[1] = place.getSubcommand();
  core.communicate(tx, rx); // throw std::runtime_error
  return place = rx[4];
}

void ics::ICS3::set(const ID& id, const Parameter& param) const {
  static std::vector<uint8_t> tx(3), rx(6);
  tx[0] = 0xC0 | id.get();
  tx[1] = param.getSubcommand();
  tx[2] = param.get();
  core.communicate(tx, rx); // throw std::runtime_error
}

ics::EepRom ics::ICS3::getRom(const ID& id) const {
  static std::vector<uint8_t> tx(2), rx(68);
  tx[0] = 0xA0 | id.get(); // tx[1] == 0
  core.communicate(tx, rx); // throw std::runtime_error
  std::array<uint8_t, 64> romData;
  std::copy(rx.begin() + 4, rx.end(), romData.begin());
  return EepRom {romData}; // need friend
}

void ics::ICS3::setRom(const ID& id, const EepRom& rom) const {
  static std::vector<uint8_t> tx(66), rx(68);
  tx[0] = 0xC0 | id.get(); // tx[1] == 0
  rom.write(tx.begin() + 2);
  core.communicate(tx, rx); // throw std::runtime_error
}
<commit_msg>Rename argument for readability<commit_after>#include"ics3/ics3.hpp"

#include"core.hpp"
#include"ics3/eeprom.hpp"
#include"ics3/parameter.hpp"
#include"ics3/id.hpp"

inline uint16_t getReceiveAngle(const std::vector<uint8_t>& rx) noexcept {
  return static_cast<uint16_t>((rx[4] << 7) | rx[5]);
}

ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate)
: core {Core::getReference(path, baudrate.get())}
{}

ics::Angle ics::ICS3::move(const ID& id, Angle angle) const {
  static std::vector<uint8_t> tx(3), rx(6);
  uint16_t send {angle.getRaw()};
  tx[0] = 0x80 | id.get();
  tx[1] = 0x7F & (send >> 7);
  tx[2] = 0x7F & send;
  core.communicate(tx, rx); // throw std::runtime_error
  angle.rawData = getReceiveAngle(rx); // need friend
  return angle;
}

ics::Angle ics::ICS3::free(const ID& id, Angle unit) const {
  static std::vector<uint8_t> tx(3), rx(6);
  tx[0] = 0x80 | id.get(); // tx[1] == tx[2] == 0
  core.communicate(tx, rx); // throw std::runtime_error
  unit.rawData = getReceiveAngle(rx); // need friend
  return unit;
}

ics::Parameter ics::ICS3::get(const ID& id, Parameter type) const {
  static std::vector<uint8_t> tx(2), rx(5);
  tx[0] = 0xA0 | id.get();
  tx[1] = type.getSubcommand();
  core.communicate(tx, rx); // throw std::runtime_error
  return type = rx[4];
}

void ics::ICS3::set(const ID& id, const Parameter& param) const {
  static std::vector<uint8_t> tx(3), rx(6);
  tx[0] = 0xC0 | id.get();
  tx[1] = param.getSubcommand();
  tx[2] = param.get();
  core.communicate(tx, rx); // throw std::runtime_error
}

ics::EepRom ics::ICS3::getRom(const ID& id) const {
  static std::vector<uint8_t> tx(2), rx(68);
  tx[0] = 0xA0 | id.get(); // tx[1] == 0
  core.communicate(tx, rx); // throw std::runtime_error
  std::array<uint8_t, 64> romData;
  std::copy(rx.begin() + 4, rx.end(), romData.begin());
  return EepRom {romData}; // need friend
}

void ics::ICS3::setRom(const ID& id, const EepRom& rom) const {
  static std::vector<uint8_t> tx(66), rx(68);
  tx[0] = 0xC0 | id.get(); // tx[1] == 0
  rom.write(tx.begin() + 2);
  core.communicate(tx, rx); // throw std::runtime_error
}
<|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2014 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: test.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hjm211324@gmail.com
 *  Date: Dec. 29, 2014
 *  Time: 11:10:09
 *  Description:
 *****************************************************************************/
#include <iostream>

int main() {
    std::cout << "Hello world!" << std::endl;

}

<commit_msg>--allow-empty_message<commit_after>/******************************************************************************
 *  Copyright (c) 2014 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: test.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hjm211324@gmail.com
 *  Date: Dec. 29, 2014
 *  Time: 11:10:09
 *  Description:
 *****************************************************************************/
#include <iostream>

int main() {
    std::cout << "Hello world!" << std::endl;

}

<|endoftext|>


<commit_before>#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <libgen.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "pty_fork.h"           /* Declaration of ptyFork() */
#include "tty_functions.h"      /* Declaration of ttySetRaw() */

#include <iostream>
#include <stdexcept>
#include <string>
#include <array>

#include "tty_state.hpp"
#include "pty_fork.hpp"

void errExit(char const * const s)
{ printf("error: %s\n", s); exit(1); }

void fatal(char const * const s)
{ errExit(s); }

int main(int const argc, char ** const argv)
try
{
  sts::tty_state tty;

  sts::pseudo_term pt{ tty };
  pt([]
  {
    char const *shell{ getenv("SHELL") };
    if(!shell || *shell == '\0')
    { shell = "/bin/sh"; }

    execlp(shell, shell, nullptr);
    throw std::runtime_error{ "shell failed to run" };
  });
  int const master_fd{ pt.get_master() };

  /* Parent: relay data between terminal and pty master */
  auto const script_fd = open((argc > 1) ? argv[1] : "typescript",
      O_WRONLY | O_CREAT | O_TRUNC,
      S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
  if(script_fd == -1)
  { errExit("open typescript"); }

  /* Place terminal in raw mode so that we can pass all terminal
     input to the pseudoterminal master untouched */
  ttySetRaw(STDIN_FILENO, &tty.term);

  std::array<char, 256> buf{};
  ssize_t num_read{};
  fd_set in_fds{};
  while(true)
  {
    FD_ZERO(&in_fds);
    FD_SET(STDIN_FILENO, &in_fds);
    FD_SET(master_fd, &in_fds);

    if(select(master_fd + 1, &in_fds, NULL, NULL, NULL) == -1)
    { errExit("select"); }

    if(FD_ISSET(STDIN_FILENO, &in_fds)) /* stdin --> pty */
    {
      num_read = read(STDIN_FILENO, buf.data(), buf.size());
      if(num_read <= 0)
      { exit(EXIT_SUCCESS); }

      if (write(master_fd, buf.data(), num_read) != num_read)
      { fatal("partial/failed write (master_fd)"); }
    }

    if(FD_ISSET(master_fd, &in_fds)) /* pty --> stdout+file */
    {
      num_read = read(master_fd, buf.data(), buf.size());
      if(num_read <= 0)
      { break; }

      if(write(STDOUT_FILENO, buf.data(), num_read) != num_read)
      { fatal("partial/failed write (STDOUT_FILENO)"); }
      if(write(script_fd, buf.data(), num_read) != num_read)
      { fatal("partial/failed write (script_fd)"); }
    }
  }
}
catch(std::exception const &e)
{
  std::cout << "exception: " << e.what() << std::endl;
}
catch(...)
{
  std::cout << "unknown error occurred" << std::endl;
}
<commit_msg>Removed unused headers<commit_after>#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <libgen.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "tty_functions.h"      /* Declaration of ttySetRaw() */

#include <iostream>
#include <stdexcept>
#include <string>
#include <array>

#include "tty_state.hpp"
#include "pty_fork.hpp"

void errExit(char const * const s)
{ printf("error: %s\n", s); exit(1); }

void fatal(char const * const s)
{ errExit(s); }

int main(int const argc, char ** const argv)
try
{
  sts::tty_state tty;

  sts::pseudo_term pt{ tty };
  pt([]
  {
    char const *shell{ getenv("SHELL") };
    if(!shell || *shell == '\0')
    { shell = "/bin/sh"; }

    execlp(shell, shell, nullptr);
    throw std::runtime_error{ "shell failed to run" };
  });
  int const master_fd{ pt.get_master() };

  /* Parent: relay data between terminal and pty master */
  auto const script_fd = open((argc > 1) ? argv[1] : "typescript",
      O_WRONLY | O_CREAT | O_TRUNC,
      S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
  if(script_fd == -1)
  { errExit("open typescript"); }

  /* Place terminal in raw mode so that we can pass all terminal
     input to the pseudoterminal master untouched */
  ttySetRaw(STDIN_FILENO, &tty.term);

  std::array<char, 256> buf{};
  ssize_t num_read{};
  fd_set in_fds{};
  while(true)
  {
    FD_ZERO(&in_fds);
    FD_SET(STDIN_FILENO, &in_fds);
    FD_SET(master_fd, &in_fds);

    if(select(master_fd + 1, &in_fds, NULL, NULL, NULL) == -1)
    { errExit("select"); }

    if(FD_ISSET(STDIN_FILENO, &in_fds)) /* stdin --> pty */
    {
      num_read = read(STDIN_FILENO, buf.data(), buf.size());
      if(num_read <= 0)
      { exit(EXIT_SUCCESS); }

      if (write(master_fd, buf.data(), num_read) != num_read)
      { fatal("partial/failed write (master_fd)"); }
    }

    if(FD_ISSET(master_fd, &in_fds)) /* pty --> stdout+file */
    {
      num_read = read(master_fd, buf.data(), buf.size());
      if(num_read <= 0)
      { break; }

      if(write(STDOUT_FILENO, buf.data(), num_read) != num_read)
      { fatal("partial/failed write (STDOUT_FILENO)"); }
      if(write(script_fd, buf.data(), num_read) != num_read)
      { fatal("partial/failed write (script_fd)"); }
    }
  }
}
catch(std::exception const &e)
{
  std::cout << "exception: " << e.what() << std::endl;
}
catch(...)
{
  std::cout << "unknown error occurred" << std::endl;
}
<|endoftext|>


<commit_before><commit_msg>Find in page should cause the scrollbar to repaint with tick marks.<commit_after><|endoftext|>


<commit_before>#include "tar.hpp"

#include <cstring>  // for strlen and memset
#include <cstdio>   // for sprintf, snprintf and sscanf
#include <cstdlib>  // for rand
#include <ctime>    // for time

#define ENABLE_LOGGING

#ifdef ENABLE_LOGGING
#  define LOG printf
#else
#  define LOG(fmt, args ...) ((void)0)
#endif

namespace tar
{
        const char FILL_CHAR = '\0';
        const int FILE_NAME_LENGTH = 100;

        struct tar_header                // From http://en.wikipedia.org/wiki/Tar_(computing)#UStar_format
        {
                char name[FILE_NAME_LENGTH];  // file name
                char mode[8];                 // file mode
                char uid[8];                  // Owner's numeric user ID
                char gid[8];                  // Group's numeric user ID
                char size[12];                // File size in bytes (octal base)
                char mtime[12];               // Last modification time in numeric Unix time format (octal)
                char checksum[8];             // Checksum for header record
                char typeflag[1];             // Link indicator (file type)
                // 0 normal file, 1 hard link, 2 soft link
                char linkname[100];           // Name of linked file
                char magic[6];                // UStar indicator "ustar"
                char version[2];              // UStar version "00"
                char uname[32];               // Owner user name
                char gname[32];               // Owner group name
                char devmajor[8];             // Device major number
                char devminor[8];             // Device minor number
                char prefix[155];             // Filename prefix
                char pad[12];
        };

        void header_setMetadata(tar_header* header)
        {
                std::memset(header, 0, sizeof(tar_header));

                std::sprintf(header->magic, "ustar");
                std::sprintf(header->mtime, "%011lo", std::time(NULL));
                std::sprintf(header->mode, "%07o", 0644);
                //TODO
                std::sprintf(header->uname, "unkown");  // ... a bit random
                std::sprintf(header->gname, "users");
                header->typeflag[0] = 0;  // always just a normal file
        }

        void header_setChecksum(tar_header* header)
        {
                /* From Wikipedia: The checksum is calculated by taking the sum of the unsigned byte values
                   of the header record with the eight checksum bytes taken to be ascii spaces. */
                unsigned int sum = 0;

                char *pointer = (char *) header;
                char *end = pointer + sizeof(tar_header);

                // Iterate over header struct until we are at checksum field.
                while (pointer < header->checksum) {
                        sum += *pointer & 0xff;
                        pointer++;
                }

                // ... then add eight 'ascii spaces' ...
                sum += ' ' * 8;
                pointer += 8;

                // ... and go until the end.
                while (pointer < end) {
                        sum += *pointer & 0xff;
                        pointer++;
                }

                std::sprintf(header->checksum, "%06o", sum);
        }

        void header_setFilesize(tar_header* header, file_size_t fileSize)
        {
                std::sprintf(header->size, "%011llo", fileSize);
        }

        void header_getFilesize(tar_header* header, file_size_t* fileSize)
        {
                std::sscanf(header->size, "%011llo", fileSize);
        }

        void header_setFilename(tar_header* header, const char* fileName)
        {
                size_t len = std::strlen(fileName);
                if (len == 0 || len >= FILE_NAME_LENGTH)  // len > 0 also ensures that the header does not start with \0
                {
                        LOG("Invalid file name for tar: %s", fileName);
                        std::sprintf(header->name, "INVALID_%d", std::rand());
                }
                else
                {
                        std::sprintf(header->name, "%s", fileName);
                }
        }

        void header_getFilename(tar_header* header, char* fileName)
        {
                std::sscanf(header->name, "%s", fileName);
        }

        /* In front of the data of every file there is this header. */
        void writeHeader(std::ostream& dst, const char* fileName, file_size_t fileSize)
        {
                tar_header header;
                header_setMetadata(&header);
                header_setFilename(&header, fileName);
                header_setFilesize(&header, fileSize);
                header_setChecksum(&header);

                dst.write((const char*)&header, sizeof(tar_header));
        }

        void readHeader(std::istream& inp, tar_header* header)
        {
                inp.read((char*)header, sizeof(tar_header));
        }

        /* The length of the data after the header must be rounded up to a
           multiple of 512 bytes, the length of the header. */
        void fill(std::ostream& dst, unsigned long fileSize)
        {
                while (fileSize % sizeof(tar_header) != 0)
                {
                        dst.put(FILL_CHAR);
                        fileSize++;
                }
        }

        void put(std::ostream& dst,
                        const char * const pathInTar,
                        char const * const dataBegin, const file_size_t fileSize)
        {
                writeHeader(dst, pathInTar, fileSize);
                dst.write(dataBegin, fileSize);
                fill(dst, fileSize);
        }

        void finish(std::ostream& dst)
        {
                /* The end of an tar is marked by at least two consecutive zero-filled records,
                   a record having the size of the header. */
                unsigned long i = 0;
                while (i < 2 * sizeof(tar_header))
                {
                        dst.put(FILL_CHAR);
                        i++;
                }
        }

        bool checkIfHeaderIsNext(std::istream& inp)
        {
                if (inp.eof() || inp.peek() == EOF)
                {
                        LOG("Can not read next file info, istream is at EOF.");
                        return false;
                }

                if (inp.peek() == FILL_CHAR)
                {
                        LOG("Can not read next file info, istream is pointing to %d, which a tar header can not start with.", FILL_CHAR);
                        return false;
                }

                return true;
        }

        bool getNextFileInfo(std::istream& inp,
                             char* pathInTar,
                             file_size_t* fileSize)
        {
                if (!checkIfHeaderIsNext(inp))
                        return false;

                tar_header header;
                readHeader(inp, &header);

                header_getFilesize(&header, fileSize);
                header_getFilename(&header, pathInTar);

                return true;
        }

        void getNextFileData(std::istream& inp,
                             char * const data,
                             const file_size_t fileSize)
        {
                if (data != NULL)  // NULL gets passed from skip
                        inp.read(data, fileSize);
                else
                        inp.seekg(fileSize, std::ios::cur);  // seek |fileSize| bytes from CURrent position

                // Advance to start of next header or to end of file
                // Works because
                // - header never starts with FILL_CHAR
                // - at end of file, peek() returns EOF.
                // - FILL_CHAR != EOF
                while (inp.peek() == FILL_CHAR)
                        inp.get();
        }

        void skip(std::istream& inp, const file_size_t fileSize)
        {
                getNextFileData(inp, NULL, fileSize);
        }

}  // namespace tar

<commit_msg>Formatting, added tar_file_type enum<commit_after>#include "tar.hpp"

#include <cstring>  // for strlen and memset
#include <cstdio>   // for sprintf, snprintf and sscanf
#include <cstdlib>  // for rand
#include <ctime>    // for time

#define ENABLE_LOGGING

#ifdef ENABLE_LOGGING
#  define LOG printf
#else
#  define LOG(fmt, args ...) ((void)0)
#endif

namespace tar
{
        const char FILL_CHAR = '\0';
        const int FILE_NAME_LENGTH = 100;

        // From http://en.wikipedia.org/wiki/Tar_(computing)#UStar_format
        typedef enum
        {
                tar_file_type_normal = 0,
                tar_file_type_hard_link = 1,
                tar_file_type_soft_link = 2,
                tar_file_type_directory = 5
        } tar_file_type;

        struct tar_header
        {
                char name[FILE_NAME_LENGTH];  // file name
                char mode[8];                 // file mode
                char uid[8];                  // Owner's numeric user ID
                char gid[8];                  // Group's numeric user ID
                char size[12];                // File size in bytes (octal base)
                char mtime[12];               // Last modification time in
                                              // numeric Unix time format (octal)
                char checksum[8];             // Checksum for header record
                char typeflag[1];             // file type, see tar_file_type
                char linkname[100];           // Name of linked file
                char magic[6];                // UStar indicator "ustar"
                char version[2];              // UStar version "00"
                char uname[32];               // Owner user name
                char gname[32];               // Owner group name
                char devmajor[8];             // Device major number
                char devminor[8];             // Device minor number
                char prefix[155];             // Filename prefix
                char pad[12];                 // padding
        };

        void header_setMetadata(tar_header* header)
        {
                std::memset(header, 0, sizeof(tar_header));

                std::sprintf(header->magic, "ustar");
                std::sprintf(header->mtime, "%011lo", std::time(NULL));
                std::sprintf(header->mode, "%07o", 0644);
                //TODO
                std::sprintf(header->uname, "unkown");  // ... a bit random
                std::sprintf(header->gname, "users");
                header->typeflag[0] = 0;  // always just a normal file
        }

        /* From Wikipedia: The checksum is calculated by taking the sum of the
         * unsigned byte values of the header record with the eight checksum
         * bytes taken to be ascii spaces. */
        void header_setChecksum(tar_header* header)
        {
                unsigned int sum = 0;

                char *pointer = (char *) header;
                char *end = pointer + sizeof(tar_header);

                // Iterate over header struct until we are at checksum field.
                while (pointer < header->checksum) {
                        sum += *pointer & 0xff;
                        pointer++;
                }

                // ... then add eight 'ascii spaces' ...
                sum += ' ' * 8;
                pointer += 8;

                // ... and go until the end.
                while (pointer < end) {
                        sum += *pointer & 0xff;
                        pointer++;
                }

                std::sprintf(header->checksum, "%06o", sum);
        }

        void header_setFilesize(tar_header* header, file_size_t fileSize)
        {
                std::sprintf(header->size, "%011llo", fileSize);
        }

        void header_getFilesize(tar_header* header, file_size_t* fileSize)
        {
                std::sscanf(header->size, "%011llo", fileSize);
        }

        void header_setFilename(tar_header* header, const char* fileName)
        {
                size_t len = std::strlen(fileName);

                // len > 0 also ensures that the header does not start with \0
                if (len == 0 || len >= FILE_NAME_LENGTH)
                {
                        LOG("Invalid file name for tar: %s", fileName);
                        std::sprintf(header->name, "INVALID_%d", std::rand());
                }
                else
                {
                        std::sprintf(header->name, "%s", fileName);
                }
        }

        void header_getFilename(tar_header* header, char* fileName)
        {
                std::sscanf(header->name, "%s", fileName);
        }

        /* Every file in a tar file starts with the tar header */
        void writeHeader(std::ostream& dst, const char* fileName, file_size_t fileSize)
        {
                tar_header header;
                header_setMetadata(&header);
                header_setFilename(&header, fileName);
                header_setFilesize(&header, fileSize);
                header_setChecksum(&header);

                dst.write((const char*)&header, sizeof(tar_header));
        }

        void readHeader(std::istream& inp, tar_header* header)
        {
                inp.read((char*)header, sizeof(tar_header));
        }

        /* The length of the data after the header must be rounded up to a
           multiple of 512 bytes, the length of the header. */
        void fill(std::ostream& dst, unsigned long fileSize)
        {
                while (fileSize % sizeof(tar_header) != 0)
                {
                        dst.put(FILL_CHAR);
                        fileSize++;
                }
        }

        void put(std::ostream& dst,
                 const char * const pathInTar,
                 char const * const dataBegin,
                 const file_size_t fileSize)
        {
                writeHeader(dst, pathInTar, fileSize);
                dst.write(dataBegin, fileSize);
                fill(dst, fileSize);
        }

        /* The end of an tar is marked by at least two consecutive zero-filled
         * records, a record having the size of the header. */
        void finish(std::ostream& dst)
        {
                unsigned long i = 0;
                while (i < 2 * sizeof(tar_header))
                {
                        dst.put(FILL_CHAR);
                        i++;
                }
        }

        bool checkIfHeaderIsNext(std::istream& inp)
        {
                if (inp.eof() || inp.peek() == EOF)
                {
                        LOG("Can not read next file info, istream is at EOF.");
                        return false;
                }

                if (inp.peek() == FILL_CHAR)
                {
                        LOG("Can not read next file info, istream is pointing"
                            "to %d, which a tar header can not start with.",
                            FILL_CHAR);
                        return false;
                }

                return true;
        }

        bool getNextFileInfo(std::istream& inp,
                             char* pathInTar,
                             file_size_t* fileSize)
        {
                if (!checkIfHeaderIsNext(inp))
                        return false;

                tar_header header;
                readHeader(inp, &header);

                header_getFilesize(&header, fileSize);
                header_getFilename(&header, pathInTar);

                return true;
        }

        void getNextFileData(std::istream& inp,
                             char * const data,
                             const file_size_t fileSize)
        {
                if (data == NULL)  // NULL gets passed from skip()
                        // seek |fileSize| bytes from CURrent position, to skip
                        inp.seekg(fileSize, std::ios::cur);
                else
                        inp.read(data, fileSize);

                // Advance to start of next header or to end of file
                // Works because
                // - header never starts with FILL_CHAR
                // - at end of file, peek() returns EOF.
                // - FILL_CHAR != EOF
                while (inp.peek() == FILL_CHAR)
                        inp.get();
        }

        void skip(std::istream& inp, const file_size_t fileSize)
        {
                getNextFileData(inp, NULL, fileSize);
        }

}  // namespace tar

<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>
#include "ThreadPool.hh"
#include "Scheduler.hh"
#include <unistd.h>

void test1(ThreadPool& tp) {
  std::vector< std::future<int> > results;

  for (int i = 0; i < 8; ++i) {
    results.emplace_back(
      tp.addTask([i] {
        return i;
      })
    );
  }
  for(auto && result: results)
    std::cout << result.get() << ' ';
  std::cout << std::endl;
}

void test2(ThreadPool& tp) {
  std::vector< std::future<int> > results;

  for (int i = 0; i < 4; ++i) {
    results.emplace_back(
      tp.addTask([i] {
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
        return i;
      })
    );
  }
  tp.stop();
  for(auto && result: results)
    std::cout << result.get() << ' ';
  std::cout << std::endl;
}

void test3(ThreadPool& tp) {
  std::future<std::string> result;
  bool stop = false;
  Task task;

  tp.start();
  result = task.assign([&stop] {
    unsigned int sec = 0;
    while (not stop) {
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      sec += 100;
      std::cout << "Active for " << sec << " ms" << std::endl;
    }
    return std::string("Test 3 passed");
  });
  task.setStopFunction([&stop] { stop = true; });
  tp.addTask(task);
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  tp.stop();
  std::cout << result.get() << std::endl;
}

void test4(ThreadPool& tp) {
  std::future<std::string> result;
  bool stop = false;
  bool pause = false;
  Task task;

  tp.start();
  result = task.assign([&stop, &pause] {
    unsigned int sec = 0;
    unsigned int paused = 0;
    while (not stop) {
      if (not pause) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        sec += 100;
        std::cout << "Active for " << sec << " ms" << std::endl;
      }
      else {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        paused += 100;
        std::cout << "Paused for " << paused << " ms" << std::endl;
      }
    }
    return std::string("Test 4 passed");
  });

  task.setStopFunction([&stop] { stop = true; });
  task.setPauseFunction([&pause] { std::cout << "Pass" << std::endl; pause = true; });
  task.setUnpauseFunction([&pause] { pause = false; });

  tp.addTask(task);
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  tp.pause();
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  tp.unpause();
  std::this_thread::sleep_for(std::chrono::milliseconds(500));
  tp.stop();
  std::cout << result.get() << std::endl;
}

void test5(ThreadPool& tp) {
  tp.start();
  tp.resize(1);
  for (int i = 0; i < 2; ++i) {
      tp.addTask([i] {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "Task " << i << " finished" << std::endl;
        return i;
      });
  }
}

void schedule1(Scheduler& scheduler) {
  auto future1 = scheduler.runAt([]() {
                  return "Done1";
                }, std::chrono::steady_clock::now() + std::chrono::milliseconds(200));
  auto future2 = scheduler.runIn([]() {
                  return "Done2";
                }, std::chrono::milliseconds(200));

  std::cout << future1.get() << std::endl;
  std::cout << future2.get() << std::endl;
}

void schedule2(Scheduler& scheduler) {
  std::vector<std::future<int>> futures;

  for (int i = 0; i < 10; ++i) {
    futures.emplace_back(scheduler.runIn([i]() {
                          return i;
                        }, std::chrono::milliseconds(100 * i))
                      );
  }
  for (auto& future : futures)
    std::cout << future.get() << std::endl;
}

void schedule3(Scheduler& scheduler) {
  scheduler.runEvery([]() {
                        std::cout << "Every second" << std::endl;
                    }, std::chrono::milliseconds(1000));
  scheduler.runIn([]() {
      std::cout << "3 seconds elapsed" << std::endl;
  }, std::chrono::seconds(3));
  std::this_thread::sleep_for(std::chrono::seconds(5));
}

void schedule4(ThreadManager& manager) {
  Scheduler scheduler(2, manager);
  bool stop = false;

  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  Task task([&stop, &scheduler]() {
    unsigned int i = 1;
    while (!stop) {
      std::this_thread::sleep_for(std::chrono::seconds(1));
      std::cout << std::to_string(i) + " second elapsed" << std::endl;
      ++i;
    }
    std::cout << "schedule4 Done" << std::endl;
  });
  task.setStopFunction([&stop]() {
    stop = true;
  });
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
  scheduler.runAt(task, std::chrono::steady_clock::now());
  getchar();
}

// Not possible to add tasks in a scheduled task atm
void schedule5(ThreadManager& manager) {
  Scheduler scheduler(2, manager);
  bool stop = false;

  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  Task task([&stop, &scheduler]() {
    unsigned int i = 1;
    while (!stop) {
      auto future = scheduler.runIn([i]() {
        return std::to_string(i) + " second elapsed";
      }, std::chrono::milliseconds(60));
      std::cout << future.get() << " " << (int)stop << std::endl;
      ++i;
    }
    std::cout << "leave" << std::endl;
  });
  task.setStopFunction([&stop]() {
    stop = true;
  });
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
  scheduler.runAt(task, std::chrono::steady_clock::now());
  getchar();
}

int main(int argc, char const *argv[]) {
  ThreadManager manager(1);
//  ThreadPool tp(2, manager);
  Scheduler scheduler(2, manager);

  // tp.start();
  // test1(tp);
  // test2(tp);
  // test3(tp);
  // test4(tp);
  // test5(tp);

//  std::cout << "------- Scheduler -------" << std::endl;

  // schedule1(scheduler);
  // schedule2(scheduler);
//  schedule3(scheduler);
  schedule4(manager);
  return 0;
}
<commit_msg>Updated the main output<commit_after>#include <chrono>
#include <iostream>
#include "ThreadPool.hh"
#include "Scheduler.hh"
#include <unistd.h>

void test1(ThreadPool& tp) {
  std::vector< std::future<int> > results;

  for (int i = 0; i < 8; ++i) {
    results.emplace_back(
      tp.addTask([i] {
        return i;
      })
    );
  }
  for(auto && result: results)
    std::cout << result.get() << ' ';
  std::cout << std::endl;
}

void test2(ThreadPool& tp) {
  std::vector< std::future<int> > results;

  for (int i = 0; i < 4; ++i) {
    results.emplace_back(
      tp.addTask([i] {
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
        return i;
      })
    );
  }
  tp.stop();
  for(auto && result: results)
    std::cout << result.get() << ' ';
  std::cout << std::endl;
}

void test3(ThreadPool& tp) {
  std::future<std::string> result;
  bool stop = false;
  Task task;

  tp.start();
  result = task.assign([&stop] {
    unsigned int sec = 0;
    while (not stop) {
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      sec += 100;
      std::cout << "Active for " << sec << " ms" << std::endl;
    }
    return std::string("Test 3 passed");
  });
  task.setStopFunction([&stop] { stop = true; });
  tp.addTask(task);
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  tp.stop();
  std::cout << result.get() << std::endl;
}

void test4(ThreadPool& tp) {
  std::future<std::string> result;
  bool stop = false;
  bool pause = false;
  Task task;

  tp.start();
  result = task.assign([&stop, &pause] {
    unsigned int sec = 0;
    unsigned int paused = 0;
    while (not stop) {
      if (not pause) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        sec += 100;
        std::cout << "Active for " << sec << " ms" << std::endl;
      }
      else {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        paused += 100;
        std::cout << "Paused for " << paused << " ms" << std::endl;
      }
    }
    return std::string("Test 4 passed");
  });

  task.setStopFunction([&stop] { stop = true; });
  task.setPauseFunction([&pause] { std::cout << "Pass" << std::endl; pause = true; });
  task.setUnpauseFunction([&pause] { pause = false; });

  tp.addTask(task);
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  tp.pause();
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  tp.unpause();
  std::this_thread::sleep_for(std::chrono::milliseconds(500));
  tp.stop();
  std::cout << result.get() << std::endl;
}

void test5(ThreadPool& tp) {
  tp.start();
  tp.resize(1);
  for (int i = 0; i < 2; ++i) {
      tp.addTask([i] {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "Task " << i << " finished" << std::endl;
        return i;
      });
  }
}

void schedule1(Scheduler& scheduler) {
  auto future1 = scheduler.runAt([]() {
                  return "Done1";
                }, std::chrono::steady_clock::now() + std::chrono::milliseconds(200));
  auto future2 = scheduler.runIn([]() {
                  return "Done2";
                }, std::chrono::milliseconds(200));

  std::cout << future1.get() << std::endl;
  std::cout << future2.get() << std::endl;
  std::cout << "Schedule1 Done" << std::endl << std::endl;
}

void schedule2(Scheduler& scheduler) {
  std::vector<std::future<int>> futures;

  for (int i = 0; i < 10; ++i) {
    futures.emplace_back(scheduler.runIn([i]() {
                          return i;
                        }, std::chrono::milliseconds(100 * i))
                      );
  }
  for (auto& future : futures)
    std::cout << future.get() << std::endl;
  std::cout << "Schedule2 Done" << std::endl << std::endl;
}

void schedule3(Scheduler& scheduler) {
  scheduler.runEvery([]() {
                        std::cout << "Every second" << std::endl;
                    }, std::chrono::milliseconds(1000));
  scheduler.runIn([]() {
      std::cout << "3 seconds elapsed" << std::endl;
  }, std::chrono::seconds(3));
  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "Schedule3 Done" << std::endl << std::endl;
}

void schedule4(ThreadManager& manager) {
  Scheduler scheduler(2, manager);
  bool stop = false;

  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  Task task([&stop, &scheduler]() {
    unsigned int i = 1;
    while (!stop) {
      std::this_thread::sleep_for(std::chrono::seconds(1));
      std::cout << std::to_string(i) + " second elapsed" << std::endl;
      ++i;
    }
    std::cout << "schedule4 Done" << std::endl << std::endl;
  });
  task.setStopFunction([&stop]() {
    stop = true;
  });
  // std::this_thread::sleep_for(std::chrono::milliseconds(10));
  scheduler.runAt(task, std::chrono::steady_clock::now());
  getchar();
}

// Not possible to add tasks in a scheduled task atm
void schedule5(ThreadManager& manager) {
  Scheduler scheduler(2, manager);
  bool stop = false;

  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  Task task([&stop, &scheduler]() {
    unsigned int i = 1;
    while (!stop) {
      auto future = scheduler.runIn([i]() {
        return std::to_string(i) + " second elapsed";
      }, std::chrono::milliseconds(60));
      std::cout << future.get() << " " << (int)stop << std::endl;
      ++i;
    }
  });
  task.setStopFunction([&stop]() {
    stop = true;
  });
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
  scheduler.runAt(task, std::chrono::steady_clock::now());
  getchar();
}

int main(int argc, char const *argv[]) {
  ThreadManager manager(1);
  ThreadPool tp(2, manager);
  Scheduler scheduler(2, manager);

 std::cout << "------- ThreadPool -------" << std::endl;

  tp.start();
  test1(tp);
  test2(tp);
  test3(tp);
  test4(tp);
  test5(tp);

 std::cout << "------- Scheduler -------" << std::endl;

  schedule1(scheduler);
  schedule2(scheduler);
  schedule3(scheduler);
  schedule4(manager);
  return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string>
#include <vector>
#include <random>
#include <algorithm>
#include <math.h>
#include <iostream>
#include <SDL.h>
#include <glm/glm.hpp>

const int FRAME_RES = 256;
std::string fractString("AABAB");
glm::vec3 FrameBuffer[FRAME_RES][FRAME_RES];
std::mt19937 m_Gen(5892753628915);
SDL_Window* m_Window = nullptr;
SDL_Surface* m_Surface = nullptr;

using namespace glm;

inline std::uint32_t ConvertPixel(const glm::vec3& pixel)
{
    int rs = m_Surface->format->Rshift;
    int gs = m_Surface->format->Gshift;
    int bs = m_Surface->format->Bshift;

    std::uint8_t r, g, b;
    if (pixel.r > 1.f)
        r = 255;

    else if (pixel.r <= 0.f)
        r = 0;
    else
        r = pixel.r * 255;

    if (pixel.g > 1.f)
        g = 255;

    else if (pixel.g <= 0.f)
        g = 0;
    else
        g = pixel.g * 255;

    if (pixel.b > 1.f)
        b = 255;

    else if (pixel.b <= 0.f)
        b = 0;
    else
        b = pixel.b * 255;

    return (b << bs) | (g << gs) | (r << rs);
}

void SwapBuffers(const vec3 frameBuf[FRAME_RES][FRAME_RES])
{
    for (int y = 0; y < FRAME_RES; y++)
    {
        Uint32 *row = (Uint32*)((Uint8*)m_Surface->pixels + y * m_Surface->pitch);
        for (int x = 0; x < FRAME_RES; x++)
            row[x] = ConvertPixel(frameBuf[y][x]);
    }
    SDL_UpdateWindowSurface(m_Window);
}

void waitForUserExit()
{
    SDL_Event e;
    bool wantToQuit = false;
    while (!wantToQuit)
    {
        SDL_PollEvent(&e);

        if (e.type == SDL_QUIT)
        {
            wantToQuit = true;
        }
    }
}

vec2 choosePoint(int a, int b)
{
    std::uniform_real_distribution<float> distributionA(a, b);
    std::uniform_real_distribution<float> distributionB(a, b);
    return vec2(distributionA(m_Gen), distributionB(m_Gen));
}

float r(int n, const vec2& chosenPoint)
{

    float a = chosenPoint.x;
    float b = chosenPoint.y;

    int Sn = n % fractString.size();
    if (fractString[Sn] == 'A')
    {
        return a;
    }
    else
    {
        return b;
    }
    return 0.f;

}

template <typename T = float>
auto clamp(T x, T a, T b) -> T
{
    return (x > a) ? ((x < b) ? x : b) : a;
}

#define ITERATIONS 10000
std::vector<float> precomtuteIterations(const vec2& cPoint)
{
    std::vector<float> result;
    result.resize(ITERATIONS);
    result[0] = 0.5f;
    for (int i = 1; i < ITERATIONS; i++)
    {
        result[i] = r(i, cPoint) * result[i - 1] * (1 - result[i - 1]);
    }
    return result;
}

float computeLyapunovExponent(const std::vector<float>& iterations, const vec2& cPoint)
{
    float result = 0.f;

    for (int i = 1; i < ITERATIONS; i++)
    {
        auto a = (2 * iterations[i]);
        auto oneminusa = 1 - a;
        auto ri = r(i, cPoint);

        result += logf(abs(ri * (oneminusa)));
    }

    return (float)(result / ITERATIONS);
}
#undef main
int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING != 0))
    {
        std::cout << "SDL_init failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Window = SDL_CreateWindow("Sword", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        FRAME_RES, FRAME_RES, SDL_WINDOW_OPENGL);

    if (!m_Window)
    {
        std::cout << "SDL_CreateWindow failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Surface = SDL_GetWindowSurface(m_Window);

    if (!m_Surface)
    {
        std::cout << "SDL_GetWindowSurface failed: " << SDL_GetError() << std::endl;
        return false;
    }

    for (int x = 0; x < FRAME_RES; x++)
    {
        for (int y = 0; y < FRAME_RES; y++)
        {
            auto point = choosePoint(2, 4);
            auto iterations = precomtuteIterations(point);
            auto lyapunovExp = computeLyapunovExponent(iterations, point);
            if (lyapunovExp > 0.f)
            {
                FrameBuffer[x][y] = vec3(0, 0.3, 1);
            }
            else if (lyapunovExp == 0.f)
            {
                FrameBuffer[x][y] = vec3(1, 0.3, 0);
            }
            else
            {
                FrameBuffer[x][y] = clamp(vec3(0.1, 0.1, 0.1) *(1- abs(lyapunovExp)),vec3(0), vec3(1));
            }
        }
        SwapBuffers(FrameBuffer);
    }

    waitForUserExit();
    return 0;
}

<commit_msg>more changes<commit_after>#include <stdio.h>
#include <string>
#include <vector>
#include <random>
#include <algorithm>
#include <math.h>
#include <iostream>
#include <SDL.h>
#include <glm/glm.hpp>

const int FRAME_RES = 256;
std::string fractString("AABAB");
glm::vec3 FrameBuffer[FRAME_RES][FRAME_RES];
std::mt19937 m_Gen(5892753628915);
SDL_Window* m_Window = nullptr;
SDL_Surface* m_Surface = nullptr;

using namespace glm;

inline std::uint32_t ConvertPixel(const glm::vec3& pixel)
{
    int rs = m_Surface->format->Rshift;
    int gs = m_Surface->format->Gshift;
    int bs = m_Surface->format->Bshift;

    std::uint8_t r, g, b;
    if (pixel.r > 1.f)
        r = 255;

    else if (pixel.r <= 0.f)
        r = 0;
    else
        r = pixel.r * 255;

    if (pixel.g > 1.f)
        g = 255;

    else if (pixel.g <= 0.f)
        g = 0;
    else
        g = pixel.g * 255;

    if (pixel.b > 1.f)
        b = 255;

    else if (pixel.b <= 0.f)
        b = 0;
    else
        b = pixel.b * 255;

    return (b << bs) | (g << gs) | (r << rs);
}

void SwapBuffers(const vec3 frameBuf[FRAME_RES][FRAME_RES])
{
    for (int y = 0; y < FRAME_RES; y++)
    {
        Uint32 *row = (Uint32*)((Uint8*)m_Surface->pixels + y * m_Surface->pitch);
        for (int x = 0; x < FRAME_RES; x++)
            row[x] = ConvertPixel(frameBuf[y][x]);
    }
    SDL_UpdateWindowSurface(m_Window);
}

void waitForUserExit()
{
    SDL_Event e;
    bool wantToQuit = false;
    while (!wantToQuit)
    {
        SDL_PollEvent(&e);

        if (e.type == SDL_QUIT)
        {
            wantToQuit = true;
        }
    }
}

vec2 choosePoint(int a, int b)
{
    std::uniform_real_distribution<float> distributionA(a, b);
    std::uniform_real_distribution<float> distributionB(a, b);
    return vec2(distributionA(m_Gen), distributionB(m_Gen));
}

float r(int n, const vec2& chosenPoint)
{

    float a = chosenPoint.x;
    float b = chosenPoint.y;

    int Sn = n % fractString.size();
    if (fractString[Sn] == 'A')
    {
        return a;
    }
    else
    {
        return b;
    }
    return 0.f;

}

template <typename T = float>
auto clamp(T x, T a, T b) -> T
{
    return (x > a) ? ((x < b) ? x : b) : a;
}

#define ITERATIONS 500
std::vector<float> precomtuteIterations(const vec2& cPoint)
{
    std::vector<float> result;
    result.resize(ITERATIONS);
    result[0] = 0.5f;
    for (int i = 1; i < ITERATIONS; i++)
    {
        result[i] = r(i, cPoint) * result[i - 1] * (1 - result[i - 1]);
    }
    return result;
}

float computeLyapunovExponent(const std::vector<float>& iterations, const vec2& cPoint)
{
    float result = 0.f;

    for (int i = 1; i < ITERATIONS; i++)
    {
        auto a = (2 * iterations[i]);
        auto oneminusa = 1 - a;
        auto ri = r(i, cPoint);

        result += logf(abs(ri * (oneminusa)));
    }

    return (float)(result / ITERATIONS);
}

#undef main
int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING != 0))
    {
        std::cout << "SDL_init failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Window = SDL_CreateWindow("LyapunovFract", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        FRAME_RES, FRAME_RES, SDL_WINDOW_OPENGL);

    if (!m_Window)
    {
        std::cout << "SDL_CreateWindow failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Surface = SDL_GetWindowSurface(m_Window);

    if (!m_Surface)
    {
        std::cout << "SDL_GetWindowSurface failed: " << SDL_GetError() << std::endl;
        return false;
    }

    for (int x = 0; x < FRAME_RES; x++)
    {
        for (int y = 0; y < FRAME_RES; y++)
        {
            auto point = choosePoint(0, 4);
            auto iterations = precomtuteIterations(point);
            auto lyapunovExp = computeLyapunovExponent(iterations, point);
            if (lyapunovExp > 0.f)
            {
                FrameBuffer[x][y] = vec3(0, 0, 1);
            }
            else if (lyapunovExp == 0.f)
            {
                FrameBuffer[x][y] = vec3(0, 1, 0);
            }
            else
            {
                FrameBuffer[x][y] = clamp(vec3(1, 1, 0.1) *(abs(lyapunovExp)),vec3(0), vec3(1));
            }
        }
        SwapBuffers(FrameBuffer);
    }
    SwapBuffers(FrameBuffer);
    waitForUserExit();
    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <boost/asio.hpp>
#include <boost/program_options.hpp>
#include "tcp_server.hpp"
#include "config.h"

int main(int argc, char * argv[])
{
	namespace po = boost::program_options;
	unsigned short port;
	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "show help message")
		("version", "show version")
		("port,p", po::value<unsigned short>(&port)->required(), "port")
	;
	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	if (vm.count("help"))
	{
		std::cout << desc << std::endl;
		return 0;
	}
	if (vm.count("version"))
	{
		std::cout << argv[0] << ' ' << VERSION_MAJOR << '.' << VERSION_MINOR << '.' << VERSION_PATCH << std::endl;
		return 0;
	}
	try
	{
		po::notify(vm);
	}
	catch (std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}
	boost::asio::io_service io_service;
	// Prepare server
	boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
	tcp_server server(io_service, endpoint);
	server.start_accept();
	io_service.run();
}<commit_msg>Catch errors related to invalid command line opts.<commit_after>#include <iostream>
#include <boost/asio.hpp>
#include <boost/program_options.hpp>
#include "tcp_server.hpp"
#include "config.h"

int main(int argc, char * argv[])
{
	namespace po = boost::program_options;
	unsigned short port;
	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "show help message")
		("version", "show version")
		("port,p", po::value<unsigned short>(&port)->required(), "port")
	;
	po::variables_map vm;
	try
	{
		po::store(po::parse_command_line(argc, argv, desc), vm);
	}
	catch (std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}
	if (vm.count("help"))
	{
		std::cout << desc << std::endl;
		return 0;
	}
	if (vm.count("version"))
	{
		std::cout << argv[0] << ' ' << VERSION_MAJOR << '.' << VERSION_MINOR << '.' << VERSION_PATCH << std::endl;
		return 0;
	}
	try
	{
		po::notify(vm);
	}
	catch (std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}
	boost::asio::io_service io_service;
	// Prepare server
	boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
	tcp_server server(io_service, endpoint);
	server.start_accept();
	io_service.run();
}<|endoftext|>


<commit_before>#include "game.hpp"

bool Game::uciHandler(std::string str) {
	std::vector<std::string> cmd = getStringArray(str);
		if(cmd[0] == "isready") {
			std::cout << "readyok\n";
		} else if(cmd[0] == "position") {
			gameHash.clear();
			gameHash.resize(0);
			if(cmd[1] == "startpos") {
				game_board.setFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
				if(cmd.size() > 3) {
					if(cmd[2] == "moves") {
						for(unsigned int i = 3; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			} else if(cmd[1] == "fen") {
				std::string fen;
				unsigned int pos = 2;

				for(unsigned int i = 2; i < 8; ++i) {
					fen += cmd[i];
					if(i != cmd.size() - 1) {
						fen.push_back(' ');
					}
					++pos;
				}

				game_board.setFen(fen);
				if(cmd.size() > pos) {
					if(cmd[pos] == "moves") {
						for(unsigned int i = pos + 1; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			}

			//gameHash.push_back(getHash(game_board));
		} else if(cmd[0] == "go") {
			if(cmd[1] == "depth") {
				max_depth = std::stoi(cmd[2]);
			  goFixedDepth();
			} else if(cmd[1] == "movetime") {
				goFixedTime(std::stoi(cmd[2]));
			} else if(cmd[1] == "infinite") {
				max_depth = 99;
				goFixedDepth();
			} else {
				wtime = 0, btime = 0;
				winc = 0, binc = 0, movestogo = 0, movestogoEnable = false;
				for(unsigned int i = 1; i < cmd.size(); ++i) {
					if(cmd[i] == "wtime") {
						wtime = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "btime") {
						btime = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "winc") {
						winc = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "binc") {
						binc = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "movestogo") {
						movestogoEnable = true;
						movestogo = std::stoi(cmd[i+1]);
					}
				}

				goTournament();
			}
		} else if(cmd[0] == "posmoves") {
			MoveArray moves;
			game_board.bitBoardMoveGenerator(moves);

			for(unsigned int i = 0; i < moves.count; ++i) {
				std::cout << moves.moveArray[i].getMoveString();
				std::cout << "\n";
			}

			game_board.evaluteAll();
			std::cout << game_board.evalute / PAWN_EV * 100 << "\n";
			std::cout << game_board.getFen() << "\n";

			std::cout << "inCheck (WHITE) : " << game_board.inCheck(WHITE) << "\n";
			std::cout << "inCheck (BLACK) : " << game_board.inCheck(BLACK) << "\n";
			std::cout << "color_hash: " << game_board.getColorHash() << "\n";
		} else if(cmd[0] == "move") {
			move(cmd[1]);
		} else if(cmd[0] == "quit") {
			return false;
		} else if(cmd[0] == "uci") {
			std::cout << "id name Zevra v1.1 build 227\n";
			std::cout << "id author sovaz1997\n";
			option.print();
			std::cout << "uciok\n";
		} else if(cmd[0] == "quit") {
			return false;
		} else if(cmd[0] == "stress") {
			game_board.stress = 0;
			double st = clock();
			for(unsigned int i = 0; i < 1000000; ++i) {
				game_board.bitBoardMoveGenerator(moveArray[0]);
			}
			std::cout << (int)(game_board.stress / ((clock() - st) / CLOCKS_PER_SEC)) << "\n";
		} else if(cmd[0] == "goback") {
			game_board.goBack();
		} else if(cmd[0] == "perft") {
			int k;
			std::cin >> k;
			double st = clock();
			uint64_t count = perft(k);
			std::cout << count << " " << (int)((double)count / (((double)clock() - (double)st) / (double)CLOCKS_PER_SEC)) << "\n";
		} else if(cmd[0] == "setoption" && cmd[1] == "name") {
			if(cmd[2] == "nullmove" && cmd[3] == "value") {
				if(cmd[4] == "true") {
					option.nullMovePrunningEnable = true;
				} else if(cmd[4] == "false") {
					option.nullMovePrunningEnable = false;
				}
			} else if(cmd[2] == "LMR" && cmd[3] == "value") {
				if(cmd[4] == "true") {
					option.lmrEnable = true;
				} else if(cmd[4] == "false") {
					option.lmrEnable = false;
				}
			}
		}

		return true;
}
<commit_msg>Zevra v1.2 r245 update<commit_after>#include "game.hpp"

bool Game::uciHandler(std::string str) {
	std::vector<std::string> cmd = getStringArray(str);
		if(cmd[0] == "isready") {
			std::cout << "readyok\n";
		} else if(cmd[0] == "position") {
			gameHash.clear();
			gameHash.resize(0);
			if(cmd[1] == "startpos") {
				game_board.setFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
				if(cmd.size() > 3) {
					if(cmd[2] == "moves") {
						for(unsigned int i = 3; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			} else if(cmd[1] == "fen") {
				std::string fen;
				unsigned int pos = 2;

				for(unsigned int i = 2; i < 8; ++i) {
					fen += cmd[i];
					if(i != cmd.size() - 1) {
						fen.push_back(' ');
					}
					++pos;
				}

				game_board.setFen(fen);
				if(cmd.size() > pos) {
					if(cmd[pos] == "moves") {
						for(unsigned int i = pos + 1; i < cmd.size(); ++i) {
							move(cmd[i]);
						}
					}
				}
			}

			//gameHash.push_back(getHash(game_board));
		} else if(cmd[0] == "go") {
			if(cmd[1] == "depth") {
				max_depth = std::stoi(cmd[2]);
			  goFixedDepth();
			} else if(cmd[1] == "movetime") {
				goFixedTime(std::stoi(cmd[2]));
			} else if(cmd[1] == "infinite") {
				max_depth = 99;
				goFixedDepth();
			} else {
				wtime = 0, btime = 0;
				winc = 0, binc = 0, movestogo = 0, movestogoEnable = false;
				for(unsigned int i = 1; i < cmd.size(); ++i) {
					if(cmd[i] == "wtime") {
						wtime = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "btime") {
						btime = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "winc") {
						winc = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "binc") {
						binc = std::stoi(cmd[i+1]);
					} else if(cmd[i] == "movestogo") {
						movestogoEnable = true;
						movestogo = std::stoi(cmd[i+1]);
					}
				}

				goTournament();
			}
		} else if(cmd[0] == "posmoves") {
			MoveArray moves;
			game_board.bitBoardMoveGenerator(moves);

			for(unsigned int i = 0; i < moves.count; ++i) {
				std::cout << moves.moveArray[i].getMoveString();
				std::cout << "\n";
			}

			game_board.evaluteAll();
			std::cout << game_board.evalute / PAWN_EV * 100 << "\n";
			std::cout << game_board.getFen() << "\n";

			std::cout << "inCheck (WHITE) : " << game_board.inCheck(WHITE) << "\n";
			std::cout << "inCheck (BLACK) : " << game_board.inCheck(BLACK) << "\n";
			std::cout << "color_hash: " << game_board.getColorHash() << "\n";
		} else if(cmd[0] == "move") {
			move(cmd[1]);
		} else if(cmd[0] == "quit") {
			return false;
		} else if(cmd[0] == "uci") {
			std::cout << "id name Zevra v1.2 r245\n";
			std::cout << "id author sovaz1997\n";
			option.print();
			std::cout << "uciok\n";
		} else if(cmd[0] == "quit") {
			return false;
		} else if(cmd[0] == "stress") {
			game_board.stress = 0;
			double st = clock();
			for(unsigned int i = 0; i < 1000000; ++i) {
				game_board.bitBoardMoveGenerator(moveArray[0]);
			}
			std::cout << (int)(game_board.stress / ((clock() - st) / CLOCKS_PER_SEC)) << "\n";
		} else if(cmd[0] == "goback") {
			game_board.goBack();
		} else if(cmd[0] == "perft") {
			int k;
			std::cin >> k;
			double st = clock();
			uint64_t count = perft(k);
			std::cout << count << " " << (int)((double)count / (((double)clock() - (double)st) / (double)CLOCKS_PER_SEC)) << "\n";
		} else if(cmd[0] == "setoption" && cmd[1] == "name") {
			if(cmd[2] == "nullmove" && cmd[3] == "value") {
				if(cmd[4] == "true") {
					option.nullMovePrunningEnable = true;
				} else if(cmd[4] == "false") {
					option.nullMovePrunningEnable = false;
				}
			} else if(cmd[2] == "LMR" && cmd[3] == "value") {
				if(cmd[4] == "true") {
					option.lmrEnable = true;
				} else if(cmd[4] == "false") {
					option.lmrEnable = false;
				}
			}
		}

		return true;
}
<|endoftext|>