Exemple #1
0
int main()
{
    
    //initialize pids
    init_pids();
    
    //initialize pwm
    pwm1.period_ms(100);
    pwm2.period_ms(100);
    pwm3.period_ms(100);
    pwm4.period_ms(100);
    pwm1.write(0.00f);
    pwm2.write(0.00f);
    pwm3.write(0.00f);
    pwm4.write(0.00f);
    bool connection=0;
    setup();//Prepare Mpu6050 For Communication
   
    if(MPU6050.testConnection())
    {
        pc.printf("MPU6050 connected...\r\n");
        connection=1;
       // myledR=1;
        myledG=0;//connection led
    }
      else 
    {
        pc.printf("MPU6050 not connected...\r\n");
        connection=0;
        //myledR=1;
        myledG=0;
    }
    while (connection)
    {
        if(MPU6050.testConnection())
        {


            getRawValues();
           //transCeiver();
           
         
         // ...add orientation data to the transmit buffer
            txData[0] =rx;
            txData[1] =ry;
            txData[2] =rz;
            txData[3] =heightF;
            // If the transmit buffer is full
          //pc.printf("Function executed \r\n");
                my_nrf24l01p.disable();
                my_nrf24l01p.setTransmitMode();
                my_nrf24l01p.enable();
                // Send the transmitbuffer via the nRF24L01+
                //wait(0.2f);
               txDatacnt=my_nrf24l01p.write(NRF24L01P_PIPE_P0, txData, sizeof(txData));                           
                my_nrf24l01p.disable();
                my_nrf24l01p.setReceiveMode();
                my_nrf24l01p.enable();
            if (my_nrf24l01p.readable())
            {
           // ...read the data into the receive buffer
            rxDataCnt = my_nrf24l01p.read(NRF24L01P_PIPE_P0, rxData, sizeof(rxData));

                recvd=rxData[0];

            // Display the receive buffer contents via the host serial link
          switch(recvd)
              {
                    case 'F':
                    myledR=1;
                    setpP-=1;
                    setpR=0;
                   // pc.printf("moving forward... \r\n");
                    rxData[0]='0';
                    break;
                    
                    case 'B':
                    myledR=1;
                    setpP+=1;
                    setpR=0;
                    //pc.printf("moving Backward...\r\n");
                    rxData[0]='0';
                    break;
                    
                    case 'S':
                    myledR=1;
                    setpP=0;
                    setpR=0;
                    //pc.printf("stoping... \r\n");
                    rxData[0]='0';
                    break;
                    
                    case 'R':
                    setpP=0;
                    setpR-=1;
                    //pc.printf("Rolling...right \r\n");
                    rxData[0]='0';
                    break;
                    
                    case 'L':
                    myledR=1;
                    setpP=0;
                    setpR+=1;
                    //pc.printf("Rolling...left \r\n");
                    rxData[0]='0';
                    break;
                   //default :
                    //pc.printf("Waiting... \r");
                    //pc.printf("Waiting... %c\r",recvd);
                    //break;
                }
           // pc.printf("recvd %c\r\n",recvd);
           }
           
             //calculate orientation and determine motor power      
             ACCEL_YANGLE=ry;ACCEL_XANGLE=rx; 
             rollF=pid_out(&roll,ACCEL_YANGLE,setpR);
             pitchF=pid_out(&pitch,ACCEL_XANGLE,setpP);
             pwmsignals((float)heightF,(float)rollF,(float)yawF,(float)pitchF);//call function for esc
            // pc.printf("Motor1:%.2f\tMotor2:%.2f\tMotor3:%.2f\tMotor4:%.2f\r",motor1power,motor2power,motor3power,motor4power);
            //writing current orientation
            pc.printf("\rPitch %.4f\tRoll %.2f\tZ_angle %.4f\t\r",rx,ry,rz);
        }
            else 
        {
                pc.printf("No connection..\r\n");
        } 
        
    }
}
Exemple #2
0
bool Mineserver::init()
{
  // expand '~', '~user' in next vars
  bool error = false;
  const char* const vars[] =
  {
    "system.path.data",
    "system.path.plugins",
    "system.path.home",
    "system.pid_file",
  };
  for (size_t i = 0; i < sizeof(vars) / sizeof(vars[0]); i++)
  {
    ConfigNode::Ptr node = config()->mData(vars[i]);
    if (!node)
    {
      LOG2(ERROR, std::string("Variable is missing: ") + vars[i]);
      error = true;
      continue;
    }
    if (node->type() != CONFIG_NODE_STRING)
    {
      LOG2(ERROR, std::string("Variable is not string: ") + vars[i]);
      error = true;
      continue;
    }

    const std::string newvalue = relativeToAbsolute(node->sData());

    node->setData(newvalue);
    LOG2(INFO, std::string(vars[i]) + " = \"" + newvalue + "\"");
  }

  if (error)
  {
    return false;
  }

  const std::string str = config()->sData("system.path.home");
#ifdef WIN32
  if (_chdir(str.c_str()) != 0)
#else
  if (chdir(str.c_str()) != 0)
#endif
  {
    LOG2(ERROR, "Failed to change working directory to: " + str);
    return false;
  }

  // Write PID to file
  std::ofstream pid_out((config()->sData("system.pid_file")).c_str());
  if (!pid_out.fail())
  {
#ifdef WIN32
    pid_out << _getpid();
#else
    pid_out << getpid();
#endif
  }
  pid_out.close();


  // screen::init() needs m_plugin
  m_plugin = new Plugin;

  init_plugin_api();

  if (config()->bData("system.interface.use_cli"))
  {
    // Init our Screen
    screen()->init(VERSION);
  }


  LOG2(INFO, "Welcome to Mineserver v" + VERSION);

  MapGen* mapgen = new MapGen;
  MapGen* nethergen = new NetherGen;
  MapGen* heavengen = new HeavenGen;
  MapGen* biomegen = new BiomeGen;
  MapGen* eximgen = new EximGen;
  m_mapGenNames.push_back(mapgen);
  m_mapGenNames.push_back(nethergen);
  m_mapGenNames.push_back(heavengen);
  m_mapGenNames.push_back(biomegen);
  m_mapGenNames.push_back(eximgen);

  m_saveInterval = m_config->iData("map.save_interval");

  m_only_helmets = m_config->bData("system.armour.helmet_strict");
  m_pvp_enabled = m_config->bData("system.pvp.enabled");
  m_damage_enabled = m_config->bData("system.damage.enabled");

  const char* key = "map.storage.nbt.directories"; // Prefix for worlds config
  if (m_config->has(key) && (m_config->type(key) == CONFIG_NODE_LIST))
  {
    std::list<std::string> tmp = m_config->mData(key)->keys();
    int n = 0;
    for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it)
    {
      m_map.push_back(new Map());
      Physics* phy = new Physics;
      phy->map = n;
      m_physics.push_back(phy);
      int k = m_config->iData((std::string(key) + ".") + (*it));
      if ((uint32_t)k >= m_mapGenNames.size())
      {
        std::ostringstream s;
        s << "Error! Mapgen number " << k << " in config. " << m_mapGenNames.size() << " Mapgens known";
        LOG2(INFO, s.str());
      }
      // WARNING: if k is too big this will be an access error! -- louisdx
      MapGen* m = m_mapGenNames[k];
      m_mapGen.push_back(m);
      n++;

    }
  }
  else
  {
    LOG2(WARNING, "Cannot find map.storage.nbt.directories.*");
  }

  if (m_map.size() == 0)
  {
    LOG2(ERROR, "No worlds in Config!");
    return false;
  }

  m_chat           = new Chat;
  m_furnaceManager = new FurnaceManager;
  m_packetHandler  = new PacketHandler;
  m_inventory      = new Inventory(m_config->sData("system.path.data") + '/' + "recipes", ".recipe", "ENABLED_RECIPES.cfg");
  m_mobs           = new Mobs;

  return true;
}
Exemple #3
0
int Mineserver::run(int argc, char *argv[])
{
  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

  // Init our Screen
  screen()->init(VERSION);
  screen()->log("Welcome to Mineserver v" + VERSION);
  updatePlayerList();

  initConstants();

  std::string file_config;
  file_config.assign(CONFIG_FILE);
  std::string file_commands;
  file_commands.assign(COMMANDS_FILE);

  if (argc > 1)
  {
    file_config.assign(argv[1]);
  }

  // Initialize conf
  Mineserver::get()->conf()->load(file_config);
  Mineserver::get()->conf()->load(file_commands, COMMANDS_NAME_PREFIX);

  // Write PID to file
  std::ofstream pid_out((Mineserver::get()->conf()->sValue("pid_file")).c_str());
  if (!pid_out.fail())
  {
#ifdef WIN32
     pid_out << _getpid();
#else
     pid_out << getpid();
#endif
  }
  pid_out.close();

  // Load MOTD
  Mineserver::get()->chat()->checkMotd(Mineserver::get()->conf()->sValue("motd_file"));

  // Set physics enable state according to config
  Mineserver::get()->physics()->enabled = (Mineserver::get()->conf()->bValue("liquid_physics"));

  // Initialize map
  Mineserver::get()->map()->init();

  if (Mineserver::get()->conf()->bValue("map_generate_spawn"))
  {
    Mineserver::get()->screen()->log("Generating spawn area...");
    int size = Mineserver::get()->conf()->iValue("map_generate_spawn_size");
    bool show_progress = Mineserver::get()->conf()->bValue("map_generate_spawn_show_progress");
#ifdef WIN32
    DWORD t_begin,t_end;
#else
    clock_t t_begin,t_end;
#endif

    for (int x=-size;x<=size;x++)
    {
#ifdef WIN32
      if(show_progress)
      {
        t_begin = timeGetTime();
      }
#else
      if(show_progress)
      {
        t_begin = clock();
      }
#endif
      for (int z = -size; z <= size; z++)
      {
        Mineserver::get()->map()->loadMap(x, z);
      }

      if(show_progress)
      {
#ifdef WIN32
        t_end = timeGetTime ();
        Mineserver::get()->screen()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos((t_end-t_begin)/(size*2+1)) + "ms per chunk");
#else
        t_end = clock();
        Mineserver::get()->screen()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos(((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1)) + "ms per chunk");
#endif
      }
    }
#ifdef _DEBUG
    Mineserver::get()->screen()->log("Spawn area ready!");
#endif
  }

  // Initialize packethandler
  Mineserver::get()->packetHandler()->init();

  // Load ip from config
  std::string ip = Mineserver::get()->conf()->sValue("ip");

  // Load port from config
  int port = Mineserver::get()->conf()->iValue("port");

  // Initialize plugins
  Mineserver::get()->plugin()->init();

#ifdef WIN32
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
    Mineserver::get()->screen()->end();
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse = 1;

  m_eventBase = (event_base*)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    Mineserver::get()->screen()->log(LOG_ERROR, "Failed to create listen socket");
    Mineserver::get()->screen()->end();
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr*)&addresslisten, sizeof(addresslisten)) < 0)
  {
    Mineserver::get()->screen()->log(LOG_ERROR, "Failed to bind");
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    Mineserver::get()->screen()->log(LOG_ERROR, "Failed to listen to socket");
    Mineserver::get()->screen()->end();
    return 1;
  }

  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

  if(ip == "0.0.0.0")
  {
    // Print all local IPs
    char name[255];
    gethostname ( name, sizeof(name));
    struct hostent* hostinfo = gethostbyname(name);
    Mineserver::get()->screen()->log("Listening on: ");
    int ipIndex = 0;
    while(hostinfo && hostinfo->h_addr_list[ipIndex])
    {
      std::string ip(inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[ipIndex++]));
      Mineserver::get()->screen()->log(" " + ip + ":" + dtos(port));
    }
  }
  else
  {
    std::string myip(ip);
    Mineserver::get()->screen()->log("Listening on " + myip + ":" + dtos(port));
  }
  //std::cout << std::endl;

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running = true;
  event_base_loopexit(m_eventBase, &loopTime);

  // Create our Server Console user so we can issue commands
  User* serverUser = new User(-1, SERVER_CONSOLE_UID);
  serverUser->changeNick("[Server]");

  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {
    // Append current command and check if user entered return
    if(Mineserver::get()->screen()->hasCommand())
    {
      // Now handle this command as normal
      Mineserver::get()->chat()->handleMsg(serverUser, Mineserver::get()->screen()->getCommand().c_str());
    }

    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);

      //If users, ping them
      if(User::all().size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        User::all()[0]->sendAll(&data, 1);

        //Send server time
        Packet pkt;
        pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Mineserver::get()->map()->mapTime;
        User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
      }

      // TODO: Run garbage collection for chunk storage dealie?
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < User::all().size(); i++)
      {
        User::all()[i]->pushMap();
        User::all()[i]->popMap();

        //Minecart hacks!!
        /*
        if(User::all()[i]->attachedTo)
        {
          Packet pkt;
          pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo <<  (sint16)10000       << (sint16)0 << (sint16)0;
          //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo <<  (sint8)100       << (sint8)0 << (sint8)0;
          User::all()[i]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
        }
        */
      }

      map()->mapTime+=20;
      if (map()->mapTime >= 24000)
      {
        map()->mapTime = 0;
      }

      map()->checkGenTrees();

      // Check for Furnace activity
      Mineserver::get()->furnaceManager()->update();
    }

    // Physics simulation every 200ms
    Mineserver::get()->physics()->update();

    // Underwater check / drowning
    int i = 0;
    int s = User::all().size();
    for(i=0;i<s;i++)
    {
      User::all()[i]->isUnderwater();
    }

//    event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
//    event_add(&m_listenEvent, NULL);

    event_base_loopexit(m_eventBase, &loopTime);
  }

#ifdef WIN32
  closesocket(m_socketlisten);
#else
  close(m_socketlisten);
#endif

  // Remove the PID file
#ifdef WIN32
  _unlink((Mineserver::get()->conf()->sValue("pid_file")).c_str());
#else
  unlink((Mineserver::get()->conf()->sValue("pid_file")).c_str());
#endif

  // End our NCurses session
  screen()->end();

  /* Free memory */
  delete m_map;
  delete m_chat;
  delete m_plugin;
  delete m_screen;
  delete m_physics;
  delete m_conf;
  delete m_furnaceManager;
  delete m_packetHandler;
  delete m_mapGen;
  delete m_logger;

  return EXIT_SUCCESS;
}
Mineserver::Mineserver(int args, char **argarray)
    :  argv(argarray),
       argc(args),
       m_socketlisten  (0),
       m_saveInterval  (0),
       m_lastSave      (std::time(NULL)),
       m_pvp_enabled   (false),
       m_damage_enabled(false),
       m_only_helmets  (false),
       m_running       (false),
       m_eventBase     (NULL),

       // core modules
       m_config        (new Config()),
       m_screen        (new CliScreen()),
       m_logger        (new Logger()),

       m_plugin        (NULL),
       m_chat          (NULL),
       m_furnaceManager(NULL),
       m_packetHandler (NULL),
       m_inventory     (NULL),
       m_mobs          (NULL)
{
    pthread_mutex_init(&m_validation_mutex,NULL);
    ServerInstance = this;
    InitSignals();

    std::srand((uint32_t)std::time(NULL));
    initPRNG();

    std::string cfg;
    std::vector<std::string> overrides;

    for (int i = 1; i < argc; i++)
    {
        const std::string arg(argv[i]);

        switch (arg[0])
        {
        case '-':   // option
            // we have only '-h' and '--help' now, so just return with help
            printHelp(0);
            throw CoreException();

        case '+':   // override
            overrides.push_back(arg.substr(1));
            break;

        default:    // otherwise, it is config file
            if (!cfg.empty())
                throw CoreException("Only single CONFIG_FILE argument is allowed!");
            cfg = arg;
            break;
        }
    }

    const std::string path_exe = "./";

    // If config file is provided as an argument
    if (!cfg.empty())
    {
        std::cout << "Searching for configuration file..." << std::endl;
        if (fileExists(cfg))
        {
            const std::pair<std::string, std::string> fullpath = pathOfFile(cfg);
            cfg = fullpath.first + PATH_SEPARATOR + fullpath.second;
            this->config()->config_path = fullpath.first;
        }
        else
        {
            std::cout << "Config not found...\n";;
            cfg.clear();
        }
    }

    if (cfg.empty())
    {
        if (fileExists(path_exe + PATH_SEPARATOR + CONFIG_FILE))
        {
            cfg = path_exe + PATH_SEPARATOR + CONFIG_FILE;
            this->config()->config_path = path_exe;
        }
        else
        {
            std::cout << "Config not found\n";
        }
    }

    // load config
    Config &configvar = *this->config();
    if (!configvar.load(cfg))
    {
        throw CoreException("Could not load config!");
    }

    m_plugin = new Plugin();

    LOG2(INFO, "Using config: " + cfg);

    if (overrides.size())
    {
        std::stringstream override_config;
        for (size_t i = 0; i < overrides.size(); i++)
        {
            LOG2(INFO, "Overriden: " + overrides[i]);
            override_config << overrides[i] << ';' << std::endl;
        }
        // override config
        if (!configvar.load(override_config))
            throw CoreException("Error when parsing overrides: maybe you forgot to doublequote string values?");
    }

    memset(&m_listenEvent, 0, sizeof(event));
    initConstants();
    // Write PID to file
    std::ofstream pid_out((config()->sData("system.pid_file")).c_str());
    if (!pid_out.fail())
    {
        pid_out << getpid();
    }
    pid_out.close();




    init_plugin_api();

    if (config()->bData("system.interface.use_cli"))
    {
        // Init our Screen
        screen()->init(VERSION);
    }


    LOG2(INFO, "Welcome to Mineserver v" + VERSION);
    LOG2(INFO, "Using zlib "+std::string(ZLIB_VERSION)+" libevent "+std::string(event_get_version()));

    LOG2(INFO, "Generating RSA key pair for protocol encryption");
    //Protocol encryption
    srand(microTime());
    if((rsa = RSA_generate_key(1024, 17, 0, 0)) == NULL)
    {
        LOG2(INFO, "KEY GENERATION FAILED!");
        exit(1);
    }
    LOG2(INFO, "RSA key pair generated.");

    /* Get ASN.1 format public key */
    x=X509_new();
    pk=EVP_PKEY_new();
    EVP_PKEY_assign_RSA(pk,rsa);
    X509_set_version(x,0);
    X509_set_pubkey(x,pk);

    int len;
    unsigned char *buf;
    buf = NULL;
    len = i2d_X509(x, &buf);

    //Glue + jesus tape, dont ask - Fador
    publicKey = std::string((char *)(buf+28),len-36);
    OPENSSL_free(buf);
    /* END key fetching */

    const std::string temp_nums="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890=-";

    const std::string temp_hex="0123456789abcdef";

    for(int i = 0; i < 4; i++)
    {
        encryptionBytes += (char)(temp_nums[rand()%temp_nums.size()]);
    }

    for(int i = 0; i < 16; i++)
    {
        serverID += (char)(temp_hex[rand()%temp_hex.size()]);
    }

    LOG2(INFO, "ServerID: " + serverID);

    if(!m_config->bData("system.user_validation"))
    {
        serverID = "-";
    }

    MapGen* mapgen = new MapGen();
    MapGen* nethergen = new NetherGen();
    MapGen* heavengen = new HeavenGen();
    MapGen* biomegen = new BiomeGen();
    MapGen* eximgen = new EximGen();
    m_mapGenNames.push_back(mapgen);
    m_mapGenNames.push_back(nethergen);
    m_mapGenNames.push_back(heavengen);
    m_mapGenNames.push_back(biomegen);
    m_mapGenNames.push_back(eximgen);

    m_saveInterval = m_config->iData("map.save_interval");

    m_only_helmets = m_config->bData("system.armour.helmet_strict");
    m_pvp_enabled = m_config->bData("system.pvp.enabled");
    m_damage_enabled = m_config->bData("system.damage.enabled");

    const char* key = "map.storage.nbt.directories"; // Prefix for worlds config
    if (m_config->has(key) && (m_config->type(key) == CONFIG_NODE_LIST))
    {
        std::list<std::string> tmp = m_config->mData(key)->keys();
        int n = 0;
        for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it)
        {
            m_map.push_back(new Map());
            Physics* phy = new Physics;
            phy->map = n;

            m_physics.push_back(phy);
            RedstoneSimulation* red = new RedstoneSimulation;
            red->map = n;
            m_redstone.push_back(red);
            int k = m_config->iData((std::string(key) + ".") + (*it));
            if ((uint32_t)k >= m_mapGenNames.size())
            {
                std::ostringstream s;
                s << "Error! Mapgen number " << k << " in config. " << m_mapGenNames.size() << " Mapgens known";
                LOG2(INFO, s.str());
            }
            // WARNING: if k is too big this will be an access error! -- louisdx
            MapGen* m = m_mapGenNames[k];
            m_mapGen.push_back(m);
            n++;
        }
    }
    else
    {
        LOG2(WARNING, "Cannot find map.storage.nbt.directories.*");
    }

    if (m_map.size() == 0)
        throw CoreException("No worlds in Config");

    m_chat           = new Chat;
    m_furnaceManager = new FurnaceManager;
    m_packetHandler  = new PacketHandler;
    m_inventory      = new Inventory(m_config->sData("system.path.data") + '/' + "recipes", ".recipe", "ENABLED_RECIPES.cfg");
    m_mobs           = new Mobs;

} // End Mineserver constructor