<commit_before>#include <iostream>
#include <algorithm>
#include <iomanip>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <crafter.h>
#include <crafter/Utils/IPResolver.h>

using namespace std;
using namespace Crafter;

unsigned long max_threads = 254;  // TODO: more elegantly, we should query for the max number of BPF devices we can use

void usage() {
    cout << "Usage: whosup -i interface -a addresses [-q] [-t threads] [-r retries] [-w timeout]" << endl;
    exit(1);
}

int main(int argc, char *const *argv) {

    string iface, addresses;
    bool quiet = false;
    int threads = 0;
    int retries = 2;
    double timeout = 1.0;

    int c;
    extern char *optarg;
    extern int optind, optopt;
    if (argc < 5) usage();
    while((c =  getopt(argc, argv, ":i:a:qt:r:w:")) != EOF) {
        switch (c) {
        case 'i':
            iface = optarg;
            break;
        case 'a':
            addresses = optarg;
            break;
        case 'q':
            quiet = true;
            break;
        case 't':
            threads = atoi(optarg);
            break;
        case 'r':
            retries = atoi(optarg);
            break;
        case 'w':
            timeout = atof(optarg);
            break;
        case ':':
            cerr << "Option -" << (char)optopt << " requires an operand" << endl;
            usage();
        case '?':
            cerr << "Unrecognised option: -" << (char)optopt << endl;
            usage();
        }
    }

    string MyIP = GetMyIP(iface);
    string MyMAC = GetMyMAC(iface);

    Ethernet ether_header;
    ether_header.SetSourceMAC(MyMAC);
    ether_header.SetDestinationMAC("ff:ff:ff:ff:ff:ff");
    ARP arp_header;
    arp_header.SetOperation(ARP::Request);
    arp_header.SetSenderIP(MyIP);
    arp_header.SetSenderMAC(MyMAC);

    vector<string> net = GetIPs(addresses);
    vector<string>::iterator ip_addr;
    vector<Packet*> request_packets;
    for(ip_addr = net.begin() ; ip_addr != net.end() ; ip_addr++) {
        arp_header.SetTargetIP(*ip_addr);
        Packet* packet = new Packet;
        packet->PushLayer(ether_header);
        packet->PushLayer(arp_header);
        request_packets.push_back(packet);
    }

    vector<Packet*> replies_packets(request_packets.size());
    if (threads == 0) {
        threads = min(net.size(), max_threads);
    }
    SendRecv(request_packets.begin(), request_packets.end(), replies_packets.begin(), iface, timeout, retries, threads);

    vector<Packet*>::iterator it_pck;
    if (!quiet) {
        cout << setfill(' ') << setw(18) << left << "Host" << setw(42) << left << "Hostname" << setw(18) << left << "MAC Address" << endl;
    }
    int counter = 0;
    for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++) {
        Packet* reply_packet = (*it_pck);
        if(reply_packet) {
            ARP* arp_layer = reply_packet->GetLayer<ARP>();
            if (! quiet) {
                cout << setfill(' ') << setw(18) << left << arp_layer->GetSenderIP() << setw(42) << left << GetHostname(arp_layer->GetSenderIP()) << setw(18) << left << arp_layer->GetSenderMAC() << endl;
            }
            counter++;
        }
    }

    cout << counter << " hosts up." << endl;

    for(it_pck = request_packets.begin() ; it_pck < request_packets.end() ; it_pck++)
        delete (*it_pck);
    for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++)
        delete (*it_pck);

    return 0;
}
<commit_msg>Attempt to fix build on OpenWrt<commit_after>#include <iostream>
#include <algorithm>
#include <iomanip>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <crafter.h>
#include <crafter/Utils/IPResolver.h>

using namespace std;
using namespace Crafter;

unsigned long max_threads = 254;  // TODO: more elegantly, we should query for the max number of BPF devices we can use

void usage() {
    cout << "Usage: whosup -i interface -a addresses [-q] [-t threads] [-r retries] [-w timeout]" << endl;
    exit(1);
}

int main(int argc, char *const *argv) {

    string iface, addresses;
    bool quiet = false;
    int threads = 0;
    int retries = 2;
    double timeout = 1.0;

    int c;
    extern char *optarg;
    extern int optind, optopt;
    if (argc < 5) usage();
    while((c =  getopt(argc, argv, ":i:a:qt:r:w:")) != EOF) {
        switch (c) {
        case 'i':
            iface = optarg;
            break;
        case 'a':
            addresses = optarg;
            break;
        case 'q':
            quiet = true;
            break;
        case 't':
            threads = atoi(optarg);
            break;
        case 'r':
            retries = atoi(optarg);
            break;
        case 'w':
            timeout = atof(optarg);
            break;
        case ':':
            cerr << "Option -" << (char)optopt << " requires an operand" << endl;
            usage();
        case '?':
            cerr << "Unrecognised option: -" << (char)optopt << endl;
            usage();
        }
    }

    string MyIP = GetMyIP(iface);
    string MyMAC = GetMyMAC(iface);

    Ethernet ether_header;
    ether_header.SetSourceMAC(MyMAC);
    ether_header.SetDestinationMAC("ff:ff:ff:ff:ff:ff");
    ARP arp_header;
    arp_header.SetOperation(ARP::Request);
    arp_header.SetSenderIP(MyIP);
    arp_header.SetSenderMAC(MyMAC);

    vector<string> net = GetIPs(addresses);
    vector<string>::iterator ip_addr;
    vector<Packet*> request_packets;
    for(ip_addr = net.begin() ; ip_addr != net.end() ; ip_addr++) {
        arp_header.SetTargetIP(*ip_addr);
        Packet* packet = new Packet;
        packet->PushLayer(ether_header);
        packet->PushLayer(arp_header);
        request_packets.push_back(packet);
    }

    vector<Packet*> replies_packets(request_packets.size());
    if (threads == 0) {
        threads = min((unsigned long) net.size(), max_threads);
    }
    SendRecv(request_packets.begin(), request_packets.end(), replies_packets.begin(), iface, timeout, retries, threads);

    vector<Packet*>::iterator it_pck;
    if (!quiet) {
        cout << setfill(' ') << setw(18) << left << "Host" << setw(42) << left << "Hostname" << setw(18) << left << "MAC Address" << endl;
    }
    int counter = 0;
    for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++) {
        Packet* reply_packet = (*it_pck);
        if(reply_packet) {
            ARP* arp_layer = reply_packet->GetLayer<ARP>();
            if (! quiet) {
                cout << setfill(' ') << setw(18) << left << arp_layer->GetSenderIP() << setw(42) << left << GetHostname(arp_layer->GetSenderIP()) << setw(18) << left << arp_layer->GetSenderMAC() << endl;
            }
            counter++;
        }
    }

    cout << counter << " hosts up." << endl;

    for(it_pck = request_packets.begin() ; it_pck < request_packets.end() ; it_pck++)
        delete (*it_pck);
    for(it_pck = replies_packets.begin() ; it_pck < replies_packets.end() ; it_pck++)
        delete (*it_pck);

    return 0;
}
<|endoftext|>


<commit_before>#include "../gymnure.h"

int main(int argc, char** argv) {

	{
		unsigned int windowWidth = 800;
		unsigned int windowHeight = 600;

		Gymnure* gymnure = new Gymnure(windowWidth, windowHeight);

		gymnure->insertData("../../assets/sky.jpg", "../../assets/cube.obj");
		gymnure->insertData("../../assets/chalet.jpg", "../../assets/chalet.obj");

		while(1) {
			if(!gymnure->draw()) {
				break;
			}
		}

		delete gymnure;
		return (EXIT_SUCCESS);
	}
}
<commit_msg>remove medivh<commit_after>#include "../gymnure.h"

int main(int argc, char** argv) {

	{
		unsigned int windowWidth = 800;
		unsigned int windowHeight = 600;

		Gymnure* gymnure = new Gymnure(windowWidth, windowHeight);

		gymnure->insertData("../../assets/sky.jpg", "../../assets/cube.obj");
		gymnure->insertData("../../assets/chalet.jpg", "../../assets/chalet.obj");

		while(1) {
			if(!gymnure->draw()) {
				break;
			}
		}

		delete gymnure;
		return (EXIT_SUCCESS);
	}
}
<|endoftext|>


<commit_before>/* main.cpp
 * This file is a part of tasks library
 * Copyright (c) tasks authors (see file `COPYRIGHT` for the license)
 */
#include <iostream>
#include <boost/array.hpp>
#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#include <boost/task.hpp>

long fibonacci( long n)
{
	if ( n == 0) return 0;
	if ( n == 1) return 1;
	long k1( 1), k2( 0);
	for ( int i( 2); i <= n; ++i)
	{
		long tmp( k1);
		k1 = k1 + k2;
		k2 = tmp;
	}
	return k1;
}

int main()
{
	// create a thread-pool
	boost::tasks::static_pool< boost::tasks::unbounded_fifo > pool( boost::tasks::poolsize( 5) );

	// execute tasks in thread-pool
	// move tasks ownership to executor
	boost::tasks::handle< long > h1(
		boost::tasks::async(
			boost::tasks::make_task( fibonacci, 10),
			pool));
	boost::tasks::handle< long > h2(
		boost::tasks::async(
			boost::tasks::make_task( fibonacci, 5),
			pool));

	std::cout << "h1: is ready == " << std::boolalpha << h1.is_ready() << "\n";
	std::cout << "h2: is ready == " << std::boolalpha << h2.is_ready() << "\n";

	// wait for completion of both tasks
	boost::tasks::waitfor_all( h1, h2);

	std::cout << "h1: is ready == " << std::boolalpha << h1.is_ready() << "\n";
	std::cout << "h2: is ready == " << std::boolalpha << h2.is_ready() << "\n";
	std::cout << "h1: has value == " << std::boolalpha << h1.has_value() << "\n";
	std::cout << "h2: has value == " << std::boolalpha << h2.has_value() << "\n";
	std::cout << "h1: has exception == " << std::boolalpha << h1.has_exception() << "\n";
	std::cout << "h2: has exception == " << std::boolalpha << h2.has_exception() << "\n";

	// get results
	std::cout << "fibonacci(10) == " << h1.get() << std::endl;
	std::cout << "fibonacci(5) == " << h2.get() << std::endl;
	return 0;
}

<commit_msg>async and sync request handling with boost.task exteriments<commit_after>/* main.cpp
 * This file is a part of tasks library
 * Copyright (c) tasks authors (see file `COPYRIGHT` for the license)
 */
#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#include <boost/task.hpp>

typedef boost::shared_ptr<class Request> RequestPtr;
class Request
{
public:
	Request(const std::string & data)
		: data_(data)
	{}

	const std::string & Read() const
	{
		std::cout<<"\tRequest "<<this<<" Read "<<data_<<"\n";
		return data_;
	}

	void Write(const std::string & answer)
	{
		std::cout<<"\tRequest "<<this<<" Write "<<answer<<"\n";
	}

private:
	std::string data_;
};

class ExternalRequestHandler
{
public:
	ExternalRequestHandler(boost::asio::io_service & io_service)
		: timer_(io_service)
	{}

	void PerformExternalReqeust(const std::string & what, boost::tasks::spin::auto_reset_event * ev)
	{
		what_ = what;
		std::cout<<"\texternal request "<<what_<<" begin\n";
		timer_.expires_from_now(boost::posix_time::milliseconds(rand()%100 + 10));
		timer_.async_wait(boost::bind(&ExternalRequestHandler::HandleTimeout, this, ev));
	}

private:

	void HandleTimeout(boost::tasks::spin::auto_reset_event * ev)
	{
		std::cout<<"\texternal request "<<what_<<" end\n";
		ev->set();
	}

private:
	boost::asio::deadline_timer timer_;
	std::string what_;
};

typedef boost::shared_ptr<class RequestHandler> RequestHandlerPtr;
class RequestHandler
{
public:
	RequestHandler(boost::asio::io_service & io_service, const RequestPtr & request)
		: io_service_(io_service)
		, request_(request)
	{}

	void Process() const
	{
		std::cout<<"\tRequestHandler "<<request_.get()<<" exec begin\n";

		std::string data = request_->Read();

		Request("query1");

		boost::tasks::handle< void > subtask1(
			boost::tasks::async(
				boost::tasks::make_task( &RequestHandler::Subtask1, this )));
		boost::tasks::handle< void > subtask2(
			boost::tasks::async(
				boost::tasks::make_task( &RequestHandler::Subtask2, this )));

		boost::tasks::waitfor_all( subtask1, subtask2);

		Request("query5");

		request_->Write("some answer");

		std::cout<<"\tRequestHandler "<<request_.get()<<" exec end\n";
	}

private:

	void Subtask1() const
	{
		Request("query2");
		ExternalRequest("extquery1");
	}

	void Subtask2() const
	{
		Request("query3");
		ExternalRequest("extquery2");
		Request("query4");
	}

	void Request(const std::string & what) const
	{
		std::cout<<"\trequest "<<what<<" begin\n";
		boost::this_thread::sleep(boost::posix_time::milliseconds(rand()%100 + 10));
		std::cout<<"\trequest "<<what<<" end\n";
	}

	void ExternalRequest(const std::string & what) const
	{
		std::cout<<"\text request "<<what<<" begin\n";
		ExternalRequestHandler external_handler(io_service_);
		boost::tasks::spin::auto_reset_event ev;
		external_handler.PerformExternalReqeust(what, &ev);
		std::cout<<"\text request "<<what<<" wait for completion\n";
		ev.wait();
		std::cout<<"\text request "<<what<<" end\n";
	}

private:
	boost::asio::io_service & io_service_;
	RequestPtr request_;
};

void dummy_handler(const boost::system::error_code&) {}

int main()
{
	std::cout<<" * main\n";

	boost::tasks::static_pool< boost::tasks::unbounded_fifo > pool( boost::tasks::poolsize( 5) );

	std::cout<<" * creating asio::io_service\n";
	boost::asio::io_service io_service;

	// keep io_service busy
	boost::asio::deadline_timer dummy_timer(io_service);
	dummy_timer.expires_from_now(boost::posix_time::seconds(10));
	dummy_timer.async_wait(&dummy_handler);

	std::cout<<" * starting asio::io_service threads\n";
	boost::thread_group io_service_thread_pool;
	for(int i = 0; i < 3; ++i)
		io_service_thread_pool.create_thread(
			boost::bind(&boost::asio::io_service::run, &io_service)
		);

	std::cout<<" * creating request\n";
	RequestPtr request(new Request("some data"));
	std::cout<<" * creating handler\n";
	RequestHandlerPtr handler(new RequestHandler(io_service, request));

	std::cout<<" * creating task for handling request\n";
	boost::tasks::handle< void > request_processing(
		boost::tasks::async(
			boost::tasks::make_task( &RequestHandler::Process, handler ),
			pool));

	std::cout<<" * waiting task for colmpletion\n";
	request_processing.wait();

	std::cout<<" * terminationg io_service threads\n";
	io_service.stop();
	io_service_thread_pool.join_all();

	std::cout<<" * done\n";

	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <random>
#include <string>

#include <SFML/Graphics.hpp>
#include "Particle.hpp"

std::random_device randDevice;
std::mt19937 gen(randDevice());
std::uniform_real_distribution<> dist(0,5);

float MapToRange(float valueToBeMapped, float lowInputRange = 0.0, int highInputRange = 600.0, int lowDestRange = 0.0, int highDestRange = 255.0)
{
    return lowDestRange + ( valueToBeMapped - lowInputRange ) * ( highDestRange - lowDestRange ) / ( highInputRange - lowInputRange );
}

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Particle Motion", sf::Style::Default);

    sf::Clock deltaTime;
    float dt = 0.00000001;

    int numberOfParticles = 800;
    int imageCounter = 0;

    std::vector<Particle> particles;

    for(size_t i = 0; i < numberOfParticles; ++i)
    {

        Particle particle;
        Position initialPosition;

        initialPosition.xPosition = (window.getSize().x / numberOfParticles)*i;
        initialPosition.yPosition = 0.0f;
        particle.setPosition(initialPosition);

        particle.setFillColor(sf::Color(0,0,100));
        auto gravFactor = dist(gen);
        float gravity = static_cast<float>(-9.8*gravFactor);

        particle.setGravity(gravity);

        particles.push_back(particle);
    }

    while(window.isOpen())
    {
        window.clear(sf::Color::White);
        ++imageCounter;

        //Handle events
        sf::Event event;
        while(window.pollEvent(event))
        {
            //Window closed or escape key pressed: Exit
            if((event.type == sf::Event::Closed) or
                    ((event.type == sf::Event::KeyPressed) and (event.key.code == sf::Keyboard::Escape)))
            {
                window.close();
                break;
            }
        }

        for(auto& particle : particles)
        {
            particle.updatePosition(dt);
            auto position = particle.getPosition();

            auto redColorValue = MapToRange(position.yPosition);
            particle.setFillColor(sf::Color(redColorValue, 0, 100));

            window.draw(particle.getParticle());

        }

        window.display();
        sf::Image image = window.capture();
        std::string imagePath = "images/image" + std::to_string(imageCounter) + ".jpg";

        image.saveToFile(imagePath);

        dt = deltaTime.restart().asSeconds();
    }

    return EXIT_SUCCESS;
}
<commit_msg>Removed image writing bit.<commit_after>#include <iostream>
#include <random>
#include <string>

#include <SFML/Graphics.hpp>
#include "Particle.hpp"

std::random_device randDevice;
std::mt19937 gen(randDevice());
std::uniform_real_distribution<> dist(0,5);

float MapToRange(float valueToBeMapped, float lowInputRange = 0.0, int highInputRange = 600.0, int lowDestRange = 0.0, int highDestRange = 255.0)
{
    return lowDestRange + ( valueToBeMapped - lowInputRange ) * ( highDestRange - lowDestRange ) / ( highInputRange - lowInputRange );
}

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Particle Motion", sf::Style::Default);

    sf::Clock deltaTime;
    float dt = 0.00000001;

    int numberOfParticles = 800;
    int imageCounter = 0;

    std::vector<Particle> particles;

    for(size_t i = 0; i < numberOfParticles; ++i)
    {

        Particle particle;
        Position initialPosition;

        initialPosition.xPosition = (window.getSize().x / numberOfParticles)*i;
        initialPosition.yPosition = 0.0f;
        particle.setPosition(initialPosition);

        particle.setFillColor(sf::Color(0,0,100));
        auto gravFactor = dist(gen);
        float gravity = static_cast<float>(-9.8*gravFactor);

        particle.setGravity(gravity);

        particles.push_back(particle);
    }

    while(window.isOpen())
    {
        window.clear(sf::Color::White);
        ++imageCounter;

        //Handle events
        sf::Event event;
        while(window.pollEvent(event))
        {
            //Window closed or escape key pressed: Exit
            if((event.type == sf::Event::Closed) or
                    ((event.type == sf::Event::KeyPressed) and (event.key.code == sf::Keyboard::Escape)))
            {
                window.close();
                break;
            }
        }

        for(auto& particle : particles)
        {
            particle.updatePosition(dt);
            auto position = particle.getPosition();

            auto redColorValue = MapToRange(position.yPosition);
            particle.setFillColor(sf::Color(redColorValue, 0, 100));

            window.draw(particle.getParticle());

        }

        window.display();

        //sf::Image image = window.capture();
        //std::string imagePath = "images/image" + std::to_string(imageCounter) + ".jpg";
        //image.saveToFile(imagePath);

        dt = deltaTime.restart().asSeconds();
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>
#include "utils.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <vector>
#include "wall.h"
#include "math.h"
#include "drawing.h"
#include "circle.h"

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

using namespace std;

vector<circle> cs ;
vector<wall> ws;
vector<wall> iws;
vector<wall> gws;

circle puck(vec2(0,0), 0.03);

vec2 p1(0,0);

bool lmbPressed = false;

void keyboard (unsigned char a, int b, int c) {
  // p1.x = ((float)(b - 300))/300;
  // p1.y = -((float)(c - 300))/300;
}

void mouseMoved (int a, int b) {

  float dx = (a - p1.x) / (600);
  float dy = (p1.y - b) / (600);

  if (lmbPressed) {
    cs[0].v.x += 0.05 * dx;
    cs[0].v.y += 0.05 * dy;

  }

  p1.x = a;
  p1.y = b;
}

void passiveMouseMoved (int b, int c) {
  p1.x = b;
  p1.y = c;
}

void mouseFunc (int button, int state, int x, int y) {
  if (button == GLUT_LEFT_BUTTON) {
    lmbPressed = state == GLUT_DOWN;
  }

  // if (state == GLUT_DOWN) {
  //   lmbPressed = true;
  // }

  // if(state != GLUT_DOWN) return;

  // float window_width = glutGet(GLUT_WINDOW_WIDTH);
  // float window_height = glutGet(GLUT_WINDOW_HEIGHT);

  // unsigned int index;
  // glReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

  // printf ("Stencil at %d %d : %d \n", x, y, index);

}

void specialKey (int key, int b, int c) {
  // switch(key) {
  // case GLUT_KEY_UP:
  //   cs[0].v.y += 0.001;
  //   break;
  // case GLUT_KEY_DOWN:
  //   cs[0].v.y -= 0.001;
  //   break;
  // case GLUT_KEY_LEFT:
  //   cs[0].v.x -= 0.001;
  //   break;
  // case GLUT_KEY_RIGHT:
  //   cs[0].v.x += 0.001;
  //   break;
  // default:
  //   return;
  // }
}

void collideWithWalls (vector<circle> & cs, vector<wall> & ws, float m) {
  for (int j = 0; j < cs.size(); j++) {
    for (int i = 0; i < ws.size(); i++) {
      vec2 o;
      wall w = ws[i];
      bool b = ws[i].collision(cs[j].c, cs[j].r, o);

      if (b) {
  	cs[j].step(-m);

  	vec2 vel(cs[j].v.x, cs[j].v.y);
  	vel = vel.reflectedIn(ws[i].p0, ws[i].p1);
  	cs[j].v = vel;

  	cs[j].step(m);
  	break;
      }
    }
  }
}

void display() {

  float m = 1;

  glClearStencil(0);

  // clear buffers
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

  glEnable(GL_STENCIL_TEST);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

  glViewport (0, 0, 600, 600);

  // reset model view
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();

  // Draw the colour ramp scale
  // Clear the projection matrix
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();

  for (wall & w : ws) { w.draw(); }

  glColor3f(0.3, 0.3, 0.3);
  for (wall & iw : iws) { iw.draw(); }
  for (wall & gw : gws) { gw.draw(); }
  glColor3f(1, 1, 1);

  glStencilFunc(GL_ALWAYS, 1, -1);
  cs[0].draw();
  cs[0].step(m);
  glStencilFunc(GL_ALWAYS, 0, -1);

  for (int i = 1; i < cs.size(); i++) {
    cs[i].draw();
    cs[i].step(m);
  }

  puck.draw();
  puck.step(m);

  cs.push_back(puck);
  bool collided[cs.size()] ;
  for (int i = 0; i < cs.size() + 1; i++) collided[i] = false;

  // Collision with other pucks
  for (int i = 0; i < cs.size(); i++) {
    for (int j = 0; j < cs.size(); j++) {

      if (i != j && !collided[i] && !collided[j] && circle::collision(cs[i], cs[j])) {
  	cs[i].step(-m); cs[j].step(-m);

  	circle::performCollision(cs[i], cs[j], 1);

  	cs[i].step(m); cs[j].step(m);
  	collided[i] = collided[j] = true;

      }
    }
  }

  collideWithWalls(cs,  ws, m);

  puck = cs[cs.size() - 1];
  cs.pop_back();

  collideWithWalls(cs, iws, m);
  collideWithWalls(cs, gws, m);

  // vector<circle> puck_;
  // puck_.push_back(puck);

  // collideWithWalls(puck_, ws, m);

  for (circle & c : cs) {
    c.v = c.v.scale(0.9);
  }
  puck.v.scale(0.9);

  glutSwapBuffers();
  glutPostRedisplay ();
}

int main(int argc, char** argv) {
  wall::genInitial(3, 0.8, 0.05, 0.2, cs, ws, iws, gws);

  // cs.push_back(circle(vec2(0, 0)), 0.01);

  // OpenGL/glut setup
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_ALPHA | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_DEPTH | GLUT_STENCIL);

  glutInitWindowSize(600, 600);
  glutInitWindowPosition(50, 50);

  glutCreateWindow("final project - Yuriy Toporovskyy, Mostapha Mohamed");
  // glClearColor(0.1, 0.3, 0.3,0.0);

  // glEnable(GL_LIGHTING);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_STENCIL_TEST);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  // glEnable(GL_COLOR_MATERIAL);

  // Set up all callback functions.
  // glutIdleFunc          ([] ()                              { st.step();                  });
  glutKeyboardFunc      (keyboard);
  glutDisplayFunc (display);
  glutSpecialFunc (specialKey);
  glutMouseFunc (mouseFunc);
  glutMotionFunc (mouseMoved);
  glutPassiveMotionFunc (passiveMouseMoved);

  // glutMotionFunc        ([] (int a, int b)                  { st.mouseMoved(a,b);         });
  // glutDisplayFunc       ([] ()                              { st.display();               });
  // glutPassiveMotionFunc ([] (int a, int b)                  { st.passiveMouseMoved(a,b);  });
  // glutReshapeFunc       ([] (int a, int b)                  { st.reshape(a,b);            });

  // glutSpecialFunc       ([] (int a, int b, int c)           { st.specialKey(a,b,c);       });
  // glutIdleFunc          ([] ()                              { st.step();                  });
  // glutKeyboardFunc      ([] (unsigned char a, int b, int c) { st.keyboard(a,b,c);         });
  // glutMotionFunc        ([] (int a, int b)                  { st.mouseMoved(a,b);         });
  // glutDisplayFunc       ([] ()                              { st.display();               });
  // glutPassiveMotionFunc ([] (int a, int b)                  { st.passiveMouseMoved(a,b);  });
  // glutReshapeFunc       ([] (int a, int b)                  { st.reshape(a,b);            });
  // glutMouseFunc         ([] (int a, int b, int c, int d)    { st.mousePressed(a,b,c,d);   });
  // glutSpecialFunc       ([] (int a, int b, int c)           { st.specialKey(a,b,c);       });

  // // Initialize menus
  // // Menu containing generators.
  // int genMenu = glutCreateMenu
  //   ([] (int i) { st.newMesh(&TerrainGenerator::generators[i]); });

  // for (int i = 0; i < (int)TerrainGenerator::generators.size(); i++) {
  //   glutAddMenuEntry(TerrainGenerator::generators[i].name.c_str(), i);
  // }

  // // Colour ramp menu
  // int colMenu = glutCreateMenu
  //   ([] (int i) { st.colourRamp = i; });

  // for (int i = 0; i < (int)ColourRamp::colourRamps.size(); i++) {
  //   glutAddMenuEntry(ColourRamp::colourRamps[i].name.c_str(), i);
  // }

  // // Main menu.
  // glutCreateMenu ([] (int i)  { });
  // glutAddSubMenu("Add to mesh...", genMenu);
  // glutAddSubMenu("Select colour ramp...", colMenu);
  // glutAttachMenu(GLUT_RIGHT_BUTTON);

  // // Second window with heightmap
  // glutInitWindowPosition(700, 50);

  // int heightMapWindow = glutCreateWindow (argv[0]);
  // glutSetWindowTitle("Heightmap");
  // glutDisplayFunc       ([] ()                              { st.displayHM();               });
  // glutReshapeFunc       ([] (int a, int b)                  { st.reshapeHM (a,b);           });
  // glutMotionFunc        ([] (int a, int b)                  { st.mouseMovedHM(a,b);         });
  // glutPassiveMotionFunc ([] (int a, int b)                  { st.passiveMouseMovedHM(a,b);  });
  // glutMouseFunc         ([] (int a, int b, int c, int d)    { st.mousePressedHM(a,b,c,d);   });

  glutMainLoop();
  return(0);
}

<commit_msg>Added sort -of AI<commit_after>
#include "utils.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <vector>
#include "wall.h"
#include "math.h"
#include "drawing.h"
#include "circle.h"

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

using namespace std;

vector<circle> cs ;
vector<wall> ws;
vector<wall> iws;
vector<wall> gws;

const float puckRadius = 0.03;

circle puck(vec2(0,0), puckRadius);

vec2 p1(0,0);

bool lmbPressed = false;

void keyboard (unsigned char a, int b, int c) {
  // p1.x = ((float)(b - 300))/300;
  // p1.y = -((float)(c - 300))/300;
}

// bool inSegment (int i, int n, float x0, float y0) {

// }

void stepAI (float m, float diff, int i, float n, circle & c, circle puck) {
  vec2 towardsPuck = puck.c - c.c ;
  float dist = towardsPuck.magnitude();

  vec2 toAdd;

  if (dist < 0.4) {
    toAdd = towardsPuck.scale((3 * diff * m) / (1 + dist));
    // c.v = c.v + toAdd;
  } else {

    float al = 2*PI*(4*i+1)/(4.0*n);

    toAdd = vec2 (cosf(al), sinf(al));

    toAdd = toAdd.scale(0.55);

    // Test
    // drawPaddle(toAdd, 0.01);

    toAdd = (toAdd - c.v).scale(diff * m);
  }

  c.v = c.v + toAdd;

  // if (toAdd.x < 0 && toAdd.y < 0) {
  //   c.v = c.v - toAdd;
  // } else {
  //   c.v = c.v + toAdd;
  // }

}

void mouseMoved (int a, int b) {

  float dx = (a - p1.x) / (600);
  float dy = (p1.y - b) / (600);

  if (lmbPressed) {
    cs[0].v.x += 0.07 * dx;
    cs[0].v.y += 0.07 * dy;

  }

  p1.x = a;
  p1.y = b;
}

void passiveMouseMoved (int b, int c) {
  p1.x = b;
  p1.y = c;
}

void mouseFunc (int button, int state, int x, int y) {
  if (button == GLUT_LEFT_BUTTON) {
    lmbPressed = state == GLUT_DOWN;
  }

  // if (state == GLUT_DOWN) {
  //   lmbPressed = true;
  // }

  // if(state != GLUT_DOWN) return;

  // float window_width = glutGet(GLUT_WINDOW_WIDTH);
  // float window_height = glutGet(GLUT_WINDOW_HEIGHT);

  // unsigned int index;
  // glReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

  // printf ("Stencil at %d %d : %d \n", x, y, index);

}

void specialKey (int key, int b, int c) {
  // switch(key) {
  // case GLUT_KEY_UP:
  //   cs[0].v.y += 0.001;
  //   break;
  // case GLUT_KEY_DOWN:
  //   cs[0].v.y -= 0.001;
  //   break;
  // case GLUT_KEY_LEFT:
  //   cs[0].v.x -= 0.001;
  //   break;
  // case GLUT_KEY_RIGHT:
  //   cs[0].v.x += 0.001;
  //   break;
  // default:
  //   return;
  // }
}

bool collideWithWalls (vector<circle> & cs, vector<wall> & ws, float m) {
  boolean r = false;
  for (int j = 0; j < cs.size(); j++) {
    for (int i = 0; i < ws.size(); i++) {
      vec2 o;
      wall w = ws[i];
      bool b = ws[i].collision(cs[j].c, cs[j].r, o);

      if (b) {
  	cs[j].step(-m);

  	vec2 vel(cs[j].v.x, cs[j].v.y);
  	vel = vel.reflectedIn(ws[i].p0, ws[i].p1);
  	cs[j].v = vel;

  	cs[j].step(m);
	r = true;
  	break;
      }
    }
  }
  return r;
}

void display() {

  float m = 1;

  glClearStencil(0);

  // clear buffers
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

  glEnable(GL_STENCIL_TEST);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

  glViewport (0, 0, 600, 600);

  // reset model view
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();

  // Draw the colour ramp scale
  // Clear the projection matrix
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();

  for (wall & w : ws) { w.draw(); }

  glColor3f(0.3, 0.3, 0.3);
  for (wall & iw : iws) { iw.draw(); }
  for (wall & gw : gws) { gw.draw(); }
  glColor3f(1, 1, 1);

  glStencilFunc(GL_ALWAYS, 1, -1);
  cs[0].draw();
  cs[0].step(m);
  glStencilFunc(GL_ALWAYS, 0, -1);

  for (int i = 1; i < cs.size(); i++) {
    cs[i].draw();
    cs[i].step(m);

// void stepAI (float m, float diff, int i, circle & c, circle puck) {

    stepAI(m, 0.005, i, 3, cs[i], puck);

  }

  puck.draw();
  puck.step(m);

  cs.push_back(puck);
  bool collided[cs.size()] ;
  for (int i = 0; i < cs.size() + 1; i++) collided[i] = false;

  // Collision with other pucks
  for (int i = 0; i < cs.size(); i++) {
    for (int j = 0; j < cs.size(); j++) {

      if (i != j && !collided[i] && !collided[j] && circle::collision(cs[i], cs[j])) {
  	cs[i].step(-m); cs[j].step(-m);

  	circle::performCollision(cs[i], cs[j], 1);

  	cs[i].step(m); cs[j].step(m);
  	collided[i] = collided[j] = true;

      }
    }
  }

  collideWithWalls(cs,  ws, m);

  puck = cs[cs.size() - 1];
  cs.pop_back();

  collideWithWalls(cs, iws, m);
  collideWithWalls(cs, gws, m);

  vector<wall> gwsC (gws);

  vector<circle> puck_;
  puck_.push_back(puck);

  if (collideWithWalls(puck_, gws, m)) {
    puck = circle(vec2(0,0), puckRadius);
    puck.m = 0.3;
  }

  for (circle & c : cs) {
    c.v = c.v.scale(0.9);
  }
  puck.v.scale(0.9);

  glutSwapBuffers();
  glutPostRedisplay ();
}

int main(int argc, char** argv) {
  wall::genInitial(3, 0.8, 0.05, 0.2, cs, ws, iws, gws);

  puck.m = 0.3;

  // OpenGL/glut setup
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_ALPHA | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_DEPTH | GLUT_STENCIL);

  glutInitWindowSize(600, 600);
  glutInitWindowPosition(50, 50);

  glutCreateWindow("final project - Yuriy Toporovskyy, Mostapha Mohamed");
  // glClearColor(0.1, 0.3, 0.3,0.0);

  // glEnable(GL_LIGHTING);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_STENCIL_TEST);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  // glEnable(GL_COLOR_MATERIAL);

  // Set up all callback functions.
  // glutIdleFunc          ([] ()                              { st.step();                  });
  glutKeyboardFunc      (keyboard);
  glutDisplayFunc (display);
  glutSpecialFunc (specialKey);
  glutMouseFunc (mouseFunc);
  glutMotionFunc (mouseMoved);
  glutPassiveMotionFunc (passiveMouseMoved);

  // glutMotionFunc        ([] (int a, int b)                  { st.mouseMoved(a,b);         });
  // glutDisplayFunc       ([] ()                              { st.display();               });
  // glutPassiveMotionFunc ([] (int a, int b)                  { st.passiveMouseMoved(a,b);  });
  // glutReshapeFunc       ([] (int a, int b)                  { st.reshape(a,b);            });

  // glutSpecialFunc       ([] (int a, int b, int c)           { st.specialKey(a,b,c);       });
  // glutIdleFunc          ([] ()                              { st.step();                  });
  // glutKeyboardFunc      ([] (unsigned char a, int b, int c) { st.keyboard(a,b,c);         });
  // glutMotionFunc        ([] (int a, int b)                  { st.mouseMoved(a,b);         });
  // glutDisplayFunc       ([] ()                              { st.display();               });
  // glutPassiveMotionFunc ([] (int a, int b)                  { st.passiveMouseMoved(a,b);  });
  // glutReshapeFunc       ([] (int a, int b)                  { st.reshape(a,b);            });
  // glutMouseFunc         ([] (int a, int b, int c, int d)    { st.mousePressed(a,b,c,d);   });
  // glutSpecialFunc       ([] (int a, int b, int c)           { st.specialKey(a,b,c);       });

  // // Initialize menus
  // // Menu containing generators.
  // int genMenu = glutCreateMenu
  //   ([] (int i) { st.newMesh(&TerrainGenerator::generators[i]); });

  // for (int i = 0; i < (int)TerrainGenerator::generators.size(); i++) {
  //   glutAddMenuEntry(TerrainGenerator::generators[i].name.c_str(), i);
  // }

  // // Colour ramp menu
  // int colMenu = glutCreateMenu
  //   ([] (int i) { st.colourRamp = i; });

  // for (int i = 0; i < (int)ColourRamp::colourRamps.size(); i++) {
  //   glutAddMenuEntry(ColourRamp::colourRamps[i].name.c_str(), i);
  // }

  // // Main menu.
  // glutCreateMenu ([] (int i)  { });
  // glutAddSubMenu("Add to mesh...", genMenu);
  // glutAddSubMenu("Select colour ramp...", colMenu);
  // glutAttachMenu(GLUT_RIGHT_BUTTON);

  // // Second window with heightmap
  // glutInitWindowPosition(700, 50);

  // int heightMapWindow = glutCreateWindow (argv[0]);
  // glutSetWindowTitle("Heightmap");
  // glutDisplayFunc       ([] ()                              { st.displayHM();               });
  // glutReshapeFunc       ([] (int a, int b)                  { st.reshapeHM (a,b);           });
  // glutMotionFunc        ([] (int a, int b)                  { st.mouseMovedHM(a,b);         });
  // glutPassiveMotionFunc ([] (int a, int b)                  { st.passiveMouseMovedHM(a,b);  });
  // glutMouseFunc         ([] (int a, int b, int c, int d)    { st.mousePressedHM(a,b,c,d);   });

  glutMainLoop();
  return(0);
}

<|endoftext|>


<commit_before>#include <unistd.h>
#include <sys/time.h>
#include "server/sess.h"
#include "util/msg_queue.h"
#include <iostream>
#include <cstring>
#include <thread>
#include "proto/protob.pb.h"
#include "arduino/cArduino.h"
#include "conf/config.h"
#include <signal.h>

using namespace std;

IUINT32 iclock();

Config *setting;
cArduino *arduino;

//cArduino arduino(ArduinoBaundRate::B19200bps, "/dev/ttyACM0");
static void sig_alarm(int signo);

int main() {

    string file("./cfg.conf");
    setting = new Config(file);
    assert(setting != nullptr);

    struct timeval time;
    gettimeofday(&time, NULL);
    srand((time.tv_sec * 1000) + (time.tv_usec / 1000));

    string serverIP;
    serverIP = setting->GetString("serverIP", "127.0.0.1");
    int port = setting->GetInt("serverPort", 9999);
    KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);
    sess->NoDelay(1, 20, 2, 1);
    sess->WndSize(128, 128);
    sess->SetMtu(1400);
    assert(sess != nullptr);
    ssize_t nsent = {0};
    ssize_t nrecv = {0};
    char *buf = (char *) malloc(128);

    char *name = (char *) "/dev/ttyACM0";
    arduino = new cArduino(ArduinoBaundRate::B19200bps, name);

    sprintf(buf, "iam");
    sess->Write(buf, strlen(buf));
    for (;;) {
        sess->Update(iclock());
        memset(buf, 0, 128);
        ssize_t n = sess->Read(buf, 128);
        if (n > 0) {

            string msg(buf);
            Msg pb;
            pb.ParseFromString(msg);
            cout << pb.content() << endl;
            string cmd = pb.content().substr(0,1);
            string rev = pb.content();
            if (cmd.compare("3")==0||cmd.compare("4")==0){
                string cmdAngle;//指令+角度
                for(int i=0;i<rev.size();i++){
                    if (rev[i]!='-'){
                        cmdAngle+=rev[i];
                    }
                }
                arduino->write(cmdAngle);
                arduino->flush();
            } else if (cmd.compare("0")==0||cmd.compare("1")==0||cmd.compare("2")==0){
                arduino->write(cmd);
                arduino->flush();
                if(pb.content().size()>=3){
                    string t = pb.content().substr(2,pb.content().size()-2);
                    int i=atoi(t.c_str());
                    signal(SIGALRM, sig_alarm);
                    alarm(i);
                }
            }

        }

        nrecv += n;

        usleep(33);
    }
}

//shijian dao le de chuli
static void sig_alarm(int signo){
    system("date");
    arduino->write("0");
    arduino->flush();
    return;
}

void
itimeofday(long *sec, long *usec) {
    struct timeval time;
    gettimeofday(&time, NULL);
    if (sec) *sec = time.tv_sec;
    if (usec) *usec = time.tv_usec;
}

IUINT64 iclock64(void) {
    long s, u;
    IUINT64 value;
    itimeofday(&s, &u);
    value = ((IUINT64) s) * 1000 + (u / 1000);
    return value;
}

IUINT32 iclock() {
    return (IUINT32) (iclock64() & 0xfffffffful);
}
//#include <unistd.h>
//#include <sys/time.h>
//#include "server/sess.h"
//#include "util/msg_queue.h"
//#include <iostream>
//#include <cstring>
//#include <thread>
//#include "proto/protob.pb.h"
//#include "arduino/cArduino.h"
//#include "conf/config.h"
//
//
//using namespace std;
//
//IUINT32 iclock();
//
//
//
//Config *setting;
//cArduino *arduino;
//
//int main() {
//
//    string file("./cfg.conf");
//    setting = new Config(file);
//    assert(setting != nullptr);
//
//    struct timeval time;
//    gettimeofday(&time, NULL);
//    srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
//
//    string serverIP;
//    serverIP = setting->GetString("serverIP", "127.0.0.1");
//    int port = setting->GetInt("serverPort", 9999);
//    KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);
//    sess->NoDelay(1, 20, 2, 1);
//    sess->WndSize(128, 128);
//    sess->SetMtu(1400);
//    assert(sess != nullptr);
//    ssize_t nsent = {0};
//    ssize_t nrecv = {0};
//    char *buf = (char *) malloc(128);
//
//
//    char *name = (char *) "/dev/ttyACM0";
//    arduino = new cArduino(ArduinoBaundRate::B19200bps, name);
//
//
//    sprintf(buf, "iam");
//    sess->Write(buf, strlen(buf));
//    for (;;) {
//        sess->Update(iclock());
//        memset(buf, 0, 128);
//        ssize_t n = sess->Read(buf, 128);
//        if (n > 0) {
//
//            string msg(buf);
//            Msg pb;
//            pb.ParseFromString(msg);
//            cout << pb.content() << endl;
//            arduino->write(pb.content());
//            arduino->flush();
//        }
//        nrecv += n;
//
//        usleep(33);
//    }
//}
//
//
//void
//itimeofday(long *sec, long *usec) {
//    struct timeval time;
//    gettimeofday(&time, NULL);
//    if (sec) *sec = time.tv_sec;
//    if (usec) *usec = time.tv_usec;
//}
//
//IUINT64 iclock64(void) {
//    long s, u;
//    IUINT64 value;
//    itimeofday(&s, &u);
//    value = ((IUINT64) s) * 1000 + (u / 1000);
//    return value;
//}
//
//IUINT32 iclock() {
//    return (IUINT32) (iclock64() & 0xfffffffful);
//}
<commit_msg>增加从树莓派读取数据的线程<commit_after>#include <unistd.h>
#include <sys/time.h>
#include "server/sess.h"
#include "util/msg_queue.h"
#include <iostream>
#include <cstring>
#include <thread>
#include "proto/protob.pb.h"
#include "arduino/cArduino.h"
#include "conf/config.h"
#include <signal.h>
#include <thread>

using namespace std;

IUINT32 iclock();

Config *setting;
cArduino *arduino;

void run(){
    while(true){
        string msg;
        msg = arduino->read();
        if (!msg.empty()){
            cout << "from arduino: " << msg << endl;
        }
    }
}

//cArduino arduino(ArduinoBaundRate::B19200bps, "/dev/ttyACM0");
static void sig_alarm(int signo);

int main() {

    string file("./cfg.conf");
    setting = new Config(file);
    assert(setting != nullptr);

    struct timeval time;
    gettimeofday(&time, NULL);
    srand((time.tv_sec * 1000) + (time.tv_usec / 1000));

    string serverIP;
    serverIP = setting->GetString("serverIP", "127.0.0.1");
    int port = setting->GetInt("serverPort", 9999);
    KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);
    sess->NoDelay(1, 20, 2, 1);
    sess->WndSize(128, 128);
    sess->SetMtu(1400);
    assert(sess != nullptr);
    ssize_t nsent = {0};
    ssize_t nrecv = {0};
    char *buf = (char *) malloc(128);

    char *name = (char *) "/dev/ttyACM0";
    arduino = new cArduino(ArduinoBaundRate::B19200bps, name);

    thread readArduinoThread(run);
    readArduinoThread.detach();

    sprintf(buf, "iam");
    sess->Write(buf, strlen(buf));
    for (;;) {
        sess->Update(iclock());
        memset(buf, 0, 128);
        ssize_t n = sess->Read(buf, 128);
        if (n > 0) {

            string msg(buf);
            Msg pb;
            pb.ParseFromString(msg);
            cout << pb.content() << endl;
            string cmd = pb.content().substr(0,1);
            string rev = pb.content();
            if (cmd.compare("3")==0||cmd.compare("4")==0){
                string cmdAngle;//指令+角度
                for(int i=0;i<rev.size();i++){
                    if (rev[i]!='-'){
                        cmdAngle+=rev[i];
                    }
                }
                arduino->write(cmdAngle);
                arduino->flush();
            } else if (cmd.compare("0")==0||cmd.compare("1")==0||cmd.compare("2")==0){
                arduino->write(cmd);
                arduino->flush();
                if(pb.content().size()>=3){
                    string t = pb.content().substr(2,pb.content().size()-2);
                    int i=atoi(t.c_str());
                    signal(SIGALRM, sig_alarm);
                    alarm(i);
                }
            }

        }

        nrecv += n;

        usleep(33);
    }
}

//shijian dao le de chuli
static void sig_alarm(int signo){
    system("date");
    arduino->write("0");
    arduino->flush();
    return;
}

void
itimeofday(long *sec, long *usec) {
    struct timeval time;
    gettimeofday(&time, NULL);
    if (sec) *sec = time.tv_sec;
    if (usec) *usec = time.tv_usec;
}

IUINT64 iclock64(void) {
    long s, u;
    IUINT64 value;
    itimeofday(&s, &u);
    value = ((IUINT64) s) * 1000 + (u / 1000);
    return value;
}

IUINT32 iclock() {
    return (IUINT32) (iclock64() & 0xfffffffful);
}
//#include <unistd.h>
//#include <sys/time.h>
//#include "server/sess.h"
//#include "util/msg_queue.h"
//#include <iostream>
//#include <cstring>
//#include <thread>
//#include "proto/protob.pb.h"
//#include "arduino/cArduino.h"
//#include "conf/config.h"
//
//
//using namespace std;
//
//IUINT32 iclock();
//
//
//
//Config *setting;
//cArduino *arduino;
//
//int main() {
//
//    string file("./cfg.conf");
//    setting = new Config(file);
//    assert(setting != nullptr);
//
//    struct timeval time;
//    gettimeofday(&time, NULL);
//    srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
//
//    string serverIP;
//    serverIP = setting->GetString("serverIP", "127.0.0.1");
//    int port = setting->GetInt("serverPort", 9999);
//    KCPSession *sess = KCPSession::Dial(serverIP.c_str(), port);
//    sess->NoDelay(1, 20, 2, 1);
//    sess->WndSize(128, 128);
//    sess->SetMtu(1400);
//    assert(sess != nullptr);
//    ssize_t nsent = {0};
//    ssize_t nrecv = {0};
//    char *buf = (char *) malloc(128);
//
//
//    char *name = (char *) "/dev/ttyACM0";
//    arduino = new cArduino(ArduinoBaundRate::B19200bps, name);
//
//
//    sprintf(buf, "iam");
//    sess->Write(buf, strlen(buf));
//    for (;;) {
//        sess->Update(iclock());
//        memset(buf, 0, 128);
//        ssize_t n = sess->Read(buf, 128);
//        if (n > 0) {
//
//            string msg(buf);
//            Msg pb;
//            pb.ParseFromString(msg);
//            cout << pb.content() << endl;
//            arduino->write(pb.content());
//            arduino->flush();
//        }
//        nrecv += n;
//
//        usleep(33);
//    }
//}
//
//
//void
//itimeofday(long *sec, long *usec) {
//    struct timeval time;
//    gettimeofday(&time, NULL);
//    if (sec) *sec = time.tv_sec;
//    if (usec) *usec = time.tv_usec;
//}
//
//IUINT64 iclock64(void) {
//    long s, u;
//    IUINT64 value;
//    itimeofday(&s, &u);
//    value = ((IUINT64) s) * 1000 + (u / 1000);
//    return value;
//}
//
//IUINT32 iclock() {
//    return (IUINT32) (iclock64() & 0xfffffffful);
//}
<|endoftext|>


<commit_before>#include <unistd.h>
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
#include <queue>
#include <string.h>

using namespace std;
using namespace boost;

void runexec(char** argv);	//will use system calls to run the
							//commands provided

string findconnect(string str);		//outputs a string of every connector

queue<string> parseline(string str);		//separate commands by connectors from the original string

//char** parsecommand(string str);	//parse the spaces from each command and output as char*

//vector<string> parsecommand(string str);	//parse the spaces from each command and output as a string

vector<char* > parsecommand(string str);	//parse the spaces from each command and output as char*

int main(int argc, char** argv) {
	string input;
	bool end = false;
	while(!end) {
		cout << "$ ";
		getline(cin, input);
		string connect = findconnect(input);	//connect stores every connector
		queue<string> cmds = parseline(input);
		while(!cmds.empty()) {
			cout << "command: " << cmds.front() << endl;
			vector<string> param = parsecommand(cmds.front());
			for(int i=0; i<param.size(); ++i) {
				cout << "param: " << param[i] << endl;
			}
			cmds.pop();
		}
		execvp("ls","ls -a");

	}
	//first we need to parse once by
	//using find() to determine the closest
	//connector to the current command
	//
	//then we take the token and execute it
	//
	//then we check the connector to see if we
	//continue running commands

	return 0;
}

//will use system calls to run the commands provided
void runexec(char** argv) {

}

string findconnect(string str) {
	string out;
	int orcon = str.find("||");
	int andcon = str.find("&&");
	int semicon = str.find(";");

	if(orcon==-1 && andcon==-1 && semicon==-1)	//if all equal to -1, it means that
		return "";								//there are no more connectors

	if(andcon==-1) {	//if there is no "&&"
		if(semicon==-1) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else if(orcon==-1) {
			out.push_back(';');
			str.erase(semicon,1);
		}
		else if(orcon<semicon) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else {
			out.push_back(';');
			str.erase(semicon,1);
		}
	}
	else if(semicon==-1) {	//if there is no ";"
		if(andcon==-1) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else if(orcon==-1) {
			out.push_back('&');
			str.erase(andcon,2);
		}
		else if(orcon<andcon) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else {
			out.push_back('&');
			str.erase(andcon,2);
		}
	}
	else if(orcon==-1) {	//if there is no "||"
		if(andcon==-1) {
			out.push_back(';');
			str.erase(semicon,1);
		}
		else if(semicon==-1) {
			out.push_back('&');
			str.erase(andcon,2);
		}
		else if(andcon<semicon) {
			out.push_back('&');
			str.erase(andcon,2);
		}
		else {
			out.push_back(';');
			str.erase(semicon,1);
		}
	}
	else if(orcon<andcon) { //checks which connector is the closest if all are inputted
		if(orcon<andcon) {
			if(orcon<semicon) {
				out.push_back('|');
				str.erase(orcon,2);
			}
			else {
				out.push_back(';');
				str.erase(semicon);
			}
		}
	}
	else if(andcon<semicon) {
		out.push_back('&'); str.erase(andcon,2);
	}
	else {
		out.push_back(';');
		str.erase(semicon,1);
	}
	out = out + findconnect(str);
	return out;
}

queue<string> parseline(string str) {
	queue<string> out;
	char_separator<char> delim(";&|");
	tokenizer< char_separator<char> > token(str, delim);

	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
		out.push(*i);
	}
	return out;
}

//char** parsecommand(string str) {
//	int size = 0;
	//tokenizer<> token(str);
	//for(tokenizer<>::iterator i=token.begin(); i!=token.end(); ++i) {
	//	size++;
	//}
	//char** out;
	//int j = 0;
	//for(tokenizer<>::iterator i=token.begin(); i!=token.end(); ++i) {
	//	*(out+j) = (*i).c_str();
	//	++j;
	//}
	//return out;
//}

//vector<string> parsecommand(string str) {
//	vector<string> out;
//	char_separator<char> delim(" ");
//	tokenizer< char_separator<char> > token(str, delim);
//	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
//		out.push_back(*i);
//		cout << "*i: " << *i << endl;
//	}
//	return out;
//}

vector<const char* > parsecommand(string str) {
	vector<const char * > out;
	char_separator<char> delim(" ");
	tokenizer< char_separator<char> > token(str, delim);
	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
		const char* temp = new char();
		temp = (*i).c_str();
		out.push_back(temp);
		delete temp;
	}
	out.push_back(NULL);
	return out;
}

<commit_msg>parsed each arguement in one command and can run commands<commit_after>#include <unistd.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
#include <queue>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

using namespace std;
using namespace boost;

void runexec(char** argv);	//will use system calls to run the
							//commands provided

string findconnect(string str);		//outputs a string of every connector

queue<string> parseline(string str);		//separate commands by connectors from the original string

void parsecommand(char** &cstrarray, string str);	//parse the spaces from each command and output as char*

//vector<string> parsecommand(string str);	//parse the spaces from each command and output as a string

//vector<const char* > parsecommand(string str);	//parse the spaces from each command and output as char*

//void parsecommand(vector<const char* > arg, string str);	//parse the spaces from each command and output as char*

int main(int argc, char** argv) {
	string input;
	bool end = false;
	while(!end) {
		cout << "$ ";
		getline(cin, input);
		string connect = findconnect(input);	//connect stores every connector
		queue<string> cmds = parseline(input);
		while(!cmds.empty()) {
			cout << "command: " << cmds.front() << endl;
			char** cstr = new char*[cmds.front().size()];
			for(unsigned int i=0; i<cmds.front().size(); ++i) {
				cstr[i] = (char*) malloc (cmds.front().size());
			}
			parsecommand(cstr, cmds.front());
			runexec(cstr);
			//vector<const char* > param = parsecommand(cmds.front());
			//vector<const char* > param(cmds.front().size()+1);
			//parsecommand(param, cmds.front());
			//for(unsigned int i=0; i<param.size(); ++i) {
				//for(unsigned int j=0; (param[i][j])!='\0'; ++j) {
//					cout << "param: " << (param[i][j]) << endl;
				//}
				//execvp(param[0],param);
				//perror("Didn't work");
			//}
			//vector<string> test;
			//test.push_back("ls ");
			//test.push_back("-a ");
			//test.push_back("-l");
			//char** troll = new char*[test.size()*2];
			//cout << "test.size() : " << test.size() << endl;
			//for(unsigned i=0; i< test.size(); ++i) {
			//	cout << "Errror at " << i << endl;
			//	cout << "test[" << i << "] : " << test[i] << endl;
			//	strcpy(troll[i],test[i].c_str());
			//	cout << "troll[" << i << "] : " << troll[i] << endl;
			//}
			//execvp(test[0], test);

			cmds.pop();
			//for(unsigned int i=0; i<cmds.front().size(); ++i) {
			//	delete test[i];
			//}
			//delete [] test;
		}

	}
	//first we need to parse once by
	//using find() to determine the closest
	//connector to the current command
	//
	//then we take the token and execute it
	//
	//then we check the connector to see if we
	//continue running commands

	return 0;
}

//will use system calls to run the commands provided
void runexec(char** argv) {
	int pid = fork();
	if(pid==-1 ) {	//meaning fork() returned an error
		perror("Error with fork().");
		exit(1);
	}
	else if(pid==0) {	//meaning we're in the child process
		cout << "This is the child process." << endl;
		cout << "argv[0] : " << argv[0] << endl;
		if(execvp(argv[0], argv)) {
			perror("There was an error in execvp." );
		}
		exit(1);
	}
	else if(pid>0) {	//meaning we're in the parent process
		if(wait(0)==-1) {
			perror("There was an error with wait()." );
		}
	}
}

string findconnect(string str) {
	string out;
	int orcon = str.find("||");
	int andcon = str.find("&&");
	int semicon = str.find(";");

	if(orcon==-1 && andcon==-1 && semicon==-1)	//if all equal to -1, it means that
		return "";								//there are no more connectors

	if(andcon==-1) {	//if there is no "&&"
		if(semicon==-1) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else if(orcon==-1) {
			out.push_back(';');
			str.erase(semicon,1);
		}
		else if(orcon<semicon) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else {
			out.push_back(';');
			str.erase(semicon,1);
		}
	}
	else if(semicon==-1) {	//if there is no ";"
		if(andcon==-1) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else if(orcon==-1) {
			out.push_back('&');
			str.erase(andcon,2);
		}
		else if(orcon<andcon) {
			out.push_back('|');
			str.erase(orcon,2);
		}
		else {
			out.push_back('&');
			str.erase(andcon,2);
		}
	}
	else if(orcon==-1) {	//if there is no "||"
		if(andcon==-1) {
			out.push_back(';');
			str.erase(semicon,1);
		}
		else if(semicon==-1) {
			out.push_back('&');
			str.erase(andcon,2);
		}
		else if(andcon<semicon) {
			out.push_back('&');
			str.erase(andcon,2);
		}
		else {
			out.push_back(';');
			str.erase(semicon,1);
		}
	}
	else if(orcon<andcon) { //checks which connector is the closest if all are inputted
		if(orcon<andcon) {
			if(orcon<semicon) {
				out.push_back('|');
				str.erase(orcon,2);
			}
			else {
				out.push_back(';');
				str.erase(semicon);
			}
		}
	}
	else if(andcon<semicon) {
		out.push_back('&'); str.erase(andcon,2);
	}
	else {
		out.push_back(';');
		str.erase(semicon,1);
	}
	out = out + findconnect(str);
	return out;
}

queue<string> parseline(string str) {
	queue<string> out;
	char_separator<char> delim(";&|");
	tokenizer< char_separator<char> > token(str, delim);

	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
		out.push(*i);
	}
	return out;
}

void parsecommand(char** &cstrarray, string str) {
	vector<string> vecstr;
	char_separator<char> delim(" ");
	tokenizer< char_separator<char> > token(str, delim);
	unsigned int in =0;
	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
		vecstr.push_back(*i);
		++in;
	}
	for(unsigned int j=0; j<vecstr.size(); ++j) {
		strcpy(cstrarray[j], vecstr[j].c_str());
	}
	cstrarray[vecstr.size()] = '\0';
}

//vector<string> parsecommand(string str) {
//	vector<string> out;
//	char_separator<char> delim(" ");
//	tokenizer< char_separator<char> > token(str, delim);
//	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
//		out.push_back(*i);
//		cout << "*i: " << *i << endl;
//	}
//	return out;
//}

//vector<const char* > parsecommand(string str) {
//void parsecommand(vector<const char* > arg, string str) {
//	vector<string> strarray;
//	char_separator<char> delim(" ");
//	tokenizer< char_separator<char> > token(str, delim);
//	for(tokenizer< char_separator<char> >::iterator i=token.begin(); i!=token.end(); ++i) {
//		strarray.push_back(*i);
//	}
//	for(unsigned int i=0; i<strarray.size(); ++i) {
//		arg[i] = &(strarray[i][0]);
//	}
//	arg[strarray.size()] = NULL;
//}

<|endoftext|>


<commit_before><commit_msg>Simplified way the rigid body tree is initialized.<commit_after><|endoftext|>


<commit_before>#include "Consumer.h"
// public methods
ndn::Consumer::Consumer(string interest_name, int interest_lifetime)
{
    this->interest_name = interest_name;
    this->interest_lifetime = interest_lifetime;
}

ndn::Consumer::~Consumer()
{
    cout << "Bye you cruel world" << endl;
}

// register prefix on NFD
void ndn::Consumer::run()
{
    Interest interest(Name(this->interest_name));  // e.g. "/example/testApp/randomData"
    interest.setInterestLifetime(time::milliseconds(this->interest_lifetime));   // time::milliseconds(1000)
    interest.setMustBeFresh(true);

    m_face.expressInterest(interest,
                           bind(&ndn::Consumer::onData, this,  _1, _2),
                           bind(&ndn::Consumer::onTimeout, this, _1));

    cout << "Sending " << interest << endl;

    // processEvents will block until the requested data received or timeout occurs
    m_face.processEvents();
}

// private methods
// react to the reception of a reply from a Producer
void ndn::Consumer::onData(const Interest& interest, const Data& data)
{
    cout << "data-packet received: " << endl;
    Block block;
    size_t buffer_size;
    const u_int8_t* buffer;

    block = data.getContent();
    buffer = block.wire();
    buffer_size = block.size();

    for(int i = 0; i < buffer_size; i++)
        cout << (char)buffer[i];
}

// react on the request / Interest timing out
void ndn::Consumer::onTimeout(const Interest& interest)
{
    cout << "Timeout " << interest << endl;
}

//
// Main entry-point
//
int main(int argc, char** argv)
{
  string appName = boost::filesystem::basename(argv[0]);

  options_description desc("Programm Options");
  desc.add_options ()
      ("name,p", value<string>()->required (), "The name of the interest to be sent (Required)")
      ("lifetime,s", value<int>(), "The lifetime of the interest in milliseconds. (Default 1000ms)");

  positional_options_description positionalOptions;
  variables_map vm;

  try
  {
    store(command_line_parser(argc, argv).options(desc)
                .positional(positionalOptions).run(),
              vm); // throws on error

    notify(vm); //notify if required parameters are not provided.
  }
  catch(boost::program_options::required_option& e)
  {
    // user forgot to provide a required option
    cerr << "name           ... The name of the interest to be sent (Required)" << endl;
    cerr << "lifetime       ... The lifetime of the interest in milliseconds. (Default 1000ms)" << endl;
    cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData" << endl;
    cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --lifetime 1000" << endl;

    cerr << "ERROR: " << e.what() << endl << endl;
    return -1;
  }
  catch(boost::program_options::error& e)
  {
    // a given parameter is faulty (e.g. given a string, asked for int)
    cerr << "ERROR: " << e.what() << endl << endl;
    return -1;
  }
  catch(exception& e)
  {
    cerr << "Unhandled Exception reached the top of main: "
              << e.what() << ", application will now exit" << endl;
    return -1;
  }

  int lifetime = 1000;
  if(vm.count ("lifetime"))
  {
    lifetime = vm["lifetime"].as<int>();
  }

  // create new Consumer instance with given parameters
  ndn::Consumer consumer(vm["name"].as<string>(),lifetime);

  try
  {
    // start producer
    consumer.run();
  }
  catch (const exception& e)
  {
    // shit happens
    cerr << "ERROR: " << e.what() << endl;
  }

  return 0;
}
<commit_msg>client slipsum works<commit_after>#include "Consumer.h"
// public methods
ndn::Consumer::Consumer(string interest_name, int interest_lifetime)
{
    this->interest_name = interest_name;
    this->interest_lifetime = interest_lifetime;
}

ndn::Consumer::~Consumer()
{
    cout << "Bye you cruel world" << endl;
}

// register prefix on NFD
void ndn::Consumer::run()
{
    Interest interest(Name(this->interest_name));  // e.g. "/example/testApp/randomData"
    interest.setInterestLifetime(time::milliseconds(this->interest_lifetime));   // time::milliseconds(1000)
    interest.setMustBeFresh(true);

    m_face.expressInterest(interest,
                           bind(&ndn::Consumer::onData, this,  _1, _2),
                           bind(&ndn::Consumer::onTimeout, this, _1));

    cout << "Sending " << interest << endl;

    // processEvents will block until the requested data received or timeout occurs
    m_face.processEvents();
}

// private methods
// react to the reception of a reply from a Producer
void ndn::Consumer::onData(const Interest& interest, const Data& data)
{
    cout << "data-packet received: " << endl;

    const Block& block = data.getContent();
    std::cout.write((const char*)block.value(),block.value_size());
    cout << endl;
}

// react on the request / Interest timing out
void ndn::Consumer::onTimeout(const Interest& interest)
{
    cout << "Timeout " << interest << endl;
}

//
// Main entry-point
//
int main(int argc, char** argv)
{
  string appName = boost::filesystem::basename(argv[0]);

  options_description desc("Programm Options");
  desc.add_options ()
      ("name,p", value<string>()->required (), "The name of the interest to be sent (Required)")
      ("lifetime,s", value<int>(), "The lifetime of the interest in milliseconds. (Default 1000ms)");

  positional_options_description positionalOptions;
  variables_map vm;

  try
  {
    store(command_line_parser(argc, argv).options(desc)
                .positional(positionalOptions).run(),
              vm); // throws on error

    notify(vm); //notify if required parameters are not provided.
  }
  catch(boost::program_options::required_option& e)
  {
    // user forgot to provide a required option
    cerr << "name           ... The name of the interest to be sent (Required)" << endl;
    cerr << "lifetime       ... The lifetime of the interest in milliseconds. (Default 1000ms)" << endl;
    cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData" << endl;
    cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --lifetime 1000" << endl;

    cerr << "ERROR: " << e.what() << endl << endl;
    return -1;
  }
  catch(boost::program_options::error& e)
  {
    // a given parameter is faulty (e.g. given a string, asked for int)
    cerr << "ERROR: " << e.what() << endl << endl;
    return -1;
  }
  catch(exception& e)
  {
    cerr << "Unhandled Exception reached the top of main: "
              << e.what() << ", application will now exit" << endl;
    return -1;
  }

  int lifetime = 1000;
  if(vm.count ("lifetime"))
  {
    lifetime = vm["lifetime"].as<int>();
  }

  // create new Consumer instance with given parameters
  ndn::Consumer consumer(vm["name"].as<string>(),lifetime);

  try
  {
    // start producer
    consumer.run();
  }
  catch (const exception& e)
  {
    // shit happens
    cerr << "ERROR: " << e.what() << endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/heartbeat_sender.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "remoting/base/constants.h"
#include "remoting/host/host_config.h"
#include "remoting/jingle_glue/iq_sender.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/signal_strategy.h"
#include "third_party/libjingle/source/talk/xmllite/xmlelement.h"
#include "third_party/libjingle/source/talk/xmpp/constants.h"

using buzz::QName;
using buzz::XmlElement;

namespace remoting {

namespace {
const char kHeartbeatQueryTag[] = "heartbeat";
const char kHostIdAttr[] = "hostid";
const char kHeartbeatSignatureTag[] = "signature";
const char kSignatureTimeAttr[] = "time";

const char kHeartbeatResultTag[] = "heartbeat-result";
const char kSetIntervalTag[] = "set-interval";

const int64 kDefaultHeartbeatIntervalMs = 5 * 60 * 1000;  // 5 minutes.
}

HeartbeatSender::HeartbeatSender(base::MessageLoopProxy* message_loop,
                                 MutableHostConfig* config)

    : state_(CREATED),
      message_loop_(message_loop),
      config_(config),
      interval_ms_(kDefaultHeartbeatIntervalMs) {
  DCHECK(config_);
}

HeartbeatSender::~HeartbeatSender() {
  DCHECK(state_ == CREATED || state_ == INITIALIZED || state_ == STOPPED);
}

bool HeartbeatSender::Init() {
  DCHECK(state_ == CREATED);

  if (!config_->GetString(kHostIdConfigPath, &host_id_)) {
    LOG(ERROR) << "host_id is not defined in the config.";
    return false;
  }

  if (!key_pair_.Load(config_)) {
    return false;
  }

  state_ = INITIALIZED;

  return true;
}

void HeartbeatSender::OnSignallingConnected(SignalStrategy* signal_strategy,
                                            const std::string& full_jid) {
  DCHECK(message_loop_->BelongsToCurrentThread());
  DCHECK(state_ == INITIALIZED || state_ == STOPPED);
  state_ = STARTED;

  full_jid_ = full_jid;

  iq_sender_.reset(new IqSender(signal_strategy));

  DoSendStanza();
  timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_), this,
               &HeartbeatSender::DoSendStanza);
}

void HeartbeatSender::OnSignallingDisconnected() {
  DCHECK(message_loop_->BelongsToCurrentThread());
  state_ = STOPPED;
  request_.reset();
  iq_sender_.reset();
}

// Ignore any notifications other than signalling
// connected/disconnected events.
void HeartbeatSender::OnAccessDenied() { }
void HeartbeatSender::OnClientAuthenticated(const std::string& jid) { }
void HeartbeatSender::OnClientDisconnected(const std::string& jid) { }
void HeartbeatSender::OnShutdown() { }

void HeartbeatSender::DoSendStanza() {
  DCHECK(message_loop_->BelongsToCurrentThread());
  DCHECK_EQ(state_, STARTED);

  VLOG(1) << "Sending heartbeat stanza to " << kChromotingBotJid;
  request_.reset(iq_sender_->SendIq(
      buzz::STR_SET, kChromotingBotJid, CreateHeartbeatMessage(),
      base::Bind(&HeartbeatSender::ProcessResponse,
                 base::Unretained(this))));
}

void HeartbeatSender::ProcessResponse(const XmlElement* response) {
  DCHECK(message_loop_->BelongsToCurrentThread());

  std::string type = response->Attr(buzz::QN_TYPE);
  if (type == buzz::STR_ERROR) {
    LOG(ERROR) << "Received error in response to heartbeat: "
               << response->Str();
    return;
  }

  // This method must only be called for error or result stanzas.
  DCHECK_EQ(std::string(buzz::STR_RESULT), type);

  const XmlElement* result_element =
      response->FirstNamed(QName(kChromotingXmlNamespace, kHeartbeatResultTag));
  if (result_element) {
    const XmlElement* set_interval_element =
        result_element->FirstNamed(QName(kChromotingXmlNamespace,
                                         kSetIntervalTag));
    if (set_interval_element) {
      const std::string& interval_str = set_interval_element->BodyText();
      int interval;
      if (!base::StringToInt(interval_str, &interval) || interval <= 0) {
        LOG(ERROR) << "Received invalid set-interval: "
                   << set_interval_element->Str();
      } else {
        SetInterval(interval * base::Time::kMillisecondsPerSecond);
      }
    }
  }
}

void HeartbeatSender::SetInterval(int interval) {
  if (interval != interval_ms_) {
    interval_ms_ = interval;

    // Restart the timer with the new interval.
    if (state_ == STARTED) {
      timer_.Stop();
      timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_),
                   this, &HeartbeatSender::DoSendStanza);
    }
  }
}

XmlElement* HeartbeatSender::CreateHeartbeatMessage() {
  XmlElement* query = new XmlElement(
      QName(kChromotingXmlNamespace, kHeartbeatQueryTag));
  query->AddAttr(QName(kChromotingXmlNamespace, kHostIdAttr), host_id_);
  query->AddElement(CreateSignature());
  return query;
}

XmlElement* HeartbeatSender::CreateSignature() {
  XmlElement* signature_tag = new XmlElement(
      QName(kChromotingXmlNamespace, kHeartbeatSignatureTag));

  int64 time = static_cast<int64>(base::Time::Now().ToDoubleT());
  std::string time_str(base::Int64ToString(time));
  signature_tag->AddAttr(
      QName(kChromotingXmlNamespace, kSignatureTimeAttr), time_str);

  std::string message = full_jid_ + ' ' + time_str;
  std::string signature(key_pair_.GetSignature(message));
  signature_tag->AddText(signature);

  return signature_tag;
}

}  // namespace remoting
<commit_msg>Stop heartbeat timer when signalling is disconnected.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/heartbeat_sender.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "remoting/base/constants.h"
#include "remoting/host/host_config.h"
#include "remoting/jingle_glue/iq_sender.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/signal_strategy.h"
#include "third_party/libjingle/source/talk/xmllite/xmlelement.h"
#include "third_party/libjingle/source/talk/xmpp/constants.h"

using buzz::QName;
using buzz::XmlElement;

namespace remoting {

namespace {
const char kHeartbeatQueryTag[] = "heartbeat";
const char kHostIdAttr[] = "hostid";
const char kHeartbeatSignatureTag[] = "signature";
const char kSignatureTimeAttr[] = "time";

const char kHeartbeatResultTag[] = "heartbeat-result";
const char kSetIntervalTag[] = "set-interval";

const int64 kDefaultHeartbeatIntervalMs = 5 * 60 * 1000;  // 5 minutes.
}

HeartbeatSender::HeartbeatSender(base::MessageLoopProxy* message_loop,
                                 MutableHostConfig* config)

    : state_(CREATED),
      message_loop_(message_loop),
      config_(config),
      interval_ms_(kDefaultHeartbeatIntervalMs) {
  DCHECK(config_);
}

HeartbeatSender::~HeartbeatSender() {
  DCHECK(state_ == CREATED || state_ == INITIALIZED || state_ == STOPPED);
}

bool HeartbeatSender::Init() {
  DCHECK(state_ == CREATED);

  if (!config_->GetString(kHostIdConfigPath, &host_id_)) {
    LOG(ERROR) << "host_id is not defined in the config.";
    return false;
  }

  if (!key_pair_.Load(config_)) {
    return false;
  }

  state_ = INITIALIZED;

  return true;
}

void HeartbeatSender::OnSignallingConnected(SignalStrategy* signal_strategy,
                                            const std::string& full_jid) {
  DCHECK(message_loop_->BelongsToCurrentThread());
  DCHECK(state_ == INITIALIZED || state_ == STOPPED);
  state_ = STARTED;

  full_jid_ = full_jid;

  iq_sender_.reset(new IqSender(signal_strategy));

  DoSendStanza();
  timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_), this,
               &HeartbeatSender::DoSendStanza);
}

void HeartbeatSender::OnSignallingDisconnected() {
  DCHECK(message_loop_->BelongsToCurrentThread());
  state_ = STOPPED;
  request_.reset();
  iq_sender_.reset();
  timer_.Stop();
}

// Ignore any notifications other than signalling
// connected/disconnected events.
void HeartbeatSender::OnAccessDenied() { }
void HeartbeatSender::OnClientAuthenticated(const std::string& jid) { }
void HeartbeatSender::OnClientDisconnected(const std::string& jid) { }
void HeartbeatSender::OnShutdown() { }

void HeartbeatSender::DoSendStanza() {
  DCHECK(message_loop_->BelongsToCurrentThread());
  DCHECK_EQ(state_, STARTED);

  VLOG(1) << "Sending heartbeat stanza to " << kChromotingBotJid;
  request_.reset(iq_sender_->SendIq(
      buzz::STR_SET, kChromotingBotJid, CreateHeartbeatMessage(),
      base::Bind(&HeartbeatSender::ProcessResponse,
                 base::Unretained(this))));
}

void HeartbeatSender::ProcessResponse(const XmlElement* response) {
  DCHECK(message_loop_->BelongsToCurrentThread());

  std::string type = response->Attr(buzz::QN_TYPE);
  if (type == buzz::STR_ERROR) {
    LOG(ERROR) << "Received error in response to heartbeat: "
               << response->Str();
    return;
  }

  // This method must only be called for error or result stanzas.
  DCHECK_EQ(std::string(buzz::STR_RESULT), type);

  const XmlElement* result_element =
      response->FirstNamed(QName(kChromotingXmlNamespace, kHeartbeatResultTag));
  if (result_element) {
    const XmlElement* set_interval_element =
        result_element->FirstNamed(QName(kChromotingXmlNamespace,
                                         kSetIntervalTag));
    if (set_interval_element) {
      const std::string& interval_str = set_interval_element->BodyText();
      int interval;
      if (!base::StringToInt(interval_str, &interval) || interval <= 0) {
        LOG(ERROR) << "Received invalid set-interval: "
                   << set_interval_element->Str();
      } else {
        SetInterval(interval * base::Time::kMillisecondsPerSecond);
      }
    }
  }
}

void HeartbeatSender::SetInterval(int interval) {
  if (interval != interval_ms_) {
    interval_ms_ = interval;

    // Restart the timer with the new interval.
    if (state_ == STARTED) {
      timer_.Stop();
      timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(interval_ms_),
                   this, &HeartbeatSender::DoSendStanza);
    }
  }
}

XmlElement* HeartbeatSender::CreateHeartbeatMessage() {
  XmlElement* query = new XmlElement(
      QName(kChromotingXmlNamespace, kHeartbeatQueryTag));
  query->AddAttr(QName(kChromotingXmlNamespace, kHostIdAttr), host_id_);
  query->AddElement(CreateSignature());
  return query;
}

XmlElement* HeartbeatSender::CreateSignature() {
  XmlElement* signature_tag = new XmlElement(
      QName(kChromotingXmlNamespace, kHeartbeatSignatureTag));

  int64 time = static_cast<int64>(base::Time::Now().ToDoubleT());
  std::string time_str(base::Int64ToString(time));
  signature_tag->AddAttr(
      QName(kChromotingXmlNamespace, kSignatureTimeAttr), time_str);

  std::string message = full_jid_ + ' ' + time_str;
  std::string signature(key_pair_.GetSignature(message));
  signature_tag->AddText(signature);

  return signature_tag;
}

}  // namespace remoting
<|endoftext|>


<commit_before>#include <allegro5/allegro5.h>
#include <allegro5/allegro_image.h>
#include "player.h"

int main()
{
	al_init();

	al_init_image_addon();

	ALLEGRO_DISPLAY *display;
	al_set_new_display_flags(ALLEGRO_WINDOWED);
	display = al_create_display(800, 600);

	al_install_keyboard();

	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	al_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)display);
	al_register_event_source(event_queue, al_get_keyboard_event_source());

	Player player;
	player.Set_position(20, al_get_display_height(display));

	float last_update = al_current_time();
	float dt;

	while(1)
	{
		float current_time = al_current_time();
		dt = current_time - last_update;
		last_update = current_time;

		ALLEGRO_EVENT event;
		if (al_get_next_event(event_queue, &event))
		{
			if (ALLEGRO_EVENT_DISPLAY_CLOSE == event.type)
			{
				break;
			}
			player.Event(event);
		}

		player.Update(dt);

		player.Draw();
		al_flip_display();
		al_clear_to_color(al_map_rgb(0, 0, 0));

		al_rest(0.001);
	}

	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
}
<commit_msg>Added ESC to quit.<commit_after>#include <allegro5/allegro5.h>
#include <allegro5/allegro_image.h>
#include "player.h"

int main()
{
	al_init();

	al_init_image_addon();

	ALLEGRO_DISPLAY *display;
	al_set_new_display_flags(ALLEGRO_WINDOWED);
	display = al_create_display(800, 600);

	al_install_keyboard();

	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	al_register_event_source(event_queue, (ALLEGRO_EVENT_SOURCE *)display);
	al_register_event_source(event_queue, al_get_keyboard_event_source());

	Player player;
	player.Set_position(20, al_get_display_height(display));

	float last_update = al_current_time();
	float dt;

	while(1)
	{
		float current_time = al_current_time();
		dt = current_time - last_update;
		last_update = current_time;

		ALLEGRO_EVENT event;
		if (al_get_next_event(event_queue, &event))
		{
			if (ALLEGRO_EVENT_DISPLAY_CLOSE == event.type ||
					ALLEGRO_EVENT_KEY_DOWN == event.type &&
					ALLEGRO_KEY_ESCAPE == event.keyboard.keycode)
			{
				break;
			}
			player.Event(event);
		}

		player.Update(dt);

		player.Draw();
		al_flip_display();
		al_clear_to_color(al_map_rgb(0, 0, 0));

		al_rest(0.001);
	}

	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
}
<|endoftext|>


<commit_before>/* The MIT License (MIT)
 *
 * Copyright (c) 2014 Colin Wallace
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/*
 * Printipi/main.cpp
 *
 * main is the program's main entry point.
 * main handles command line arguments, and instantiates the serial communications, State, and machine-specific driver.
 * Driver type is passed into this compilation unit as a command-line argument (gcc -DMACHINE=...)
 *
 * Printipi Github repository: https://github.com/Wallacoloo/printipi/
 * Printipi Google Group (forum): https://groups.google.com/forum/#!forum/printipi
 *
 * Miscellaneous Printipi discussions:
 *   http://forums.reprap.org/read.php?2,396157
 *   https://groups.google.com/forum/#!searchin/deltabot/wallacoloo|sort:relevance/deltabot/JQNpmnlYYUc/_6V6SYcOGMUJ
 *   http://youtube.com/watch?v=g4UD5MRas3E
 *   http://youtube.com/watch?v=gAruwqOEuPs
 */

#define COMPILING_MAIN //used elsewhere to do one-time warnings, etc.

#include "compileflags.h"

//Includes for the CATCH testing framework
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

#include <string>
#include <sys/mman.h> //for mlockall
#include <iostream> //for std::cin
#include "common/logging.h"

#include "gparse/com.h"
#include "state.h"
#include "argparse.h"
#include "filesystem.h"

//MACHINE_PATH is calculated in the Makefile and then passed as a define through the make system (ie gcc -DMACHINEPATH='"path"')
//To set the path, call make MACHINE_PATH=...
//or, call make MACHINE=<machine>, eg MACHINE=rpi::KosselPi (case-sensitive) and the path will be calculated from that (src/machines/rpi/kossel.h)
#include MACHINE_PATH

#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)

static void printUsage(char* cmd) {
    //#ifndef NO_USAGE_INFO
    LOGE("usage: %s [input-file] [output-file] [--help] [--quiet] [--verbose] [--do-tests [CATCH-arguments ...] ]\n", cmd);
    LOGE("  if input-file is not provided, it defaults to stdin\n");
    LOGE("  if output-file is not provided, it defaults to strout\n");
    LOGE("  --do-tests is only recognized if program was compiled with ENABLE_TESTS=1\n");
    LOGE("examples:\n");
    LOGE("  print a gcode file: %s file.gcode\n", cmd);
    LOGE("  mock serial port: %s /dev/tty3dpm /dev/tty3dps\n", cmd);
}

int main_(int argc, char **argv) {
    //useful to setup fail-safe exit routines first-thing for catching debug info.
    SchedulerBase::configureExitHandlers();

    if (argparse::cmdOptionExists(argv, argv+argc, "--quiet")) {
        logging::disable();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--debug")) {
        logging::enableDebug();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--verbose")) {
        logging::enableVerbose();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "-h") || argparse::cmdOptionExists(argv, argv+argc, "--help")) {
        printUsage(argv[0]);
        return 0;
    }
    LOG("Printipi: built for machine: '" STRINGIFY(MACHINE) "'\n");

    char* fsRootArg = argparse::getArgumentForCmdOption(argv, argv+argc, "--fsroot");
    std::string fsRoot = fsRootArg ? std::string(fsRootArg) : "/";
    LOG("Filesystem root: %s\n", fsRoot.c_str());
    FileSystem fs(fsRoot);

    #if ENABLE_TESTS
        int doTestsArgIdx = argparse::getCmdOptionIdx(argv, argv+argc, "--do-tests");
        if (doTestsArgIdx != -1) {
            // prepare arguments for the test suite:
            // place argv[0] (executable path) at current index, overwriting --do-tests
            //   and modify argc & argv.
            argv[doTestsArgIdx] = argv[0];
            argc -= doTestsArgIdx;
            int result = Catch::Session().run(argc, argv);
            return result;
        }
    #endif

    // run the normal program
    gparse::Com com;
    //if input is stdin, or a two-way pipe, then it likely means we want to keep that channel open forever
    //  whereas if it's a gcode file, then calls to M32 (print from file) should pause the original input file
    bool keepPersistentCom = false;

    //if no arguments, or if first argument (and therefore all args) is an option,
    //  then take gcode commands from stdin
    if (argc < 2 || argv[1][0] == '-') {
        //std::cin does not allow to check if there are characters to be read, whereas /dev/stdin DOES.
        //  we need nonblocking I/O, so this is crucial.
        //com = std::move(gparse::Com(gparse::Com::shareOwnership(&std::cin)));
        com = std::move(gparse::Com("/dev/stdin"));
        //reading from stdin; want to keep that channel active even when printing from file, etc.
        keepPersistentCom = true;
    } else {
        //otherwise, first parameter must be a filename from which to read gcode commands
        //second argument is for the output file
        if (argc > 2 && argv[2][0] != '-') {
            com = std::move(gparse::Com(std::string(argv[1]), std::string(argv[2])));
            //hints at a dual-way pipe (host <-> firmware communication); preserve communiation channel to host
            keepPersistentCom = true;
        } else {
            //no second file; just read from the supplied input file
            com = std::move(gparse::Com(std::string(argv[1])));
        }
    }

    //prevent page-swaps to increase performace:
    int retval = mlockall(MCL_FUTURE|MCL_CURRENT);
    if (retval) {
        LOGW("Warning: mlockall (prevent memory swaps) in main.cpp::main() returned non-zero: %i\n", retval);
    }

    State<machines::MACHINE> state(machines::MACHINE(), fs, keepPersistentCom);
    state.addComChannel(std::move(com));
    state.eventLoop();
    return 0;
}

int main(int argc, char** argv) {
    try { //wrap in a try/catch loop so we can safely clean up (disable IOs)
        return main_(argc, argv);
    } catch (const std::exception *e) {
        LOGE("caught std::exception*: %s. ... Exiting\n", e->what());
        #if CLEAN_EXIT
            return 1; //don't rethrow exceptions; return an error code instead
        #endif
        throw;
    } catch (const std::exception &e) {
        LOGE("caught std::exception&: %s. ... Exiting\n", e.what());
        #if CLEAN_EXIT
            return 1; //don't rethrow exceptions; return an error code instead
        #endif
        throw;
    } catch (...) {
        LOGE("caught unknown exception. Exiting\n");
        #if CLEAN_EXIT
            return 1; //don't rethrow exceptions; return an error code instead
        #endif
        throw;
    }
}

<commit_msg>Fix command line parsing with Catch (--do-tests)<commit_after>/* The MIT License (MIT)
 *
 * Copyright (c) 2014 Colin Wallace
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/*
 * Printipi/main.cpp
 *
 * main is the program's main entry point.
 * main handles command line arguments, and instantiates the serial communications, State, and machine-specific driver.
 * Driver type is passed into this compilation unit as a command-line argument (gcc -DMACHINE=...)
 *
 * Printipi Github repository: https://github.com/Wallacoloo/printipi/
 * Printipi Google Group (forum): https://groups.google.com/forum/#!forum/printipi
 *
 * Miscellaneous Printipi discussions:
 *   http://forums.reprap.org/read.php?2,396157
 *   https://groups.google.com/forum/#!searchin/deltabot/wallacoloo|sort:relevance/deltabot/JQNpmnlYYUc/_6V6SYcOGMUJ
 *   http://youtube.com/watch?v=g4UD5MRas3E
 *   http://youtube.com/watch?v=gAruwqOEuPs
 */

#define COMPILING_MAIN //used elsewhere to do one-time warnings, etc.

#include "compileflags.h"

//Includes for the CATCH testing framework
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

#include <string>
#include <sys/mman.h> //for mlockall
#include <iostream> //for std::cin
#include "common/logging.h"

#include "gparse/com.h"
#include "state.h"
#include "argparse.h"
#include "filesystem.h"

//MACHINE_PATH is calculated in the Makefile and then passed as a define through the make system (ie gcc -DMACHINEPATH='"path"')
//To set the path, call make MACHINE_PATH=...
//or, call make MACHINE=<machine>, eg MACHINE=rpi::KosselPi (case-sensitive) and the path will be calculated from that (src/machines/rpi/kossel.h)
#include MACHINE_PATH

#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)

static void printUsage(char* cmd) {
    //#ifndef NO_USAGE_INFO
    LOGE("usage: %s [input-file] [output-file] [--help] [--quiet] [--verbose] [--do-tests [CATCH-arguments ...] ]\n", cmd);
    LOGE("  if input-file is not provided, it defaults to stdin\n");
    LOGE("  if output-file is not provided, it defaults to strout\n");
    LOGE("  --do-tests is only recognized if program was compiled with ENABLE_TESTS=1\n");
    LOGE("examples:\n");
    LOGE("  print a gcode file: %s file.gcode\n", cmd);
    LOGE("  mock serial port: %s /dev/tty3dpm /dev/tty3dps\n", cmd);
}

int main_(int fullArgc, char **argv) {
    //useful to setup fail-safe exit routines first-thing for catching debug info.
    SchedulerBase::configureExitHandlers();
    // alter argc in order to ignore everything after "--do-tests"
    int doTestsArgIdx = argparse::getCmdOptionIdx(argv, argv+fullArgc, "--do-tests");
    int argc = (doTestsArgIdx == -1) ? fullArgc : doTestsArgIdx;
    if (argparse::cmdOptionExists(argv, argv+argc, "--quiet")) {
        logging::disable();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--debug")) {
        logging::enableDebug();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--verbose")) {
        logging::enableVerbose();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "-h") || argparse::cmdOptionExists(argv, argv+argc, "--help")) {
        printUsage(argv[0]);
        return 0;
    }
    LOG("Printipi: built for machine: '" STRINGIFY(MACHINE) "'\n");

    char* fsRootArg = argparse::getArgumentForCmdOption(argv, argv+argc, "--fsroot");
    std::string fsRoot = fsRootArg ? std::string(fsRootArg) : "/";
    LOG("Filesystem root: %s\n", fsRoot.c_str());
    FileSystem fs(fsRoot);

    #if ENABLE_TESTS
        if (doTestsArgIdx != -1) {
            // prepare arguments for the test suite:
            // place argv[0] (executable path) at current index, overwriting --do-tests
            //   and modify argc & argv.
            argv[doTestsArgIdx] = argv[0];
            int numToPass = fullArgc - doTestsArgIdx;
            int result = Catch::Session().run(numToPass, &argv[doTestsArgIdx]);
            return result;
        }
    #endif

    // run the normal program
    gparse::Com com;
    //if input is stdin, or a two-way pipe, then it likely means we want to keep that channel open forever
    //  whereas if it's a gcode file, then calls to M32 (print from file) should pause the original input file
    bool keepPersistentCom = false;

    //if no arguments, or if first argument (and therefore all args) is an option,
    //  then take gcode commands from stdin
    if (argc < 2 || argv[1][0] == '-') {
        //std::cin does not allow to check if there are characters to be read, whereas /dev/stdin DOES.
        //  we need nonblocking I/O, so this is crucial.
        //com = std::move(gparse::Com(gparse::Com::shareOwnership(&std::cin)));
        com = std::move(gparse::Com("/dev/stdin"));
        //reading from stdin; want to keep that channel active even when printing from file, etc.
        keepPersistentCom = true;
    } else {
        //otherwise, first parameter must be a filename from which to read gcode commands
        //second argument is for the output file
        if (argc > 2 && argv[2][0] != '-') {
            com = std::move(gparse::Com(std::string(argv[1]), std::string(argv[2])));
            //hints at a dual-way pipe (host <-> firmware communication); preserve communiation channel to host
            keepPersistentCom = true;
        } else {
            //no second file; just read from the supplied input file
            com = std::move(gparse::Com(std::string(argv[1])));
        }
    }

    //prevent page-swaps to increase performace:
    int retval = mlockall(MCL_FUTURE|MCL_CURRENT);
    if (retval) {
        LOGW("Warning: mlockall (prevent memory swaps) in main.cpp::main() returned non-zero: %i\n", retval);
    }

    State<machines::MACHINE> state(machines::MACHINE(), fs, keepPersistentCom);
    state.addComChannel(std::move(com));
    state.eventLoop();
    return 0;
}

int main(int argc, char** argv) {
    try { //wrap in a try/catch loop so we can safely clean up (disable IOs)
        return main_(argc, argv);
    } catch (const std::exception *e) {
        LOGE("caught std::exception*: %s. ... Exiting\n", e->what());
        #if CLEAN_EXIT
            return 1; //don't rethrow exceptions; return an error code instead
        #endif
        throw;
    } catch (const std::exception &e) {
        LOGE("caught std::exception&: %s. ... Exiting\n", e.what());
        #if CLEAN_EXIT
            return 1; //don't rethrow exceptions; return an error code instead
        #endif
        throw;
    } catch (...) {
        LOGE("caught unknown exception. Exiting\n");
        #if CLEAN_EXIT
            return 1; //don't rethrow exceptions; return an error code instead
        #endif
        throw;
    }
}

<|endoftext|>


<commit_before>#include <iostream>
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Shell.h"
#include "Input.h"

using namespace std;

int main() {
    Input in;
    queue<string> tasks;

    // to exit while loop, user must type exit
    while(1) {

        in.getInput();
        // bool test = in.isTest();
        // cout << "test: " << test << endl;
        // exit(0);
        tasks = in.Parse();

        cout << "size: " << tasks.size() << endl;

        while (tasks.size() != 0) {
            cout << tasks.front() << endl;
            tasks.pop();
        }

        exit(0);

        // bool determines whether command was successful
        bool comp_status = true;
        char** c;
        Execute ex;
        while (tasks.size() != 0) {

            // if at any point the user has exit
            if (tasks.front() == "exit") {
                cout << "You have exited shell." << endl;
                exit(0);
            }

            //------------------------------------------------------------------

            else if (tasks.front() == "&&") {
	            tasks.pop(); //gets rid of the &&
                // if the command before this one does returns F,then dont do
                // //the next command
	            if(comp_status == false) {
		        // so the && connector should have already been deleted,
                // this is a while loop to
                // delete the next commands so that they wont run if
                // the command before fails
		            if(tasks.size() != 0) {
			            if(tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				            tasks.pop();
			            }
		            }
	            }
            }
            //------------------------------------------------------------------

            else if (tasks.front() == "||") {
		        tasks.pop();  // gets rid of the ||
		        if(comp_status == true) {
			        if(tasks.size() != 0) {
			  	        if (tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				 	        tasks.pop();
			  	        }
		  	        }
		        }
	        }

            // simply pop the semicolon and continue looping
	        else if (tasks.front() == ";") {
                tasks.pop();
	        }

            //-----------------------------------------------------------------

            // task was not a connector, and therefore a command
            else {
                c = in.toChar(tasks.front());
                ex.execute(c, comp_status);
	            tasks.pop();
	        }

        }
    cout << flush;

    }

    return 0;
}
<commit_msg>working on parentheses in main<commit_after>#include <iostream>
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Shell.h"
#include "Input.h"

using namespace std;

int main() {
    Input in;
    queue<string> tasks;

    // to exit while loop, user must type exit
    while(1) {

        in.getInput();
        // bool test = in.isTest();
        // cout << "test: " << test << endl;
        // exit(0);
        tasks = in.Parse();

        cout << "size: " << tasks.size() << endl;

        while (tasks.size() != 0) {
            cout << tasks.front() << endl;
            tasks.pop();
        }

        exit(0);

        // bool determines whether command was successful
        bool comp_status = true;
        char** c;
	int num = 0;
        Execute ex;
        while (tasks.size() != 0) {

            // if at any point the user has exit
            if (tasks.front() == "exit") {
                cout << "You have exited shell." << endl;
                exit(0);
            }

            //------------------------------------------------------------------

            else if (tasks.front() == "&&") {
	            tasks.pop(); //gets rid of the &&
                // if the command before this one does returns F,then dont do
                // //the next command
	            if(comp_status == false) {
		        // so the && connector should have already been deleted,
                // this is a while loop to
                // delete the next commands so that they wont run if
                // the command before fails
		            if(tasks.size() != 0) {
			            if(tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				            tasks.pop();
			            }
		            }
	            }
            }
            //------------------------------------------------------------------

            else if (tasks.front() == "||") {
		        tasks.pop();  // gets rid of the ||
		        if(comp_status == true) {
			        if(tasks.size() != 0) {
			  	        if (tasks.front() != "&&" || tasks.front() != "||" ||
                                tasks.front() != ";") {
				 	        tasks.pop();
			  	        }
		  	        }
		        }
	        }

            // simply pop the semicolon and continue looping
	    else if (tasks.front() == ";") {
		    tasks.pop();
	    }

	    //------------------------------------------------------------------

	    else if (tasks.front() == "(") {
		    // gets rid of (
		    tasks.pop();

            //-----------------------------------------------------------------

            // task was not a connector, and therefore a command
            else {
                c = in.toChar(tasks.front());
                ex.execute(c, comp_status);
	            tasks.pop();
	        }

        }
    cout << flush;

    }

    return 0;
}
<|endoftext|>