Esempio n. 1
0
static void
do_whichof(char *args[], int nargs, enum whichof_t flag,
           char *buff, char **bp, dbref executor,
           dbref caller, dbref enactor, NEW_PE_INFO *pe_info, int eflags,
           int isbool)
{
  int j;
  char tbuf[BUFFER_LEN], *tp;
  char sep[BUFFER_LEN];
  char const *ap;
  int first = 1;
  tbuf[0] = '\0';

  if (eflags <= 0)
    eflags = PE_DEFAULT;

  if (flag == DO_ALLOF) {
    /* The last arg is a delimiter. Parse it in place. */
    char *sp = sep;
    const char *arglast = args[nargs - 1];
    if (process_expression(sep, &sp, &arglast, executor,
                           caller, enactor, eflags, PT_DEFAULT, pe_info))
      return;
    *sp = '\0';
    nargs--;
  } else
    sep[0] = '\0';

  for (j = 0; j < nargs; j++) {
    tp = tbuf;
    ap = args[j];
    if (process_expression(tbuf, &tp, &ap, executor, caller,
                           enactor, eflags, PT_DEFAULT, pe_info))
      return;
    *tp = '\0';
    if ((isbool && parse_boolean(tbuf)) || (!isbool && strlen(tbuf))) {
      if (!first && *sep) {
        safe_str(sep, buff, bp);
      } else
        first = 0;
      safe_str(tbuf, buff, bp);
      if (flag == DO_FIRSTOF)
        return;
    }
  }
  if (flag == DO_FIRSTOF)
    safe_str(tbuf, buff, bp);
}
Esempio n. 2
0
static PyObject *
cu5_pennpy_eval_str(int id, const char *to_eval, char *wenv_buf, int wenv_argc)
{
    char rbuff[BUFFER_LEN], *rp;

    CU5_PennPy_Eval_State old_state;
    int ii, pe_ret;

    /* Evaluate string. */
    cu5_pennpy_push_eval_state(&old_state);

    for (ii = 0; ii < wenv_argc; ii++) {
        global_eval_context.wenv[ii] = &wenv_buf[ii * BUFFER_LEN];
    }

    rp = rbuff;
    pe_ret = process_expression(rbuff, &rp, &to_eval, id, id, GOD,
                                PE_DEFAULT, PT_DEFAULT, NULL);

    cu5_pennpy_pop_eval_state(&old_state);

    /* Return in Python string. */
    if (pe_ret) {
        PyErr_SetString(PyExc_RuntimeError, "CPU limit reached");
        return NULL;
    }

    return PyString_FromStringAndSize(rbuff, rp - rbuff);
}
Esempio n. 3
0
/** qsort() comparision routine used by sortby() */
int
u_comp(const void *s1, const void *s2)
{
  char result[BUFFER_LEN], *rp;
  char const *tbuf;
  int n;

  /* Our two arguments are passed as %0 and %1 to the sortby u-function. */

  /* Note that this function is for use in conjunction with our own
   * sane_qsort routine, NOT with the standard library qsort!
   */
  global_eval_context.wenv[0] = (char *) s1;
  global_eval_context.wenv[1] = (char *) s2;

  /* Run the u-function, which should return a number. */

  tbuf = ucomp_buff;
  rp = result;
  if (process_expression(result, &rp, &tbuf,
                         ucomp_executor, ucomp_caller, ucomp_enactor,
                         PE_DEFAULT, PT_DEFAULT, ucomp_pe_info))
    return 0;
  n = parse_integer(result);

  return n;
}
Esempio n. 4
0
int cell_expression(CELL *cell)
{
  int return_value;

  if (!cell->existing || !cell->alive)
    return (0);
  return_value = process_expression(&(cell->transsys_instance));
  return (return_value);
}
Esempio n. 5
0
static void
do_whichof(char *args[], int nargs, enum whichof_t flag,
           char *buff, char **bp, dbref executor,
           dbref caller, dbref enactor, PE_Info *pe_info, int isbool)
{
  int j;
  char tbuf[BUFFER_LEN], *tp;
  char const *sp;
  char sep = ' ';
  int first = 1;
  tbuf[0] = '\0';
  if (flag == DO_ALLOF) {
    /* The last arg is a delimiter. Parse it in place. */
    char insep[BUFFER_LEN];
    char *isep = insep;
    const char *arglast = args[nargs - 1];
    process_expression(insep, &isep, &arglast, executor,
                       caller, enactor, PE_DEFAULT, PT_DEFAULT, pe_info);
    *isep = '\0';
    strcpy(args[nargs - 1], insep);
    if (!delim_check(buff, bp, nargs, args, nargs, &sep))
      return;
    nargs--;
  }

  for (j = 0; j < nargs; j++) {
    tp = tbuf;
    sp = args[j];
    process_expression(tbuf, &tp, &sp, executor, caller,
                       enactor, PE_DEFAULT, PT_DEFAULT, pe_info);
    *tp = '\0';
    if ((isbool && parse_boolean(tbuf)) || (!isbool && strlen(tbuf))) {
      if (!first) {
        safe_chr(sep, buff, bp);
      } else
        first = 0;
      safe_str(tbuf, buff, bp);
      if (flag == DO_FIRSTOF)
        return;
    }
  }
  if (flag == DO_FIRSTOF)
    safe_str(tbuf, buff, bp);
}
Esempio n. 6
0
/** Change a player's password.
 * \verbatim
 * This function implements @password.
 * \endverbatim
 * \param executor the executor.
 * \param enactor the enactor.
 * \param old player's current password.
 * \param newobj player's desired new password.
 * \param queue_entry the queue entry \@password is being executed in
 */
void
do_password(dbref executor, dbref enactor, const char *old, const char *newobj,
            MQUE *queue_entry)
{
  if (!queue_entry->port) {
    char old_eval[BUFFER_LEN];
    char new_eval[BUFFER_LEN];
    char const *sp;
    char *bp;

    sp = old;
    bp = old_eval;
    if (process_expression(old_eval, &bp, &sp, executor, executor, enactor,
                           PE_DEFAULT, PT_DEFAULT, NULL))
      return;
    *bp = '\0';
    old = old_eval;

    sp = newobj;
    bp = new_eval;
    if (process_expression(new_eval, &bp, &sp, executor, executor, enactor,
                           PE_DEFAULT, PT_DEFAULT, NULL))
      return;
    *bp = '\0';
    newobj = new_eval;
  }

  if (!password_check(executor, old)) {
    notify(executor, T("The old password that you entered was incorrect."));
  } else if (!ok_password(newobj)) {
    notify(executor, T("Bad new password."));
  } else {
    (void) atr_add(executor, pword_attr, password_hash(newobj, NULL), GOD, 0);
    notify(executor, T("You have changed your password."));
  }
}
Esempio n. 7
0
char *CHSInterface::EvalExpression(char *input, HS_DBREF executor,
                                   HS_DBREF caller, HS_DBREF enactor)
{
#ifdef PENNMUSH
    static char tbuf[BUFFER_LEN];
#else
    static char tbuf[LBUF_SIZE];
#endif

    *tbuf = '\0';

#ifdef PENNMUSH                 // No change in code between versions
    char *bp;
    const char *p;
    //char *rsaves[10];

    bp = tbuf;
    p = input;
    process_expression(tbuf, &bp, &p, executor, caller, enactor,
                       PE_DEFAULT, PT_DEFAULT, NULL);
    *bp = '\0';
#endif


#if defined(TM3) || defined(MUX)
    char *bp, *str;
    bp = tbuf;
    str = input;

#ifdef TM3
    exec(tbuf, &bp, 0, executor, enactor, EV_EVAL,
         &input, wenv, m_uiEnvVariableCount);
#endif

#ifdef MUX
    mux_exec(tbuf, &bp, 0, executor, enactor, EV_EVAL,
             &input, wenv, m_uiEnvVariableCount);

#endif

    *bp = '\0';

#endif

    return tbuf;
}
Esempio n. 8
0
grammar load_grammar(std::string const & nameOfMain, std::map<std::string, wirth_production_def> const & productions) {
	(void)dont_care;
	parser p;
	std::map<std::string, production_def> temp;
	std::map<std::u32string, std::shared_ptr<details::literal>> literalNodes;
	std::map<std::string, std::shared_ptr<details::production>> productionNodes;
	for (auto const & entry : productions) {
		production_def def;
		abstract_syntax_graph asg = p.parse(builtins::wirth, expressionDfa, entry.second.definition);
		def.tree = process_expression(entry.second.definition, asg.root, asg, literalNodes, productionNodes);
		def.assoc = entry.second.assoc;
		def.precedences = entry.second.precedences;
		def.filter = entry.second.filter;
		temp[entry.first] = def;
	}
	return grammar(nameOfMain, temp);
}
Esempio n. 9
0
/** Helper function for calling \@functioned funs.
 * \param buff string to store result of evaluation.
 * \param bp pointer into end of buff.
 * \param obj object on which the ufun is stored.
 * \param attrib pointer to attribute on which the ufun is stored.
 * \param nargs number of arguments passed to the ufun.
 * \param args array of arguments passed to the ufun.
 * \param executor executor.
 * \param caller caller (unused).
 * \param enactor enactor.
 * \param pe_info pointer to structure for process_expression data.
 * \param extra_flags extra PE_ flags to pass in (PE_USERFN or 0).
 */
void
do_userfn(char *buff, char **bp, dbref obj, ATTR *attrib, int nargs,
          char **args, dbref executor, dbref caller
          __attribute__ ((__unused__)), dbref enactor, NEW_PE_INFO *pe_info,
          int extra_flags)
{
  int j;
  int made_pe_info = 0;
  char *tbuf;
  char const *tp;
  int pe_flags = PE_DEFAULT | extra_flags;
  PE_REGS *pe_regs;

  if (nargs > 10)
    nargs = 10;                 /* maximum ten args */

  /* save our stack */
  if (!pe_info) {
    made_pe_info = 1;
    pe_info = make_pe_info("pe_info-do_userfn");
  }

  /* copy the appropriate args into pe_regs */
  pe_regs = pe_regs_localize(pe_info, PE_REGS_ARG, "do_userfn");
  for (j = 0; j < nargs; j++) {
    pe_regs_setenv_nocopy(pe_regs, j, args[j]);
  }

  tp = tbuf = safe_atr_value(attrib);
  if (AF_NoDebug(attrib))
    pe_flags |= PE_NODEBUG;     /* no_debug overrides debug */
  else if (AF_Debug(attrib))
    pe_flags |= PE_DEBUG;

  process_expression(buff, bp, &tp, obj, executor, enactor, pe_flags,
                     PT_DEFAULT, pe_info);

  free(tbuf);

  pe_regs_restore(pe_info, pe_regs);
  pe_regs_free(pe_regs);

  if (made_pe_info) {
    free_pe_info(pe_info);
  }
}
Esempio n. 10
0
/** Given a ufun, executor, enactor, PE_Info, and arguments for %0-%9,
 *  call the ufun with appropriate permissions on values given for
 *  wenv_args. The value returned is stored in the buffer pointed to
 *  by ret, if given.
 * \param ufun The ufun_attrib that was initialized by fetch_ufun_attrib
 * \param ret If desired, a pointer to a buffer in which the results
 *            of the process_expression are stored in.
 * \param caller The caller (%@).
 * \param enactor The enactor. (%#)
 * \param pe_info The pe_info passed to the FUNCTION
 * \param user_regs Other arguments that may want to be added. This nests BELOW
 *                the pe_regs created by call_ufun. (It is checked first)
 * \param data a void pointer to extra data. Currently only used to pass the
 *             name to use, when UFUN_NAME is given.
 * \retval 0 success
 * \retval 1 process_expression failed. (CPU time limit)
 */
bool
call_ufun_int(ufun_attrib * ufun, char *ret, dbref caller, dbref enactor,
              NEW_PE_INFO *pe_info, PE_REGS *user_regs, void *data)
{
  char rbuff[BUFFER_LEN];
  char *rp, *np = NULL;
  int pe_ret;
  char const *ap;
  char old_attr[BUFFER_LEN];
  int made_pe_info = 0;
  PE_REGS *pe_regs;
  PE_REGS *pe_regs_old;
  int pe_reg_flags = 0;

  /* Make sure we have a ufun first */
  if (!ufun)
    return 1;
  if (!pe_info) {
    pe_info = make_pe_info("pe_info.call_ufun");
    made_pe_info = 1;
  } else {
    strcpy(old_attr, pe_info->attrname);
  }

  pe_regs_old = pe_info->regvals;

  if (ufun->ufun_flags & UFUN_LOCALIZE)
    pe_reg_flags |= PE_REGS_Q;
  else {
    pe_reg_flags |= PE_REGS_NEWATTR;
    if (ufun->ufun_flags & UFUN_SHARE_STACK)
      pe_reg_flags |= PE_REGS_ARGPASS;
  }

  pe_regs = pe_regs_localize(pe_info, pe_reg_flags, "call_ufun");

  rp = pe_info->attrname;
  if (*ufun->attrname == '\0') {
    safe_str("#LAMBDA", pe_info->attrname, &rp);
    safe_chr('/', pe_info->attrname, &rp);
    safe_str(ufun->contents, pe_info->attrname, &rp);
  } else {
    safe_dbref(ufun->thing, pe_info->attrname, &rp);
    safe_chr('/', pe_info->attrname, &rp);
    safe_str(ufun->attrname, pe_info->attrname, &rp);
  }
  *rp = '\0';

  /* If the user doesn't care about the return of the expression,
   * then use our own rbuff.  */
  if (!ret)
    ret = rbuff;
  rp = ret;

  /* Anything the caller wants available goes on the bottom of the stack */
  if (user_regs) {
    user_regs->prev = pe_info->regvals;
    pe_info->regvals = user_regs;
  }

  if (ufun->ufun_flags & UFUN_NAME) {
    char *name = (char *) data;
    if (!name || !*name)
      name = (char *) Name(enactor);
    safe_str(name, ret, &rp);
    if (!(ufun->ufun_flags & UFUN_NAME_NOSPACE))
      safe_chr(' ', ret, &rp);
    np = rp;
  }


  /* And now, make the call! =) */
  ap = ufun->contents;
  pe_ret = process_expression(ret, &rp, &ap, ufun->thing, caller,
                              enactor, ufun->pe_flags, PT_DEFAULT, pe_info);
  *rp = '\0';

  if ((ufun->ufun_flags & UFUN_NAME) && np == rp) {
    /* Attr was empty, so we take off the name again */
    *ret = '\0';
  }

  /* Restore call_ufun's pe_regs */
  if (user_regs) {
    pe_info->regvals = user_regs->prev;
  }

  /* Restore the pe_regs stack. */
  pe_regs_restore(pe_info, pe_regs);
  pe_regs_free(pe_regs);

  pe_info->regvals = pe_regs_old;

  if (!made_pe_info) {
    /* Restore the old attrname. */
    strcpy(pe_info->attrname, old_attr);
  } else {
    free_pe_info(pe_info);
  }

  return pe_ret;
}
Esempio n. 11
0
/** The switch command.
 * \verbatim
 * For lack of better place the @switch code is here.
 * @switch expression=args
 * \endverbatim
 * \param executor the executor.
 * \param expression the expression to test against cases.
 * \param argv array of cases and actions.
 * \param enactor the object that caused this code to run.
 * \param first if 1, run only first matching case; if 0, run all matching cases.
 * \param notifyme if 1, perform a notify after executing matched cases.
 * \param regexp if 1, do regular expression matching; if 0, wildcard globbing.
 * \param queue_type the type of queue to run any new commands as
 * \param queue_entry the queue entry \@switch is being run in
 */
void
do_switch(dbref executor, char *expression, char **argv, dbref enactor,
          int first, int notifyme, int regexp, int queue_type,
          MQUE *queue_entry)
{
  int any = 0, a;
  char buff[BUFFER_LEN], *bp;
  char const *ap;
  char *tbuf1;
  PE_REGS *pe_regs;

  if (!argv[1])
    return;

  /* now try a wild card match of buff with stuff in coms */
  for (a = 1;
       !(first && any) && (a < (MAX_ARG - 1)) && argv[a] && argv[a + 1];
       a += 2) {
    /* eval expression */
    ap = argv[a];
    bp = buff;
    if (process_expression(buff, &bp, &ap, executor, enactor, enactor,
                           PE_DEFAULT, PT_DEFAULT, queue_entry->pe_info)) {
      return;
    }
    *bp = '\0';
    /* check for a match */
    pe_regs = pe_regs_create(PE_REGS_SWITCH | PE_REGS_CAPTURE, "do_switch");
    pe_regs_set(pe_regs, PE_REGS_SWITCH, "t0", expression);
    if (regexp ? regexp_match_case_r(buff, expression, 0,
                                     NULL, 0, NULL, 0, pe_regs, 0)
        : local_wild_match(buff, expression, pe_regs)) {
      tbuf1 = replace_string("#$", expression, argv[a + 1]);
      if (!any) {
        /* Add the new switch context to the parent queue... */
        any = 1;
      }
      if (queue_type & QUEUE_INPLACE) {
        new_queue_actionlist(executor, enactor, enactor, tbuf1, queue_entry,
                             PE_INFO_SHARE, queue_type, pe_regs);
      } else {
        new_queue_actionlist(executor, enactor, enactor, tbuf1, queue_entry,
                             PE_INFO_CLONE, queue_type, pe_regs);
      }
      mush_free(tbuf1, "replace_string.buff");
    }
  }
  /* do default if nothing has been matched */
  if ((a < MAX_ARG) && !any && argv[a]) {
    tbuf1 = replace_string("#$", expression, argv[a]);
    pe_regs = pe_regs_create(PE_REGS_SWITCH | PE_REGS_CAPTURE, "do_switch");
    pe_regs_set(pe_regs, PE_REGS_SWITCH, "t0", expression);
    if (queue_type & QUEUE_INPLACE) {
      new_queue_actionlist(executor, enactor, enactor, tbuf1, queue_entry,
                           PE_INFO_SHARE, queue_type, pe_regs);
    } else {
      new_queue_actionlist(executor, enactor, enactor, tbuf1, queue_entry,
                           PE_INFO_CLONE, queue_type, pe_regs);
    }
    mush_free(tbuf1, "replace_string.buff");
  }

  if (!(queue_type & QUEUE_INPLACE) && notifyme) {
    parse_que(executor, enactor, "@notify me", NULL);
  }
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
	uint8_t *tab_rp_bits;
	uint16_t *tab_rp_registers;
	uint16_t *rd_position_registers;
    uint16_t *tab_rp_registers_bad;
    modbus_t *ctx;

/***********************************************************************
* feedback is used to store the return value of every called function
* rc is used to store the return value of the modbus command 
* resend is used to define the resend times if the command is failed
* i is used for the loop parameter
* insert_bit is used to indicate the calibarate function if there is value to set
* num is used to store the number of data blocks in database 
* use_backend is used to indicate the modbus mode is rtu
* next_option is used to take the command options
* pre_step, curr_step are used to indicate the previous step number and current position step number
* pre_length and value indicate the latest posiotion in database and current position
* SLEN is a kind of struct used to store the database blocks
************************************************************************/
    int feedback,i; 
	int insert_bit, nb_points,num =0;
	int next_option;
	long curr_step;
	long pystep = -1;
	double value;
	double pdepth,pspacing,pdwell,pinterval;
	double profiled,stopped;
	double depth,dwell,spacing,interval;
	double last_position;
	int profilebit =0,feedback1,feedback2;
	int modbus=0;
	int motor_stop = 0;
	char * command_arg = "";
	char * return_value;
	double in_position = 0;
	SLEN *examp;
	ARF  *config, *profile,*off_set;
	modbus_mapping_t *mb_mapping;
	int   ShmID;      
	int *ShmPTR;
	int stop_indicator = 0;

	key_t MyKey;
	MyKey   = ftok(".", 's');    
    ShmID   = shmget(MyKey, sizeof(int), IPC_CREAT | 0666);
    ShmPTR  = (int *) shmat(ShmID, NULL, 0);

	tab_rp_registers = (uint16_t *) malloc(4 * sizeof(uint16_t));
	rd_position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
	tab_rp_registers_bad = (uint16_t *) malloc(2 * sizeof(uint16_t));

	config = (ARF*)malloc( 10 * sizeof(ARF) );
	if ( config == NULL ) 
	{
		printf("Error: Out of Memory, use ./master reset to reset memory\n"); 
		exit(1);
	}
	const char *const short_options = "hd::u::l:p::cD::w::s::i::gSmt::";
	const struct option long_options[] = {
        { "help",              0,NULL, 'h'},
        { "down",              2,NULL, 'd'},
		{ "up",                2,NULL, 'u'},
		{ "length",            1,NULL, 'l'},
		{ "position",          2,NULL, 'p'},
		{ "count",             0,NULL, 'c'},
		{ "Depth",             2,NULL, 'D'},
		{ "well",              2,NULL, 'w'},
		{ "spacing",           2,NULL, 's'},
		{ "interval",          2,NULL, 'i'},
		{ "go",                0,NULL, 'g'},
		{ "System",            0,NULL, 'S'},
		{ "motor",             0,NULL, 'm'},
		{ "time",              2,NULL, 't'},
        { NULL, 0, NULL, 0  },

    };

	if (argc < 2) 
	{
		print_comusage (stderr, 1);
		return_value = json_option("status:",-1);
		return return_value;
	}
	program_name = argv[0];
	/*Get the first argument that passed through main function but does not contain*/
	command_name = argv[1];
	if(argc > 2)
	{
		command_arg  = argv[2];
	}
/*******************************************************************************************
* The next three command_name are used to control the motor through modbus	(need modbus)  *
********************************************************************************************/

	if ( strcmp(command_name, "go") == 0 ) {
		double curr_position;
		char *recd = (char*)malloc(10*sizeof(char));
		double offset;
		int re_send = 0;
		*ShmPTR = 0;
		modbus = 0;
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		
		if (next_option == -1) print_comusage (stderr, 1);
		while (next_option != -1) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);
				case 'd':  
				godown:
						enable(0);
						initbus(1);
				/*		sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						feedback = godown(ctx);
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							re_send++;
							goto godown;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
				*/
						feedback = process_go_down(1);
						if((feedback == 0) && (re_send < 1))
						{
							printf("get false recycle power\n");
							enable(0);
							initbus(0);
							re_send++;
							goto godown;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
						break;	
				case 'u':
				goup: 
						enable(0);
						initbus(1);
				/*
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						feedback = goup(ctx);
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							re_send++;
							goto goup;
						}
				*/
						feedback = process_go_up(1);
						if((feedback == 0) && (re_send < 1))
						{
							printf("Get false recycle power\n");
							enable(0);
							initbus(0);
							re_send++;
							goto goup;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
						break;	
				case 'p':
						enable(0);
						initbus(1);
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						in_position = atof(optarg);		
						off_set = (ARF*)malloc(15*sizeof(ARF));
	    				off_set = getconfig(&num,off_set);
						offset = off_set[10].value;
						in_position = in_position - offset;
						//printf("inposition is %f offset is %f\n",in_position,offset);
						free(off_set);
						//system("/home/sampler/kingkong.sh");
				gotoposition:
						if (in_position <= 0)
						{
							if( process_read_home_switch(1) == 0)
							{
								feedback = process_go_home(1);
							}
							else
								feedback = 1;
						}
						else 
						{
							pystep = process_read_step(1);
							curr_position = process_position(pystep);
							if ( !(( (in_position -0.1) <= curr_position ) && ( curr_position <= (in_position + 0.1) )) ) 
							{
								feedback = process_go_position(1,in_position);
								return_value = json_option("status",feedback);
							}
						}
						if((feedback == 0)&&(re_send <1))
						{
							printf("get false recycle power");
							enable(0);
							initbus(0);
							enable(0);
							initbus(1);
							re_send++;
							goto gotoposition;
						}
						break;	
					case '?':
						print_comusage (stderr, 1);
					default:
						abort ();
				}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		//If the go command is failed, then exit the current process and power off the controller 	
		if(feedback == 0)
		{
			printf("1\n");
			//*ShmPTR = 1;
			enable(0);
			initbus(0);
			return_value = json_option("status",-1);
			return return_value;
		}
		do{
			usleep(5000);
			stop_indicator = process_check(1);
		}while(stop_indicator != 0);
		//printf("stop\n");
		sleep(1);
		pystep = process_read_step(1);
		curr_position = process_position(pystep);
		//printf("cur position is %f\n",curr_position);
		if(curr_position != -1)
		{
			login("Go to command set last position");
			curr_position = curr_position + offset;
			setconfig(9,curr_position);
			// In order to avoid "Read status command shutdown the power by accident
			enable(0);
			initbus(0);		
			return_value = json_option("status",1);
		}
		else return_value = json_option("status",-1);
	}

	if ( strcmp(command_name, "stop") == 0 ) 
	{ 		
		if(check_power() == 1)
		{
			/*sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			feedback = stop(ctx);
			if(feedback == -1)stop(ctx);
			*/
			process_stop(1);
		}
	}

    if ( strcmp(command_name, "position") == 0 ) 
	{ 
		login("Check position command");
		int resend = 0;
		double temp_position,offset;
		char *rec = (char*)malloc(10*sizeof(char));
		stop_indicator = *ShmPTR;
		uint16_t * position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
		off_set = (ARF*)malloc(15*sizeof(ARF));
	    off_set = getconfig(&num,off_set);
		offset = off_set[10].value;
checkposition:
		if (check_power()== 1) 
		{
			ctx = modbusconnection(ctx);
			modbus = 1;
			temp_position = checkposition(ctx,position_registers);
			sprintf(rec,"The position read is %f",temp_position);
			login(rec);
			if(temp_position != -1)
			{
				login("Check position set last position");
				//This sentence is used to show the position with offset 
				temp_position = temp_position + offset;
				feedback = setconfig(9,temp_position);
			}
			else 
			{
				if(resend < 2)
				{
					resend++;					
					goto checkposition;
				}
				else return -100;
			}
		}
		else 
		{
			config = getconfig(&num,config);
			temp_position = config[8].value;
		}
		return_value = json_float_option("status",temp_position);
		printf("%s\n",return_value);
	}
/***********************************************************************
*         0: motor is stopped                                          *
*         1: motor is going down                                       *
*         2: motor is going up                                         *
*         3: motor is ramp up                                          *
*         4: motor is ramp down   									   *
*		   (need modbus)             						           *
*                                               	                   *
************************************************************************/
	if(strcmp(command_name, "status") == 0) 
	{
		stop_indicator = *ShmPTR;
		if (check_power()== 1) 
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
			if(next_option == -1) print_comusage (stderr, 1);
			while(next_option != -1) 
			{
				switch (next_option) 
				{
					case 'h':
							print_comusage(stdout, 0);	
					case 'S':
							feedback = checksystemstatus(ctx,tab_rp_registers);
							return_value = json_option("status",feedback);
							break;	
					case 'm':
							feedback = checkmotorstatus(ctx,tab_rp_registers);
							return_value = json_option("status",feedback);
							break;
					case '?':
							print_comusage (stderr, 1);
					default:
							abort ();
				}
				next_option = getopt_long (argc, argv, short_options, long_options, NULL);
			}	
			if(feedback == -1)
			{
				return_value = json_option("status",0);
			}
		}
		else 
		{
			return_value = json_option("status",0);
			//login("Check status from database");
		}
		printf("%s\n",return_value);
	}

/****************************************************************************************
*      The next three command_name are used to control the database through sqlite3	    *
*****************************************************************************************/
	if ( strcmp(command_name, "factory_default") == 0 ) 
	{
		feedback1 = reset(0);
		feedback2 = dbinit(0);
		if ( (feedback1 == 1) && (feedback2 == 1)) 
		{
			return_value = json_float_option("status",1);
			printf("%s\n",return_value);
		}
		else 
		{
			return_value = json_float_option("status",-1);
			printf("%s\n",return_value);		
		}
	}

	if ( strcmp(command_name, "reset") == 0 ) 
	{
		feedback = reset(0);
		if(feedback == 1)
		{
			feedback = expected_time_reset();
		}
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "init") == 0 ) 
	{
		feedback = -1;
		if ( strcmp(command_arg, "all") == 0 ) 
		{
			feedback = dbinit(0);
			if(feedback == 1)
			{
				feedback = expected_time_init();
			}
		}
		if ( strcmp(command_arg, "calibrate" ) == 0 ) 
		{ 
			setconfig(6,0);
			feedback = dbinit(1); 
		}
		if ( strcmp(command_arg, "configure" ) == 0 ) 
		{
			feedback = dbinit(2);
		}
		if ( feedback == -1 ) 
		{
			return_value = json_float_option("status",-1);
			print_comusage (stderr, 1);
		}
		else return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name,"get") == 0 ) 
	{
		examp = getall(&num,examp);
		return_value = json_array_option(num,examp);
		free(examp);
		printf("%s",return_value);
	}
	if ( strcmp(command_name,"set_offset") == 0 ) 
	{
		double offset;		
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		if ( next_option == -1 ) print_comusage (stderr, 1);
		while( next_option != -1 ) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);	
				case 'l':
						if(optarg!=0)offset = strtod(optarg,NULL);
						insert_bit = 1;
						break;	
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
			}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		feedback = setconfig(11,offset);
		return_value = json_option("status",feedback);
		printf("%s",return_value);
	}
	if ( strcmp(command_name,"get_offset") == 0 ) 
	{
		double offset;		
		off_set = (ARF*)malloc(15*sizeof(ARF));
	    off_set = getconfig(&num,off_set);
		offset = off_set[10].value;
		return_value = json_float_option("status",offset);
		printf("%s",return_value);	
		free(off_set);
	}
/**************************************************************************
*      The next three command_name are used to calibrate (need modbus)     *                     
***************************************************************************/
	if ( strcmp(command_name, "calibrate") == 0 ) 
	{	
		double calibrate;
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);	
		modbus = 1;	
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);

		if ( next_option == -1 ) print_comusage (stderr, 1);
		config = getconfig(&num,config);
		calibrate = config[5].value;
		if ( calibrate == 0 ) 
		{
			reset(1);
			setconfig(6,1.0);
			set(num,0,0);
		}
		while( next_option != -1 ) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);	
				case 'l':
						if(optarg!=0)value = atof(optarg);
						insert_bit = 1;
						break;	
				case 'c':
						getall(&num,examp);
						return_value = json_option("status",num);
						printf("%s\n",return_value);
						break;
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
			}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		if ( insert_bit == 1 ) 
		{
			curr_step = checksteps(ctx,rd_position_registers);
			if ( curr_step < 0 ) curr_step =0;//do not need
			feedback = checkvalue(curr_step,value);
			if ( feedback == 1 ) 
			{
				feedback = set(num,curr_step,value);
				return_value = json_option("status",feedback);
			} 
			else 
			{
				return_value = json_option("status",-1);
			}	
		}
		/*if ( checkmotorstatus(ctx,tab_rp_registers) == 0 ) 
		{	
			enable(0);
			initbus(0);
		}*/
		printf("%s\n",return_value);
	}


/***********************************************************************
*         The following functions are used for profile				   *
*                                               	                   *
************************************************************************/
	if ( strcmp(command_name, "profile") == 0 ) 
	{
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		if ( next_option == -1 ) print_comusage (stderr, 1);
		while ( next_option != -1 ) 
		{
			switch (next_option) {
				case 'h':
						print_comusage(stdout, 0);	
				case 'd':
						if(optarg!=0)depth = atof(optarg);
						profilebit = 1;
						break;	
				case 's':
						if(optarg!=0)spacing = atof(optarg);
						profilebit = 1;
						break;
				case 'w':
						if(optarg!=0)dwell = atof(optarg);
						profilebit = 1;
						break;
				case 'i':
						//if(optarg!=0)interval = atof(optarg);
						if(optarg!=0)interval = strtod(optarg,NULL);
						profilebit = 1;
						break;
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
				}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	

		if ( profilebit == 1 ) 
		{
			feedback = set_profile(depth,spacing,dwell,interval);
		}
		//Want to get the expected profile time and save it in database
		profile_time_check(interval);
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "profileget" ) == 0) 
	{
		profile = getconfig(&num,config);
		return_value = json_profile_option(num-2,profile);
		free(profile);
		printf("%s",return_value);	
	}
	if ( strcmp(command_name, "profile_check" ) == 0) 
	{
		int *expected_profile_time;
		long remain_profile_time;
		config = getconfig(&num,config);
		pinterval = config[3].value;
		if(pinterval == 0)	
		{
			printf("-999\n");
			return -999;
		}
		expected_profile_time = (int*)malloc(10*sizeof(int));
		if(expected_profile_time == NULL){printf("error\n");exit(1);}
		expected_time_get(expected_profile_time);
		remain_profile_time = auto_run(0,expected_profile_time);
		if(remain_profile_time <=0 )remain_profile_time = 0;
		printf("%d\n",remain_profile_time);
		free(expected_profile_time);
		return remain_profile_time;
	}
	if ( strcmp(command_name, "profile_reset") == 0 ) 
	{
		//feedback = dbinit(2);
		//reading_hourly();
		system("ps aux | grep -e 'master profilego' | grep -v grep | awk '{print $2}' | xargs -i kill {}");
		feedback = set_profile(0,0,0,0);
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "profilego") == 0 ) 
	{	
		double stayposition, curr_position,tmp,cal_position;
		double sdl_read,offset;
		long wait_time,motor_status;
		int year;
		time_t fail_time;
		int stop_check = -1;
		int count,fini_count,re_try1 = 0,re_power1 =0,re_try = 0,re_send=0;
		int i=1,sample = 0,profile_times,sample_indicator;
		int * expected_tm, *curr_time,inter_val;
		setconfig(10,0);
	profile:
		/* The following eight lines are used to get profile arguments from database */
		config = getconfig(&num,config);
		pdepth = config[0].value;
		pspacing = config[1].value;
		pdwell = config[2].value;
		pinterval = config[3].value;	
		profiled = config[4].value;
		sample = config[9].value;
		offset = config[10].value;
		profile_times = 1+(pdepth - offset)/pspacing;		// Caculate the profile times
		inter_val = (int)pinterval;
		if(pinterval == 0){schedule_reading();goto profile;}
	   	if(profiled == 0 )
		{
			config = getconfig(&num,config);
			pdepth = config[0].value;
			pspacing = config[1].value;
			pdwell = config[2].value;
			pinterval = config[3].value;	
			profiled = config[4].value;
			sample = config[9].value;
			/* 
				The following part are used to get the expected profile time and 
				compare with current time
			*/
			expected_tm = (int*)malloc(10*sizeof(int));
			curr_time = (int*)malloc(10*sizeof(int));
			if(curr_time == NULL){printf("error\n");exit(1);}
			if(expected_tm == NULL){printf("error\n");exit(1);}
			do{
				config = getconfig(&num,config);
				sample = config[9].value;
				expected_time_get(expected_tm);
				wait_time= auto_run(0,expected_tm);
				curr_time = check_time(curr_time);
				sample_indicator = curr_time[3]%inter_val;
				printf("Wait for next profile\n");
				//because the board will boot up 3 minutes after clock time
				if(wait_time < -600)
				{
					profile_time_check(pinterval);
					goto profile;
				}					
				sleep(1);
			}while(wait_time>0);
			free(expected_tm);	
		four_minute_delay:
			sleep(1);
			curr_time = check_time(curr_time);
			if((curr_time[4]>=4) &&(curr_time[4]<=10))goto start_profile;
			if(curr_time[4]<4)goto four_minute_delay;
			if(curr_time[4]>10)goto profile;
		}
	start_profile:
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		if(ctx == NULL)goto profile;
		modbus = 1;
		sleep(9);
		if ( profiled == 0 ) 
		{
			if (process_syncclock() == 0) 
			{
				login("Failed in connectting with SDL");
				return;
			}
			if (process_expression(3,1,profile_times,0) == 0)
			{	
				login("Failed in send profile to SDL");
				return;
			}		
			login("Start Profiling");
			if( process_read_home_switch(1) == 0)
			{
				gotoposition(ctx, 0,rd_position_registers);   //Do not need to check if it is home because we want it home anyway
				do{
					usleep(5000);
					stop_check = process_check(1);
				}while(stop_check != 0);
				if(process_pass_through_check() == 0)initbus(0); 
				setconfig(5,1);		//Set the profile flag 
				sleep(pdwell);
			}
			else
			{
				setconfig(5,1);
				sleep(pdwell);
			}
		}	
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		/* This following part is used to determine where is destination  */
		curr_position = checkposition(ctx,tab_rp_registers) + offset;
		cal_position = i*pspacing + offset;
		if ( cal_position < pdepth )
		{
			stayposition = cal_position;
		}
		else 
			stayposition = pdepth;
		i++;
		stayposition = stayposition - offset;
		gotoposition(ctx,stayposition,tab_rp_registers);
position1:
			sleep(1);		
			ctx = modbusconnection(ctx);
			curr_position = checkposition(ctx,tab_rp_registers) + offset;
			if(curr_position == -1)
			{
				if(re_power1 < 3)
				{		
					if(re_try1 < 2)
					{
						sleep(3);
						re_try1++;
						goto position1;
					}
					else
					{
						re_try1 = 0;
						enable(0);
						initbus(0);
						sleep(3);
						initbus(1);
						sleep(1);
						re_power1++;
						goto position1;
					}
				}
				else
				{
					enable(0);
					initbus(0);
					enable(1);
					re_power1 = 0;
					return -1;
				}
			}
			if (!((stayposition -0.1) <= curr_position ) && (curr_position <= (stayposition + 0.1)))goto position1;
		wait_for_stop(ctx, tab_rp_registers);
		//Here check position in order to determine if it is destination now 
		curr_position = checkposition(ctx,tab_rp_registers)+offset;
		setconfig(9,curr_position);
		printf("Go to sleep for dwell time\n");
		if(process_pass_through_check() == 0)initbus(0);	// Add this part to check if it is passing command
		sleep(pdwell);
		if (((pdepth -0.1) <= curr_position) && (curr_position <= (pdepth + 0.1))) 
		{ 
			setconfig(5,0);	//Set profile flag here to avoid reprofile if something wrong happens during following
			profile_time_check(pinterval);		// Set next profile time
			enable(0);
			initbus(1);
			ctx = modbusconnection(ctx);
			gotoposition(ctx,0,rd_position_registers);		// After finish profile, go home
			wait_for_stop(ctx, tab_rp_registers);
			sleep(1);
			enable(0);
			if(process_pass_through_check() == 0) initbus(0);	//Check is pass through
			enable(1);
			setconfig(9,offset); //Save the position 0
			sleep(40);
			goto profile;
		}
		goto profile;

	}
/***********************************************************************
*          The next three command_name are used                        *
*             to control the date and time         	                   *
************************************************************************/
	if ( strcmp(command_name, "checktime") == 0 ) 
	{
	/*
		char *sdate;
		if ( (sdate = malloc( 80 * sizeof(char) ) )== NULL)return NULL; 
		sdate = current_time(sdate);
		return_value = json_option_string("status",sdate);
		printf("%s\n",return_value);
		free(sdate);
	*/
		//long pystep = process_read_step(1);
		//process_position(pystep);
		//process_expression(3,1,3,1);
		//process_pass_through_check();
		//process_syncclock();
		process_expression(3,1,3,0);
		process_read_home_switch(1);
    }
	if ( strcmp(command_name, "settime") == 0 ) 
	{
    	if ( argc < 4 ) 
		{ 
			print_comusage (stderr, 1); 
		}
        char *date = argv[2];
        char *time = argv[3];
        int *buf = (int*)malloc(6*sizeof(int)); 
		parse(buf,date,time);
        int i,m_buf[6];
        for(i=0;i<=5;i++) 
		{ 
			m_buf[i]=*(buf+i); 
		}
		feedback = set_time(&m_buf);
        return_value = json_option("status:",feedback);
        printf("%s\n",return_value);
		login("Set local time");
		login(return_value);
		sleep(5);
	}
	if ( strcmp(command_name, "voltage") == 0 ) 
	{
		double voltage;	
		voltage = voltage_read();
		return_value = json_float_option("status",voltage);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "temp") == 0 ) 
	{
		double temp;
		temp = temp_read();
		return_value = json_float_option("status",temp);
		printf("%s\n",return_value);
	}
	if(strcmp(command_name, "enable_power") == 0)
	{
		enable(0);
		initbus(1);
		return_value = json_option("status:",1);
	}

	if(strcmp(command_name, "disable_power") == 0)
	{
		enable(0);
		initbus(0);
		return_value = json_option("status:",1);
	}
	if ( strcmp(command_name, "backup") == 0 ) 
	{
		feedback = system("cp /home/sampler/lr.sl3   /home/sampler/lr_default.sl3");
		if(feedback == -1)
		{
			return_value = json_float_option("status",-1);
		}
		else return_value = json_float_option("status",1);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "restore") == 0 ) 
	{
		feedback = system("cp /home/sampler/lr_default.sl3  /home/sampler/lr.sl3");
		if(feedback == -1)
		{
			return_value = json_float_option("status",-1);
		}
		else return_value = json_float_option("status",1);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "debug") == 0 ) 
	{
		long return_steps;
		char *debug_result;
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		modbus = 1;
		uint16_t *debug_position_registers = (uint16_t*)malloc(2*sizeof(uint16_t));
		debug_result = (char*)malloc(50*sizeof(char));
		return_steps = checksteps(ctx,debug_position_registers);
		sprintf(debug_result,"%x,%x,%x\n",debug_position_registers[0],debug_position_registers[1],return_steps);
		json_option_string("status",debug_result);
		printf("%s\n",debug_result);
		initbus(0);
		
	}
	if ( strcmp(command_name, "power_check") == 0 ) 
	{
		int power_status = check_power();
		printf("Power is %d\n",power_status);
	}
	if ( strcmp(command_name, "sdl") == 0 ) 
	{
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl != NULL)
		{
			double vol = sdltest(sdl);
			return_value = json_float_option("status",vol);
			printf("%s\n",return_value);
			setsdl(30000,vol);
			login("Read SDL");
			login(return_value);
		}
		else setsdl(30000,-100000);
		modbus_close(sdl);
  		modbus_free(sdl);
	}
	if ( strcmp(command_name, "sdl_reset") == 0 ) 
	{
		resetsdl();
	}
	if ( strcmp(command_name, "sdl_get") == 0 ) 
	{
		int num_records;		
		SLEN * sdl_records;
		sdl_records = (SLEN*)malloc(100*sizeof(SLEN));
		sdl_records = getsdl(&num_records, sdl_records);
		return_value = json_sdl_option(num_records,sdl_records);
		printf("%s\n",return_value);
		free(sdl_records);
	}
	if ( strcmp(command_name, "sdl_uploadtime") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_setuploadtime(sdl,12,5,21,12,50,0);
	}
	if ( strcmp(command_name, "sdl_settime") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else  sdl_rtc_time(sdl,12,5,25,7,58,0);
	}
	if ( strcmp(command_name, "sdl_readsize") == 0 )
	{
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_readbuffsize(sdl);
	} 
	if ( strcmp(command_name, "sdl_readsensor") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_read_sensor(sdl,1,1);
	}
	if ( strcmp(command_name, "sdl_upload") == 0 ) 
	{
		//sdl_read_log_data(16);
		int number;
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else 
		{
			profile_save_data(sdl);
		}
		modbus_close(sdl);
	}
	if ( strcmp(command_name, "sdl_sample") == 0 ) 
	{
		int number;
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else 
		{
			sdl_read_sensor(sdl,1,1);
			sleep(60);
			sample_save_data(sdl);
			//sdl_start_profile(sdl,2);
		}
		modbus_close(sdl);
	}
	if ( strcmp(command_name, "shutdown") == 0 ) 
	{
		feedback = system("/sbin/shutdown now");
	}
	if ( strcmp(command_name, "maxstep") == 0 ) 
	{
		enable(0);
		initbus(1);		
		sleep(1);
		ctx = modbusconnection(ctx);
		modbus = 1;
		feedback = set_max_step(ctx,rd_position_registers);
		return_value = json_option("status",feedback);
		initbus(0);
	}
	if(strcmp(command_name, "slave") == 0)
	{
		slave();
	} 
	if(strcmp(command_name, "motor_status") == 0) 
	{
		if (check_power()== 1) 
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			feedback = checkmotorstatus(ctx,tab_rp_registers);
			if(feedback == -1)
			{
				printf("0\n");				
				return 0;
			}
			else 
			{
				printf("%d\n",feedback);
				return feedback;
			}
		}
		else
		{
			printf("0\n");
			return 0;
		}		
	}
close:
	/* Free the memory */
	free(config);
    free(tab_rp_registers);
	free(rd_position_registers);
	//modbus_mapping_free(mb_mapping);
    /* Close the connection */
	if (modbus == 1)	
	{
    	modbus_close(ctx);
	}
	if (motor_stop == 1) 
	{
		printf("stop setting\n");
		setconfig(9,last_position);
	}
    return return_value;
}