Exemplo n.º 1
0
// A subset of printf
void klogf(char* string, ...) {
    va_list args;
    va_start(args, string);
    for (size_t i = 0; string[i] != '\0'; ++i) {
        if (string[i] == '%') {
            ++i;
            switch(string[i]) {
                case '%':
                    write_serial(COM1, '%');
                    break;
                case 'u':
                    klog_uint(va_arg(args, uint32_t), 8);
                    break;
                case 'd':
                case 'i':
                case 'p':
                case 'x':
                    if (i+1 == 'u') {
                        klog_uint(va_arg(args, uint32_t), 8);
                    }
                    break;
                case 'l':
                    if (i+1 == 'u') {
                        klog_uint(va_arg(args, uint32_t), 16);
                    }
                    break;
            }
            continue;
        }
        write_serial(COM1, string[i]);
    }
    va_end(args);
}
Exemplo n.º 2
0
/* Generates a new serial number for a certificate. */
long get_serial()
{
	long serial = read_serial();

	if (serial == INVALID_SERIAL) { /* Read failed */
		/* Generate a new serial */
		RAND_pseudo_bytes((unsigned char*)&serial, sizeof(serial));
		serial &= 0x0FFFFFFF; /* Fix sign and allow loads of serials before an overflow occurs */
		RAND_cleanup();
		write_serial(serial);
	} else
		write_serial(++serial); /* Update serial file */

	return serial;
}
Exemplo n.º 3
0
void say_hello(){

    packet greeting;
    greeting.type = PKT_HELLO;
    write_serial(&greeting);
    return;
}
Exemplo n.º 4
0
void wakeup (struct serial *s)

{
	sleep (1);
	if (write_serial (s, "+++", 3) == -1) error (1, 0, "could not write");
	sleep (1);
}
Exemplo n.º 5
0
/*
 * write_serial_str: write_serial for strings
 */
__export void write_serial_str(char *data)
{
	char ch;

	while ((ch = *data++))
		write_serial(ch);
}
Exemplo n.º 6
0
const char *logputs( const char *str ){
	int i;

	for ( i = 0; str[i]; i++ );
	write_serial( str, i );

	return str;
}
Exemplo n.º 7
0
void close_serial(){

    packet goodbye;
    goodbye.type = PKT_GDBY;
    write_serial(&goodbye);
    fclose(dev);
	return;
}
Exemplo n.º 8
0
int kvprintf( const char *format, va_list args ){
	int	slen = strlen( format );
	int i = 0;
	int signed_int;
	unsigned unsigned_int;
	char buf;
	const char *str;

	for ( i = 0; i < slen; i++ ){
		if ( format[i] == '%' ){
			switch( format[++i] ){
				case '%':
					buf = '%';
					write_serial( &buf, 1 );
					break;

				case 'c':
					buf = va_arg( args, int );
					write_serial( &buf, 1 );
					break;

				case 's':
					str = va_arg( args, char * );
					logputs( str );
					break;

				case 'd':
					signed_int = va_arg( args, int );
					print_num( signed_int );
					break;

				case 'u':
					unsigned_int = va_arg( args, unsigned );
					print_num( unsigned_int );
					break;

				case 'x':
					unsigned_int = va_arg( args, unsigned );
					print_hex( unsigned_int );
					break;
			}

		} else {
			write_serial( format + i, 1 );
		}
	}
Exemplo n.º 9
0
void print_num( unsigned input ){
	unsigned i, a;
	char buf[32];

	if ( !input ){
		buf[0] = '0';
		write_serial( buf, 1 );
		return;
	}

	for ( i = 0, a = input; a; a = a / 10 ){
		buf[i++] = a % 10 + '0';
	}

	while( i-- ){
		write_serial( &buf[i], 1 );
	}
}
Exemplo n.º 10
0
Arquivo: cons.c Projeto: t-crest/ospat
pok_bool_t pok_cons_write (const char *s, size_t length)
{
   for (; length > 0; length--)
 #ifdef POK_NEEDS_QEMU_SETUP
		write_serial (*s++);
 #else
		putchar((int)(*s++));	
 #endif
   return 0;
}
Exemplo n.º 11
0
static void klog_uint(uint64_t n, uint32_t length) {
    unsigned char buf[length];
    unsigned int c;
    // We explicitly abuse integer overflow!
    for (c = length-1; c < length; --c) {
        buf[c] = n % 16;
        n /= 16;
    }
    write_serial(COM1, '0');
    write_serial(COM1, 'x');
    ++c;
    for (; c < length; ++c) {
        if (buf[c] >= 10) {
            write_serial(COM1, buf[c] + 'a' - 10);
        } else {
            write_serial(COM1, buf[c] + '0');
        }
    }
}
Exemplo n.º 12
0
void print_hex( unsigned input ){
	unsigned i, a;
	char *hextab = "0123456789abcdef";
	char buf[32];

	if ( !input ){
		buf[0] = '0';
		write_serial( buf, 1 );
		return;
	}

	for ( i = 0, a = input; a; a = a / 16 ){
		buf[i++] = hextab[ a % 16 ];
	}

	while( i-- ){
		write_serial( &buf[i], 1 );
	}
}
Exemplo n.º 13
0
void putc(char c) {
	syncRAII<remutex> sync(vga_mutex);
	write_serial(c);
	if(x >= 80 || c == '\n') {
		x = 0;
		y++;
		if(c == '\n') { return; }
	}
	vga_mem[y * 80 + x++] = 7 << 8 | c;
}
Exemplo n.º 14
0
int at_cmd (struct serial *s)

{
	char buf [32];
	ssize_t r;
	if (write_serial (s, "AT\r", 3) == -1) error (1, 0, "could not write");
	memset (buf, 0, sizeof (buf));
	r = read_serial (s, buf, sizeof (buf) - 1);
	if (r < 0) return -1;
	else if (r == 0) return -1;
	if (!strcmp (buf, "OK\r")) return 0;
	return (-1);
}
Exemplo n.º 15
0
void puts(const char *s) {
	syncRAII<remutex> sync(vga_mutex);
	while(*s) {
		if(x >= 80 || *s == '\n') {
			x = 0;
			y++;
			if(*s == '\n') {
				write_serial(*s);
				s++;
				continue;
			}
		}
		if(y > 25) {
			y = 23;
			x = 0;
			memmove((void *)vga_mem, (void *)(vga_mem + 2 * 80), 23 * 80 * 2);
			memset((void *)(vga_mem + 23 * 80), 0, 2 * 80 * 2);
		}
		write_serial(*s);
		vga_mem[y * 80 + x++] = 7 << 8 | *s++;
	}
}
Exemplo n.º 16
0
static void printchar(char **str, int c)
{
	
    if (str) {
        **str = c;
        ++(*str);
    } else {
        putchar(c);
        writechar_fb(c);
#ifdef USE_SERIAL
        write_serial(c);
#endif
    }
}
Exemplo n.º 17
0
ssize_t __serial_write(struct file_info *fp, const void *buf, size_t count)
{
    const char *bufp = buf;
    size_t n = 0;

    (void)fp;

    if (!syslinux_serial_console_info()->iobase)
	return count;		/* Nothing to do */

    while (count--) {
	write_serial(*bufp++);
	n++;
    }

    return n;
}
Exemplo n.º 18
0
size_t write_verify_read(void* com_port, unsigned char* in, size_t inlen, unsigned char* out, size_t outlen)
{
    size_t        ret;
    unsigned char buf[4096];

    ret = write_serial(com_port, in, inlen);
    if(ret != inlen)
    {
        return (unsigned int)-1;
    }
    ret = read_serial(com_port, buf, inlen+outlen);
    if(ret < inlen || memcmp(in, buf, inlen))
    {
        printf("%s: Read %Ix bytes\n", __FUNCTION__, ret);
        printbuffer(buf, ret); 
        return (unsigned int)-1;
    }
    //printbuffer(buf, ret); 
    memmove(out, buf+inlen, ret-inlen);
    return ret-inlen;
}
Exemplo n.º 19
0
void serial_writestring(const char* data) {
	size_t datalen = strlen(data);
	for (size_t i = 0; i < datalen; i++)
		write_serial(data[i]);
}
Exemplo n.º 20
0
int main(int argc, char *argv[])

{
  speed_t baud = B57600;  // default baudrate
  stdinfd = fileno(stdin);
  stdoutfd = fileno(stdout);
  serialfd = -1;
  erlpipefd = -1;
  struct termios oldserial, oldstdin;
 
 
 //saveterminal(stdinfd,oldstdin);
 // check(tcgetattr(stdinfd,&oldstdin) == 0, "Failed to backup stdin");

 // if erlang mode is set then redirect stderr to erlerr.txt

   

  //read command line arguments
  check(parsecmdargs(argc, argv) != -1,"Command Line Argument Failure");


  if(erlang == TRUE)
     {
       freopen("erlerr.txt", "w", stderr);
     }  
 debug("pid is %d", getpid());
  //setup pipe if require doesn't work yet 
   if(pipedebug == 1) //
   {
  
     check(makepipe(ERLPIPE) == 0, "Pipe creation or opening failed for: ");
     debug("Pipe created:");
     debug("Process %d opening erlpipe", getpid());
     erlpipefd = open(ERLPIPE, O_WRONLY|O_NONBLOCK); 
     check(erlpipefd > 0, "Erlpipe failed to open pipe: %s\nSetup reader in second terminal\n tail -f erlpipe",ERLPIPE);
     debug("Erlpipe opened");
     /*
     check(makepipe(ERLPIPEIN) == 0, "Erlpipein  creation or opening failed for: "); 
     debug("Pipe created:");
     debug("Process %d opening erlpipein", getpid());
     erlpipeinfd = open(ERLPIPEIN);
     check(erlpipeinfd > 0, "Erlpipein: Failed to open pipe: %s\nSetup reader in second terminal\n tail -f erlpipe",ERLPIPEIN);
     debug("Erlpipe opened"); */
    }
    
   // save terminal settings
 
 
  //get baud rate from command line arguments
  baud = getbaud(baudrate);
  check(baud != B0, "Illegal baud rate"); 
  
  if(serial == TRUE){

  //open serial port
  serialfd = open(serialport, O_RDWR);
  check(serialfd > 0,"Can't open serial port\n Try dmesg | grep tty from shell \n");    
  debug("Opened serial port: %s",serialport);
 
  //set serial port to raw mode
  check(makeraw(serialfd)==0,"Failed to set serial port raw mode");
 //set baudrate serial
  check(setspeed(serialfd,baud)==0,"Failed to set baud rate");
  debug("Baud rate set to: %d", baudrate);
  }

  //set stdin to raw mode
  // check(makeraw(stdinfd)==0, "Failed to set stdin to raw mode");
  // debug("Not Entered raw mode:");

 
  
  //send acknowledge to erlang???

 /* Watch stdinfd and serialfd
       if input is available process then output
       Serial -> Erlang
       Erlang -> Serial
    */ 
  
  /*
  int numbytes;
  while(1){
  numbytes = read_erlang(erlmesg.mesg);
  check(numbytes > 0, "Read error from erlang");
	debug("Read %d bytes from Erlang", numbytes);
	write_serial(numbytes, erlmesg.mesg);
	debug("Wrote %d bytes to serial:", numbytes);
  }
  //main loop
  */
	
  {
    fd_set readfds;
    int maxfd;
    int is, numbytes;
    FD_ZERO(&readfds);
    
    maxfd = (stdinfd > serialfd) ? stdinfd : serialfd;
    maxfd = (maxfd > erlpipeinfd) ? maxfd : erlpipeinfd;

      
    while(1){
      if(serial){
      FD_SET(serialfd, &readfds);
      }
      
      if(pipedebug){
	  FD_SET(erlpipeinfd, &readfds);
	}

      FD_SET(stdinfd, &readfds);
      
      
      is = select(maxfd+1, &readfds, NULLFDS, NULLFDS, NULLTV);
      check(is>0,"Select error -"); 
      
      if (serial && FD_ISSET(serialfd,&readfds)){ // Serial porth ready to read
	FD_CLR(serialfd,&readfds);
	

	numbytes = read(serialfd, erlmesg.mesg, MAXMESG);
	check(numbytes > 0, "Read error from serial port");
	write_erlang(numbytes, erlmesg.mesg);

      }

      if (FD_ISSET(stdinfd,&readfds)){  //Stdin-Erlang ready to read
 	FD_CLR(stdinfd, &readfds);
	
        numbytes = read_erlang(erlmesg.mesg);
	check(numbytes > 0, "Read error from erlang");
	debug("Read %d bytes from Erlang", numbytes);
	write_serial(numbytes, erlmesg.mesg);
	debug("Wrote %d bytes to serial:", numbytes);

      }
      // input pipe
      /*
      if (pipedebug && (FD_ISSET(erlpipeinfd,&readfds)){  
	FD_CLR(erlpipeinfd, &readfds);

    }
      */
    }
  
}	  
  //hanldle input from erlang
  //handle input from serial port
  // restoreterminal(stdinfd,&oldstdin);

	//  tcsetattr(stdinfd,TCSANOW,&oldstdin);
    return 0;

 error:
    //restoreterminal(stdinfd,&oldstdin);
    //    tcsetattr(stdinfd,TCSANOW,&oldstdin);;
    debug("Restored terminal");
    exit(1);
   
    }
Exemplo n.º 21
0
// ------------------------------------------------------------------------------------------------
// Run the KISS virtual TNC
void kiss_run(serial_t *serial_parms, spi_parms_t *spi_parms, arguments_t *arguments)
// ------------------------------------------------------------------------------------------------
{
    static const size_t   bufsize = RADIO_BUFSIZE;
    uint32_t timeout_value;
    uint8_t  rx_buffer[bufsize], tx_buffer[bufsize];
    uint8_t  rtx_toggle; // 1:Tx, 0:Rx
    uint8_t  rx_trigger; 
    uint8_t  tx_trigger; 
    uint8_t  force_mode;
    int      rx_count, tx_count, byte_count, ret;
    uint64_t timestamp;
    struct timeval tp;  

    set_serial_parameters(serial_parms, arguments);
    init_radio_int(spi_parms, arguments);
    memset(rx_buffer, 0, bufsize);
    memset(tx_buffer, 0, bufsize);
    radio_flush_fifos(spi_parms);
    
    verbprintf(1, "Starting...\n");

    force_mode = 1;
    rtx_toggle = 0;
    rx_trigger = 0;
    tx_trigger = 0;
    rx_count = 0;
    tx_count = 0;
    radio_init_rx(spi_parms, arguments); // init for new packet to receive Rx
    radio_turn_rx(spi_parms);            // Turn Rx on

    while(1)
    {    
        byte_count = radio_receive_packet(spi_parms, arguments, &rx_buffer[rx_count]); // check if anything was received on radio link

        if (byte_count > 0)
        {
            rx_count += byte_count;  // Accumulate Rx
            
            gettimeofday(&tp, NULL);
            timestamp = tp.tv_sec * 1000000ULL + tp.tv_usec;
            timeout_value = arguments->tnc_radio_window;
            force_mode = (timeout_value == 0);

            if (rtx_toggle) // Tx to Rx transition
            {
                tx_trigger = 1; // Push Tx
            }
            else
            {
                tx_trigger = 0;
            }

            radio_init_rx(spi_parms, arguments); // Init for new packet to receive
            rtx_toggle = 0;
        }

        byte_count = read_serial(serial_parms, &tx_buffer[tx_count], bufsize - tx_count);

        if (byte_count > 0)
        {
            tx_count += byte_count;  // Accumulate Tx

            gettimeofday(&tp, NULL);
            timestamp = tp.tv_sec * 1000000ULL + tp.tv_usec;
            timeout_value = arguments->tnc_serial_window;
            force_mode = (timeout_value == 0);

            if (!rtx_toggle) // Rx to Tx transition
            {
                rx_trigger = 1;
            }
            else
            {
                rx_trigger = 0;
            }

            rtx_toggle = 1;
        }

        if ((rx_count > 0) && ((rx_trigger) || (force_mode))) // Send bytes received on air to serial
        {
            radio_wait_free();            // Make sure no radio operation is in progress
            radio_turn_idle(spi_parms);   // Inhibit radio operations
            verbprintf(2, "Received %d bytes\n", rx_count);
            ret = write_serial(serial_parms, rx_buffer, rx_count);
            verbprintf(2, "Sent %d bytes on serial\n", ret);
            radio_init_rx(spi_parms, arguments); // Init for new packet to receive Rx
            radio_turn_rx(spi_parms);            // Put back into Rx
            rx_count = 0;
            rx_trigger = 0;
        }

        if ((tx_count > 0) && ((tx_trigger) || (force_mode))) // Send bytes received on serial to air 
        {
            if (!kiss_command(tx_buffer))
            {
                radio_wait_free();            // Make sure no radio operation is in progress
                radio_turn_idle(spi_parms);   // Inhibit radio operations (should be superfluous since both Tx and Rx turn to IDLE after a packet has been processed)
                radio_flush_fifos(spi_parms); // Flush result of any Rx activity

                verbprintf(2, "%d bytes to send\n", tx_count);

                if (tnc_tx_keyup_delay)
                {
                    usleep(tnc_tx_keyup_delay);
                }

                radio_send_packet(spi_parms, arguments, tx_buffer, tx_count);

                radio_init_rx(spi_parms, arguments); // init for new packet to receive Rx
                radio_turn_rx(spi_parms);            // put back into Rx
            }

            tx_count = 0;
            tx_trigger = 0;            
        }

        if (!force_mode)
        {
            gettimeofday(&tp, NULL);

            if ((tp.tv_sec * 1000000ULL + tp.tv_usec) > timestamp + timeout_value)
            {
                force_mode = 1;
            }                        
        }

        radio_wait_a_bit(4);
    }
}
Exemplo n.º 22
0
static void emit(char ch)
{
    write_serial(ch);
}
Exemplo n.º 23
0
KINEMATIC_STATE line_generator(KINEMATIC_STATE current_state, KINEMATIC_STATE target_state, void (*step_motors)(bool, bool, bool, bool, bool, bool, bool, bool, int) ){

    float x1 = current_state.x;
    float y1 = current_state.y;
    float z1 = current_state.z;
    float x2 = target_state.x;
    float y2 = target_state.y;
    float z2 = target_state.z;

    float feed_rate_1 = current_state.feed_rate;
    float feed_rate_2 = target_state.feed_rate;

    float e1 = current_state.extrude_length;
    float e2 = target_state.extrude_length;


    float z1_error = current_state.z1_error;
    float z2_error = current_state.z2_error;
    float z3_error = current_state.z3_error;

    //motor control booleans
    bool z1_dir = false;
    bool z2_dir = false;
    bool z3_dir = false;
    bool e_dir =false;

    bool z1_step = false;
    bool z3_step = false;
    bool z2_step = false;
    bool e_step =false;


    //calulation values
    float x = 0.0f;
    float y = 0.0f;
    float z = 0.0f;
    float e = current_state.extrude_error;
    float zzz1 = 0.0f;
    float zzz3 = 0.0f;
    float zzz2 = 0.0f;
    float prev_zzz1 = 0.0f;
    float prev_zzz3 = 0.0f;
    float prev_zzz2 = 0.0f;
    float delta_x = x2 - x1;
    float delta_y = y2 - y1;
    float delta_z = z2 - z1;
    float delta_e = e2 - e1;
    float ratio = 0.0f;
    float distance = sqrtf(powf(delta_x,2) + powf(delta_y,2) + powf(delta_z,2));

    int num_steps = (int)((distance / LINE_STEP_SIZE) + 0.5f); //add 0.5 so the number is rounded rather than truncated when converted to int 

    if (feed_rate_1 == 0.0f){
        feed_rate_1 = 9000.0f;
    }
    int current_delay = (int)((float)Z_MM_STEP_SIZE / ((float)feed_rate_1/(float)FEED_RATE_CONSTANT));
    int target_delay = (int)((float)Z_MM_STEP_SIZE / ((float)feed_rate_2/(float)FEED_RATE_CONSTANT));
    float delay = (float)current_delay;
    float delay_delta = (float)target_delay - (float)current_delay;
    float delay_step = 0;
    //int current_delay = 400;

    

    //set the previous value to the start point
    xyz_to_zzz(x1, y1, z1, &prev_zzz1, &prev_zzz2, &prev_zzz3);

    float num_extrude_steps = (delta_e/EXTRUDE_PER_STEP);
    float extrude_steps_per_itter  =0;

    if (num_steps > 0){
        extrude_steps_per_itter = num_extrude_steps / (float)num_steps;
        delay_step = delay_delta/(float)num_steps;
    }else{
        extrude_steps_per_itter = 0;
    }


    char debug_buffer[128];
    sprintf(debug_buffer,"\tDELAY: %f\n", delay);
    write_serial(debug_buffer);
    sprintf(debug_buffer,"\tDELAY DELTA: %f\n", delay_delta);
    write_serial(debug_buffer);
    sprintf(debug_buffer,"\tDELAY STEP: %f\n", delay_step);
    write_serial(debug_buffer);


    int step = 0;
    for(step = 0; step < num_steps; step++){
        delay += delay_step;

        ratio = ((float)step + 1) / ((float)num_steps);

        x = x1 + ratio * delta_x;
        y = y1 + ratio * delta_y;
        z = z1 + ratio * delta_z;
        xyz_to_zzz(x, y, z, &zzz1, &zzz2, &zzz3);
        z1_error += prev_zzz1 - zzz1;
        z2_error += prev_zzz2 - zzz2;
        z3_error += prev_zzz3 - zzz3;

        e += extrude_steps_per_itter;
        if (e > 1.0f){
            e_dir = true;
            e_step = true;
            e = e - 1.0f;
        }else if(e < -1.0f){
            e_dir = false;
            e_step = true;
            e = e + 1.0f;
        }else{
            e_step = false;
        }


        if(z1_error >= Z_MM_STEP_SIZE){
            //step forward
            z1_error = z1_error - Z_MM_STEP_SIZE;
            z1_dir = false;
            z1_step = true;
        } 
        else if(z1_error <= -Z_MM_STEP_SIZE){
            //step backward
            z1_error = z1_error + Z_MM_STEP_SIZE;
            z1_dir = true;
            z1_step = true;
        }
        else{
        	z1_step = false;
        }

        if(z2_error >= Z_MM_STEP_SIZE){
            //step forward
            z2_error = z2_error - Z_MM_STEP_SIZE;
            z2_dir = false;
            z2_step = true;
        } 
        else if(z2_error <= -Z_MM_STEP_SIZE){
            //step backward
            z2_error = z2_error + Z_MM_STEP_SIZE;
            z2_dir = true;
            z2_step = true;
        }
        else{
        	z2_step = false;
        }

        if(z3_error >= Z_MM_STEP_SIZE){
            //step forward
            z3_error = z3_error - Z_MM_STEP_SIZE;
            z3_dir = false;
            z3_step = true;
        } 
        else if(z3_error <= -Z_MM_STEP_SIZE){
            //step backward
            z3_error = z3_error + Z_MM_STEP_SIZE;
            z3_dir = true;
            z3_step = true;
        }
        else{
        	z3_step = false;
        }

        step_motors(z1_dir, z1_step, z2_dir, z2_step, z3_dir, z3_step, e_dir, e_step, (int)delay);
        prev_zzz1 = zzz1;
        prev_zzz2 = zzz2;
        prev_zzz3 = zzz3;
        z1_step = false;
        z2_step = false;
        z3_step = false;
    }

    target_state.z1_error = z1_error;
    target_state.z2_error = z2_error;
    target_state.z3_error = z3_error;
    
    //if e gets broken, clear it otherwise extrusion will be messed up on next run
    if (e > 1.0f) e =0.0f;
    if (e < 1.0f) e =0.0f;
    target_state.extrude_error = e;

    return target_state;
}
Exemplo n.º 24
0
int main(void)
{
	setup();
	
	char response_buffer[128];

	bool resend = false;

	GCODE_STATE previous_command; //stores the previous gcode command
    GCODE_STATE current_command; //stores the next gcode command
    init_gcode_state(&previous_command);
    init_gcode_state(&current_command);

	KINEMATIC_STATE current;
	KINEMATIC_STATE goal;
	init_kinematic_state(&current);
	init_kinematic_state(&goal);

	test_extuder(4000,4000);	
	calibrate(6000,3000);
	
	while (1){
		//should echo back any string sent to board over serial
		usbd_poll(usbd_dev);
		if(strlen(usb_buf) > 0){

			//if it's a re-sent command we don't want to overwrite the previous
			//command with something broken
			if (resend == false){
				previous_command = current_command;
			}else{
				//clear the resend
				resend = false;
			}

			current_command = parse_gcode(usb_buf);
			clear_USB_buffer();			
			current_command.x_offset = previous_command.x_offset;
			current_command.y_offset = previous_command.y_offset;
			current_command.z_offset = previous_command.z_offset;
			current_command.extrude_offset = previous_command.extrude_offset;
			//current_command.feed_rate = previous_command.feed_rate;

			//Handle checksums
			if(current_command.checksum_set){
				if (current_command.checksum != current_command.calculated_checksum){
					//if things get buggered, send a resend command
					sprintf(response_buffer, "rs %i\n", current_command.line_number);
					write_serial(response_buffer);
                    resend = true;
                    continue;
                }
			}

			//Handle GCommands
			if (current_command.g_command_set){
				//G0 Rapid move
				//G1 Controlled move
				if (current_command.g_command == 0.0f || current_command.g_command == 1.0f){
					if (current_command.x_set) goal.x = current_command.x + current_command.x_offset;
					if (current_command.y_set) goal.y = current_command.y + current_command.y_offset;
					//remember - z is inverted
					if (current_command.z_set) goal.z = (-current_command.z) + current_command.z_offset;
					if (current_command.extrude_length_set) goal.extrude_length = current_command.extrude_length + current_command.extrude_offset;

					if(current_command.feed_rate_set){
						goal.feed_rate = current_command.feed_rate;
					}else{
						//current_command.feed_rate = previous_command.feed_rate;
						//goal.feed_rate = current_command.feed_rate;
					}
					current = line_generator(current, goal, step_motors);
				}
				//G92 Set Position (without move)
				if (current_command.g_command == 92.0f){
					if (current_command.x_set){
						current_command.x_offset = current.x - current_command.x;
					}
					if (current_command.y_set){
						current_command.y_offset = current.y - current_command.y;
					}
					if (current_command.z_set){
						//remember - z is inverted
						current_command.z_offset = current.z - (-current_command.z);
					}
					if (current_command.extrude_length_set){
						current_command.extrude_offset = current.extrude_length - current_command.extrude_length;
					}
				}
			}
			
			if (current_command.m_command_set){
				//TODO: Sort the spindle code out so that it can be rotated in both directions
				//for now it is only used to control an acuator which is off or on.
				//M3 Spindle ON clockwise
				if (current_command.m_command == 3.0f){
					set_spindle(true);
				}
				//M4 Spindle ON counter-clockwise
				if (current_command.m_command == 3.0f){
					set_spindle(true);
				}
				//M5 Spindle OFF
				if (current_command.m_command == 5.0f){
					set_spindle(false);
					
				}
				//M105 get extruder temperature
				if (current_command.m_command == 105.0f){
					sprintf(response_buffer, "ok\n T:%d", read_adc());
					write_serial_string(response_buffer);
					continue;
				}
			}

			//DO NOT PUT CODE BELOW THIS POINT UNLESS THE "continue"'s in the above code
			//are taken care of or not important.

			//use the repsponse buffer because fuckit
			sprintf(response_buffer, "ok\n");
			write_serial_string(response_buffer);
		}
	}
}
Exemplo n.º 25
0
/**
 * @brief openac main program
 *
 * @param argc number of arguments
 * @param argv pointer to the argument values
 */
int main(int argc, char **argv)
{
	certificate_t *attr_cert   = NULL;
	certificate_t *userCert   = NULL;
	certificate_t *signerCert = NULL;
	private_key_t *signerKey  = NULL;

	time_t notBefore = UNDEFINED_TIME;
	time_t notAfter  = UNDEFINED_TIME;
	time_t validity = 0;

	char *keyfile = NULL;
	char *certfile = NULL;
	char *usercertfile = NULL;
	char *outfile = NULL;
	char *groups = "";
	char buf[BUF_LEN];

	chunk_t passphrase = { buf, 0 };
	chunk_t serial = chunk_empty;
	chunk_t attr_chunk = chunk_empty;

	int status = 1;

	/* enable openac debugging hook */
	dbg = openac_dbg;

	passphrase.ptr[0] = '\0';

	openlog("openac", 0, LOG_AUTHPRIV);

	/* initialize library */
	atexit(library_deinit);
	if (!library_init(NULL))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "openac", argv[0]))
	{
		fprintf(stderr, "integrity check of openac failed\n");
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "openac.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	/* initialize optionsfrom */
	options_t *options = options_create();

	/* handle arguments */
	for (;;)
	{
		static const struct option long_opts[] = {
			/* name, has_arg, flag, val */
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "optionsfrom", required_argument, NULL, '+' },
			{ "quiet", no_argument, NULL, 'q' },
			{ "cert", required_argument, NULL, 'c' },
			{ "key", required_argument, NULL, 'k' },
			{ "password", required_argument, NULL, 'p' },
			{ "usercert", required_argument, NULL, 'u' },
			{ "groups", required_argument, NULL, 'g' },
			{ "days", required_argument, NULL, 'D' },
			{ "hours", required_argument, NULL, 'H' },
			{ "startdate", required_argument, NULL, 'S' },
			{ "enddate", required_argument, NULL, 'E' },
			{ "out", required_argument, NULL, 'o' },
			{ "debug", required_argument, NULL, 'd' },
			{ 0,0,0,0 }
		};

		int c = getopt_long(argc, argv, "hv+:qc:k:p;u:g:D:H:S:E:o:d:", long_opts, NULL);

		/* Note: "breaking" from case terminates loop */
		switch (c)
		{
			case EOF:	/* end of flags */
				break;

			case 0: /* long option already handled */
				continue;

			case ':':	/* diagnostic already printed by getopt_long */
			case '?':	/* diagnostic already printed by getopt_long */
			case 'h':	/* --help */
				usage(NULL);
				status = 1;
				goto end;

			case 'v':	/* --version */
				printf("openac (strongSwan %s)\n", VERSION);
				status = 0;
				goto end;

			case '+':	/* --optionsfrom <filename> */
				{
					char path[BUF_LEN];

					if (*optarg == '/')	/* absolute pathname */
					{
						strncpy(path, optarg, BUF_LEN);
						path[BUF_LEN-1] = '\0';
					}
					else			/* relative pathname */
					{
						snprintf(path, BUF_LEN, "%s/%s", OPENAC_PATH, optarg);
					}
					if (!options->from(options, path, &argc, &argv, optind))
					{
						status = 1;
						goto end;
					}
				}
				continue;

			case 'q':	/* --quiet */
				stderr_quiet = TRUE;
				continue;

			case 'c':	/* --cert */
				certfile = optarg;
				continue;

			case 'k':	/* --key */
				keyfile = optarg;
				continue;

			case 'p':	/* --key */
				if (strlen(optarg) >= BUF_LEN)
				{
					usage("passphrase too long");
					goto end;
				}
				strncpy(passphrase.ptr, optarg, BUF_LEN);
				passphrase.len = min(strlen(optarg), BUF_LEN);
				continue;

			case 'u':	/* --usercert */
				usercertfile = optarg;
				continue;

			case 'g':	/* --groups */
				groups = optarg;
				continue;

			case 'D':	/* --days */
				if (optarg == NULL || !isdigit(optarg[0]))
				{
					usage("missing number of days");
					goto end;
				}
				else
				{
					char *endptr;
					long days = strtol(optarg, &endptr, 0);

					if (*endptr != '\0' || endptr == optarg || days <= 0)
					{
						usage("<days> must be a positive number");
						goto end;
					}
					validity += 24*3600*days;
				}
				continue;

			case 'H':	/* --hours */
				if (optarg == NULL || !isdigit(optarg[0]))
				{
					usage("missing number of hours");
					goto end;
				}
				else
				{
					char *endptr;
					long hours = strtol(optarg, &endptr, 0);

					if (*endptr != '\0' || endptr == optarg || hours <= 0)
					{
						usage("<hours> must be a positive number");
						goto end;
					}
					validity += 3600*hours;
				}
				continue;

			case 'S':	/* --startdate */
				if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
				{
					usage("date format must be YYYYMMDDHHMMSSZ");
					goto end;
				}
				else
				{
					chunk_t date = { optarg, 15 };

					notBefore = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
				}
				continue;

			case 'E':	/* --enddate */
				if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
				{
					usage("date format must be YYYYMMDDHHMMSSZ");
					goto end;
				}
				else
				{
					chunk_t date = { optarg, 15 };
					notAfter = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
				}
				continue;

			case 'o':	/* --out */
				outfile = optarg;
				continue;

			case 'd':	/* --debug */
				debug_level = atoi(optarg);
				continue;

			default:
				usage("");
				status = 0;
				goto end;
		}
		/* break from loop */
		break;
	}

	if (optind != argc)
	{
		usage("unexpected argument");
		goto end;
	}

	DBG1(DBG_LIB, "starting openac (strongSwan Version %s)", VERSION);

	/* load the signer's RSA private key */
	if (keyfile != NULL)
	{
		mem_cred_t *mem;
		shared_key_t *shared;

		mem = mem_cred_create();
		lib->credmgr->add_set(lib->credmgr, &mem->set);
		shared = shared_key_create(SHARED_PRIVATE_KEY_PASS,
								   chunk_clone(passphrase));
		mem->add_shared(mem, shared, NULL);
		signerKey = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
									   BUILD_FROM_FILE, keyfile,
									   BUILD_END);
		lib->credmgr->remove_set(lib->credmgr, &mem->set);
		mem->destroy(mem);
		if (signerKey == NULL)
		{
			goto end;
		}
		DBG1(DBG_LIB, "  loaded private key file '%s'", keyfile);
	}

	/* load the signer's X.509 certificate */
	if (certfile != NULL)
	{
		signerCert = lib->creds->create(lib->creds,
										CRED_CERTIFICATE, CERT_X509,
										BUILD_FROM_FILE, certfile,
										BUILD_END);
		if (signerCert == NULL)
		{
			goto end;
		}
	}

	/* load the users's X.509 certificate */
	if (usercertfile != NULL)
	{
		userCert = lib->creds->create(lib->creds,
									  CRED_CERTIFICATE, CERT_X509,
									  BUILD_FROM_FILE, usercertfile,
									  BUILD_END);
		if (userCert == NULL)
		{
			goto end;
		}
	}

	/* compute validity interval */
	validity = (validity)? validity : DEFAULT_VALIDITY;
	notBefore = (notBefore == UNDEFINED_TIME) ? time(NULL) : notBefore;
	notAfter =  (notAfter  == UNDEFINED_TIME) ? time(NULL) + validity : notAfter;

	/* build and parse attribute certificate */
	if (userCert != NULL && signerCert != NULL && signerKey != NULL &&
		outfile != NULL)
	{
		/* read the serial number and increment it by one */
		serial = read_serial();

		attr_cert = lib->creds->create(lib->creds,
							CRED_CERTIFICATE, CERT_X509_AC,
							BUILD_CERT, userCert,
							BUILD_NOT_BEFORE_TIME, notBefore,
							BUILD_NOT_AFTER_TIME, notAfter,
							BUILD_SERIAL, serial,
							BUILD_IETF_GROUP_ATTR, groups,
							BUILD_SIGNING_CERT, signerCert,
							BUILD_SIGNING_KEY, signerKey,
							BUILD_END);
		if (!attr_cert)
		{
			goto end;
		}

		/* write the attribute certificate to file */
		if (attr_cert->get_encoding(attr_cert, CERT_ASN1_DER, &attr_chunk))
		{
			if (chunk_write(attr_chunk, outfile, 0022, TRUE))
			{
				DBG1(DBG_APP, "  written attribute cert file '%s' (%d bytes)",
						 outfile, attr_chunk.len);
				write_serial(serial);
				status = 0;
			}
			else
			{
				DBG1(DBG_APP, "  writing attribute cert file '%s' failed: %s",
					 outfile, strerror(errno));
			}
		}
	}
	else
	{
		usage("some of the mandatory parameters --usercert --cert --key --out "
			  "are missing");
	}

end:
	/* delete all dynamically allocated objects */
	DESTROY_IF(signerKey);
	DESTROY_IF(signerCert);
	DESTROY_IF(userCert);
	DESTROY_IF(attr_cert);
	free(attr_chunk.ptr);
	free(serial.ptr);
	closelog();
	dbg = dbg_default;
	options->destroy(options);
	exit(status);
}
Exemplo n.º 26
0
void pm_write_serial(com32sys_t *regs)
{
	write_serial(regs->eax.b[0]);
}