void shutDown() {
	cout << "System shutting down." << endl;
	websocket_server.close(currentState.client, 0, "shutdown");
	websocket_server.stop();
	gpioTerminate();
	std::exit(EXIT_SUCCESS);
	//system("shutdown -P now");
	return;
}
예제 #2
0
파일: wload.cpp 프로젝트: thaingo/hCraft
		static bool
		add_to_autoload (server& srv, const std::string& world_name)
		{
			auto& conn = srv.sql ().pop ();
			int count = conn.query (
				"SELECT count(*) FROM `autoloaded-worlds` WHERE `name`='"
				+ world_name + "'").step ().at (0).as_int ();
			if (count != 0)
				return false;
			
			conn.execute (
				"INSERT INTO `autoloaded-worlds` (`name`) VALUES ('"
				+ world_name + "')");
			srv.sql ().push (conn);
			return true;
		}
예제 #3
0
파일: servers.hpp 프로젝트: ghoff/accessl
    void report_time(const server& s, boost::posix_time::time_duration time)
    {
        server_times_.update_resp_time(s.get_id(), time.total_microseconds());
        uint32_t new_reqs_sec = server_times_.reqs_sec(s);

        update_server(s, new_reqs_sec);
    }
예제 #4
0
파일: wunload.cpp 프로젝트: hCraft/hCraft
		static bool
		remove_from_autoload (server& srv, const std::string& world_name)
		{
			auto& conn = srv.sql ().pop ();
			int count = conn.query (
				"SELECT count(*) FROM `autoload-worlds` WHERE `name`='"
				+ world_name + "'").step ().at (0).as_int ();
			if (count == 0)
				return false;
			
			conn.execute (
				"DELETE FROM `autoload-worlds` WHERE `name`='"
				+ world_name + "'");
			srv.sql ().push (conn);
			return true;
		}
예제 #5
0
파일: servers.hpp 프로젝트: ghoff/accessl
    void report_timeout(const server& s)
    {
        server_times_.update_resp_timeout(s.get_id());
        uint32_t new_reqs_sec = server_times_.reqs_sec(s);

        update_server(s, new_reqs_sec);
    }
예제 #6
0
    void _test_websocket_server::send_msg(const test_websocket_msg& msg)
    {
        // Wait for the websocket server to be initialized.
        pplx::task<void>(m_server_connected).wait();
        const auto& data = msg.data();
        auto flags = websocketpp::frame::opcode::close;
        switch (msg.msg_type())
        {
        case test_websocket_message_type::WEB_SOCKET_UTF8_MESSAGE_TYPE:
            flags = websocketpp::frame::opcode::text; // WebSocket::FRAME_FLAG_FIN | WebSocket::FRAME_OP_TEXT;
            break;
        case test_websocket_message_type::WEB_SOCKET_BINARY_MESSAGE_TYPE:
            flags = websocketpp::frame::opcode::binary; // WebSocket::FRAME_FLAG_FIN | WebSocket::FRAME_OP_BINARY;
            break;
        case test_websocket_message_type::WEB_SOCKET_CLOSE_TYPE:
            flags = websocketpp::frame::opcode::close; // WebSocket::FRAME_OP_CLOSE;
            break;
		case test_websocket_message_type::WEB_SOCKET_UTF8_FRAGMENT_TYPE:
        case test_websocket_message_type::WEB_SOCKET_BINARY_FRAGMENT_TYPE:
        default:
            throw std::runtime_error("invalid message type");
        }

        std::string strmsg(data.begin(), data.end());

        if (msg.msg_type() == test_websocket_message_type::WEB_SOCKET_CLOSE_TYPE)
        {
            close(strmsg);
        }
        else
        {
            // std::cerr << "Sending message from server: " << strmsg << std::endl;
            m_srv.send(m_con, strmsg, flags);
        }
    }
예제 #7
0
	int senddata( const server &sv, const char *buffer, u32 len ) { 
		sockaddr_in to = ( sv.tosockaddr() );
		int bytes = sendto( mSocket, buffer, len, 0, (sockaddr *)&to, sizeof( to ) );
		if ( bytes > 0 )
			UPLOAD.update( bytes + UDP_HEADER_SIZE );

		return ( bytes ); 
	}
예제 #8
0
파일: servers.hpp 프로젝트: ghoff/accessl
 void update_server(const server& s, uint32_t new_reqs_sec)
 {
     server_tree_iter_map::const_iterator it = servers_map_.find(s.get_id());
     if (it != servers_map_.end())
     {
         servers_.change_count(it->second, new_reqs_sec);
     }
 }
예제 #9
0
/* Run server and return output test rig */
std::string run_server_test(server& s, std::string input) {
    server::connection_ptr con;
    std::stringstream output;
	
	s.register_ostream(&output);
	s.clear_access_channels(websocketpp::log::alevel::all);
    s.clear_error_channels(websocketpp::log::elevel::all);
	
	con = s.get_connection();
	con->start();
	
	std::stringstream channel;
	
	channel << input;
	channel >> *con;
	
	return output.str();
}
void * speedometer(void * argument) {
	const timespec waitTime = { 0, MOUSE_SAMPLE_RATE };
	cout << waitTime.tv_nsec << " " << waitTime.tv_sec << endl;

	int fd;
	struct input_event ie;

	if ((fd = open(MOUSE_FILE, O_RDONLY)) == -1) {
		perror("opening device");
		//     exit(1);
	}
	int flags = fcntl(fd, F_GETFL, 0);
	fcntl(fd, F_SETFL, flags | O_NONBLOCK);
	int counter = 0;

	while (true) {
		//cout << "hello from the speedometer" << endl;
		nanosleep(&waitTime, NULL);
		//cout << "wait over" << endl;
		counter = 0;

		while (read(fd, &ie, sizeof(struct input_event)) != -1) {
			//cout << "reading mouse" << endl;
			if ((ie.type == 2) && (ie.code == 8)) {
				counter++;
				//	cout << "new mouse event " << counter << endl;
			}
		}

		//cout << "aquireing mutex" << endl;

		//cout << "aquired mutex" << endl;
		currentState.speed = (counter * MOUSE_MM_PER_CLICK) * 10;   //mm/s
		currentState.distanceTraveled = counter * MOUSE_MM_PER_CLICK;	//mm.
		//cout << "speed: " << currentState.speed << " distance: " << currentState.distanceTraveled << endl;

		ptree answerJson;
		stringstream jsonWriteStream;

		answerJson.put("speed", currentState.speed);
		answerJson.put("distanceTraveled", currentState.distanceTraveled);
		write_json(jsonWriteStream, answerJson);
		//cout << "sending speedometer" << endl;
		//pthread_mutex_lock(&watchDog_mutex);
		if (currentState.connected) {
			websocket_server.send(currentState.client, jsonWriteStream.str(),
					websocketpp::frame::opcode::text);

		}
		//pthread_mutex_unlock(&watchDog_mutex);
		//cout << "released mutex" << endl;
	}

	return 0;
}
예제 #11
0
파일: worker.cpp 프로젝트: apohl79/petrel
void worker::do_accept(tcp::acceptor& acceptor, server& srv) {
    while (acceptor.is_open()) {
        bs::error_code ec;
        // get an io service to use for a new client, we pick them via round robin
        auto& worker = srv.impl()->get_worker();
        auto& iosvc = worker.io_service();
        auto new_session = std::make_shared<session>(srv, iosvc);
        acceptor.async_accept(new_session->socket(), bfa::yield[ec]);
        if (!ec) {
            worker.add_session(new_session);
            worker.m_new_session_cv.notify_one();
        }
    }
}
예제 #12
0
파일: irc.cpp 프로젝트: BizarreCake/hCraft
	/* 
	 * Constructs a new IRC client on top of hte specified socket and event base.
	 */
	irc_client::irc_client (server &srv, struct event_base *evbase, int sock)
		: srv (srv), log (srv.get_logger ())
	{
		this->evbase = evbase;
		this->sock = sock;
		
		this->bufev = bufferevent_socket_new (evbase, sock, BEV_OPT_CLOSE_ON_FREE);
		
		bufferevent_setcb (this->bufev, &hCraft::irc_client::handle_read,
			&hCraft::irc_client::handle_write, &hCraft::irc_client::handle_event, this);
		bufferevent_enable (this->bufev, EV_READ | EV_WRITE);
		
		this->total_read = 0;
		this->fail = false;
		this->connected = false;
	}
bool validate(server & s, connection_hdl hdl) {
    server::connection_ptr con = s.get_con_from_hdl(hdl);

    std::cout << "Cache-Control: " << con->get_request_header("Cache-Control") << std::endl;

    const std::vector<std::string> & subp_requests = con->get_requested_subprotocols();
    std::vector<std::string>::const_iterator it;

    for (it = subp_requests.begin(); it != subp_requests.end(); ++it) {
        std::cout << "Requested: " << *it << std::endl;
    }

    if (subp_requests.size() > 0) {
        con->select_subprotocol(subp_requests[0]);
    }

    return true;
}
예제 #14
0
             void block_generation_loop()
             {
                while( !_block_gen_loop_complete.canceled() )
                {
                   if( _pending.size() && (fc::time_point::now() - _current_block.timestamp) > fc::seconds(60) )
                   {
                      signed_block next_block;
                      next_block.number     = _current_block.number + 1;
                      auto next_diff        = _current_block.difficulty * 500 / _pending.size(); 
                      next_diff             = (_current_block.difficulty * 99 + next_diff) / 100;
                      next_block.difficulty = std::max<uint64_t>(next_diff, 1000 );
                      next_block.timestamp  = fc::time_point::now();
       
                      for( auto rec : _pending )
                      {
                         next_block.records.push_back( rec.second );
                      }
       
                      next_block.sign( _trustee_key );
                      _block_database.store(next_block.number,next_block);
       
                      for( uint32_t rec = 0; rec < next_block.records.size(); ++rec )
                      {
                         auto new_rec = next_block.records[rec];
                         auto hist = _self->fetch_history( new_rec.name );
                         hist.updates.push_back( name_index( next_block.number, rec ) );
                         _name_index.store( new_rec.name, hist );
                         _key_to_name.store( new_rec.active_key.to_base58(), new_rec.name );
                      }
       
                      _current_block = next_block;
                      _current_block_id = _current_block.id();

                      fc::path block_file = _data_dir / "block" / fc::to_string( uint64_t(_current_block.number) );

                      std::ofstream out( block_file.generic_string().c_str() );
                      auto block_str = fc::json::to_pretty_string( _current_block );
                      out.write( block_str.c_str(), block_str.size() );
                   }
                   fc::usleep( fc::seconds( 1 ) );
                }
             }
예제 #15
0
 /// Constructor
 connection(
     server& parent,
     tcp::endpoint const& ep,
     tcp::socket&& sock)
     : log_(parent.log_)
     , ep_(ep)
     , ws_(std::move(sock))
     , timer_(ws_.get_io_service(), (clock_type::time_point::max)())
     , strand_(ws_.get_io_service())
     , id_([]
         {
             static std::atomic<std::size_t> n{0};
             return ++n;
         }())
 {
     // Invoke the callback for new connections if set.
     // This allows the settings on the websocket stream
     // to be adjusted. For example to turn compression
     // on or off or adjust the read and write buffer sizes.
     //
     if(parent.mod_)
         parent.mod_(ws_);
 }
예제 #16
0
	static void
	_init_sql_tables (world *w, server &srv)
	{
		soci::session sql (srv.sql_pool ());
		
		// block history table
		sql.once <<
			"CREATE TABLE IF NOT EXISTS `block_history_" << w->get_name () << "` ("
			"`x` INT, `y` INT, `z` INT, " // pos
			"`old_id` SMALLINT UNSIGNED, `old_meta` TINYINT UNSIGNED, `old_ex` TINYINT UNSIGNED, " // old value
			"`new_id` SMALLINT UNSIGNED, `new_meta` TINYINT UNSIGNED, `new_ex` TINYINT UNSIGNED, " // new value
			"`pid` INTEGER UNSIGNED, `time` BIGINT UNSIGNED)";
		{
			// create index
			int c;
			sql << "SELECT Count(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS "
				"WHERE table_schema=DATABASE() AND table_name='block_history_" << w->get_name ()
				<< "' AND index_name='bh_index_" << w->get_name () << "'", soci::into (c);
			if (c == 0)
				sql.once <<
					"CREATE INDEX `bh_index_" << w->get_name () << "` ON `block_history_"
					<< w->get_name () << "` (`x`, `y`, `z`)";
		}
	}
예제 #17
0
             void handle_request( const fc::http::request& r, const fc::http::server::response& s )
             {
                 //ilog( "handle request ${r}", ("r",r.path) );
                 s.add_header( "Connection", "close" );

                 try {
                    auto pos = r.path.find( "/", 1 );
                    auto first_dir = r.path.substr(1,pos);
                    //ilog( "command: ${command}", ("command",first_dir) );
                    if( first_dir == "pending" )
                    {
                       s.set_status( fc::http::reply::OK );
                       auto pending_json = fc::json::to_string( _pending );
                       s.set_length( pending_json.size() );
                       s.write( pending_json.c_str(), pending_json.size() );
                    }
                    else if( first_dir == "update_record" )
                    {
                       FC_ASSERT( r.body.size() );
                       std::string str(r.body.data(),r.body.size());
                       auto rec = fc::json::from_string( str ).as<signed_name_record>();

                       _self->update_record( rec );

                       s.set_status( fc::http::reply::RecordCreated );
                       s.set_length( 12 );
                       s.write( "Record Created", 12 );
                    }
                    else if( first_dir == "fetch_by_name/" )
                    {
                       auto name = r.path.substr( pos+1, std::string::npos );
                       auto record  = _self->fetch_record( name );
                       s.set_status( fc::http::reply::Found );
                       auto blkjson = fc::json::to_string( record );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else if( first_dir == "fetch_by_key/" )
                    {
                       auto key = r.path.substr( pos+1, std::string::npos );
                       auto record  = _self->fetch_record_by_key( key );
                       s.set_status( fc::http::reply::Found );

                       auto blkjson = fc::json::to_string( record );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else if( first_dir == "store_key/" )
                    {
                       auto name = r.path.substr( pos+1, std::string::npos );
                       std::string str(r.body.data(),r.body.size());
                       auto rec = fc::json::from_string( str ).as<stored_key>();

                       _self->store_key( name, rec );
                       s.set_status( fc::http::reply::RecordCreated );
                       s.set_length( 12 );
                       s.write( "Record Created", 12 );
                    }
                    else if( first_dir == "fetch_key/" )
                    {
                       auto user_name = r.path.substr( pos+1, std::string::npos );
                       auto key_data  = _self->fetch_key(  user_name );
                       s.set_status( fc::http::reply::Found );

                       auto blkjson = fc::json::to_string( key_data );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else if( first_dir == "fetch_block/" )
                    {
                       auto block_num = r.path.substr( pos+1, std::string::npos );
                       auto blk = _self->fetch_block(  fc::to_uint64( block_num ) );
                       s.set_status( fc::http::reply::Found );
                       auto blkjson = fc::json::to_string( blk );
                       s.set_length( blkjson.size() );
                       s.write( blkjson.c_str(), blkjson.size() );
                    }
                    else
                    {
                       auto dotpos = r.path.find( ".." );
                       FC_ASSERT( dotpos == std::string::npos );
                       auto filename = _data_dir / r.path.substr(1,std::string::npos);
                       if( fc::exists( filename ) )
                       {
                          FC_ASSERT( !fc::is_directory( filename ) );
                          auto file_size = fc::file_size( filename );
                          FC_ASSERT( file_size != 0 );

                          fc::file_mapping fm( filename.generic_string().c_str(), fc::read_only );
                          fc::mapped_region mr( fm, fc::read_only, 0, fc::file_size( filename ) );

                          s.set_status( fc::http::reply::OK );
                          s.set_length( file_size );
                          s.write( (const char*)mr.get_address(), mr.get_size() );
                          return;
                       }
                       s.set_status( fc::http::reply::NotFound );
                       s.set_length( 9 );
                       s.write( "Not Found", 9 );
                    }
                 } 
                 catch ( const fc::exception& e )
                 {
                    s.set_status( fc::http::reply::BadRequest );
                    auto msg = e.to_detail_string();
                    s.set_length( msg.size() );
                    if( msg.size() )
                    {
                      s.write( msg.c_str(), msg.size() );
                    }
                 }
             }
예제 #18
0
파일: main.cpp 프로젝트: oeo4b/Cframes
int main(int argc, char **argv) {
  /* Program start */
  /*
   * 
   *
   */
  int i;
  int port = 5000;
  char *bind = (char *)"0.0.0.0";
  bool daemon = false;

  /* Help info */
  for(i=0;i<argc;i++) {
    if(strcmp(argv[i],"-h")==0||strcmp(argv[i],"--help")==0) {
      out("Usage: cframes [options]\n");
      out("\t-p, --port PORT\tBind server socket to specified PORT\n");
      out("\t\t\tDefault: 5000\n");
      out("\t-b, --bind IP\tBind server to specified IP\n");
      out("\t\t\tDefault: 0.0.0.0\n");
      out("\t-d, --daemon\tForks server process\n");
      out("\t-h, --help\tDisplay this help and exit\n");
      out("\t-v, --version\tDisplay version information and exit\n");
      return 0;
    }
  }

  /* Version info */
  for(i=0;i<argc;i++) {
    if(strcmp(argv[i],"-v")==0||strcmp(argv[i],"--version")==0) {
      out("cframes 1.0.1\n");
      return 0;
    }
  }

  /* Program arguments */
  for(i=0;i<argc;i++) {
    if(strcmp(argv[i],"-p")==0||strcmp(argv[i],"--port")==0) {
      port = (int)argv[i+1];
    }
    if(strcmp(argv[i],"-b")==0||strcmp(argv[i],"--bind")==0) {
      bind = (char *)argv[i+1];
    }
    if(strcmp(argv[i],"-d")==0||strcmp(argv[i],"--daemon")==0) {
      daemon = true;
    }
  }

  /* Start the server */
  out("Starting cframes server...........");
  s.start(port);
  out("OK\n");
  out("Listening on http://");
  out(bind);out(":");out("5000");out("\n\n");

  /* Single-threaded forever loop to handle requests -- NOTE: eventually will have a daemon option -d */
  for(i=0;i<50;i++) { www(); }

  /* Stop the server */
  s.stop();
	
  return 0;
}
예제 #19
0
파일: servers.hpp 프로젝트: ghoff/accessl
 int compare_port(const server& other) const {
     return get_port() - other.get_port();
 }
예제 #20
0
    void on_open(connection_hdl hdl) {
        holdThreads[hdl]=0;//just an example.  Creates a new item for every connection.  Gets deleted on close
        m_server.send(hdl,"message", websocketpp::frame::opcode::text);
	}
예제 #21
0
	void run(uint16_t port) {
		m_server.listen(port);
		m_server.start_accept();
		m_server.run();
	}
int main() {
	////////////////////////init current state////////////////
	currentState.connected = false;
	currentState.autonomous = false;
	currentState.cruise = false;
	currentState.leftTurn = false;
	currentState.rightTurn = false;
	currentState.turnPeaked = false;
	currentState.signalOn = false;
	currentState.obsticle = false;
	currentState.servoInt = 0;
	currentState.motorInt = 0;
	currentState.speed = 0;
	currentState.lastMessageTime = 0;
	currentState.distanceTraveled = 0;
	currentState.lastRequestedMotorInt = 0;
	currentState.sonarRange = 200;
	currentState.cameraAngle = 0;

	////////////////////////GPIO setup////////////////////////
	int GPIOstatus;
	int GPIOfrequencySteering;
	int GPIOfrequencyMotor;
	GPIOstatus = gpioInitialise();				//required for GPIO to function

	if (GPIOstatus < 0)							//did we succeed
			{
		fprintf(stderr, "pigpio initialisation failed.\n");
		return 1;
	}

	//steering
	gpioSetPWMrange(GPIO_STEERING_CONTROL, 255);
	gpioSetPWMfrequency(GPIO_STEERING_CONTROL, 0);
	GPIOfrequencySteering = gpioGetPWMfrequency(GPIO_STEERING_CONTROL);
	int GPIOrangeSteering = gpioGetPWMrange(GPIO_MOTOR_CONTROL);
	//motor
	gpioSetPWMrange(GPIO_MOTOR_CONTROL, 255);
	gpioSetPWMfrequency(GPIO_MOTOR_CONTROL, 250);
	int GPIOrangeMotor = gpioGetPWMrange(GPIO_MOTOR_CONTROL);
	GPIOfrequencyMotor = gpioGetPWMfrequency(GPIO_MOTOR_CONTROL);
	cout << "FREQ: Using " << GPIOfrequencySteering << " for steering and "
			<< GPIOfrequencyMotor << " for motor." << endl;
	cout << "RANGE: Using " << GPIOrangeSteering << " for steering and "
			<< GPIOrangeMotor << "for motor." << endl;
	//gpioSetAlertFunc(GPIOsteeringControl, GPIOcallBack);
	gpioServo(GPIO_STEERING_CONTROL, SERVO_CENTER);	//set steering to straight
	//set mode of turn signals to output
	gpioSetMode(GPIO_RIGHT_TURN_SIGNAL, PI_OUTPUT);
	gpioSetMode(GPIO_LEFT_TURN_SIGNAL, PI_OUTPUT);

	/////////////////////////threads////////////////////////////
	pthread_create(&watchDog_th, NULL, watchDog, NULL);
	pthread_create(&turnSignal_th, NULL, turnSignal, NULL);
	//pthread_create(&sonar_th, NULL, sonar, NULL);
	pthread_create(&speedometer_th, NULL, speedometer, NULL);
	pthread_create(&laneDetect_th, NULL, laneDetect, NULL);
	pthread_create(&motorControl_th, NULL, motorControl, NULL);

	////////////////////////Websocket Server setup////////////////////////
	//what function should be called on a new message
	websocket_server.set_message_handler(&on_message);//what function should be called on a new message
	websocket_server.set_open_handler(&on_open);
	websocket_server.set_close_handler(&on_close);
	websocket_server.init_asio();
	//What ip version and port should we listen on
	websocket_server.listen(boost::asio::ip::tcp::v4(), 8080);
	websocket_server.start_accept();
	//Way to much log
	websocket_server.clear_access_channels(websocketpp::log::alevel::all);
	cout << "Starting RoadStar server" << endl;
	websocket_server.run();									//start the server

	gpioTerminate();

	return 0;
}
예제 #23
0
root_room::root_room(server &svr) :
	private_room(svr, "_root_room", svr.get_root()->get_password())
{}
void on_message(websocketpp::connection_hdl hdl, server::message_ptr msg) {
	try {

		//cout << "message" << endl;
		//immediatly send back a message for timing purposes
		//websocket_server.send(hdl ,"TIME",websocketpp::frame::opcode::text);

		//parse the json
		ptree parsedJson;
		stringstream jsonStream;
		jsonStream << msg->get_payload();
		read_json(jsonStream, parsedJson);

		if (parsedJson.get<bool>("triangle")) {
			cout << "Received triangle" << endl;
			shutDown();
		}

		//toggle autonomous mode
		if (parsedJson.get<bool>("start")) {
			pthread_mutex_lock(&autonomous_mutex);
			if (currentState.autonomous == true) {
				currentState.autonomous = false;
				cout << "Autonomous mode off." << endl;
			} else {
				currentState.autonomous = true;
				cout << "Autonomous mode on." << endl;
			}
			pthread_mutex_unlock(&autonomous_mutex);
		}
		pthread_mutex_lock(&autonomous_mutex);
		if (currentState.autonomous != true) {

			//update the servo values
			currentState.servoInt = (int) (SERVO_CENTER
					+ (parsedJson.get<double>("leftAnalog_x")
							* MAX_STEERING_OFFSET));

			if (parsedJson.get<double>("rightAnalog_y") < 0) {
				currentState.cruise = false;
			}

			if (currentState.cruise == false) {
				//skip the center range
				int requestedMotorInt = 0;
				pthread_mutex_lock(&obsticle_mutex);
				if ((parsedJson.get<double>("rightAnalog_y") > 0)
						&& (currentState.obsticle != true)) {
					//forward
					//cout << "rightAnalog_y: " << parsedJson.get<double>("rightAnalog_y") << endl;
					requestedMotorInt = (int) (parsedJson.get<double>(
							"rightAnalog_y") * MOTOR_FORWARD_RANGE);
					//cout << "requestedMotirInt(forward): " << requestedMotorInt << endl;
					if ((requestedMotorInt - currentState.lastRequestedMotorInt)
							> ACCELERATION_THRESHOLD) {
						requestedMotorInt = currentState.lastRequestedMotorInt
								+ ACCELERATION_THRESHOLD;
						//cout << "Don't accelerate so quickly!" << endl;
					}
					currentState.motorInt = MOTOR_FORWARD_START
							+ requestedMotorInt;

				} else if (parsedJson.get<double>("rightAnalog_y") < 0) {
					//backward
					//cout << "rightAnalog_y: " << parsedJson.get<double>("rightAnalog_y") << endl;
					requestedMotorInt = -1
							* (int) (parsedJson.get<double>("rightAnalog_y")
									* MOTOR_BACKWARD_RANGE);
					//cout << "requestedMotirInt(backward): " << requestedMotorInt << endl;
					if ((currentState.lastRequestedMotorInt - requestedMotorInt)
							> ACCELERATION_THRESHOLD) {
						requestedMotorInt = currentState.lastRequestedMotorInt
								- ACCELERATION_THRESHOLD;
						//cout << "Don't accelerate (backwards) so quickly!" << endl;
					}
					currentState.motorInt = MOTOR_BACKWARD_START
							- requestedMotorInt;
					if (currentState.cruise) {
						currentState.cruise = false;
						//	cout << "Cruise mode off." << endl;
					}

				} else {
					//stop
					currentState.motorInt = SERVO_CENTER;
				}
				pthread_mutex_unlock(&obsticle_mutex);
				//cout << "updating lastRequestedMotorInt: " << currentState.lastRequestedMotorInt << endl;
				currentState.lastRequestedMotorInt = requestedMotorInt;

				//update motor
				//cout << "Current value of motorInt: " << currentState.motorInt << endl;
				gpioServo(GPIO_MOTOR_CONTROL, currentState.motorInt);
			}
			//update servo
			gpioServo(GPIO_STEERING_CONTROL, currentState.servoInt);

			//toggle turn signal
			//right
			pthread_mutex_lock(&turnSignal_mutex);
			if (parsedJson.get<bool>("R1")) {
				if (currentState.rightTurn == true) {
					currentState.rightTurn = false;
					currentState.leftTurn = false;
					//cout << "Right turn signal off." << endl;
				} else {
					currentState.rightTurn = true;
					currentState.leftTurn = false;
					//cout << "Right turn signal on." << endl;
				}

			}
			//left
			if (parsedJson.get<bool>("L1")) {
				if (currentState.leftTurn == true) {
					currentState.leftTurn = false;
					currentState.rightTurn = false;
					//cout << "Left turn signal off." << endl;
				} else {
					currentState.leftTurn = true;
					currentState.rightTurn = false;
					//cout << "Left turn signal on." << endl;
				}
			}

			//check for peak
			if (currentState.leftTurn || currentState.rightTurn) {
				if (currentState.turnPeaked) {
					if (currentState.servoInt == SERVO_CENTER) {
						currentState.leftTurn = false;
						currentState.rightTurn = false;
						currentState.turnPeaked = false;
						//cout << "Turn complete" << endl;
					}
				} else {
					if (currentState.leftTurn) {
						if (currentState.servoInt
								< (SERVO_CENTER - TURN_THRESHOLD)) {
							currentState.turnPeaked = true;
						}
					} else if (currentState.rightTurn) {
						if (currentState.servoInt
								> (SERVO_CENTER + TURN_THRESHOLD)) {
							currentState.turnPeaked = true;
						}
					}
				}
			}
			pthread_mutex_unlock(&turnSignal_mutex);

			//toggle cruise mode
			if (parsedJson.get<bool>("left")) {
				if (currentState.cruise == true) {
					currentState.cruise = false;
					cout << "Cruise mode off" << endl;
				} else {
					currentState.cruise = true;
					cout << "Cruise mode on" << endl;
				}
			}
			if (parsedJson.get<bool>("up")) {
				currentState.motorInt = currentState.motorInt + 10;
				gpioServo(GPIO_MOTOR_CONTROL, currentState.motorInt);
				//cout << "Current value of motorInt: " << currentState.motorInt << endl;
			} else if (parsedJson.get<bool>("down")) {
				currentState.motorInt = currentState.motorInt - 10;
				gpioServo(GPIO_MOTOR_CONTROL, currentState.motorInt);
				//cout << "Current value of motorInt: " << currentState.motorInt << endl;
			}

		}
		pthread_mutex_unlock(&autonomous_mutex);
		ptree answerJson;
		stringstream jsonWriteStream;

		answerJson.put("left_blinker", currentState.leftTurn);
		answerJson.put("right_blinker", currentState.rightTurn);
		write_json(jsonWriteStream, answerJson);
		//cout << "sending speedometer" << endl;

		if (currentState.connected) {
			websocket_server.send(currentState.client, jsonWriteStream.str(),
					websocketpp::frame::opcode::text);

		}

		//keep track of message recieved times.
		unsigned long currentTime = time(NULL);
		pthread_mutex_lock(&watchDog_mutex);

		//cout << "currentTime=" << currentTime << endl;
		currentState.lastMessageTime = currentTime;
		currentState.connected = true;
		pthread_mutex_unlock(&watchDog_mutex);

	} catch (std::exception const& e) {
		cerr << "<ERROR>" << endl;
		cerr << e.what() << endl;
		cerr << msg->get_payload() << endl;
		cerr << "</ERROR>" << endl;
	}

}
예제 #25
0
	WS(){
		m_server.init_asio();
		m_server.set_open_handler(bind(&WS::on_open,this,::_1));
		m_server.set_close_handler(bind(&WS::on_close,this,::_1));
		m_server.set_message_handler(bind(&WS::on_message,this,::_1,::_2));
	}