<commit_before>/* Copyright (C) 2004 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "commands.h"

#include "instance_map.h"
#include "messages.h"
#include "mysqld_error.h"
#include "mysql_manager_error.h"
#include "protocol.h"
#include "buffer.h"

#include <m_string.h>
#include <mysql.h>

/* implementation for Show_instances: */

/*
  The method sends a list of instances in the instance map to the client.

  SYNOPSYS
    Show_instances::do_command()
    net               The network connection to the client.

  RETURN
    0 - ok
    1 - error occured
*/

int Show_instances::do_command(struct st_net *net)
{
  Buffer send_buff;  /* buffer for packets */
  LIST name, status;
  NAME_WITH_LENGTH name_field, status_field;
  LIST *field_list;
  uint position=0;

  name_field.name= (char *) "instance_name";
  name_field.length= 20;
  name.data= &name_field;
  status_field.name= (char *) "status";
  status_field.length= 20;
  status.data= &status_field;
  field_list= list_add(NULL, &status);
  field_list= list_add(field_list, &name);

  send_fields(net, field_list);

  {
    Instance *instance;
    Instance_map::Iterator iterator(instance_map);

    instance_map->lock();
    while ((instance= iterator.next()))
    {
      position= 0;
      store_to_string(&send_buff, instance->options.instance_name, &position);
      if (instance->is_running())
        store_to_string(&send_buff, (char *) "online", &position);
      else
        store_to_string(&send_buff, (char *) "offline", &position);
      if (my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }
    instance_map->unlock();
  }
  if (send_eof(net))
    goto err;
  if (net_flush(net))
    goto err;

  return 0;
err:
  return 1;
}

int Show_instances::execute(struct st_net *net, ulong connection_id)
{
  if (do_command(net))
    return ER_OUT_OF_RESOURCES;

  return 0;
}

/* implementation for Flush_instances: */

int Flush_instances::execute(struct st_net *net, ulong connection_id)
{
  if (instance_map->flush_instances())
    return ER_OUT_OF_RESOURCES;

  net_send_ok(net, connection_id);
  return 0;
}

/* implementation for Show_instance_status: */

Show_instance_status::Show_instance_status(Instance_map *instance_map_arg,
                                           const char *name, uint len)
  :Command(instance_map_arg)
{
  Instance *instance;

  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
  {
    instance_name= instance->options.instance_name;
  }
  else
    instance_name= NULL;
}

/*
  The method sends a table with a status of requested instance to the client.

  SYNOPSYS
    Show_instance_status::do_command()
    net               The network connection to the client.
    instance_name     The name of the instance.

  RETURN
    0 - ok
    1 - error occured
*/

int Show_instance_status::do_command(struct st_net *net,
                                     const char *instance_name)
{
  enum { MAX_VERSION_LENGTH= 40 };
  Buffer send_buff;  /* buffer for packets */
  LIST name, status, version;
  LIST *field_list;
  NAME_WITH_LENGTH name_field, status_field, version_field;
  uint position=0;

  /* create list of the fileds to be passed to send_fields */
  name_field.name= (char *) "instance_name";
  name_field.length= 20;
  name.data= &name_field;
  status_field.name= (char *) "status";
  status_field.length= 20;
  status.data= &status_field;
  version_field.name= (char *) "version";
  version_field.length= MAX_VERSION_LENGTH;
  version.data= &version_field;
  field_list= list_add(NULL, &version);
  field_list= list_add(field_list, &status);
  field_list= list_add(field_list, &name);

  send_fields(net, field_list);

  {
    Instance *instance;

    store_to_string(&send_buff, (char *) instance_name, &position);
    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))
      goto err;
    if (instance->is_running())
    {
      store_to_string(&send_buff, (char *) "online", &position);
      store_to_string(&send_buff, "unknown", &position);
    }
    else
    {
      store_to_string(&send_buff, (char *) "offline", &position);
      store_to_string(&send_buff, (char *) "unknown", &position);
    }

    if (send_buff.is_error() ||
        my_net_write(net, send_buff.buffer, (uint) position))
      goto err;
  }

  send_eof(net);
  net_flush(net);

  return 0;

err:
  return 1;
}

int Show_instance_status::execute(struct st_net *net, ulong connection_id)
{
  if ((instance_name))
  {
    if (do_command(net, instance_name))
      return ER_OUT_OF_RESOURCES;
    return 0;
  }
  else
  {
    return ER_BAD_INSTANCE_NAME;
  }
}

/* Implementation for Show_instance_options */

Show_instance_options::Show_instance_options(Instance_map *instance_map_arg,
                                             const char *name, uint len):
  Command(instance_map_arg)
{
  Instance *instance;

  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
  {
    instance_name= instance->options.instance_name;
  }
  else
    instance_name= NULL;
}

int Show_instance_options::do_command(struct st_net *net,
                                      const char *instance_name)
{
  enum { MAX_VERSION_LENGTH= 40 };
  Buffer send_buff;  /* buffer for packets */
  LIST name, option;
  LIST *field_list;
  NAME_WITH_LENGTH name_field, option_field;
  uint position=0;

  /* create list of the fileds to be passed to send_fields */
  name_field.name= (char *) "option_name";
  name_field.length= 20;
  name.data= &name_field;
  option_field.name= (char *) "value";
  option_field.length= 20;
  option.data= &option_field;
  field_list= list_add(NULL, &option);
  field_list= list_add(field_list, &name);

  send_fields(net, field_list);

  {
    Instance *instance;

    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))
      goto err;
    store_to_string(&send_buff, (char *) "instance_name", &position);
    store_to_string(&send_buff, (char *) instance_name, &position);
    if (my_net_write(net, send_buff.buffer, (uint) position))
      goto err;
    if ((instance->options.mysqld_path))
    {
      position= 0;
      store_to_string(&send_buff, (char *) "mysqld-path", &position);
      store_to_string(&send_buff,
                     (char *) instance->options.mysqld_path,
                     &position);
      if (send_buff.is_error() ||
          my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }

    if ((instance->options.nonguarded))
    {
      position= 0;
      store_to_string(&send_buff, (char *) "nonguarded", &position);
      store_to_string(&send_buff, "", &position);
      if (send_buff.is_error() ||
          my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }

    /* loop through the options stored in DYNAMIC_ARRAY */
    for (uint i= 0; i < instance->options.options_array.elements; i++)
    {
      char *tmp_option, *option_value;
      get_dynamic(&(instance->options.options_array), (gptr) &tmp_option, i);
      option_value= strchr(tmp_option, '=');
      /* split the option string into two parts */
      *option_value= 0;
      position= 0;
      store_to_string(&send_buff, tmp_option + 2, &position);
      store_to_string(&send_buff, option_value + 1, &position);
      /* join name and the value into the same option again */
      *option_value= '=';
      if (send_buff.is_error() ||
          my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }
  }

  send_eof(net);
  net_flush(net);

  return 0;

err:
  return 1;
}

int Show_instance_options::execute(struct st_net *net, ulong connection_id)
{
  if ((instance_name))
  {
    if (do_command(net, instance_name))
      return ER_OUT_OF_RESOURCES;
    return 0;
  }
  else
  {
    return ER_BAD_INSTANCE_NAME;
  }
}

/* Implementation for Start_instance */

Start_instance::Start_instance(Instance_map *instance_map_arg,
                               const char *name, uint len)
  :Command(instance_map_arg)
{
  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
    instance_name= instance->options.instance_name;
}

int Start_instance::execute(struct st_net *net, ulong connection_id)
{
  uint err_code;
  if (instance == 0)
  {
    return ER_BAD_INSTANCE_NAME; /* haven't found an instance */
  }
  else
  {
    if ((err_code= instance->start()))
      return err_code;

    if (!(instance->options.nonguarded))
        instance_map->guardian->guard(instance);

    net_send_ok(net, connection_id);
    return 0;
  }
}

/* Implementation for Stop_instance: */

Stop_instance::Stop_instance(Instance_map *instance_map_arg,
                               const char *name, uint len)
  :Command(instance_map_arg)
{
  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
    instance_name= instance->options.instance_name;
}

int Stop_instance::execute(struct st_net *net, ulong connection_id)
{
  uint err_code;

  if (instance == 0)
  {
    return ER_BAD_INSTANCE_NAME; /* haven't found an instance */
  }
  else
  {
    if (!(instance->options.nonguarded))
        instance_map->guardian->
               stop_guard(instance);
    if ((err_code= instance->stop()))
      return err_code;
    net_send_ok(net, connection_id);
    return 0;
  }
}

int Syntax_error::execute(struct st_net *net, ulong connection_id)
{
  return ER_SYNTAX_ERROR;
}
<commit_msg>Fix for bug #9808<commit_after>/* Copyright (C) 2004 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "commands.h"

#include "instance_map.h"
#include "messages.h"
#include "mysqld_error.h"
#include "mysql_manager_error.h"
#include "protocol.h"
#include "buffer.h"

#include <m_string.h>
#include <mysql.h>

/* implementation for Show_instances: */

/*
  The method sends a list of instances in the instance map to the client.

  SYNOPSYS
    Show_instances::do_command()
    net               The network connection to the client.

  RETURN
    0 - ok
    1 - error occured
*/

int Show_instances::do_command(struct st_net *net)
{
  Buffer send_buff;  /* buffer for packets */
  LIST name, status;
  NAME_WITH_LENGTH name_field, status_field;
  LIST *field_list;
  uint position=0;

  name_field.name= (char *) "instance_name";
  name_field.length= 20;
  name.data= &name_field;
  status_field.name= (char *) "status";
  status_field.length= 20;
  status.data= &status_field;
  field_list= list_add(NULL, &status);
  field_list= list_add(field_list, &name);

  send_fields(net, field_list);

  {
    Instance *instance;
    Instance_map::Iterator iterator(instance_map);

    instance_map->lock();
    while ((instance= iterator.next()))
    {
      position= 0;
      store_to_string(&send_buff, instance->options.instance_name, &position);
      if (instance->is_running())
        store_to_string(&send_buff, (char *) "online", &position);
      else
        store_to_string(&send_buff, (char *) "offline", &position);
      if (my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }
    instance_map->unlock();
  }
  if (send_eof(net))
    goto err;
  if (net_flush(net))
    goto err;

  return 0;
err:
  return 1;
}

int Show_instances::execute(struct st_net *net, ulong connection_id)
{
  if (do_command(net))
    return ER_OUT_OF_RESOURCES;

  return 0;
}

/* implementation for Flush_instances: */

int Flush_instances::execute(struct st_net *net, ulong connection_id)
{
  if (instance_map->flush_instances())
    return ER_OUT_OF_RESOURCES;

  net_send_ok(net, connection_id);
  return 0;
}

/* implementation for Show_instance_status: */

Show_instance_status::Show_instance_status(Instance_map *instance_map_arg,
                                           const char *name, uint len)
  :Command(instance_map_arg)
{
  Instance *instance;

  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
  {
    instance_name= instance->options.instance_name;
  }
  else
    instance_name= NULL;
}

/*
  The method sends a table with a status of requested instance to the client.

  SYNOPSYS
    Show_instance_status::do_command()
    net               The network connection to the client.
    instance_name     The name of the instance.

  RETURN
    0 - ok
    1 - error occured
*/

int Show_instance_status::do_command(struct st_net *net,
                                     const char *instance_name)
{
  enum { MAX_VERSION_LENGTH= 40 };
  Buffer send_buff;  /* buffer for packets */
  LIST name, status, version;
  LIST *field_list;
  NAME_WITH_LENGTH name_field, status_field, version_field;
  uint position=0;

  /* create list of the fileds to be passed to send_fields */
  name_field.name= (char *) "instance_name";
  name_field.length= 20;
  name.data= &name_field;
  status_field.name= (char *) "status";
  status_field.length= 20;
  status.data= &status_field;
  version_field.name= (char *) "version";
  version_field.length= MAX_VERSION_LENGTH;
  version.data= &version_field;
  field_list= list_add(NULL, &version);
  field_list= list_add(field_list, &status);
  field_list= list_add(field_list, &name);

  send_fields(net, field_list);

  {
    Instance *instance;

    store_to_string(&send_buff, (char *) instance_name, &position);
    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))
      goto err;
    if (instance->is_running())
    {
      store_to_string(&send_buff, (char *) "online", &position);
      store_to_string(&send_buff, "unknown", &position);
    }
    else
    {
      store_to_string(&send_buff, (char *) "offline", &position);
      store_to_string(&send_buff, (char *) "unknown", &position);
    }

    if (send_buff.is_error() ||
        my_net_write(net, send_buff.buffer, (uint) position))
      goto err;
  }

  send_eof(net);
  net_flush(net);

  return 0;

err:
  return 1;
}

int Show_instance_status::execute(struct st_net *net, ulong connection_id)
{
  if ((instance_name))
  {
    if (do_command(net, instance_name))
      return ER_OUT_OF_RESOURCES;
    return 0;
  }
  else
  {
    return ER_BAD_INSTANCE_NAME;
  }
}

/* Implementation for Show_instance_options */

Show_instance_options::Show_instance_options(Instance_map *instance_map_arg,
                                             const char *name, uint len):
  Command(instance_map_arg)
{
  Instance *instance;

  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
  {
    instance_name= instance->options.instance_name;
  }
  else
    instance_name= NULL;
}

int Show_instance_options::do_command(struct st_net *net,
                                      const char *instance_name)
{
  enum { MAX_VERSION_LENGTH= 40 };
  Buffer send_buff;  /* buffer for packets */
  LIST name, option;
  LIST *field_list;
  NAME_WITH_LENGTH name_field, option_field;
  uint position=0;

  /* create list of the fileds to be passed to send_fields */
  name_field.name= (char *) "option_name";
  name_field.length= 20;
  name.data= &name_field;
  option_field.name= (char *) "value";
  option_field.length= 20;
  option.data= &option_field;
  field_list= list_add(NULL, &option);
  field_list= list_add(field_list, &name);

  send_fields(net, field_list);

  {
    Instance *instance;

    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))
      goto err;
    store_to_string(&send_buff, (char *) "instance_name", &position);
    store_to_string(&send_buff, (char *) instance_name, &position);
    if (my_net_write(net, send_buff.buffer, (uint) position))
      goto err;
    if ((instance->options.mysqld_path))
    {
      position= 0;
      store_to_string(&send_buff, (char *) "mysqld-path", &position);
      store_to_string(&send_buff,
                     (char *) instance->options.mysqld_path,
                     &position);
      if (send_buff.is_error() ||
          my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }

    if ((instance->options.nonguarded))
    {
      position= 0;
      store_to_string(&send_buff, (char *) "nonguarded", &position);
      store_to_string(&send_buff, "", &position);
      if (send_buff.is_error() ||
          my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }

    /* loop through the options stored in DYNAMIC_ARRAY */
    for (uint i= 0; i < instance->options.options_array.elements; i++)
    {
      char *tmp_option, *option_value;
      get_dynamic(&(instance->options.options_array), (gptr) &tmp_option, i);
      option_value= strchr(tmp_option, '=');
      /* split the option string into two parts if it has a value */

      position= 0;
      if (option_value != NULL)
      {
        *option_value= 0;
        store_to_string(&send_buff, tmp_option + 2, &position);
        store_to_string(&send_buff, option_value + 1, &position);
        /* join name and the value into the same option again */
        *option_value= '=';
      }
      else store_to_string(&send_buff, tmp_option + 2, &position);

      if (send_buff.is_error() ||
          my_net_write(net, send_buff.buffer, (uint) position))
        goto err;
    }
  }

  send_eof(net);
  net_flush(net);

  return 0;

err:
  return 1;
}

int Show_instance_options::execute(struct st_net *net, ulong connection_id)
{
  if ((instance_name))
  {
    if (do_command(net, instance_name))
      return ER_OUT_OF_RESOURCES;
    return 0;
  }
  else
  {
    return ER_BAD_INSTANCE_NAME;
  }
}

/* Implementation for Start_instance */

Start_instance::Start_instance(Instance_map *instance_map_arg,
                               const char *name, uint len)
  :Command(instance_map_arg)
{
  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
    instance_name= instance->options.instance_name;
}

int Start_instance::execute(struct st_net *net, ulong connection_id)
{
  uint err_code;
  if (instance == 0)
  {
    return ER_BAD_INSTANCE_NAME; /* haven't found an instance */
  }
  else
  {
    if ((err_code= instance->start()))
      return err_code;

    if (!(instance->options.nonguarded))
        instance_map->guardian->guard(instance);

    net_send_ok(net, connection_id);
    return 0;
  }
}

/* Implementation for Stop_instance: */

Stop_instance::Stop_instance(Instance_map *instance_map_arg,
                               const char *name, uint len)
  :Command(instance_map_arg)
{
  /* we make a search here, since we don't want t store the name */
  if ((instance= instance_map->find(name, len)))
    instance_name= instance->options.instance_name;
}

int Stop_instance::execute(struct st_net *net, ulong connection_id)
{
  uint err_code;

  if (instance == 0)
  {
    return ER_BAD_INSTANCE_NAME; /* haven't found an instance */
  }
  else
  {
    if (!(instance->options.nonguarded))
        instance_map->guardian->
               stop_guard(instance);
    if ((err_code= instance->stop()))
      return err_code;
    net_send_ok(net, connection_id);
    return 0;
  }
}

int Syntax_error::execute(struct st_net *net, ulong connection_id)
{
  return ER_SYNTAX_ERROR;
}
<|endoftext|>


<commit_before>/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)
#pragma implementation
#endif

#include "listener.h"
#include "priv.h"
#include <m_string.h>
#include <mysql.h>
#include <violite.h>
#ifndef __WIN__
#include <sys/un.h>
#endif
#include <sys/stat.h>

#include "thread_registry.h"
#include "options.h"
#include "instance_map.h"
#include "log.h"
#include "mysql_connection.h"
#include "portability.h"

/*
  Listener_thread - incapsulates listening functionality
*/

class Listener_thread: public Listener_thread_args
{
public:
  Listener_thread(const Listener_thread_args &args);
  ~Listener_thread();
  void run();
private:
  static const int LISTEN_BACK_LOG_SIZE= 5;     /* standard backlog size */
  ulong total_connection_count;
  Thread_info thread_info;

  int     sockets[2];
  int     num_sockets;
  fd_set  read_fds;
private:
  void handle_new_mysql_connection(Vio *vio);
  int   create_tcp_socket();
  int   create_unix_socket(struct sockaddr_un &unix_socket_address);
};

Listener_thread::Listener_thread(const Listener_thread_args &args) :
  Listener_thread_args(args.thread_registry, args.options, args.user_map,
                       args.instance_map)
  ,total_connection_count(0)
  ,thread_info(pthread_self())
  ,num_sockets(0)
{
}

Listener_thread::~Listener_thread()
{
}

/*
  Listener_thread::run() - listen all supported sockets and spawn a thread
  to handle incoming connection.
  Using 'die' in case of syscall failure is OK now - we don't hold any
  resources and 'die' kills the signal thread automatically. To be rewritten
  one day.
  See also comments in mysqlmanager.cc to picture general Instance Manager
  architecture.
*/

void Listener_thread::run()
{
  int n= 0;

#ifndef __WIN__
  /* we use this var to check whether we are running on LinuxThreads */
  pid_t thread_pid;

  thread_pid= getpid();

  struct sockaddr_un unix_socket_address;
  /* set global variable */
  linuxthreads= (thread_pid != manager_pid);
#endif

  thread_registry.register_thread(&thread_info);

  my_thread_init();

  FD_ZERO(&read_fds);

  /* I. prepare 'listen' sockets */
  if (create_tcp_socket())
    goto err;

#ifndef __WIN__
  if (create_unix_socket(unix_socket_address))
    goto err;
#endif

  /* II. Listen sockets and spawn childs */
  for (int i= 0; i < num_sockets; i++)
    n= max(n, sockets[i]);
  n++;

  timeval tv;
  while (!thread_registry.is_shutdown())
  {
    fd_set read_fds_arg= read_fds;
    /*
      We should reintialize timer as on linux it is modified
      to reflect amount of time not slept.
    */
    tv.tv_sec= 0;
    tv.tv_usec= 100000;

    /*
      When using valgrind 2.0 this syscall doesn't get kicked off by a
      signal during shutdown. This results in failing assert
      (Thread_registry::~Thread_registry). Valgrind 2.2 works fine.
    */
    int rc= select(n, &read_fds_arg, 0, 0, &tv);

    if (rc == 0 || rc == -1)
    {
      if (rc == -1 && errno != EINTR)
        log_error("Listener_thread::run(): select() failed, %s",
                  strerror(errno));
      continue;
    }

    for (int socket_index= 0; socket_index < num_sockets; socket_index++)
    {
      /* Assuming that rc > 0 as we asked to wait forever */
      if (FD_ISSET(sockets[socket_index], &read_fds_arg))
      {
        int client_fd= accept(sockets[socket_index], 0, 0);
        /* accept may return -1 (failure or spurious wakeup) */
        if (client_fd >= 0)                    // connection established
        {
          Vio *vio= vio_new(client_fd, socket_index == 0 ?
                            VIO_TYPE_SOCKET : VIO_TYPE_TCPIP,
                            socket_index == 0 ? 1 : 0);
          if (vio != 0)
            handle_new_mysql_connection(vio);
          else
          {
            shutdown(client_fd, SHUT_RDWR);
            close(client_fd);
          }
        }
      }
    }
  }

  /* III. Release all resources and exit */

  log_info("Listener_thread::run(): shutdown requested, exiting...");

  for (int i= 0; i < num_sockets; i++)
    close(sockets[i]);

#ifndef __WIN__
  unlink(unix_socket_address.sun_path);
#endif

  thread_registry.unregister_thread(&thread_info);
  my_thread_end();
  return;

err:
  // we have to close the ip sockets in case of error
  for (int i= 0; i < num_sockets; i++)
    close(sockets[i]);

  thread_registry.unregister_thread(&thread_info);
  thread_registry.request_shutdown();
  my_thread_end();
  return;
}

void set_non_blocking(int socket)
{
#ifndef __WIN__
  int flags= fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags | O_NONBLOCK);
#else
  u_long arg= 1;
  ioctlsocket(socket, FIONBIO, &arg);
#endif
}

void set_no_inherit(int socket)
{
#ifndef __WIN__
  int flags= fcntl(socket, F_GETFD, 0);
  fcntl(socket, F_SETFD, flags | FD_CLOEXEC);
#endif
}

int Listener_thread::create_tcp_socket()
{
  /* value to be set by setsockopt */
  int arg= 1;

  int ip_socket= socket(AF_INET, SOCK_STREAM, 0);
  if (ip_socket == INVALID_SOCKET)
  {
    log_error("Listener_thead::run(): socket(AF_INET) failed, %s",
              strerror(errno));
    return -1;
  }

  struct sockaddr_in ip_socket_address;
  bzero(&ip_socket_address, sizeof(ip_socket_address));

  ulong im_bind_addr;
  if (options.bind_address != 0)
  {
    if ((im_bind_addr= (ulong) inet_addr(options.bind_address)) == INADDR_NONE)
      im_bind_addr= htonl(INADDR_ANY);
  }
  else
    im_bind_addr= htonl(INADDR_ANY);
  uint im_port= options.port_number;

  ip_socket_address.sin_family= AF_INET;
  ip_socket_address.sin_addr.s_addr= im_bind_addr;

  ip_socket_address.sin_port= (unsigned short)
    htons((unsigned short) im_port);

  setsockopt(ip_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &arg, sizeof(arg));
  if (bind(ip_socket, (struct sockaddr *) &ip_socket_address,
           sizeof(ip_socket_address)))
  {
    log_error("Listener_thread::run(): bind(ip socket) failed, '%s'",
              strerror(errno));
    close(ip_socket);
    return -1;
  }

  if (listen(ip_socket, LISTEN_BACK_LOG_SIZE))
  {
    log_error("Listener_thread::run(): listen(ip socket) failed, %s",
              strerror(errno));
    close(ip_socket);
    return -1;
  }

  /* set the socket nonblocking */
  set_non_blocking(ip_socket);

  /* make sure that instances won't be listening our sockets */
  set_no_inherit(ip_socket);

  FD_SET(ip_socket, &read_fds);
  sockets[num_sockets++]= ip_socket;
  log_info("accepting connections on ip socket");
  return 0;
}

#ifndef __WIN__
int Listener_thread::
create_unix_socket(struct sockaddr_un &unix_socket_address)
{
  int unix_socket= socket(AF_UNIX, SOCK_STREAM, 0);
  if (unix_socket == INVALID_SOCKET)
  {
    log_error("Listener_thead::run(): socket(AF_UNIX) failed, %s",
              strerror(errno));
    return -1;
  }

  bzero(&unix_socket_address, sizeof(unix_socket_address));

  unix_socket_address.sun_family= AF_UNIX;
  strmake(unix_socket_address.sun_path, options.socket_file_name,
          sizeof(unix_socket_address.sun_path));
  unlink(unix_socket_address.sun_path); // in case we have stale socket file

  /*
    POSIX specifies default permissions for a pathname created by bind
    to be 0777. We need everybody to have access to the socket.
  */
  mode_t old_mask= umask(0);
  if (bind(unix_socket, (struct sockaddr *) &unix_socket_address,
           sizeof(unix_socket_address)))
  {
    log_error("Listener_thread::run(): bind(unix socket) failed, "
              "socket file name is '%s', error '%s'",
              unix_socket_address.sun_path, strerror(errno));
    close(unix_socket);
    return -1;
  }

  umask(old_mask);

  if (listen(unix_socket, LISTEN_BACK_LOG_SIZE))
  {
    log_error("Listener_thread::run(): listen(unix socket) failed, %s",
              strerror(errno));
    close(unix_socket);
    return -1;
  }

  /* set the socket nonblocking */
  set_non_blocking(unix_socket);

  /* make sure that instances won't be listening our sockets */
  set_no_inherit(unix_socket);

  log_info("accepting connections on unix socket %s",
           unix_socket_address.sun_path);
  sockets[num_sockets++]= unix_socket;
  FD_SET(unix_socket, &read_fds);
  return 0;
}
#endif

/*
  Create new mysql connection. Created thread is responsible for deletion of
  the Mysql_connection_thread_args and Vio instances passed to it.
  SYNOPSYS
    handle_new_mysql_connection()
*/

void Listener_thread::handle_new_mysql_connection(Vio *vio)
{
  if (Mysql_connection_thread_args *mysql_thread_args=
      new Mysql_connection_thread_args(vio, thread_registry, user_map,
                                       ++total_connection_count,
                                       instance_map)
      )
  {
    /*
      Initialize thread attributes to create detached thread; it seems
      easier to do it ad-hoc than have a global variable for attributes.
    */
    pthread_t mysql_thd_id;
    pthread_attr_t mysql_thd_attr;
    pthread_attr_init(&mysql_thd_attr);
    pthread_attr_setdetachstate(&mysql_thd_attr, PTHREAD_CREATE_DETACHED);
    if (set_stacksize_n_create_thread(&mysql_thd_id, &mysql_thd_attr,
                                      mysql_connection, mysql_thread_args))
    {
      delete mysql_thread_args;
      vio_delete(vio);
      log_error("handle_one_mysql_connection():"
                "set_stacksize_n_create_thread(mysql) failed");
    }
    pthread_attr_destroy(&mysql_thd_attr);
  }
  else
    vio_delete(vio);
}

pthread_handler_t listener(void *arg)
{
  Listener_thread_args *args= (Listener_thread_args *) arg;
  Listener_thread listener(*args);
  listener.run();
  /*
    args is a stack variable because listener thread lives as long as the
    manager process itself
  */
  return 0;
}

<commit_msg>  relying on loop counter variables being local to the loop body if    declared in the 'for' statement is not portable, some compilers   still don't implement this ANSI C++ specification (Bug #14995)<commit_after>/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)
#pragma implementation
#endif

#include "listener.h"
#include "priv.h"
#include <m_string.h>
#include <mysql.h>
#include <violite.h>
#ifndef __WIN__
#include <sys/un.h>
#endif
#include <sys/stat.h>

#include "thread_registry.h"
#include "options.h"
#include "instance_map.h"
#include "log.h"
#include "mysql_connection.h"
#include "portability.h"

/*
  Listener_thread - incapsulates listening functionality
*/

class Listener_thread: public Listener_thread_args
{
public:
  Listener_thread(const Listener_thread_args &args);
  ~Listener_thread();
  void run();
private:
  static const int LISTEN_BACK_LOG_SIZE= 5;     /* standard backlog size */
  ulong total_connection_count;
  Thread_info thread_info;

  int     sockets[2];
  int     num_sockets;
  fd_set  read_fds;
private:
  void handle_new_mysql_connection(Vio *vio);
  int   create_tcp_socket();
  int   create_unix_socket(struct sockaddr_un &unix_socket_address);
};

Listener_thread::Listener_thread(const Listener_thread_args &args) :
  Listener_thread_args(args.thread_registry, args.options, args.user_map,
                       args.instance_map)
  ,total_connection_count(0)
  ,thread_info(pthread_self())
  ,num_sockets(0)
{
}

Listener_thread::~Listener_thread()
{
}

/*
  Listener_thread::run() - listen all supported sockets and spawn a thread
  to handle incoming connection.
  Using 'die' in case of syscall failure is OK now - we don't hold any
  resources and 'die' kills the signal thread automatically. To be rewritten
  one day.
  See also comments in mysqlmanager.cc to picture general Instance Manager
  architecture.
*/

void Listener_thread::run()
{
  int i, n= 0;

#ifndef __WIN__
  /* we use this var to check whether we are running on LinuxThreads */
  pid_t thread_pid;

  thread_pid= getpid();

  struct sockaddr_un unix_socket_address;
  /* set global variable */
  linuxthreads= (thread_pid != manager_pid);
#endif

  thread_registry.register_thread(&thread_info);

  my_thread_init();

  FD_ZERO(&read_fds);

  /* I. prepare 'listen' sockets */
  if (create_tcp_socket())
    goto err;

#ifndef __WIN__
  if (create_unix_socket(unix_socket_address))
    goto err;
#endif

  /* II. Listen sockets and spawn childs */
  for (i= 0; i < num_sockets; i++)
    n= max(n, sockets[i]);
  n++;

  timeval tv;
  while (!thread_registry.is_shutdown())
  {
    fd_set read_fds_arg= read_fds;
    /*
      We should reintialize timer as on linux it is modified
      to reflect amount of time not slept.
    */
    tv.tv_sec= 0;
    tv.tv_usec= 100000;

    /*
      When using valgrind 2.0 this syscall doesn't get kicked off by a
      signal during shutdown. This results in failing assert
      (Thread_registry::~Thread_registry). Valgrind 2.2 works fine.
    */
    int rc= select(n, &read_fds_arg, 0, 0, &tv);

    if (rc == 0 || rc == -1)
    {
      if (rc == -1 && errno != EINTR)
        log_error("Listener_thread::run(): select() failed, %s",
                  strerror(errno));
      continue;
    }

    for (int socket_index= 0; socket_index < num_sockets; socket_index++)
    {
      /* Assuming that rc > 0 as we asked to wait forever */
      if (FD_ISSET(sockets[socket_index], &read_fds_arg))
      {
        int client_fd= accept(sockets[socket_index], 0, 0);
        /* accept may return -1 (failure or spurious wakeup) */
        if (client_fd >= 0)                    // connection established
        {
          Vio *vio= vio_new(client_fd, socket_index == 0 ?
                            VIO_TYPE_SOCKET : VIO_TYPE_TCPIP,
                            socket_index == 0 ? 1 : 0);
          if (vio != 0)
            handle_new_mysql_connection(vio);
          else
          {
            shutdown(client_fd, SHUT_RDWR);
            close(client_fd);
          }
        }
      }
    }
  }

  /* III. Release all resources and exit */

  log_info("Listener_thread::run(): shutdown requested, exiting...");

  for (i= 0; i < num_sockets; i++)
    close(sockets[i]);

#ifndef __WIN__
  unlink(unix_socket_address.sun_path);
#endif

  thread_registry.unregister_thread(&thread_info);
  my_thread_end();
  return;

err:
  // we have to close the ip sockets in case of error
  for (i= 0; i < num_sockets; i++)
    close(sockets[i]);

  thread_registry.unregister_thread(&thread_info);
  thread_registry.request_shutdown();
  my_thread_end();
  return;
}

void set_non_blocking(int socket)
{
#ifndef __WIN__
  int flags= fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags | O_NONBLOCK);
#else
  u_long arg= 1;
  ioctlsocket(socket, FIONBIO, &arg);
#endif
}

void set_no_inherit(int socket)
{
#ifndef __WIN__
  int flags= fcntl(socket, F_GETFD, 0);
  fcntl(socket, F_SETFD, flags | FD_CLOEXEC);
#endif
}

int Listener_thread::create_tcp_socket()
{
  /* value to be set by setsockopt */
  int arg= 1;

  int ip_socket= socket(AF_INET, SOCK_STREAM, 0);
  if (ip_socket == INVALID_SOCKET)
  {
    log_error("Listener_thead::run(): socket(AF_INET) failed, %s",
              strerror(errno));
    return -1;
  }

  struct sockaddr_in ip_socket_address;
  bzero(&ip_socket_address, sizeof(ip_socket_address));

  ulong im_bind_addr;
  if (options.bind_address != 0)
  {
    if ((im_bind_addr= (ulong) inet_addr(options.bind_address)) == INADDR_NONE)
      im_bind_addr= htonl(INADDR_ANY);
  }
  else
    im_bind_addr= htonl(INADDR_ANY);
  uint im_port= options.port_number;

  ip_socket_address.sin_family= AF_INET;
  ip_socket_address.sin_addr.s_addr= im_bind_addr;

  ip_socket_address.sin_port= (unsigned short)
    htons((unsigned short) im_port);

  setsockopt(ip_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &arg, sizeof(arg));
  if (bind(ip_socket, (struct sockaddr *) &ip_socket_address,
           sizeof(ip_socket_address)))
  {
    log_error("Listener_thread::run(): bind(ip socket) failed, '%s'",
              strerror(errno));
    close(ip_socket);
    return -1;
  }

  if (listen(ip_socket, LISTEN_BACK_LOG_SIZE))
  {
    log_error("Listener_thread::run(): listen(ip socket) failed, %s",
              strerror(errno));
    close(ip_socket);
    return -1;
  }

  /* set the socket nonblocking */
  set_non_blocking(ip_socket);

  /* make sure that instances won't be listening our sockets */
  set_no_inherit(ip_socket);

  FD_SET(ip_socket, &read_fds);
  sockets[num_sockets++]= ip_socket;
  log_info("accepting connections on ip socket");
  return 0;
}

#ifndef __WIN__
int Listener_thread::
create_unix_socket(struct sockaddr_un &unix_socket_address)
{
  int unix_socket= socket(AF_UNIX, SOCK_STREAM, 0);
  if (unix_socket == INVALID_SOCKET)
  {
    log_error("Listener_thead::run(): socket(AF_UNIX) failed, %s",
              strerror(errno));
    return -1;
  }

  bzero(&unix_socket_address, sizeof(unix_socket_address));

  unix_socket_address.sun_family= AF_UNIX;
  strmake(unix_socket_address.sun_path, options.socket_file_name,
          sizeof(unix_socket_address.sun_path));
  unlink(unix_socket_address.sun_path); // in case we have stale socket file

  /*
    POSIX specifies default permissions for a pathname created by bind
    to be 0777. We need everybody to have access to the socket.
  */
  mode_t old_mask= umask(0);
  if (bind(unix_socket, (struct sockaddr *) &unix_socket_address,
           sizeof(unix_socket_address)))
  {
    log_error("Listener_thread::run(): bind(unix socket) failed, "
              "socket file name is '%s', error '%s'",
              unix_socket_address.sun_path, strerror(errno));
    close(unix_socket);
    return -1;
  }

  umask(old_mask);

  if (listen(unix_socket, LISTEN_BACK_LOG_SIZE))
  {
    log_error("Listener_thread::run(): listen(unix socket) failed, %s",
              strerror(errno));
    close(unix_socket);
    return -1;
  }

  /* set the socket nonblocking */
  set_non_blocking(unix_socket);

  /* make sure that instances won't be listening our sockets */
  set_no_inherit(unix_socket);

  log_info("accepting connections on unix socket %s",
           unix_socket_address.sun_path);
  sockets[num_sockets++]= unix_socket;
  FD_SET(unix_socket, &read_fds);
  return 0;
}
#endif

/*
  Create new mysql connection. Created thread is responsible for deletion of
  the Mysql_connection_thread_args and Vio instances passed to it.
  SYNOPSYS
    handle_new_mysql_connection()
*/

void Listener_thread::handle_new_mysql_connection(Vio *vio)
{
  if (Mysql_connection_thread_args *mysql_thread_args=
      new Mysql_connection_thread_args(vio, thread_registry, user_map,
                                       ++total_connection_count,
                                       instance_map)
      )
  {
    /*
      Initialize thread attributes to create detached thread; it seems
      easier to do it ad-hoc than have a global variable for attributes.
    */
    pthread_t mysql_thd_id;
    pthread_attr_t mysql_thd_attr;
    pthread_attr_init(&mysql_thd_attr);
    pthread_attr_setdetachstate(&mysql_thd_attr, PTHREAD_CREATE_DETACHED);
    if (set_stacksize_n_create_thread(&mysql_thd_id, &mysql_thd_attr,
                                      mysql_connection, mysql_thread_args))
    {
      delete mysql_thread_args;
      vio_delete(vio);
      log_error("handle_one_mysql_connection():"
                "set_stacksize_n_create_thread(mysql) failed");
    }
    pthread_attr_destroy(&mysql_thd_attr);
  }
  else
    vio_delete(vio);
}

pthread_handler_t listener(void *arg)
{
  Listener_thread_args *args= (Listener_thread_args *) arg;
  Listener_thread listener(*args);
  listener.run();
  /*
    args is a stack variable because listener thread lives as long as the
    manager process itself
  */
  return 0;
}

<|endoftext|>


<commit_before>#include "text.hpp"
#include "../data/data_library.hpp"
#include "../utility/error.hpp"
#include "../json/json.hpp"

#include <QFileInfo>

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

namespace datavis {

string TextSourceParser::m_possible_delimiters = " \t;:|/\\";

bool TextSourceParser::isPossibleDelimiter(char c)
{
    return m_possible_delimiters.find(c) != string::npos;
}

TextSourceParser::Format TextSourceParser::inferFormat(const string &line)
{
    Format format;

    if (line.empty())
        throw Error("Empty line.");

    if (line[0] == '"' || line[0] == '\'')
    {
        format.quoted = true;
        format.quote_mark = line[0];
    }

    int index = 0;

    string::size_type pos = 0;
    while(pos < line.size())
    {
        ++index;

        // Skip a field (all characters until a possible delimiter)

        if (format.quoted)
        {
            if (line[pos] != format.quote_mark)
                throw Error("Field without opening quotation mark.");
            pos = line.find(format.quote_mark, pos+1);
            if (pos == string::npos)
                throw Error("Field without closing quotation mark.");
            ++pos;
            if (pos < line.size())
            {
                if (index == 1)
                {
                        if (!isPossibleDelimiter(line[pos]))
                            throw Error("Quoted field is not followed by a delimiter.");
                        format.delimiter = line[pos];
                 }
                else
                {
                    if (line[pos] != format.delimiter)
                        throw Error("Quoted field is not followed by the delimiter.");
                }
                ++pos;
            }
        }
        else
        {
            if (index == 1)
            {
                for(; pos < line.size(); ++pos)
                {
                    if (isPossibleDelimiter(line[pos]))
                    {
                        format.delimiter = line[pos];
                        ++pos;
                        break;
                    }
                }
            }
            else
            {
                pos = line.find(format.delimiter, pos);
                if (pos != string::npos)
                    ++pos;
            }
        }
    }

    format.count = index;

    return format;
}

TextSourceParser::TextSourceParser(const Format & format):
    m_format(format)
{
#if 0
    cerr << "Created parser with format: " << endl
         << "- Quoted: " << m_format.quoted << endl
         << "- Quote mark: '" << m_format.quote_mark << "'" << endl
         << "- Delimiter: '" << m_format.delimiter << "'" << endl
         << "- Count: " << m_format.count << endl;
#endif
}

vector<string> TextSourceParser::parse(const string & line)
{
    vector<string> fields;

    if (line.empty())
        throw Error("Empty line.");

    string::size_type pos = 0;
    int index = 0;

    if (m_format.quoted)
    {
        while (index < m_format.count && pos < line.size())
        {
            if (index > 0)
            {
                if (line[pos] != m_format.delimiter)
                    throw Error("Missing delimiter after field.");
                ++pos;
                if (pos >= line.size())
                    throw Error("Missing field after delimiter.");
            }

            if (line[pos] != m_format.quote_mark)
                throw Error("Field without opening quotation mark.");

            ++pos;

            string::size_type start = pos;

            pos = line.find(m_format.quote_mark, pos);
            if (pos == string::npos)
                throw Error("Field without closing quotation mark.");

            string::size_type size = pos - start;

            auto field = line.substr(start, size);
            fields.push_back(field);

            ++pos;
            ++index;
        }
    }
    else
    {
        while (index < m_format.count && pos < line.size())
        {
            string::size_type start = pos;
            pos = line.find(m_format.delimiter, pos);

            string field;
            if (pos == string::npos)
                field = line.substr(start);
            else
                field = line.substr(start, pos - start);

            fields.push_back(field);

            if (pos != string::npos)
                ++pos;

           ++index;
        }
    }

    if (index < m_format.count)
        throw Error("Too few fields.");
    if (pos < line.size())
        throw Error("Unexpected data at end of line.");

    return fields;
}

TextSource::TextSource(const string & file_path, DataLibrary * lib):
    DataSource(lib),
    m_file_path(file_path)
{
    m_name = QFileInfo(QString::fromStdString(file_path)).fileName().toStdString();
}

DataSetInfo TextSource::info(int) const
{
    return inferInfo();
}

DataSetInfo TextSource::inferInfo() const
{
    DataSetInfo info;
    info.id = "data";

    ifstream file(m_file_path);
    if (!file.is_open())
        throw Error("Failed to open file.");

    string first_line;
    std::getline(file, first_line);
    if (!file)
        throw Error("Failed to read a line.");

    auto format = TextSourceParser::inferFormat(first_line);
    if (format.count < 1)
        throw Error("No fields.");

    info.attributes.resize(format.count);

    TextSourceParser parser(format);
    auto fields = parser.parse(first_line);

    bool has_field_names = false;
    if (std::isalpha(fields.front()[0]))
    {
        has_field_names = true;
        for (int i = 0; i < format.count; ++i)
            info.attributes[i].name = fields[i];
    }

    {
        int record_count = has_field_names ? 0 : 1;
        string line;
        while(std::getline(file, line))
            ++record_count;

        info.dimensions.resize(1);
        info.dimensions.front().size = record_count;
    }

    return info;
}

DataSetPtr TextSource::dataset(int)
{
    if (!m_dataset)
        m_dataset = getData();

    return m_dataset;
}

DataSetPtr TextSource::getData()
{
    vector<string> lines;

    {
        ifstream file(m_file_path);
        if (!file.is_open())
            throw Error("Failed to open file.");

        string line;
        while(std::getline(file, line))
            lines.push_back(line);
    }

    if (lines.empty())
        throw Error("No lines.");

    auto format = TextSourceParser::inferFormat(lines.front());
    if (format.count < 1)
        throw Error("No fields.");

    TextSourceParser parser(format);

    auto fields = parser.parse(lines.front());
    bool has_field_names = std::isalpha(fields.front()[0]);

    size_t record_count = lines.size();
    if (has_field_names) record_count -= 1;

    vector<int> data_size { int(record_count) };
    auto dataset = make_shared<DataSet>("data", data_size, format.count);
    dataset->setSource(this);

    if (has_field_names)
    {
        for (int i = 0; i < format.count; ++i)
            dataset->attribute(i).name = fields[i];
    }

    DataSet::Dimension dim;
    dim.size = record_count;
    dataset->setDimension(0, dim);

    int line_index = has_field_names ? 1 : 0;
    for (size_t record_index = 0; record_index < record_count; ++record_index, ++line_index)
    {
        auto fields = parser.parse(lines[line_index]);
        for (int i = 0; i < format.count; ++i)
        {
            double value = stof(fields[i]);
            dataset->data(i).data()[record_index] = value;
        }
    }

    return dataset;
}

TextPackageSource::TextPackageSource(const string & path, DataLibrary * lib):
    DataSource(lib),
    m_dir_path(path),
    // FIXME:
    m_file_path(path + "/datapackage.json")
{
    m_name = QFileInfo(QString::fromStdString(path)).fileName().toStdString();

    parseDescriptor();
}

int TextPackageSource::index(const string & id) const
{
    for(int i = 0; i < m_members.size(); ++i)
    {
        if (m_members[i].info.id == id)
            return i;
    }

    return -1;
}

DataSetInfo TextPackageSource::info(int index) const
{
    return m_members[index].info;
}

DataSetPtr TextPackageSource::dataset(int index)
{
    if (!m_members[index].dataset)
        loadDataSet(index);

    return m_members[index].dataset;
}

using nlohmann::json;

static void parseResourceDescription(TextPackageSource::Member & member, const json & data)
{
    string path = data.at("path");

    member.path = path;

    member.info.id = path;

    if (data.find("format") != data.end())
    {
        auto format_data = data["format"];

        member.format.quoted = format_data.value("quoted", false);

        string quote_mark = format_data.value("quote_mark", "'");
        if (quote_mark.size() != 1)
            throw Error("Quote mark is not a single character.");
        member.format.quote_mark = quote_mark[0];

        string delimiter = format_data.at("delimiter");
        if (delimiter.size() != 1)
            throw Error("Delimiter is not a single character.");

        member.format.delimiter = delimiter[0];
    }

    if (data.find("fields") != data.end())
    {
        for (const auto & field : data["fields"])
        {
            DataSet::Attribute attribute;
            attribute.name = field.value("name", "");
            member.info.attributes.push_back(attribute);
        }
    }
    else
    {
        member.info.attributes.resize(1);
    }

    member.format.count = member.info.attributes.size();

    for (const auto & dimension_data : data.at("dimensions"))
    {
        DataSet::Dimension dimension;

        dimension.name = dimension_data.value("name", "");
        dimension.size = dimension_data.at("size");
        dimension.map.scale = dimension_data.value("scale", 1);
        dimension.map.offset = dimension_data.value("offset", 0);

        member.info.dimensions.push_back(dimension);
    }

    if (member.info.dimensions.empty())
    {
        throw Error("Descriptor does not declare any dimensions.");
    }
}

#if 0
static void inferResource(TextPackageSource::Member & member, const string & base_path)
{
    // FIXME:
    string path = base_path + '/' + member.path;

    ifstream file(path);
    if (!file.is_open())
        throw Error("Failed to open descriptor file.");

    string first_line;
    std::getline(file, first_line);
    if (!file)
        throw Error("Failed to read a line.");

    if (member.format.delimiter == 0)
    {
        auto format = TextSourceParser::inferFormat(first_line);
        member.format = format;
        if (member.info.attributes.empty())
            member.info.attributes.resize(format.count);
        else if (member.info.attributes.size() != format.count)
            throw Error("Number of attributes does not match number of fields.");
    }
    else
    {
        if (member.info.attributes.empty())
        {
            member.info.attributes.resize(1);
            member.format.count = 1;
        }
    }

    if (member.info.dimensions.empty())
    {
        int line_count = 1;

        string line;
        while(std::getline(file, line))
            ++line_count;

        DataSet::Dimension dim;
        dim.size = line_count;
        member.info.dimensions.push_back(dim);
    }
}
#endif

void TextPackageSource::parseDescriptor()
{
    using nlohmann::json;

    ifstream file(m_file_path);
    if (!file.is_open())
        throw Error("Failed to open descriptor file.");

    json data;

    try
    {
        file >> data;

        auto resources = data.at("resources");

        m_members.reserve(resources.size());

        for(auto resource : resources)
        {
            m_members.emplace_back();
            parseResourceDescription(m_members.back(), resource);
        }
    }
    catch (json::exception & e)
    {
        throw Error(string("Failed to parse descriptor: ") + e.what());
    }
}

void TextPackageSource::loadDataSet(int index)
{
    Member & member = m_members[index];

    // FIXME:
    string path = m_dir_path + '/' + member.path;

    vector<string> lines;

    // Read lines from file
    {
        ifstream file(path);
        if (!file.is_open())
            throw Error("Failed to open resource file: " + path);

        string line;
        while(std::getline(file, line))
            lines.push_back(line);
    }

    // Confirm total size of dataset
    {
        size_t total_size = 1;
        for (const auto & dim : member.info.dimensions)
        {
            total_size *= dim.size;
        }

        if (lines.size() != total_size)
        {
            throw Error("Number of records does not match data space size.");
        }
    }

    // Create DataSet

    vector<int> data_size;
    for (int i = 0; i < member.info.dimensions.size(); ++i)
    {
        data_size.push_back(member.info.dimensions[i].size);
    }

    auto dataset = make_shared<DataSet>(member.path, data_size, member.info.attributes.size());
    dataset->setSource(this);

    for (int i = 0; i < member.info.attributes.size(); ++i)
    {
        dataset->attribute(i) = member.info.attributes[i];
    }
    for (int i = 0; i < member.info.dimensions.size(); ++i)
    {
        const auto & dim = member.info.dimensions[i];

        dataset->setDimension(i, dim);

        DimensionPtr gdim = library()->dimension(dim.name);
        if (gdim)
        {
            cout << "TextPackageSource: Setting global dimension: " << dim.name << endl;
            dataset->setGlobalDimension(i, gdim);
        }

    }

    // Fill DataSet with data

    TextSourceParser parser(member.format);

    for (size_t line_index = 0; line_index < lines.size(); ++line_index)
    {
        auto fields = parser.parse(lines[line_index]);
        for (int i = 0; i < fields.size(); ++i)
        {
            double value = stof(fields[i]);
            dataset->data(i).data()[line_index] = value;
        }
    }

    member.dataset = dataset;
}

}

<commit_msg>IO / Text Package: Fix data source name<commit_after>#include "text.hpp"
#include "../data/data_library.hpp"
#include "../utility/error.hpp"
#include "../json/json.hpp"

#include <QFileInfo>
#include <QDir>

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

namespace datavis {

string TextSourceParser::m_possible_delimiters = " \t;:|/\\";

bool TextSourceParser::isPossibleDelimiter(char c)
{
    return m_possible_delimiters.find(c) != string::npos;
}

TextSourceParser::Format TextSourceParser::inferFormat(const string &line)
{
    Format format;

    if (line.empty())
        throw Error("Empty line.");

    if (line[0] == '"' || line[0] == '\'')
    {
        format.quoted = true;
        format.quote_mark = line[0];
    }

    int index = 0;

    string::size_type pos = 0;
    while(pos < line.size())
    {
        ++index;

        // Skip a field (all characters until a possible delimiter)

        if (format.quoted)
        {
            if (line[pos] != format.quote_mark)
                throw Error("Field without opening quotation mark.");
            pos = line.find(format.quote_mark, pos+1);
            if (pos == string::npos)
                throw Error("Field without closing quotation mark.");
            ++pos;
            if (pos < line.size())
            {
                if (index == 1)
                {
                        if (!isPossibleDelimiter(line[pos]))
                            throw Error("Quoted field is not followed by a delimiter.");
                        format.delimiter = line[pos];
                 }
                else
                {
                    if (line[pos] != format.delimiter)
                        throw Error("Quoted field is not followed by the delimiter.");
                }
                ++pos;
            }
        }
        else
        {
            if (index == 1)
            {
                for(; pos < line.size(); ++pos)
                {
                    if (isPossibleDelimiter(line[pos]))
                    {
                        format.delimiter = line[pos];
                        ++pos;
                        break;
                    }
                }
            }
            else
            {
                pos = line.find(format.delimiter, pos);
                if (pos != string::npos)
                    ++pos;
            }
        }
    }

    format.count = index;

    return format;
}

TextSourceParser::TextSourceParser(const Format & format):
    m_format(format)
{
#if 0
    cerr << "Created parser with format: " << endl
         << "- Quoted: " << m_format.quoted << endl
         << "- Quote mark: '" << m_format.quote_mark << "'" << endl
         << "- Delimiter: '" << m_format.delimiter << "'" << endl
         << "- Count: " << m_format.count << endl;
#endif
}

vector<string> TextSourceParser::parse(const string & line)
{
    vector<string> fields;

    if (line.empty())
        throw Error("Empty line.");

    string::size_type pos = 0;
    int index = 0;

    if (m_format.quoted)
    {
        while (index < m_format.count && pos < line.size())
        {
            if (index > 0)
            {
                if (line[pos] != m_format.delimiter)
                    throw Error("Missing delimiter after field.");
                ++pos;
                if (pos >= line.size())
                    throw Error("Missing field after delimiter.");
            }

            if (line[pos] != m_format.quote_mark)
                throw Error("Field without opening quotation mark.");

            ++pos;

            string::size_type start = pos;

            pos = line.find(m_format.quote_mark, pos);
            if (pos == string::npos)
                throw Error("Field without closing quotation mark.");

            string::size_type size = pos - start;

            auto field = line.substr(start, size);
            fields.push_back(field);

            ++pos;
            ++index;
        }
    }
    else
    {
        while (index < m_format.count && pos < line.size())
        {
            string::size_type start = pos;
            pos = line.find(m_format.delimiter, pos);

            string field;
            if (pos == string::npos)
                field = line.substr(start);
            else
                field = line.substr(start, pos - start);

            fields.push_back(field);

            if (pos != string::npos)
                ++pos;

           ++index;
        }
    }

    if (index < m_format.count)
        throw Error("Too few fields.");
    if (pos < line.size())
        throw Error("Unexpected data at end of line.");

    return fields;
}

TextSource::TextSource(const string & file_path, DataLibrary * lib):
    DataSource(lib),
    m_file_path(file_path)
{
    m_name = QFileInfo(QString::fromStdString(file_path)).fileName().toStdString();
}

DataSetInfo TextSource::info(int) const
{
    return inferInfo();
}

DataSetInfo TextSource::inferInfo() const
{
    DataSetInfo info;
    info.id = "data";

    ifstream file(m_file_path);
    if (!file.is_open())
        throw Error("Failed to open file.");

    string first_line;
    std::getline(file, first_line);
    if (!file)
        throw Error("Failed to read a line.");

    auto format = TextSourceParser::inferFormat(first_line);
    if (format.count < 1)
        throw Error("No fields.");

    info.attributes.resize(format.count);

    TextSourceParser parser(format);
    auto fields = parser.parse(first_line);

    bool has_field_names = false;
    if (std::isalpha(fields.front()[0]))
    {
        has_field_names = true;
        for (int i = 0; i < format.count; ++i)
            info.attributes[i].name = fields[i];
    }

    {
        int record_count = has_field_names ? 0 : 1;
        string line;
        while(std::getline(file, line))
            ++record_count;

        info.dimensions.resize(1);
        info.dimensions.front().size = record_count;
    }

    return info;
}

DataSetPtr TextSource::dataset(int)
{
    if (!m_dataset)
        m_dataset = getData();

    return m_dataset;
}

DataSetPtr TextSource::getData()
{
    vector<string> lines;

    {
        ifstream file(m_file_path);
        if (!file.is_open())
            throw Error("Failed to open file.");

        string line;
        while(std::getline(file, line))
            lines.push_back(line);
    }

    if (lines.empty())
        throw Error("No lines.");

    auto format = TextSourceParser::inferFormat(lines.front());
    if (format.count < 1)
        throw Error("No fields.");

    TextSourceParser parser(format);

    auto fields = parser.parse(lines.front());
    bool has_field_names = std::isalpha(fields.front()[0]);

    size_t record_count = lines.size();
    if (has_field_names) record_count -= 1;

    vector<int> data_size { int(record_count) };
    auto dataset = make_shared<DataSet>("data", data_size, format.count);
    dataset->setSource(this);

    if (has_field_names)
    {
        for (int i = 0; i < format.count; ++i)
            dataset->attribute(i).name = fields[i];
    }

    DataSet::Dimension dim;
    dim.size = record_count;
    dataset->setDimension(0, dim);

    int line_index = has_field_names ? 1 : 0;
    for (size_t record_index = 0; record_index < record_count; ++record_index, ++line_index)
    {
        auto fields = parser.parse(lines[line_index]);
        for (int i = 0; i < format.count; ++i)
        {
            double value = stof(fields[i]);
            dataset->data(i).data()[record_index] = value;
        }
    }

    return dataset;
}

TextPackageSource::TextPackageSource(const string & path, DataLibrary * lib):
    DataSource(lib),
    m_dir_path(path),
    // FIXME:
    m_file_path(path + "/datapackage.json")
{
    m_name = QDir(QString::fromStdString(path)).dirName().toStdString();

    parseDescriptor();
}

int TextPackageSource::index(const string & id) const
{
    for(int i = 0; i < m_members.size(); ++i)
    {
        if (m_members[i].info.id == id)
            return i;
    }

    return -1;
}

DataSetInfo TextPackageSource::info(int index) const
{
    return m_members[index].info;
}

DataSetPtr TextPackageSource::dataset(int index)
{
    if (!m_members[index].dataset)
        loadDataSet(index);

    return m_members[index].dataset;
}

using nlohmann::json;

static void parseResourceDescription(TextPackageSource::Member & member, const json & data)
{
    string path = data.at("path");

    member.path = path;

    member.info.id = path;

    if (data.find("format") != data.end())
    {
        auto format_data = data["format"];

        member.format.quoted = format_data.value("quoted", false);

        string quote_mark = format_data.value("quote_mark", "'");
        if (quote_mark.size() != 1)
            throw Error("Quote mark is not a single character.");
        member.format.quote_mark = quote_mark[0];

        string delimiter = format_data.at("delimiter");
        if (delimiter.size() != 1)
            throw Error("Delimiter is not a single character.");

        member.format.delimiter = delimiter[0];
    }

    if (data.find("fields") != data.end())
    {
        for (const auto & field : data["fields"])
        {
            DataSet::Attribute attribute;
            attribute.name = field.value("name", "");
            member.info.attributes.push_back(attribute);
        }
    }
    else
    {
        member.info.attributes.resize(1);
    }

    member.format.count = member.info.attributes.size();

    for (const auto & dimension_data : data.at("dimensions"))
    {
        DataSet::Dimension dimension;

        dimension.name = dimension_data.value("name", "");
        dimension.size = dimension_data.at("size");
        dimension.map.scale = dimension_data.value("scale", 1);
        dimension.map.offset = dimension_data.value("offset", 0);

        member.info.dimensions.push_back(dimension);
    }

    if (member.info.dimensions.empty())
    {
        throw Error("Descriptor does not declare any dimensions.");
    }
}

#if 0
static void inferResource(TextPackageSource::Member & member, const string & base_path)
{
    // FIXME:
    string path = base_path + '/' + member.path;

    ifstream file(path);
    if (!file.is_open())
        throw Error("Failed to open descriptor file.");

    string first_line;
    std::getline(file, first_line);
    if (!file)
        throw Error("Failed to read a line.");

    if (member.format.delimiter == 0)
    {
        auto format = TextSourceParser::inferFormat(first_line);
        member.format = format;
        if (member.info.attributes.empty())
            member.info.attributes.resize(format.count);
        else if (member.info.attributes.size() != format.count)
            throw Error("Number of attributes does not match number of fields.");
    }
    else
    {
        if (member.info.attributes.empty())
        {
            member.info.attributes.resize(1);
            member.format.count = 1;
        }
    }

    if (member.info.dimensions.empty())
    {
        int line_count = 1;

        string line;
        while(std::getline(file, line))
            ++line_count;

        DataSet::Dimension dim;
        dim.size = line_count;
        member.info.dimensions.push_back(dim);
    }
}
#endif

void TextPackageSource::parseDescriptor()
{
    using nlohmann::json;

    ifstream file(m_file_path);
    if (!file.is_open())
        throw Error("Failed to open descriptor file.");

    json data;

    try
    {
        file >> data;

        auto resources = data.at("resources");

        m_members.reserve(resources.size());

        for(auto resource : resources)
        {
            m_members.emplace_back();
            parseResourceDescription(m_members.back(), resource);
        }
    }
    catch (json::exception & e)
    {
        throw Error(string("Failed to parse descriptor: ") + e.what());
    }
}

void TextPackageSource::loadDataSet(int index)
{
    Member & member = m_members[index];

    // FIXME:
    string path = m_dir_path + '/' + member.path;

    vector<string> lines;

    // Read lines from file
    {
        ifstream file(path);
        if (!file.is_open())
            throw Error("Failed to open resource file: " + path);

        string line;
        while(std::getline(file, line))
            lines.push_back(line);
    }

    // Confirm total size of dataset
    {
        size_t total_size = 1;
        for (const auto & dim : member.info.dimensions)
        {
            total_size *= dim.size;
        }

        if (lines.size() != total_size)
        {
            throw Error("Number of records does not match data space size.");
        }
    }

    // Create DataSet

    vector<int> data_size;
    for (int i = 0; i < member.info.dimensions.size(); ++i)
    {
        data_size.push_back(member.info.dimensions[i].size);
    }

    auto dataset = make_shared<DataSet>(member.path, data_size, member.info.attributes.size());
    dataset->setSource(this);

    for (int i = 0; i < member.info.attributes.size(); ++i)
    {
        dataset->attribute(i) = member.info.attributes[i];
    }
    for (int i = 0; i < member.info.dimensions.size(); ++i)
    {
        const auto & dim = member.info.dimensions[i];

        dataset->setDimension(i, dim);

        DimensionPtr gdim = library()->dimension(dim.name);
        if (gdim)
        {
            cout << "TextPackageSource: Setting global dimension: " << dim.name << endl;
            dataset->setGlobalDimension(i, gdim);
        }

    }

    // Fill DataSet with data

    TextSourceParser parser(member.format);

    for (size_t line_index = 0; line_index < lines.size(); ++line_index)
    {
        auto fields = parser.parse(lines[line_index]);
        for (int i = 0; i < fields.size(); ++i)
        {
            double value = stof(fields[i]);
            dataset->data(i).data()[line_index] = value;
        }
    }

    member.dataset = dataset;
}

}

<|endoftext|>


<commit_before>#include "WPILib.h"
#include <string>

using std::string;

//Written by Javed Nissar with some help from Fayaad/Jay/Harry
/**
 * This is a demo program showing the use of the RobotDrive class.
 * The SampleRobot class is the base of a robot application that will automatically call your
 * Autonomous and OperatorControl methods at the right time as controlled by the switches on
 * the driver station or the field controls.
 *
 * WARNING: While it may look like a good choice to use for your code if you're inexperienced,
 * don't. Unless you know what you are doing, complex code will be much more difficult under
 * this system. Use IterativeRobot or Command-Based instead if you're new.
 */
/*
If you are at any point disturbed by the code below, please stare at
the safety pig.
                         _
 _._ _..._ .-',     _.._(`))
'-. `     '  /-._.-'    ',/
   )         \            '.
  / _    _    |             \
 |  a    a    /              |
 \   .-.                     ;
  '-('' ).-'       ,'       ;
     '-;           |      .'
        \           \    /
        | 7  .__  _.-\   \
        | |  |  ``/  /`  /
       /,_|  |   /,_/   /
          /,_/      '`-'
*/
class Robot: public SampleRobot
{
	RobotDrive myRobot; // robot drive system
	Joystick controller;
	Talon forkLift;
	Solenoid leftHook;
	Solenoid rightHook;
	Timer pneumaticTimer;
	unsigned int secondsForPulley;
	double secondsForPneumatic;

public:
	Robot() :
			myRobot(0, 1),	// these must be initialized in the same order
			controller(0),
			forkLift(2),
			leftHook(0),
			rightHook(1)// as they are declared above.
	{
		myRobot.SetExpiration(0.1);
		secondsForPulley=5;
		secondsForPneumatic=0.5;
	}

	/**
	 * Drive left & right motors for 2 seconds then stop
	 */
	void Autonomous()
	{
		myRobot.SetSafetyEnabled(false);
		myRobot.Drive(-0.5, 0.0); 	// drive forwards half speed
		Wait(2.0); 				//    for 2 seconds
		myRobot.Drive(0.0, 0.0); 	// stop robot
	}

	/**
	 * Runs the motors with arcade steering.
	 */
	void forwardsPulley(){
		forkLift.Set(0.75);
	}
	void backwardsPulley(){
		forkLift.Set(-0.5);
	}
	void stopPulley(){
		forkLift.Set(0);
	}
	string CanHooksBeMoved(){
		if(pneumaticTimer.Get()>0){
			return "No";
		}else{
			return "Yes";
		}
	}
	void OperatorControl()
	{
		myRobot.SetSafetyEnabled(true);
		while (IsOperatorControl() && IsEnabled())
		{
			myRobot.ArcadeDrive(controller,false); // drive with arcade style (use left stick of controller) without squared inputs
			/*when you move the right stick of controller upwards, the pulley will move upwards
			 *the motor of the pulley will be at 75% forwards
			 *the need for it to be above 0.1 is to accommodate the drift of the right stick of the controller (joystick value is never 0)
			 */
			if(controller.GetRawAxis(3)>0.1){
				forwardsPulley();
			}
			/*
			 * when you move right stick of controller downwards, the pulley will move downwards
			 * the motor of the pulley will be at 50% reverse
			 */
			else if(controller.GetRawAxis(3)<-0.1){
				backwardsPulley();
			}
			//when right stick of controller is left alone, motor will not exert force on pulley; thus, causing the pulley to drift downwards.
			else{
				stopPulley();
			}
			//provide status on whether or not hooks can be moved
			SmartDashboard::PutString("Can I press right trigger to move hooks",CanHooksBeMoved());
			//if button 8 on the controller is pressed (the right trigger on Maninder's red controller) and the timer on the pneumatic is not active
			//this is meant to prevent the hooks from bouncing by ensuring that the button input is not taken at all times
			if(controller.GetRawButton(8)&&!(pneumaticTimer.Get()>0)){
				if(leftHook.Get()){
					leftHook.Set(false);
					rightHook.Set(false);	//moves left hook and right hook back to default position
				}else{
					leftHook.Set(true);		//moves left hook and right hook forwards
					rightHook.Set(true);
				}
				pneumaticTimer.Start();
			}else if(pneumaticTimer.Get()>secondsForPneumatic){
				//stop and reset timer to enable buttons to operate
				pneumaticTimer.Stop();
				pneumaticTimer.Reset();
			}
			Wait(0.005);			// wait for a motor update time
		}
	}

	/**
	 * Runs during test mode
	 */
	void Test()
	{
	}
};

START_ROBOT_CLASS(Robot);
<commit_msg>added Arrowbots logo<commit_after>#include "WPILib.h"
#include <string>

using std::string;

//Written by Javed Nissar with some help from Fayaad/Jay/Harry
/**
 * This is a demo program showing the use of the RobotDrive class.
 * The SampleRobot class is the base of a robot application that will automatically call your
 * Autonomous and OperatorControl methods at the right time as controlled by the switches on
 * the driver station or the field controls.
 *
 * WARNING: While it may look like a good choice to use for your code if you're inexperienced,
 * don't. Unless you know what you are doing, complex code will be much more difficult under
 * this system. Use IterativeRobot or Command-Based instead if you're new.
 */
/*
                                   .'########:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ,## `#######
                                ;############+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::, ##` #######.
                             ,################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  ##  #######
                           :###################:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ;#' ,######+
                         .#####################:::::::::::::::::::::::::::::::::::::'+;::::::::::::::::::::::::::::::::::::::'++;::::::::::::::::::::::::::::::. ##  #######`
                        #######################+::::::::::::::::::::::::::::::::::;#####:::::######+::::::#######::::::::::#######+:::::::#:::::::::::::#;:::::: `##  #######
                      `#########################::::::::::::::::::::::::::::::::::#':::#+:::::'#::;##::::::;#::;##::::::::##:::::;##::::::#;::::::::::::#:::::::: +#: '######'
                     '##########################:::::::::::::::::::::::::::::::::+#:::::#:::::'#::::##:::::;#::::##::::::#+::::::::##:::::+#:::::::::::+#::::::::` ##  #######
                    ############################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#:::::;#:::::#;::::##::::::::::#+:::::#:::::::::::#'::::::::: .## `#######
                   #############################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#+::::;#:::::+#:::;#:::::::::::;#:::::#:::::+:::::#::::::::::: ##. +######,
                  '. ###########################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::+#::::;#:::::'#:::#+::::::::::::#;::::#+::::#::::'#:::::::::::  ##  #######
              ;##`  +###########################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::+#::::;#:::::'#:::#:::::::::::::+#::::;#::::#;:::#+:::::::::::: ;#+ ,######+
          `#####,   ############################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#'::::;#:::::#+:::#:::::::::::::;#:::::#:::'##:::#:::::::::::::. ##` #######`
           ####+   ;###########################':::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#:::::;#:::::#::::#:::::::::::::;#:::::#+::#+#::;#:::::::::::::: `##  #######
           `###      ,#########################::::::::::::::::::::::::::::::::::#':::::#:::::'#::::#+:::::;#::::##::::#:::::::::::::'#:::::'#::#:#::#+::::::::::::::: +#: '######'
            ##`        .#######################:::::::::::::::::::::::::::::::::;#';;;;;#:::::'#;;+##::::::;#;;+##:::::#;::::::::::::#+::::::#:;#:#+:#::::::::::::::::` ##  #######
             #           ,#####################:::::::::::::::::::::::::::::::::#########:::::'####;:::::::;####'::::::+#::::::::::::#:::::::#'#+:;#:#::::::::::::::::: .## `#######
             `   #+        '##################;::::::::::::::::::::::::::``::::::#':::::#:::::'#:##::::::::;#:+#::::::::#:::::::::::+#:::::::+##:::#+#:::::::::::::::::: ##. +######,
            .#  '####:       #################:::::::::::::::::::::::::::.  :::::#':::::#:::::'#::##:::::::;#::##:::::::+#:::::::::;#:::::::::##:::##;::::::::::::::::::` ##  #######
            ##` #######'      '###############:::::::::::::::::::::::::::.   ,:::#':::::#:::::'#:::#'::::::;#:::#+:::::::##:::::::'#+:::::::::##:::'#:::::::::::::::::::: :#+ ,#######
           `###+#########;     ,#############+:::::::::::::::::::::::.        `::#':::::#:::::'#:::;#::::::;#::::#;:::::::###;::'##'::::::::::+;::::#::::::::::::::::::::, ##` #######.
           ################,    ,############:::::::::::::::::::::,            ::#':::::#:::::'#::::##:::::;#::::'#::::::::;######::::::::::::::::::'::::::::::::::::::::: `##  #######
           #########.########    :###########:::::::::::::::::::`             ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '#; ;######+
          ,########,  :#######.   '##########:::::::::::::::::.       `.::.  ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::. ##  #######
          #########     +######'   #########'::::::::::::::::     .:::::::, ::::::''''''':::::::::::::::::;######'::::::::::::'''''''''':::::::::###+::::::::::::::::::::::: `## `#######
          #########      `#######   ########:::::::::::::::,   `:::::::::::,::::::+########:::::::::::::;##########'::::::::::##########:::::::+######;:::::::::::::::::::::: ##. +######:
          ########'        '######  .#######::::::::::::::`  `::::::::::::::::::::+#;;;;'###:::::::::::+###;:::::####:::::::::;;;;##;;;;::::::'##;::'##::::::::::::::::::::::` ##  #######
         ,########;         `######  #######:::::::::::::   ::::::  ,:::::::::::::+#::::::##::::::::::###::::::::::###::::::::::::##::::::::::##::::::#::::::::::::::::::::::: :#+ .#######
         +########+           ######  #####+::::::::::::  ,::::.     :::::::::::::+#::::::;#;::::::::+##::::::::::::+##:::::::::::##:::::::::;#'::::::::::::::::::::::::::::::, ##` #######.
         ##########            ;##### '####;:::::::::::  ::::`       ,::::::::::::+#:::::::#'::::::::##::::::::::::::##'::::::::::##:::::::::+#::::::::::::::::::::::::::::::::  ##  #######
         ##########             .##### ####::::::::::: .:::          .::::::::::::+#::::::'#;:::::::##::::::::::::::::##::::::::::##:::::::::##::::::::::::::::::::::::::::::::: '#; ;######+
         ##########.             `#####+###:::::::::: :::`           ,::::::::::::+#::::::##::::::::##::::::::::::::::'#':::::::::##:::::::::+#:::::::::::::::::::::::::::::::::. ##  #######
         ###########               ########:::::::::`::`             :::::::::::;##########;:::::::+#::::::::::::::::::##:::::::::##::::::::::##::::::::::::::::::::::::::::::::: `## `#######
         ###########                #######::::::::.::              .:::::::::::###########::::::::##::::::::::::::::::##:::::::::##::::::::::##'::::::::::::::::::::::::::::::::: ##, '######;
         ############              ;#######:::::::::`               ::::::::::::::+#:::::###;::::::##::::::::::::::::::+#:::::::::##:::::::::::###+::::::::::::::::::::::::::::::. ##  #######
         ############.          ,##########::::::::::`             :::::::::::::::+#::::::;##::::::##::::::::::::::::::;#;::::::::##::::::::::::#####+::::::::::::::::::::::::::: ;#' :######+
         #############`     `'#############::::::::::::::.        ::::::::::::::::+#:::::::'##:::::#+::::::::::::::::::;#;::::::::##::::::::::::::'####:::::::::::::::::::::::::  ##  #######
         ##################################:::::::::::::::::::::::::::::::::::::::+#::::::::##:::::##::::::::::::::::::;#;::::::::##:::::::::::::::::###:::::::::::::::::::::::, ##` #######,
         ###################################::::::::::::::::::::::::::::::::::::::+#::::::::'#:::::##::::::::::::::::::+#:::::::::##::::::::::::::::::##;:::::::::::::::::::::: ,## .#######
         '########,+########################::::::::::::::::::::::::::::::::::::::+#:::::::::#'::::##::::::::::::::::::##:::::::::##:::::::::::::::::::##:::::::::::::::::::::` ##  #######
         .######' ##########################':::::::::::::::::::::::::::::::::::::+#:::::::::#'::::+#::::::::::::::::::##:::::::::##:::::::::::::::::::##::::::::::::::::::::: ##, +######;
          ###### ####' ######################:::::::::::::::::::::::::::::::::::::+#::::::::;#;:::::##::::::::::::::::'#':::::::::##:::::::::::::::::::##:::::::::::::::::::: `##  #######
          ##### ####.  `######################::::::::::::::::::::::::::::::::::::+#::::::::+#::::::##::::::::::::::::##::::::::::##:::::::::::::::::::##:::::::::::::::::::. ##  #######
          #########.    ######################+:::::::::::::::::::::::::::::::::::+#::::::::##:::::::##::::::::::::::##'::::::::::##::::::::;#;::::::::##::::::::::::::::::: '#; :######+
          .########      ######################+::::::::::::::::::::::::::::::::::+#:::::::##':::::::+##::::::::::::+##:::::::::::##:::::::::##:::::::;#+::::::::::::::::::  ##  #######
           #########     `######################+:::::::::::::::::::::::::::::::::+#::::::+##:::::::::###::::::::::###::::::::::::##:::::::::##'::::::##::::::::::::::::::, ##` #######.
           +###### #      .#######################::::::::::::::::::::::::::::::::+#;;;;+###:::::::::::+###::::::+###:::::::::::::##::::::::::###:::;##':::::::::::::::::: :## .#######
            ######  ;       ########################::::::::::::::::::::::::::::::+#######+:::::::::::::;##########'::::::::::::::##:::::::::::#######'::::::::::::::::::` ##  #######
            ######  ``       +########################'::::::::::::::::;##::::::::'++++';:::::::::::::::::;######;::::::::::::::::++::::::::::::'###+:::::::::::::::::::: ##. +######:
            `#####.  :.       `############################+';;;;''+#####::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: .##  #######
             ######    #         '#######################################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::. ##  #######
              #####     ``          ,###################################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '#; ;######+
              :#####                     `:'###########################+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  ##  #######
               #####`                                    +#############::##########################################################################################::, ##` #######.
                #####                                    #############::;###################;;;##;;;###':#######'######;;;+#+;;;###':;####;;;#####################+:: :#+ ,#######
                `#####                                  `############;::#####################;###:####+##:##:##+:########;#####+##:###;##+########################::` ##  #######
                 ,#####                                ;############'::######################;###:####'##;###'#;:########'####'##'#####:#+#######################;:: ##. +######:
                  :#####                           ,;',,###########+::#######################;##+:+###'##;###+:#:#######;:####:##:#####+#+;:+####################:: .##  #######
                   :#####,                            `###########'::########################;###:####'##;######:#########:###'##:#####+####+###################::. ##  #######
                    ,######.                         .###########'::#########################;###:####::::######:#########'##+###:#####:#####'#################':: +#; ;######'
                     `#######'`                    ,############;::##########################;###:####'##;######:######+##:##:####'####'#####+#################:: `##  #######
                       ##########+;.`     ``.:;+###############:::###########################:###:::##'##;######:######+;:###'#####:';'###:;;#################::, ##` #######.
                        :####################################':::############################################################################################+:: :#+ ,#######
                          +#################################::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;::  ##  #######
                            +#############################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ##. #######,
                              '########################+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: .## `#######
                                `'##################+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::` ##  #######
                                    `:+#########':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +#: '######'
*/
class Robot: public SampleRobot
{
	RobotDrive myRobot; // robot drive system
	Joystick controller;
	Talon forkLift;
	Solenoid leftHook;
	Solenoid rightHook;
	Timer pneumaticTimer;
	unsigned int secondsForPulley;
	double secondsForPneumatic;

public:
	Robot() :
			myRobot(0, 1),	// these must be initialized in the same order
			controller(0),
			forkLift(2),
			leftHook(0),
			rightHook(1)// as they are declared above.
	{
		myRobot.SetExpiration(0.1);
		secondsForPulley=5;
		secondsForPneumatic=0.5;
	}

	/**
	 * Drive left & right motors for 2 seconds then stop
	 */
	void Autonomous()
	{
		myRobot.SetSafetyEnabled(false);
		myRobot.Drive(-0.5, 0.0); 	// drive forwards half speed
		Wait(2.0); 				//    for 2 seconds
		myRobot.Drive(0.0, 0.0); 	// stop robot
	}

	/**
	 * Runs the motors with arcade steering.
	 */
	void forwardsPulley(){
		forkLift.Set(0.75);
	}
	void backwardsPulley(){
		forkLift.Set(-0.5);
	}
	void stopPulley(){
		forkLift.Set(0);
	}
	string CanHooksBeMoved(){
		if(pneumaticTimer.Get()>0){
			return "No";
		}else{
			return "Yes";
		}
	}
	void OperatorControl()
	{
		myRobot.SetSafetyEnabled(true);
		while (IsOperatorControl() && IsEnabled())
		{
			myRobot.ArcadeDrive(controller,false); // drive with arcade style (use left stick of controller) without squared inputs
			/*when you move the right stick of controller upwards, the pulley will move upwards
			 *the motor of the pulley will be at 75% forwards
			 *the need for it to be above 0.1 is to accommodate the drift of the right stick of the controller (joystick value is never 0)
			 */
			if(controller.GetRawAxis(3)>0.1){
				forwardsPulley();
			}
			/*
			 * when you move right stick of controller downwards, the pulley will move downwards
			 * the motor of the pulley will be at 50% reverse
			 */
			else if(controller.GetRawAxis(3)<-0.1){
				backwardsPulley();
			}
			//when right stick of controller is left alone, motor will not exert force on pulley; thus, causing the pulley to drift downwards.
			else{
				stopPulley();
			}
			//provide status on whether or not hooks can be moved
			SmartDashboard::PutString("Can I press right trigger to move hooks",CanHooksBeMoved());
			//if button 8 on the controller is pressed (the right trigger on Maninder's red controller) and the timer on the pneumatic is not active
			//this is meant to prevent the hooks from bouncing by ensuring that the button input is not taken at all times
			if(controller.GetRawButton(8)&&!(pneumaticTimer.Get()>0)){
				if(leftHook.Get()){
					leftHook.Set(false);
					rightHook.Set(false);	//moves left hook and right hook back to default position
				}else{
					leftHook.Set(true);		//moves left hook and right hook forwards
					rightHook.Set(true);
				}
				pneumaticTimer.Start();
			}else if(pneumaticTimer.Get()>secondsForPneumatic){
				//stop and reset timer to enable buttons to operate
				pneumaticTimer.Stop();
				pneumaticTimer.Reset();
			}
			Wait(0.005);			// wait for motor update time
		}
	}

	/**
	 * Runs during test mode
	 */
	void Test()
	{
	}
};

START_ROBOT_CLASS(Robot);
<|endoftext|>