Beispiel #1
0
int main(int argc, char *argv[])
{
	int serial_dev;
	int ret;
	char data[256];

	if (argc < 2) {
		fprintf(stderr, "Please specify serial device to use \r\n");
		return -1;
	}
	
	printf("Serial device to open: %s \r\n", argv[1]);
	
	serial_dev = serial_open(argv[1]);
	if (serial_dev < 0) {
		fprintf(stderr, "Unable to open serial device: %s: %s\r\n", argv[1], strerror(errno));
		return -1;
	}
	
	if (serial_setup(serial_dev, 115200)) {
		fprintf(stderr, "Unable to setup serial device: %s: %s\r\n", argv[1], strerror(errno));
	}

	while (1) {
		serial_write(serial_dev, "Testing");
		ret = serial_read(serial_dev, data, sizeof(data));
		if (ret <= 0) {
			printf("No data available \r\n");
		} else {
			printf("Serial data received:\r\n");
			printf("%s\r\n", data);
		}
		sleep(1);
	}
}
static void
sis_85c471_write(uint16_t port, uint8_t val, void *priv)
{
    sis_85c471_t *dev = (sis_85c471_t *) priv;
    uint8_t index = (port & 1) ? 0 : 1;
    uint8_t valxor;

    if (index) {
	if ((val >= 0x50) && (val <= 0x76))
		dev->cur_reg = val;
	return;
    } else {
	if ((dev->cur_reg < 0x50) || (dev->cur_reg > 0x76))
		return;
	valxor = val ^ dev->regs[dev->cur_reg - 0x50];
	/* Writes to 0x52 are blocked as otherwise, large hard disks don't read correctly. */
	if (dev->cur_reg != 0x52)
		dev->regs[dev->cur_reg - 0x50] = val;
    }

    switch(dev->cur_reg) {
	case 0x73:
		if (valxor & 0x40) {
			ide_pri_disable();
			if (val & 0x40)
				ide_pri_enable();
		}
		if (valxor & 0x20) {
			serial_remove(dev->uart[0]);
			serial_remove(dev->uart[1]);
			if (val & 0x20) {
				serial_setup(dev->uart[0], SERIAL1_ADDR, SERIAL1_IRQ);
				serial_setup(dev->uart[0], SERIAL2_ADDR, SERIAL2_IRQ);
			}
		}
		if (valxor & 0x10) {
			lpt1_remove();
			if (val & 0x10)
				lpt1_init(0x378);
		}
		break;
    }

    dev->cur_reg = 0;
}
Beispiel #3
0
void __init
brcm_setup(void)
{
	char *value;

	/* Get global SB handle */
	sih = si_kattach(SI_OSH);

	/* Initialize clocks and interrupts */
	si_mips_init(sih, SBMIPS_VIRTIRQ_BASE);

	if (BCM330X(current_cpu_data.processor_id) &&
		(read_c0_diag() & BRCM_PFC_AVAIL)) {
		/* 
		 * Now that the sih is inited set the  proper PFC value 
		 */	
		printk("Setting the PFC to its default value\n");
		enable_pfc(PFC_AUTO);
	}


#ifdef CONFIG_SERIAL_CORE
	/* Initialize UARTs */
	serial_setup(sih);
#endif /* CONFIG_SERIAL_CORE */

	/* Override default command line arguments */
	value = nvram_get("kernel_args");
	if (value && strlen(value) && strncmp(value, "empty", 5))
		strncpy(arcs_cmdline, value, sizeof(arcs_cmdline));


	if ((lanports_enable = getgpiopin(NULL, "lanports_enable", GPIO_PIN_NOTDEFINED)) ==
		GPIO_PIN_NOTDEFINED)
		lanports_enable = 0;

	/* wombo reset */
	if ((wombo_reset = getgpiopin(NULL, "wombo_reset", GPIO_PIN_NOTDEFINED)) !=
	    GPIO_PIN_NOTDEFINED) {
		int reset = 1 << wombo_reset;

		printk("wombo_reset set to gpio %d\n", wombo_reset);

		si_gpioout(sih, reset, 0, GPIO_DRV_PRIORITY);
		si_gpioouten(sih, reset, reset, GPIO_DRV_PRIORITY);
		bcm_mdelay(10);

		si_gpioout(sih, reset, reset, GPIO_DRV_PRIORITY);
		bcm_mdelay(20);
	}

	/* Generic setup */
	_machine_restart = bcm947xx_machine_restart;
	_machine_halt = bcm947xx_machine_halt;
	pm_power_off = bcm947xx_machine_halt;

}
void x_misc_setup(void)
{
    random_setup();
    loadbang_setup();
    namecanvas_setup();
    serial_setup();
    cputime_setup();
    realtime_setup();
}
static void
wd76c10_write(uint16_t port, uint16_t val, void *priv)
{
        switch (port)
        {
                case 0x0092:
                wd76c10_0092 = val;
                        
                mem_a20_alt = val & 2;
                mem_a20_recalc();
                break;
                
                case 0x2072:
                wd76c10_2072 = val;
                
                serial_remove(wd76c10_uart[0]);
                if (!(val & 0x10))
                {
                        switch ((val >> 5) & 7)
                        {
                                case 1: serial_setup(wd76c10_uart[0], 0x3f8, 4); break;
                                case 2: serial_setup(wd76c10_uart[0], 0x2f8, 4); break;
                                case 3: serial_setup(wd76c10_uart[0], 0x3e8, 4); break;
                                case 4: serial_setup(wd76c10_uart[0], 0x2e8, 4); break;
                                default: break;
                        }
                }
                serial_remove(wd76c10_uart[1]);
                if (!(val & 0x01))
                {
                        switch ((val >> 1) & 7)
                        {
                                case 1: serial_setup(wd76c10_uart[1], 0x3f8, 3); break;
                                case 2: serial_setup(wd76c10_uart[1], 0x2f8, 3); break;
                                case 3: serial_setup(wd76c10_uart[1], 0x3e8, 3); break;
                                case 4: serial_setup(wd76c10_uart[1], 0x2e8, 3); break;
                                default: break;
                        }
                }
                break;

                case 0x2872:
                wd76c10_2872 = val;
                
                fdc_remove(wd76c10_fdc);
                if (!(val & 1))
                   fdc_set_base(wd76c10_fdc, 0x03f0);
                break;
                
                case 0x5872:
                wd76c10_5872 = val;
                break;
        }
}
Beispiel #6
0
// Initialize hardware devices
void
device_hardware_setup(void)
{
    usb_setup();
    ps2port_setup();
    block_setup();
    lpt_setup();
    serial_setup();
    cbfs_payload_setup();
}
void setup(void)
{
    led_setup();

    serial_setup();
    interrupt_setup();
    i2c_setup();

    INTCON3bits.INT2IF = 0;

    //Print a welcome message in case someone plugs it up
    printf("Welcome to the RVAsec Badge!\n\r\n\r");
}
Beispiel #8
0
static int
pcr_set_comm_speed(RIG *rig, int rate)
{
	int err;
	const char *rate_cmd;

	/* limit maximum rate */
	if (rate > 38400)
		rate = 38400;

	switch (rate) {
	case 300:
		rate_cmd = "G100";
		break;
	case 1200:
		rate_cmd = "G101";
		break;
	case 2400:
		rate_cmd = "G102";
		break;
	case 9600:
	default:
		rate_cmd = "G103";
		break;
	case 19200:
		rate_cmd = "G104";
		break;
	case 38400:
		rate_cmd = "G105";
		break;
	}

	rig_debug(RIG_DEBUG_VERBOSE, "%s: setting speed to %d with %s\n",
		__func__, rate, rate_cmd);

	/* the answer will be sent at the new baudrate,
	 * so we do not use pcr_transaction
	 */
	err = pcr_send(rig, rate_cmd);
	if (err != RIG_OK)
		return err;

	rig->state.rigport.parm.serial.rate = rate;
	serial_setup(&rig->state.rigport);

	/* check if the pcr is still alive */
	return pcr_check_ok(rig);
}
void configure_system() {
	    
	kill_interrupts();	// turn off interrupts just in case

	turn_analog_inputs_off();	// kill those pesky analogue inputs
	
	
	serial_setup(BRGH_HIGH_SPEED, SPBRG_19200);

	turn_peripheral_ints_on();
	turn_global_ints_on();

	draw_setup_io();
	draw_init();

}
Beispiel #10
0
int main(void)
{
  volatile int is_done = 0;

  osc_setup();
  int_setup();
  serial_setup();
  m600_setup();

  while (!is_done)
    {
      m600_request_t req;
      m600_reply_t rep;

      if (m600_read_request(&req) == -1)
	continue ;

      switch (req)
	{
	case M600_REQ_READ_CARD:
	  {
	    toggle_led(0);

	    rep.alarms = m600_read_card(rep.card_data);
	    break;
	  }

	case M600_REQ_READ_ALARMS:
	  {
	    toggle_led(1);

	    rep.alarms = m600_read_alarms();
	    break;
	  }

	default:
	  {
	    break;
	  }
	}

      m600_write_reply(&rep);
    }

  return 0;
}
Beispiel #11
0
// Initialize hardware devices
static void
init_hw(void)
{
    usb_setup();
    ps2port_setup();
    lpt_setup();
    serial_setup();

    floppy_setup();
    ata_setup();
    ahci_setup();
    cbfs_payload_setup();
    ramdisk_setup();
    virtio_blk_setup();
    virtio_scsi_setup();
    lsi_scsi_setup();
}
Beispiel #12
0
void configure_system() {
	    
	kill_interrupts();	// turn off interrupts just in case

	turn_analog_inputs_off();	// kill those pesky analogue inputs
	
	#ifdef USB_SERIAL_DEBUG 
		serial_setup(BRGH_HIGH_SPEED, SPBRG_57600);
	#endif
	
	usb_cdc_setup();

	usb_setup();
	
	turn_usb_ints_on();
	turn_peripheral_ints_on();
	turn_global_ints_on();
}
Beispiel #13
0
struct ols_t *OLS_Init(char *port, unsigned long speed)
{
	int fd;
	int ret;
	struct ols_t *ols;

	fd = serial_open(port);
	if (fd < 0) {
		fprintf(stderr, "Unable to open port '%s' \n", port);
		return NULL;
	}

	ret = serial_setup(fd, speed);
	if (ret) {
		fprintf(stderr, "Unable to set serial port parameters \n");
		return NULL;
	}

	ols = malloc(sizeof(struct ols_t));
	if (ols == NULL) {
		fprintf(stderr, "Error allocating memory \n");
		return NULL;
	}

	ols->fd = fd;
	ols->verbose = 0;
	ols->flash = NULL;

	ret = OLS_GetID(ols);
	if (ret) {
		fprintf(stderr, "Unable to read ID \n");
		free(ols);
		return NULL;
	}

	ret = OLS_GetFlashID(ols);
	if (ret) {
		fprintf(stderr, "Unable to read Flash ID \n");
		free(ols);
		return NULL;
	}

	return ols;
}
Beispiel #14
0
void configure_system() {
	    
	kill_interrupts();	// turn off interrupts just in case

	turn_analog_inputs_off();	// kill those pesky analogue inputs
	
	lcd_setup();	// Setup the pins (output / input)
	lcd_init ();	// Configure chip ready for display

	sure_2416_setup();
	
	serial_setup(BRGH_HIGH_SPEED, SPBRG_19200);

	turn_peripheral_ints_on();
	turn_global_ints_on();

	// Currently this does debug, so do it after the serial port is up
	sure_2416_init();
}
Beispiel #15
0
int main( int argc, char **argv )
{
    int count;

    serial_setup();
    count = sensor_setup();
    printf( "%d sensors found\n", count );

    if( !count )
        return( 0 );

    while( 1 )
    {
        sensor_poll();
        sleep(5);
    }

    return( 0 );
}
Beispiel #16
0
// Initialize hardware devices
void
device_hardware_setup(void)
{
    usb_setup();
    ps2port_setup();
    lpt_setup();
    serial_setup();

    floppy_setup();
    ata_setup();
    ahci_setup();
    cbfs_payload_setup();
    ramdisk_setup();
    virtio_blk_setup();
    virtio_scsi_setup();
    lsi_scsi_setup();
    esp_scsi_setup();
    megasas_setup();
    pvscsi_setup();
}
void main (void)
{
unsigned char serial_rx_byte;

	//I/O's
	PORTB = 0x30;
	TRISB = 0x31;	

#if 0
	
	INTCONbits.GIE=0;
	INTCONbits.PEIE=1;
	INTCONbits.INT0IE=1;
	INTCONbits.INT0IF=0;

	/* Inicializa enquanto as interrupções estão desabilitadas.  */
	bt1=0;
	
	INTCONbits.GIE=1;
	
#endif

	serial_setup();

	// TODO: USER CODE!!
    while(1)
    {
		if (PIR1bits.RC1IF==1)
		{
			serial_rx_byte=RCREG1;
			if (bt1==0)
				bt1=1;
			else
				bt1=0;
		}
		if (bt1==1)
			PIN_LED1=LED_ACIONADO;
		else
			PIN_LED1=LED_DESACIONADO;
	}
}
Beispiel #18
0
int main(int argc, char *argv[])
{
	int serverfd = -1;
	serial_control_t ttyctl;

	printf("\n");
	program_printf("version %s\n", VERSION);

	parse_command_line(argc, argv);

	forward_test_case(0);

	ttyfd = serial_open(tty_name);
	memset(&ttyctl, 0, sizeof(serial_control_t));
	ttyctl.fd = ttyfd;

	if (access(DEFAULT_TTY_CONFIG, F_OK) != 0) {
		/* config file not exsit, just create it */		
		create_config_file(DEFAULT_TTY_CONFIG);
	}

	read_config_file(&ttyctl);
	if (serial_setup(&ttyctl) != EXIT_SUCCESS) {
		error_printf("serial_control error\n");
		return EXIT_FAILURE;
	}

	forward_test_case(1);

	if (forward_create_server(&serverfd) != 0) {
		error_printf("forward_create_server error\n");
		return EXIT_FAILURE;
	}

	if (forward_accept_client(serverfd, ttyfd) != 0) {
		error_printf("forward_accept_client error\n");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
Beispiel #19
0
void main_first_test(int argc, char* argv[])
{
  uint8_t buffer[1024];
  UNUSED(argc);
  UNUSED(argv);  
  
  int32_t fd, nbRead, nbWrite;
  fd = serial_setup(argv[1], 9600, SERIAL_PARITY_OFF, SERIAL_RTSCTS_OFF, SERIAL_STOPNB_1);
  if (fd >= 0)
  {
    fprintf(stdout, "serial correctly configurated fd = %d\n", fd);
    nbWrite = serial_write(fd, (uint8_t*) "+++", 3);
    fprintf(stdout, "nbWrite = %d\n", nbWrite);

    fd_set rfs;
    struct timeval waitTime;
    waitTime.tv_sec = 2;
    waitTime.tv_usec = 0;
    FD_ZERO(&rfs);
    FD_SET(fd, &rfs);
    //retry:
    if ((select(fd + 1, &rfs, NULL, NULL, &waitTime) > 0))
    {
      if (FD_ISSET(fd, &rfs))
      {
        nbRead = read(fd, buffer, 1024);
        while (nbRead > 0)
        {
          fprintf(stdout, "nbRead = %d\n", nbRead);
          for (int i = 0; i < nbRead; i++)
          {
            fprintf(stdout, "0x%x (%c) ", buffer[i], buffer[i]);
          }
          fprintf(stdout, "\n");
          nbRead = read(fd, buffer, 1024);
          //   goto retry;
        }
      }
    }
  }  
}
Beispiel #20
0
void test_serial(const char *arg) {
    logmsgf("IRQs state = 0x%x\n", (uint)irq_get_mask());

    uint8_t saved_color = vcsa_get_attribute(VIDEOMEM_VCSA);

    k_printf("Use <Esc> to quit, <Del> for register info, <F1> to toggle char/code mode\n");
    serial_setup();

    //poll_serial();

    poll_exit = false;
    serial_set_on_receive(on_serial_received);
    kbd_set_onpress(on_press);

    while (!poll_exit) cpu_halt();

    kbd_set_onpress(null);
    serial_set_on_receive(null);

    vcsa_set_attribute(0, saved_color);
}
Beispiel #21
0
int main(void)
{
  uint32_t msize;
  uint32_t rsize;

#ifdef DAC_USE_VREF
  vref_setup();
#endif /* DAC_USE_VREF */

  dac_setup();
  dac_enable();

  serial_setup();

  msize = 0;

  while (1)
  {
    rsize = serial_get_rsize();
    if (rsize > (sizeof(pload_msg) - msize)) rsize = sizeof(pload_msg) - msize;
    if (rsize == 0) continue ;

    /* stop the generator if active */

    if (pload_flags & PLOAD_FLAG_IS_STARTED)
    {
#if 0 /* DEBUG */
      SERIAL_WRITE_STRING("stopping\r\n");
#endif /* DEBUG */

      pload_flags &= ~PLOAD_FLAG_IS_STARTED;
      pit_stop(1);
    }

    serial_read((uint8_t*)&pload_msg + msize, rsize);
    msize += rsize;
    if (msize != sizeof(pload_msg)) continue ;

    /* new message */
    msize = 0;

    if (pload_msg.op != PLOAD_MSG_OP_SET_STEPS) continue ;

    /* start the generator */

    if ((pload_flags & PLOAD_FLAG_IS_STARTED) == 0)
    {
#if 0 /* DEBUG */
      SERIAL_WRITE_STRING("starting\r\n");
#endif /* DEBUG */

      pload_step_index = 0;
      pload_tick_count = (uint32_t)pload_msg.u.steps.arg1[0];
      pload_repeat_index = 0;
      pload_current = (int32_t)pload_msg.u.steps.arg0[0];

      dac_set(ma_to_dac((uint32_t)pload_current));

#if 0 /* DEBUG */
      SERIAL_WRITE_STRING("dac_set:");
      serial_write(uint32_to_string((uint32_t)pload_current), 8);
      SERIAL_WRITE_STRING("\r\n");
#endif /* DEBUG */

      pload_flags |= PLOAD_FLAG_IS_STARTED;
      pit_start(1, F_BUS / PLOAD_CLOCK_FREQ);
    }
  }

  return 0;
}
int main(int argc, char** argv)
{
  int opt;
  char buffer[256] = {0},IRCode;
  char version[4];
  int fd;
  int res,c;
  int flag=0,firsttime=0;
  char *param_port = NULL;
  char *param_speed = NULL;
  int j,repeat_test =1;   // repeat test several times
    printf("-------------------------------------------------------------------------\n");

    printf("\n");
    printf(" IR TOY SELF TEST utility v0.1 (CC-0)\n");
    printf(" http://dangerousprototypes.com\n");
    printf("\n");
    printf("-------------------------------------------------------------------------\n");



if (argc <= 1)  {

		print_usage(argv[0]);
		exit(-1);
	}

while ((opt = getopt(argc, argv, "ms:d:")) != -1) {
       // printf("%c  \n",opt);
		switch (opt) {

			case 'd':  // device   eg. com1 com12 etc
				if ( param_port != NULL){
					printf(" Device/PORT error!\n");
					exit(-1);
				}
				param_port = strdup(optarg);
				break;
            case 's':
				if (param_speed != NULL) {
					printf(" Speed should be set: eg  115200 \n");
					exit(-1);
				}
				param_speed = strdup(optarg);

				break;
 			case 'm':    //modem debugging for testing
                   modem =TRUE;   // enable modem mode
				break;

			default:
				printf(" Invalid argument %c", opt);
				print_usage(argv[0]);
				//exit(-1);
				break;
		}
	}

 //defaults here --------------
    if (param_port==NULL){
        printf(" No serial port set\n");
		print_usage(argv[0]);
		exit(-1);
    }

    if (param_speed==NULL)
          param_speed=strdup("115200");




    printf("\n Parameters used: Device = %s,  Speed = %s\n\n",param_port,param_speed);


    flag=0;
    //
    // Loop and repeat test as needed for manufacturing
    //
    //TO DO: add loop here
     printf(" Press Esc to exit, any other key to start the self-test \n\n");
    while(1){

     //pause for space, or ESC to exit

     if (flag==1)
     {
     printf("\n--------------------- Starting a new IR Toy Self Test-------------------------\n");

     }

     printf("\n Hold the IR Toy very close to something white for the self-test \n");

	 while(1){
        Sleep(1);
        if (flag==1){
            flag=0;   //has flag been set to just go testing?
            break;    // proceed with test
         }
        if(kbhit()){
           c = getch();
           if(c == 27){
                printf("\n Esc key hit, stopping...\n");
                printf(" (Bye for now!)\n");
                exit(-1);
            }else {//make space only
                printf("\n Starting test! \n");
                break;
            }
        }
    }


    //
    // Open serial port
    //

	printf(" Opening IR Toy on %s at %sbps...\n", param_port, param_speed);
	fd = serial_open(param_port);
	if (fd < 0) {
		fprintf(stderr, " Error opening serial port\n");
		return -1;
	}

    //
	// Enter binary mode, then enter a protocol mode
	//
	serial_setup(fd,(speed_t) param_speed);


    printf(" Starting IR TOY self-test...\n");


    serial_write( fd, "\x00", 1);

    printf(" Getting self-test result...\n");
    //Sleep(1000);  // how long to wait to get response?
    //res= serial_read(fd, buffer, sizeof(buffer)); //put reply to buffer ...
    //printf("%s\n",buffer);
    serial_write( fd, "v", 1);       //sent as 'v','\0'    //ask version
    res= serial_read(fd, version, 4);  //get version

    if (res>0){
        printf(" IR Toy version: %s\n",buffer);
    }
    else{
        fprintf(stderr," Error: IR Toy doesn't have a reply for version command\n ");
    }
    //    loop here if needed to send test commnd repeatedly
    for (j=0;j<repeat_test;j++)
    {
       printf("Test no: %i of %i \n",j+1,repeat_test);

    serial_write( fd, "t", 1);   // send test command

    Sleep(1000);
    res= serial_read(fd, buffer, sizeof(buffer));  // get reply


    if (res >0){   //we have a replay
          printf(" IR Toy Self Test Reply: %s\n",buffer);
           printf(" ");
           for(c=0; c<res; c++){
               IRCode=buffer[c];
               printf("%c", IRCode);
            }
            printf("\n");

            if (strncmp(version, buffer, 4)==0) {    // get version
                //get and display version, test is good
                printf("\n\n Test passed! OK! :) \n\n");
            }else{
                printf("\n\n ERROR: test FAILED! :( \n\n");
               //  FAI1 - IR receiver error (error bit 0)
              //  FAI2 - IR LED error (error bit 1)
              //  FAI3 - both errors (error bits 0 & 1)
                // c has character value '1'...'3'
               switch (buffer[3]){
                  case '1':
                          fprintf(stderr," FAI1 - IR receiver error \n ");
                          break;
                  case '2':
                          fprintf(stderr," FAI2 - FAI2 - IR LED error\n ");
                          break;
                  case '3':
                          fprintf(stderr," FAI3 - IR receiver error  and FAI2 - IR LED error\n ");
                          break;
                  default:
                         fprintf(stderr," Invalid response from IR Toy\n ");
                          break;
                } //switch
            }  // fail code

        }else{ // if (res >0)
             printf(" IR Toy did not reply anything.. Please check connections. \n");
        }

    }
       if (firsttime==0){    // run here once and don't say again the next time
        printf(" Press any key to continue...\n");
        firsttime=1;
        while(1){
            Sleep(1);
            if(kbhit()){
               c = getch();
                break;
            }
        }
       }

       //close port so they can attach the next Bus Pirate
        serial_close(fd);


        //TODO: Loop back to pause after this
        printf("\n Connect another IR Toy  and press any key to start the self-test again \n");
        printf(" Or hit ESC key to stop and end the test.\n");

        while(1){
        Sleep(1);
        if(kbhit()){
           c = getch();
           if(c == 27){
                printf("\n Esc key hit, stopping...\n");
                printf(" (Bye for now!)\n");
                exit(-1);
            }else {//make space only
                flag=1;  //flag to tell the other loop to bypass another keypress

                break;
            }
        }
    }

  } // while (1)
#define FREE(x) if(x) free(x);
	FREE(param_port);
	FREE(param_speed);
    return 0;
}  //main
int main(int argc, char* argv[]) {
	int ret = 1;
	parser_err_t perr;
	
	(void) signal(SIGINT, caught_sigint);

	printf("stm32flash - http://stm32flash.googlecode.com/\n\n");
	if (parse_options(argc, argv) != 0)
		goto close;

	if (wr) {
		/* first try hex */
		if (!force_binary) {
			parser = &PARSER_HEX;
			p_st = parser->init();
			if (!p_st) {
				fprintf(stderr, "%s Parser failed to initialize\n", parser->name);
				goto close;
			}
		}

		if (force_binary || (perr = parser->open(p_st, filename, 0)) != PARSER_ERR_OK) {
			if (force_binary || perr == PARSER_ERR_INVALID_FILE) {
				if (!force_binary) {
					parser->close(p_st);
					p_st = NULL;
				}

				/* now try binary */
				parser = &PARSER_BINARY;
				p_st = parser->init();
				if (!p_st) {
					fprintf(stderr, "%s Parser failed to initialize\n", parser->name);
					goto close;
				}
				perr = parser->open(p_st, filename, 0);
			}

			/* if still have an error, fail */
			if (perr != PARSER_ERR_OK) {
				fprintf(stderr, "%s ERROR: %s\n", parser->name, parser_errstr(perr));
				if (perr == PARSER_ERR_SYSTEM) perror(filename);
				goto close;
			}
		}

		fprintf(stdout, "Using Parser : %s\n", parser->name);
	} else {
		parser = &PARSER_BINARY;
		p_st = parser->init();
		if (!p_st) {
			fprintf(stderr, "%s Parser failed to initialize\n", parser->name);
			goto close;
		}
	}

	serial = serial_open(device);
	if (!serial) {
		perror(device);
		goto close;
	}

	if (serial_setup(
		serial,
		baudRate,
		SERIAL_BITS_8,
		SERIAL_PARITY_EVEN,
		SERIAL_STOPBIT_1
	) != SERIAL_ERR_OK) {
		perror(device);
		goto close;
	}

	printf("Serial Config: %s\n", serial_get_setup_str(serial));
	if (!(stm = stm32_init(serial, init_flag))) goto close;

	printf("Version      : 0x%02x\n", stm->bl_version);
	printf("Option 1     : 0x%02x\n", stm->option1);
	printf("Option 2     : 0x%02x\n", stm->option2);
	printf("Device ID    : 0x%04x (%s)\n", stm->pid, stm->dev->name);
	printf("RAM          : %dKiB  (%db reserved by bootloader)\n", (stm->dev->ram_end - 0x20000000) / 1024, stm->dev->ram_start - 0x20000000);
	printf("Flash        : %dKiB (sector size: %dx%d)\n", (stm->dev->fl_end - stm->dev->fl_start ) / 1024, stm->dev->fl_pps, stm->dev->fl_ps);
	printf("Option RAM   : %db\n", stm->dev->opt_end - stm->dev->opt_start);
	printf("System RAM   : %dKiB\n", (stm->dev->mem_end - stm->dev->mem_start) / 1024);

	uint8_t		buffer[256];
	uint32_t	addr;
	unsigned int	len;
	int		failed = 0;

	if (rd) {
		printf("\n");

		if ((perr = parser->open(p_st, filename, 1)) != PARSER_ERR_OK) {
			fprintf(stderr, "%s ERROR: %s\n", parser->name, parser_errstr(perr));
			if (perr == PARSER_ERR_SYSTEM) perror(filename);
			goto close;
		}

		addr = stm->dev->fl_start + (spage * stm->dev->fl_ps);
		fflush(stdout);
		fprintf(stdout, "\033[?25l");
		while(addr < stm->dev->fl_end) {
			uint32_t left	= stm->dev->fl_end - addr;
			len		= sizeof(buffer) > left ? left : sizeof(buffer);
			if (!stm32_read_memory(stm, addr, buffer, len)) {
				fprintf(stderr, "Failed to read memory at address 0x%08x, target write-protected?\n", addr);
				goto close;
			}
			assert(parser->write(p_st, buffer, len) == PARSER_ERR_OK);
			addr += len;

			fprintf(stdout,
				"\033[1GRead address 0x%08x (%.2f%%) ",
				addr,
				(100.0f / (float)(stm->dev->fl_end - stm->dev->fl_start)) * (float)(addr - stm->dev->fl_start)
			);
			fflush(stdout);
		}
		fprintf(stdout,	"Done.\n");
		fprintf(stdout, "\033[?25h");
		ret = 0;
		goto close;

	} else if (wu) {
		fprintf(stdout, "Write-unprotecting flash\n");
		/* the device automatically performs a reset after the sending the ACK */
		reset_flag = 0;
		stm32_wunprot_memory(stm);
		fprintf(stdout,	"Done.\n");

	} else if (wr) {
		printf("\n");

		off_t 	offset = 0;
		ssize_t r;
		unsigned int size = parser->size(p_st);

		if (size > stm->dev->fl_end - stm->dev->fl_start) {
			fprintf(stderr, "File provided larger then available flash space.\n");
			goto close;
		}

		if (!stm32_erase_memory(stm, spage, npages)) {
			fprintf(stderr, "Failed to erase memory\n");
			goto close;
		}

		addr = stm->dev->fl_start + (spage * stm->dev->fl_ps);
		fflush(stdout);
                fprintf(stdout, "\033[?25l");
		while(addr < stm->dev->fl_end && offset < size) {
			uint32_t left	= stm->dev->fl_end - addr;
			len		= sizeof(buffer) > left ? left : sizeof(buffer);
			len		= len > size - offset ? size - offset : len;

			if (parser->read(p_st, buffer, &len) != PARSER_ERR_OK)
				goto close;
	
			again:
			if (!stm32_write_memory(stm, addr, buffer, len)) {
				fprintf(stderr, "Failed to write memory at address 0x%08x\n", addr);
				goto close;
			}

			if (verify) {
				uint8_t compare[len];
				if (!stm32_read_memory(stm, addr, compare, len)) {
					fprintf(stderr, "Failed to read memory at address 0x%08x\n", addr);
					goto close;
				}

				for(r = 0; r < len; ++r)
					if (buffer[r] != compare[r]) {
						if (failed == retry) {
							fprintf(stderr, "Failed to verify at address 0x%08x, expected 0x%02x and found 0x%02x\n",
								(uint32_t)(addr + r),
								buffer [r],
								compare[r]
							);
							goto close;
						}
						++failed;
						goto again;
					}

				failed = 0;
			}

			addr	+= len;
			offset	+= len;

			fprintf(stdout,
				"\033[1GWrote %saddress 0x%08x (%.2f%%) ",
				verify ? "and verified " : "\n",
				addr,
				(100.0f / size) * offset
			);
			fflush(stdout);

		}

		fprintf(stdout,	"Done.\n");
                fprintf(stdout, "\033[?25h");
		ret = 0;
		goto close;
	} else
		ret = 0;

close:
	if (stm && exec_flag && ret == 0) {
		if (execute == 0)
			execute = stm->dev->fl_start;

		fprintf(stdout, "\nStarting execution at address 0x%08x... ", execute);
		fflush(stdout);
		if (stm32_go(stm, execute)) {
			reset_flag = 0;
			fprintf(stdout, "done.\n");
		} else
			fprintf(stdout, "failed.\n");
	}

	if (stm && reset_flag) {
		fprintf(stdout, "\nResetting device... ");
		fflush(stdout);
		if (stm32_reset_device(stm))
			fprintf(stdout, "done.\n");
		else	fprintf(stdout, "failed.\n");
	}


	cleanup();
	printf("\n");
	return ret;
}
Beispiel #24
0
int main(int argc, char** argv)
{  
  zigbee_obj zigbee;
  int32_t fd;
  uint32_t status;
  uint8_t indicationStatus;
  uint8_t buffer[50];
 
  if (argc != 2)
  {
    fprintf(stderr, "Usage : %s tty_device\n", argv[0]);
  }
  
  fd = serial_setup(argv[1], 9600, SERIAL_PARITY_OFF, SERIAL_RTSCTS_OFF, SERIAL_STOPNB_1);
  if (fd < 0)
  {
    fprintf(stderr, "not possible to configurate serial line\n");
    return EXIT_FAILURE;
  }
  else
  {
    fprintf(stdout, "serial line ok, fd = %d\n", fd);
  }
  
  openlog("zb_controler", 0, LOG_USER);
  
  zigbee_protocol_initialize(&zigbee, fd, buffer, 50);
  
  read_hardware_data(&zigbee);
  
  status = configure(&zigbee);
  if (status == 0)
  {
    status = zigbee_protocol_setNodeIdentifier(&zigbee, "ZBC1");
  }
  
  if (status == 0)
  {
    status = zigbee_protocol_startJoinNetwork(&zigbee, ZIGBEE_JOINING_ALWAYS_ACTIVATED);
  }
  
  if (status == 0) 
  {
    fprintf(stdout, "Network activated, wait for end of scanning\n");
    status = zigbee_protocol_waitEndOfAssociation(&zigbee, &indicationStatus);
    fprintf(stdout, "Network association activated status = 0x%x, joining status = 0x%x\n", status, indicationStatus);
  }
  
  if ((status == 0) && (indicationStatus == 0))
  {
    zigbee_panID currentPanID;
    status = zigbee_protocol_getPanID(&zigbee, &currentPanID);
    fprintf(stdout, "curren PAN ID = %d,%d,%d,%d,%d,%d,%d,%d\n", currentPanID[0], currentPanID[1], currentPanID[2], currentPanID[3], currentPanID[4], currentPanID[5], currentPanID[6], currentPanID[7]);

    uint16_t maxRFPayloadBytes;
    status = zigbee_protocol_getMaxRFPayloadBytes(&zigbee, &maxRFPayloadBytes);
    fprintf(stdout, "maxRFPayloadBytes = %d\n", maxRFPayloadBytes);
    
    fprintf(stdout, "Wait For Data reception\n");
    uint8_t top;
    top = 0;
    while (1)
    {
      zb_handle_status statusH;
      uint8_t signalStrenght;
      statusH = zigbee_handle(&zigbee);
      if (statusH == ZB_RX_FRAME_RECEIVED)
      {
        status = zigbee_protocol_getReceivedSignalStrength(&zigbee, &signalStrenght);
        fprintf(stdout, "signal Strenght of last reception : 0x%x\n", signalStrenght);
      }
      /*
      uint8_t data;
      bool dataReceived;
      dataReceived =  serial_read(fd, &data, 1);
      if (dataReceived == true)
      {
        fprintf(stdout, "%.2x\n", data);
      }*/
#if 0
      sleep(1);
      zigbee_64bDestAddr myEndDevice = { 0x00, 0x13, 0xa2, 0x00, 0x40, 0xbd, 0x47, 0x28 };
      char data[50];
      //myEndDevice[0] = 0; myEndDevice[1] = 0x13; myEndDevice[2] = 0xa2; myEndDevice[3] = 0;
      //myEndDevice[4] = 0x40; myEndDevice[5] = 0xbd; myEndDevice[6] = 0x47; myEndDevice[7] = 0x28;
      sprintf(data, "top %d", top); top++;
      zigbee_protocol_sendData(&zigbee, &myEndDevice, ZIGBEE_UNKNOWN_16B_ADDR, (uint8_t*) data, strlen(data)+1);
#endif
/*
      sleep(10);
      zigbee_protocol_nodeDiscover(&zigbee);*/
    }
  }
  else
  {
    fprintf(stdout, "Error : ");
    if (status == 0)
    {
      fprintf(stdout, "%s\n", zigbee_get_indicationError(indicationStatus));
    }
  }
  
  closelog();
  return EXIT_SUCCESS;
}
Beispiel #25
0
/*
 * pcr_open
 * - send power on
 * - set auto update off
 *
 * Assumes rig!=NULL
 */
int
pcr_open(RIG * rig)
{
	struct rig_state *rs = &rig->state;
	struct pcr_priv_data *priv = (struct pcr_priv_data *) rs->priv;

	int err;
	int wanted_serial_rate;
	int startup_serial_rate;

	/*
	 * initial communication is at 9600bps for PCR 100/1000
	 * once the power is on, the serial speed can be changed with G1xx
	 */
    if (rig->caps->rig_model == RIG_MODEL_PCR1500 ||
            rig->caps->rig_model == RIG_MODEL_PCR2500)
        startup_serial_rate = 38400;
    else
        startup_serial_rate = 9600;

	wanted_serial_rate = rs->rigport.parm.serial.rate;
	rs->rigport.parm.serial.rate = startup_serial_rate;

	serial_setup(&rs->rigport);

	/* let the pcr settle and flush any remaining data*/
	usleep(100*1000);
	serial_flush(&rs->rigport);

	/* try powering on twice, sometimes the pcr answers H100 (off) */
	pcr_send(rig, "H101");
	usleep(100*250);

	pcr_send(rig, "H101");
	usleep(100*250);

	serial_flush(&rs->rigport);

	/* return RIG_ERJCTED if power is off */
	err = pcr_transaction(rig, "H1?");
	if (err != RIG_OK)
		return err;

	priv->power = RIG_POWER_ON;

	/* turn off auto update (just to be sure) */
	err = pcr_transaction(rig, "G300");
	if (err != RIG_OK)
		return err;

	/* set squelch and volume */
	err = pcr_set_squelch(rig, RIG_VFO_MAIN, priv->main_rcvr.squelch);
	if (err != RIG_OK)
		return err;

	err = pcr_set_volume(rig, RIG_VFO_MAIN, priv->main_rcvr.volume);
	if (err != RIG_OK)
		return err;

	/* get device features */
	pcr_get_info(rig);

	/* tune to last freq */
	err = pcr_set_freq(rig, RIG_VFO_MAIN, priv->main_rcvr.last_freq);
	if (err != RIG_OK)
		return err;

	if ((rig->state.vfo_list & RIG_VFO_SUB) == RIG_VFO_SUB) {
	    err = pcr_set_squelch(rig, RIG_VFO_SUB, priv->sub_rcvr.squelch);
	    if (err != RIG_OK)
	        return err;

	    err = pcr_set_volume(rig, RIG_VFO_SUB, priv->sub_rcvr.volume);
	    if (err != RIG_OK)
	        return err;

	    err = pcr_set_freq(rig, RIG_VFO_SUB, priv->sub_rcvr.last_freq);
	    if (err != RIG_OK)
	        return err;

	    pcr_set_vfo(rig, RIG_VFO_MAIN);
	}

	/* switch to different speed if requested */
	if (wanted_serial_rate != startup_serial_rate && wanted_serial_rate >= 300)
		return pcr_set_comm_speed(rig, wanted_serial_rate);

	return RIG_OK;
}
Beispiel #26
0
int main(int argc, char *argv[]) {
  struct sockaddr_in sin;
  struct sockaddr_un sun;
  struct hostent *he;
  socklen_t slen;
  pid_t pid, sid;
  FILE *fLog, *fPid;
  bool background;
  char *modeArg, *device, *serialMode, *pidPath, *logPath;
  int opt, num;

  signal(SIGINT, handler_sig);
  signal(SIGTERM, handler_sig);

  if (argc < 3) usage(argv[0]);

  cmnStamp = false;

  squash = DEF_SQUASH;
  background = false;
  run = true;
  modeArg = device = serialMode = pidPath = logPath = NULL;
  he = NULL;
  mode = fdServer = fdClient = 0;

  while ((opt = getopt(argc, argv, "bp:l:d:m:s:t:u:")) != -1)
    switch (opt) {
      case 'b': background = true;                  break;
      case 'p': pidPath = optarg;                   break;
      case 'l': logPath = optarg;                   break;
      case 'd': device = optarg;                    break;
      case 'm': serialMode = optarg;                break;
      case 's': squash = atoi(optarg);              break;
      case 't': mode = MODE_TCP; modeArg = optarg;  break;
      case 'u': mode = MODE_UNIX; modeArg = optarg; break;
      default:  usage(argv[0]);                     break;
    }

  if (mode == 0) usage(argv[0]);

  if (device == NULL) {
    device = malloc(sizeof(DEF_DEV));
    strcpy(device, DEF_DEV);
  }
  dbg(printf("DEVICE: %s\n", device));

  if (serialMode == NULL) {
    serialMode = malloc(sizeof(DEF_MODE));
    strcpy(serialMode, DEF_MODE);
  }
  dbg(printf("SERIAL MODE: %s\n", serialMode));
  serial_parse(serialMode);

  switch (mode) {
    case MODE_UNIX:
      bzero(&sun, sizeof(sun));
      sun.sun_family = AF_UNIX;

      num = strlen(modeArg);
      if ((num < 1) || (num > UNIX_PATH_MAX))
        die("Unix socket path to short/long");
      if (access(modeArg, F_OK) == 0)
        warn("File exists at the specified path");
      strncpy((char *)&sun.sun_path, modeArg, UNIX_PATH_MAX);
      dbg(printf("socket at: %s\n", sun.sun_path));
      break;

    case MODE_TCP:
      bzero(&sin, sizeof(sin));
      sin.sin_family = AF_INET;

      if ((he = gethostbyname(strtok(modeArg, ":"))) == NULL)
        die("Can't find IP for the supplied HOST");
      memcpy(he->h_addr_list[0], &sin.sin_addr, sizeof(sin.sin_addr));

      num = atoi(strtok(NULL, ":"));
      if ((num < 1) || (num > 65535))
        die("Invalid PORT number");
      sin.sin_port = htons(num);
      dbg(printf("host: '%s' port: '%d'\n", he->h_name, num));
      break;
    default:
      usage(argv[0]);
      break;
  }

  if ((fdPanel = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
    die("Can't open serial port device");
  if (flock(fdPanel, LOCK_EX) != 0)
    die("Can't lock serial port");
  serial_setup(fdPanel);

  cli_setup();

  switch (mode) {
    case MODE_UNIX:
      if ((fdServer = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
        die("Can't create a UNIX socket");

      if (bind(fdServer, (struct sockaddr *)&sun, sizeof(sun)) != 0)
        die("Can't bind socket to specified PATH");
      break;

    case MODE_TCP:
      if ((fdServer = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        die("Can't create a TCP socket");

      if (bind(fdServer, (struct sockaddr *)&sin, sizeof(sin)) != 0)
        die("Can't bind socket to specified HOST:PORT");

      setsockopt(fdServer, SOL_SOCKET, SO_REUSEADDR, &num, sizeof(num));
      break;
  }

  if (listen(fdServer, 1) != 0)
    die("Can't listen on socket");

  if (background) {
    if (pidPath == NULL) {
      pidPath = malloc(sizeof(DEF_PID));
      strcpy(pidPath, DEF_PID);
    }
    dbg(printf("pid path: %s\n", pidPath));

    if (access(pidPath, F_OK) == 0)
      die("PID file exists, already running?");
    if ((fPid = fopen(pidPath, "w")) == NULL)
      die("Can't open PID file");

    if (logPath == NULL) {
      logPath = malloc(sizeof(DEF_LOG));
      strcpy(logPath, DEF_LOG);
    }
    dbg(printf("log path: %s\n", logPath));

    if ((fLog = fopen(logPath, "a")) == NULL)
      die("Can't open log file");
    if (dup2(fileno(fLog), STDOUT_FILENO) == -1)
      die("Can't redirect STDOUT");
    if (dup2(fileno(fLog), STDERR_FILENO) == -1)
      die("Can't redirect STDRR");
    fclose(fLog);

    cmnStamp = true;

    pid = fork();
    if (pid < 0)
      die("Can't fork into background");
    if (pid > 0)
      exit(0);

    if ((sid = setsid()) < 0)
      die("Can't request new sid");

    note("Daemon running with PID: %d", sid);
    fprintf(fPid, "%d\n", sid);
    fclose(fPid);

    note("Panel device: %s", device);
    note("Serial config: %s", serialMode);
    switch (mode) {
      case MODE_UNIX:
        note("UNIX socket at: %s", sun.sun_path);               break;
      case MODE_TCP:
        note("TCP socket at: %s:%d", he->h_name, ntohs(sin.sin_port)); break;
    }
  }

  while (run) {
    dbg(printf("Waiting for client...\n"));
    switch (mode) {
      case MODE_UNIX:
        if (((fdClient = accept(fdServer, (struct sockaddr *)&sun, &slen)) < 0) && run)
          die("Error on accept");
        break;

      case MODE_TCP:
        if ((fdClient = accept(fdServer, (struct sockaddr *)&sin, &slen)) < 0) {
          if (run) die("Error on accept");
          else break;
        }
        note("Client from: %s:%d", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
        break;
    }

    if (!run) break;

    note("Client connected");
    cli_loop();
    note("Client disconnected");
    close(fdClient);
  }

  if (mode == MODE_UNIX)
    if (unlink(sun.sun_path) != 0)
      warn("Can't remove UNIX socket");

  if (background)
    if (unlink(pidPath) != 0)
      warn("Can't remove PID file");

  exit(0);
}
int main(int argc, char** argv)
{
    int opt;
    char  ADCraw[2]= {0};
    int fd;
    int res,c,adc;
    float voltage,vout ;
    int flag=0,firsttime=0;
    char *param_port = NULL;
    char *param_speed = NULL;

    printf("-------------------------------------------------------\n");
    printf("\n");
    printf(" Bus Pirate HVP Adapter SELF TEST utility v0.3 (CC-0)\n");
    printf(" http://www.dangerousprototypes.com\n");
    printf("\n");
    printf("-------------------------------------------------------\n");

    if (argc <= 1) {
        printf(" Help Menu\n");
        print_usage(argv[0]);
        exit(-1);
    }

    while ((opt = getopt(argc, argv, "ms:p:")) != -1) {
        // printf("%c  \n",opt);
        switch (opt) {

        case 'p':  // device   eg. com1 com12 etc
            if ( param_port != NULL) {
                printf(" Device/PORT error!\n");
                exit(-1);
            }
            param_port = strdup(optarg);
            break;
        case 's':
            if (param_speed != NULL) {
                printf(" Speed should be set: eg  115200 \n");
                exit(-1);
            }
            param_speed = strdup(optarg);

            break;
        case 'm':    //modem debugging for testing
            modem =TRUE;   // enable modem mode
            break;

        default:
            printf(" Invalid argument %c", opt);
            print_usage(argv[0]);
            //exit(-1);
            break;
        }
    }

    if (param_port==NULL) {
        printf(" No serial port set\n");
        print_usage(argv[0]);
        exit(-1);
    }

    if (param_speed==NULL)
        param_speed=strdup("115200");


    printf("\n Parameters used: Device = %s,  Speed = %s\n\n",param_port,param_speed);
    flag=0;

    printf(" Opening Bus Pirate on %s at %sbps...\n", param_port, param_speed);
    fd = serial_open(param_port);
    if (fd < 0) {
        fprintf(stderr, " Error opening serial port\n");
        return -1;
    }
    //Set Speed of port
    serial_setup(fd,(speed_t) param_speed);

    //printf(" Configuring Bus Pirate HVP Adapter...\n");
    //go into binary bitbang mode
    printf(" Going into Binary Bitbang mode..");
    if(BP_EnableBinary(fd)!=BBIO) {
        printf(" Buspirate cannot switch to binary bitbang mode :( \n");
        return -1;
    }

    //
    // Loop and repeat test as needed for manufacturing
    //

    printf(" Press Esc to exit, any other key to start the self-test \n\n");
    while(1) {

        //pause for space, or ESC to exit

        if (flag==1) {
            printf("\n--------------------- Starting a new Test-------------------------\n");
        }
        while(1) {
            Sleep(1);
            if (flag==1) {
                flag=0;   //has flag been set to just go testing?
                break;    // proceed with test
            }
            if(kbhit()) {
                c = getch();
                if(c == 27) {
                    printf("\n Esc key hit, stopping...\n");
                    printf(" (Bye for now!)\n");
                    exit(-1);
                }
                else {//make space only
                    printf("\n Starting test! \n");
                    break;
                }
            }
        }



//
// Open serial port
//
        //
        //Start self-test
        // 010xxxxx - Configure pins as input(1) or output(0): AUX|MOSI|CLK|MISO|CS
        // should configured as output 01000000 = 0x40

        printf(" Configuring pin direction: 01001100...\n");
        //printf(" sending 01000000...");
        BP_WriteToPirateNoCheck(fd,"\x4C");
        //printf("OK\n");
        //1xxxxxxx - Set on (1) or off (0): POWER|PULLUP|AUX|MOSI|CLK|MISO|CS
        //11000000 - on :  poweronly = 0xC0
        printf(" Sending Command to power on : 11010000....");
        BP_WriteToPirateNoCheck(fd,"\xD2");//c0
        printf("OK\n");
        Sleep(100);

        //
        // Done with setup ,start with testing
        // 00010100 - Take voltage probe measurement (returns 2 bytes)
        // 00010100 = 0x14

        printf(" Voltage Probe measurement...,sending 00010100 \n");
        serial_write( fd, "\x14",1 );
        res=0;
        while(res==0) {
            Sleep(1); //how long wait for a reply?
            res = serial_read(fd, ADCraw, 2);
        }
        //for debugging without hardware using only modem, use -m to pass
        if (modem==TRUE) {
            res=2;
            ADCraw[0]=0x02;
            ADCraw[1]=0xA6;
        }
        // comment the above if with hardware
        if (res!=2) {
            printf(" Expecting 2 bytes returned but got %i instead\n",res);
            printf(" Voltage Measurement: !!!!FAIL!!!! \n");
        }
        else
        {
            // Take a measurement from the Bus Pirate voltage probe.
            //  Returns a 2 byte ADC reading, high 8bits come first.
            //  To determine the actual voltage measurement:
            // Raw reading: 0x2A6 (678)
            // Actual voltage: (678/1024)*3.3volts=2.18volts
            // Scale for resistor divider: Vin = (Vout*(R1+R2))/R2 = (2.18volts*(49K+10K))/10K = 12.86volts (ideal is 13volts)

            adc = ADCraw[0] << 8;
            adc |= (ADCraw[1]&0x00ff);
            vout= ((float)adc/1024.0f)*3.3f;
            voltage =(vout*(49.0f+10.0f))/10.0f;

            printf(" ADC Reading: %2.1f Volts (%02X, %02X)\n",voltage, (char)ADCraw[0], ((char)ADCraw[1]&0xff));
            if(voltage > 10.5 ) {
                printf(" Voltage Measurement: ****PASS**** \n");
            } else {
                printf(" Voltage Measurement: !!!!FAIL!!!! \n");
            }

        }

        printf(" Pins to input: 01011111...\n");
        //printf(" sending 01000000...");
        BP_WriteToPirateNoCheck(fd,"\x5F");
        //power off
        //1xxxxxxx - Set on (1) or off (0): POWER|PULLUP|AUX|MOSI|CLK|MISO|CS
        //10000000 - off :  power only = 0x80
        printf( " powering off.....\n");
        BP_WriteToPirateNoCheck(fd,"\x80");


        //TODO: Loop back to pause after this
        printf("\n Connect another HVP adapter and press any key to test again \n");
        printf(" Or hit ESC key to stop and end the test.\n");

        while(1) {
            Sleep(1);
            if(kbhit()) {
                c = getch();
                if(c == 27) {
                    printf("\n Esc key hit, stopping...\n");
                    res = serial_write( fd, "\x0F", 1);  //exit BBIO
                    //close port so they can attach the next Bus Pirate
                    serial_close(fd);
                    printf(" (Bye for now!)\n");
                    exit(-1);
                } else {//make space only
                    flag=1;  //flag to tell the other loop to bypass another keypress

                    break;
                }
            }
        }
    }

#define FREE(x) if(x) free(x);
    FREE(param_port);
    FREE(param_speed);
    return 0;
}
Beispiel #28
0
int main(int argc, char** argv)
{
int opt;
  char buffer[256] = {0}, i;
  int fd;
  int res,c;
  int new_state,state=0;

  char *param_port = NULL;
  char *param_speed = NULL;
  char *param_polarity=NULL;
  char *param_clockedge=NULL;
  char *param_rawdata=NULL;

//  int clock_edge;
// int polarity;
 //default speed
 // param_port=strdup("COM3");    //default for debugging


    printf("-------------------------------------------------------\n");
    printf("\n");
    printf(" Bus Pirate binary mode SPI SNIFFER utility v0.2 (CC-0)\n");
    printf(" http://dangerousprototypes.com\n");
    printf("\n");
    printf("-------------------------------------------------------\n");
   printf("\n\n\n");

//p == port
// p=polarity
// e=clock edge

if (argc <= 1)  {
	    printf("ERROR: Invalid argument(s).\n\n");
	    printf("Help Menu\n");
		print_usage(argv[0]);
		exit(-1);
	}

while ((opt = getopt(argc, argv, "ms:p:e:d:r:")) != -1) {
       // printf("%c  \n",opt);
		switch (opt) {

			case 'd':  // device   eg. com1 com12 etc
				if ( param_port != NULL){
					printf("Device/PORT error!\n");
					exit(-1);
				}
				param_port = strdup(optarg);
				break;
			case 'e':      // clock edge
 				if (param_clockedge != NULL) {
					printf("Clock Edge should be 0 or 1\n");
					exit(-1);
				}
				param_clockedge = strdup(optarg);

				break;
			case 'p':
				if (param_polarity != NULL) {
					printf("Polarity must be 0 or 1\n");
					exit(-1);
				}
				param_polarity = strdup(optarg);

				break;
			case 's':
				if (param_speed != NULL) {
					printf("Speed should be set: eg  115200 \n");
					exit(-1);
				}
				param_speed = strdup(optarg);

				break;
			case 'r':      // raw data
 				if (param_rawdata != NULL) {
					printf("Raw Data should be 0 or 1\n");
					exit(-1);
				}
				param_rawdata = strdup(optarg);

				break;
			case 'm':    //modem debugging for testing
                   modem =TRUE;   // enable modem mode
				break;

			default:
				printf("Invalid argument %c", opt);
				print_usage(argv[0]);
				//exit(-1);
				break;
		}
	}
    printf(" Press escape to exit \n");
    printf("\n");



    //param_port=strdup("COM3");
    //Set default if NULL
    if (param_port==NULL){
        printf("No serial port set\n");
		print_usage(argv[0]);
		exit(-1);
    }

    if (param_clockedge==NULL)
          param_clockedge=strdup("1");

    if (param_polarity==NULL)
          param_polarity=strdup("0");

    if (param_speed==NULL)
          param_speed=strdup("115200");

    if (param_rawdata==NULL)
          param_rawdata=strdup("0");


    printf("\n  Parameters used: Device = %s,  Speed = %s, Clock Edge= %s, Polarity= %s\n\n",param_port,param_speed,param_clockedge,param_polarity);


    //
    // Open serial port
    //

	printf(" Opening Bus Pirate on %s at %sbps...\n", param_port, param_speed);
	fd = serial_open(param_port);
	if (fd < 0) {
		fprintf(stderr, "Error opening serial port\n");
		return -1;
	}

    //
	// Enter binary mode, then enter a protocol mode
	//
	serial_setup(fd,(speed_t) atoi(param_speed));

	printf(" Starting SPI sniffer...\n");


	if (modem==TRUE){    // connected to modem for testing response	{

              serial_write( fd, "ATI3\x0D\0",5 );
	          usleep(1);
	          res= serial_read(fd, buffer, sizeof(buffer));
	          printf("\n %s\n",buffer);

              serial_write( fd, "ATI4\x0D\0",5 );
	          usleep(1);
	          res= serial_read(fd, buffer, sizeof(buffer));
	          printf("\n %s\n",buffer);
              serial_write( fd, "ATI7\x0D\0",5 );
	          usleep(1);
	          res= serial_read(fd, buffer, sizeof(buffer));
	          printf("\n %s\n",buffer);


	}
	else
	{


          fprintf(stderr, " Configuring Bus Pirate...\n");
   	      BP_EnableMode(fd, SPI); //enter BBIO then SPI
    //
	//Start sniffer
	//

    //configure according to user settings
    //1000wxyz - SPI config, w=HiZ/3.3v, x=CKP idle, y=CKE edge, z=SMP sample
            i=0x80;
            if(strncmp(param_clockedge, "1", 1)==0)
                i|=0x02;
            if(strncmp(param_polarity, "1", 1)==0)
                i|=0x04;

            BP_WriteToPirate(fd, &i);

    //start the sniffer
             serial_write( fd, "\x0E", 1);

    //
    // Done with setup
    //
	}


	printf(" (OK) Happy sniffing! Press ESC to stop.\n");

    //
    // Loop and print input from the serial port
    //
	 while(1){

        usleep(1);
        res= serial_read(fd, buffer, 100);

        if(res>0){
            for(c=0; c<res; c++){
            if(strncmp(param_rawdata, "1", 1)==0) printf("%02X ", (uint8_t)buffer[c]);
	    else {
		switch(state) {
			default:
			case 0:	// waiting CS active
				if (buffer[c]==0x5B) {
					printf("[");
					new_state=1;
		  		} else {
					printf("Sync\n");
					new_state=0;
				}
				break;
			case 1:	// check for data or CS inactive
				if (buffer[c]==0x5C) {
					new_state=2;
				} else if (buffer[c]==0x5D) {
					printf("]\n");
					new_state=0;
				} else {
					printf("Sync\n");
					new_state=0;
				}
				break;
			case 2:	// MPI
				printf("0x%02X(", (uint8_t) buffer[c]);
				new_state=3;
				break;
			case 3:	// MPO
				printf("0x%02X)", (uint8_t) buffer[c]);
				new_state=1;
				break;
		}
		state=new_state;
	    }
            }
        }

#ifdef WIN32
        if(kbhit()){
           c = getch();

           if(c == 27){
                printf("\n Esc key hit, stopping...\n");
                printf(" Clean up Bus Pirate...\n");
                buffer[0]=0x00;//exit sniffer
                buffer[1]=0x00;//exit spi
                buffer[2]=0x0f;//exit BBIO
                res = serial_write( fd, buffer, 3);
                printf(" (Bye for now!)\n");
                break;
            }
        }
#endif

    }    //hit enter to stop

#define FREE(x) if(x) free(x);

	FREE(param_port);
	FREE(param_speed);
    return 0;
}
Beispiel #29
0
int main(int argc, char** argv)
{
  int opt;
  char buffer[256] = {0}, i;
  int fd;
  int res,c;
  int flag=0,firsttime=0;
  char *param_port = NULL;
  char *param_speed = NULL;
  char param_test=1;

//  int clock_edge;
// int polarity;
 //default speed
 // param_port=strdup("COM3");    //default for debugging


    printf("-------------------------------------------------------\n");
    printf("\n");
    printf(" Bus Pirate binary mode SELF TEST utility v0.1 (CC-0)\n");
    printf(" http://dangerousprototypes.com\n");
    printf("\n");
    printf("-------------------------------------------------------\n");
    // printf("\n");

//p == port
// p=polarity
// e=clock edge

if (argc <= 1)  {

	    printf(" Help Menu\n");
		print_usage(argv[0]);
		exit(-1);
	}

while ((opt = getopt(argc, argv, "mRs:d:")) != -1) {
       // printf("%c  \n",opt);
		switch (opt) {

			case 'd':  // device   eg. com1 com12 etc
				if ( param_port != NULL){
					printf(" Device/PORT error!\n");
					exit(-1);
				}
				param_port = strdup(optarg);
				break;
            case 's':
				if (param_speed != NULL) {
					printf(" Speed should be set: eg  115200 \n");
					exit(-1);
				}
				param_speed = strdup(optarg);

				break;
            case 'R': //do short self test
				param_test = 0;
				break;
			case 'm':    //modem debugging for testing
                   modem =TRUE;   // enable modem mode
				break;

			default:
				printf(" Invalid argument %c", opt);
				print_usage(argv[0]);
				//exit(-1);
				break;
		}
	}
   // printf(" Press escape to exit \n");
  //  printf("\n");



    //param_port=strdup("COM3");
    //Set default if NULL
    if (param_port==NULL){
        printf(" No serial port set\n");
		print_usage(argv[0]);
		exit(-1);
    }

    if (param_speed==NULL)
          param_speed=strdup("115200");


    printf("\n Parameters used: Device = %s,  Speed = %s\n\n",param_port,param_speed);

    if(param_test==1){//full self-test
        printf(" Full self-test, attach jumpers (+5V to VPU) and (+3.3V to ADC)\n");
    }else{//short test
        printf(" !!!Warning, short self-test only!!!\n Many things will NOT be tested!!!\n");
    }

    flag=0;
    //
    // Loop and repeat test as needed for manufacturing
    //
    //TO DO: add loop here
     printf(" Press Esc to exit, any other key to start the self-test \n\n");
    while(1){

     //pause for space, or ESC to exit

     if (flag==1)
     {
     printf("\n--------------------- Starting a new Test-------------------------\n");

     }
	 while(1){
        Sleep(1);
        if (flag==1){
            flag=0;   //has flag been set to just go testing?
            break;    // proceed with test
         }
        if(kbhit()){
           c = getch();
           if(c == 27){
                printf("\n Esc key hit, stopping...\n");
                printf(" (Bye for now!)\n");
                exit(-1);
            }else {//make space only
                printf("\n Starting test! \n");
                break;
            }
        }
    }



    //
    // Open serial port
    //

	printf(" Opening Bus Pirate on %s at %sbps...\n", param_port, param_speed);
	fd = serial_open(param_port);
	if (fd < 0) {
		fprintf(stderr, " Error opening serial port\n");
		return -1;
	}

    //
	// Enter binary mode, then enter a protocol mode
	//
	serial_setup(fd,(speed_t) param_speed);

	if (modem==TRUE){    // connected to modem for testing response	{

              serial_write( fd, "ATI3\x0D\0",5 );
	          Sleep(1);
	          res= serial_read(fd, buffer, sizeof(buffer));
	          printf("\n %s\n",buffer);

              serial_write( fd, "ATI4\x0D\0",5 );
	          Sleep(1);
	          res= serial_read(fd, buffer, sizeof(buffer));
	          printf("\n %s\n",buffer);
              serial_write( fd, "ATI7\x0D\0",5 );
	          Sleep(1);
	          res= serial_read(fd, buffer, sizeof(buffer));
	          printf("\n %s\n",buffer);


	}
	else
	{


          fprintf(stderr, " Configuring Bus Pirate...\n");
   	      //BP_EnableMode(fd, SPI); //enter BBIO then SPI
   	      if(BP_EnableBinary(fd)!=BBIO){
                fprintf(stderr, " Buspirate cannot switch to binary mode :( \n");
                return -1;
   	 }
    //
	//Start self-test
	//
            printf(" Starting self-test...\n");

            if(param_test==1){//full self-test
                serial_write( fd, "\x11", 1);
            }else{//short test
                serial_write( fd, "\x10", 1);
            }

    //
    // Done with setup
    //
	}

        printf(" Getting self-test result...\n");
        Sleep(1000);  // how long to wait to get response?

        res = serial_read(fd, &i, 1); //get number of errors...

        if(i>0){
            printf("\n %u ERRORS!!! WARNING!!! :(\n\n", (uint8_t)i);
            printf(" MODE LED should be on!!!\n ");
        }else{
            printf("\n Self-test passed :)\n\n");
            printf(" MODE LED should blink!!!\n");

        }
        //  pause after the result

       if (firsttime==0){    // run here once and don't say again the next time
        printf(" Press any key to continue...\n");
        firsttime=1;
        while(1){
            Sleep(1);
            if(kbhit()){
               c = getch();
                break;
            }
        }
       }

        buffer[0]=0xFF;//exit self-test
        buffer[1]=0x0f;//exit BBIO
        res = serial_write( fd, buffer, 2);

        //close port so they can attach the next Bus Pirate
        serial_close(fd);


        //TODO: Loop back to pause after this
        printf("\n Connect another Bus Pirate  and press any key to start the self-test again \n");
        printf(" Or hit ESC key to stop and end the test.\n");

        while(1){
        Sleep(1);
        if(kbhit()){
           c = getch();
           if(c == 27){
                printf("\n Esc key hit, stopping...\n");
                printf(" (Bye for now!)\n");
                exit(-1);
            }else {//make space only
                flag=1;  //flag to tell the other loop to bypass another keypress

                break;
            }
        }
    }
	}

#define FREE(x) if(x) free(x);
	FREE(param_port);
	FREE(param_speed);
    return 0;
}
Beispiel #30
0
int main(int argc, char** argv)
{
	int opt;
	uint8_t buffer[MAX_BUFFER]={0};
	uint8_t temp[2]={0};  // command buffer
//	struct stat stbuf;
	int fd,timeout_counter;
	int res,c, nparam_bytechunks, bytePointer, readSize;
	long fileSize;
	FILE *XSVF;
//	int  xsvf;
    int timer_out=0;
	char *param_port = NULL;
	char *param_speed = NULL;
	char *param_XSVF=NULL;
	char *param_bytechunks=NULL;
	int  jtag_reset=FALSE;
    int  chainscan=FALSE;

    const char *XSVF_ERROR[]={  "XSVF_ERROR_NONE",
                                "XSVF_ERROR_UNKNOWN",
                                "XSVF_ERROR_TDOMISMATCH",
                                "XSVF_ERROR_MAXRETRIES",
                                "XSVF_ERROR_ILLEGALCMD",
                                "XSVF_ERROR_ILLEGALSTATE",
                                "XSVF_ERROR_DATAOVERFLOW",
                                "XSVF_ERROR_LAST",
                                "XSVF_READY_FOR_DATA",
                                 0 };

	printf("-----------------------------------------------------------------------------\n");
	printf("\n");
	printf(" BusPirate XSVF Player V.01\n");
	printf(" http://www.dangerousprototypes.com\n");
	printf("\n");
	printf("-----------------------------------------------------------------------------\n");



	if (argc <= 1)  {
		print_usage(argv[0]);
		exit(-1);
	}


	while ((opt = getopt(argc, argv, "s:p:f:rx")) != -1) {

		switch (opt) {
			case 'p':  // device   eg. com1 com12 etc
				if ( param_port != NULL){
					printf("Device/PORT error!\n");
					exit(-1);
				}
				param_port = strdup(optarg);
                break;
            case 'r':
                jtag_reset=TRUE;
                break;
            case 'x':
                chainscan=TRUE;
            	break;
			case 'f':
				if (param_XSVF != NULL) {
					printf(" No XSVF file \n");
					exit(-1);
				}
				param_XSVF = strdup(optarg);

				break;

			case 's':
				if (param_speed != NULL) {
					printf(" Speed should be set: eg  115200 \n");
					exit(-1);
				}
				param_speed = strdup(optarg);

				break;

			default:
				printf(" Invalid argument %c", opt);
				print_usage(argv[0]);
				exit(-1);
				break;
		}
	}

	if (param_port==NULL){
		printf(" No serial port specified\n");
		print_usage(argv[0]);
		exit(-1);
	}

    nparam_bytechunks=MAX_BUFFER;

	if (param_speed==NULL) {
		param_speed=strdup("115200");  //default is 115200kbps
	}


	fd = serial_open(param_port);
	if (fd < 0) {
		fprintf(stderr, " Error opening serial port\n");
		return -1;
	}

	//setup port and speed
	serial_setup(fd,(speed_t) atoi(param_speed)); 

	if (jtag_reset==TRUE){
        printf(" Performing Reset..\n");
        temp[0]=0x01;
        serial_write( fd, (char *)temp, 1 );
        Sleep(1);
        printf(" Done \n\n");
	}

	// perform Chain scan
	 // Send 0x02 to perform a chain scan
     // Wait for 1 byte, the number of bytes that will be returned
     // Get that many bytes
	if (chainscan==TRUE) {
		printf(" Performing Chain Scan..\n");
		temp[0]=0x02;
		serial_write( fd, (char *)temp, 1 );
		Sleep(1);
		res=0;
		timeout_counter=0;

		while (res==0) {
			res= serial_read(fd, (char *)buffer, sizeof(buffer));
			Sleep(1);
			timeout_counter++;
			if (timeout_counter>=5) {
			printf(" Got no reply for a Chain scan\n");
			} else {
			printf(" Waiting for a chain scan reply\n");
			}
		}
		if (res >0) {
			printf(" Chain Scan Result:" );
			for(c=0;c<res;c++){
			printf(" %02X",buffer[c]);
			}
			printf("\n\n");

		}
	}

   if (param_XSVF !=NULL) {
		//open the XSVF file
            XSVF = fopen(param_XSVF, "rb");
            if (XSVF == NULL) {
                printf(" Error opening file\n");
            }
            fseek(XSVF, 0, SEEK_END);
            fileSize = ftell(XSVF);
            fseek(XSVF, 0, SEEK_SET);
            printf(" File is %lu bytes, ",fileSize);

            bin_buf = (uint8_t*)malloc(fileSize);
            if (bin_buf == NULL) {
               printf(" Error allocating %ld bytes of memory\n", (long)fileSize);
               return -1;
            }
            memset(bin_buf, 0, fileSize);

            res = fread(bin_buf, sizeof(uint8_t), fileSize, XSVF);
            if (res <= 0) {
                printf(" Error reading file %s \n", param_XSVF);
            }
            printf(" Read %i bytes\n",res);

            fclose(XSVF);


	} else {
		printf(" No file specified. Need an input xsvf file \n");
		exit(-1);
	}
	printf(" Opening Bus Pirate on %s at %sbps, using XSVF file %s \n", param_port, param_speed,param_XSVF);

	// Enter XSVF Player Mode
	//Open the port and send 0x03 to enter XSVF player mode
	printf(" Entering XSVF Player Mode\n");
	temp[0]=0x03;
	serial_write( fd, (char *)temp, 1 );

	// Wait for 0xFF, if <0xFF then it is finished or error codes (see below)
    bytePointer=0; //where we are in the byte buffer array
    readSize=MAX_BUFFER; //hack this to be a full chunk
    cnt=0;
    printf(" Waiting for first data request...");
	while(1) {

            //wait for reply before sending the next chunks
			timeout_counter=0;
			timer_out=0;   // 0 if ok, else -1 if exit
			while(1) {
				res= serial_read(fd, (char *)buffer, sizeof(buffer));
				if(res>0){
                    printf("ok\n");
				  // wait for 0xFF and send data, or error
					if ((buffer[0]!=XSVF_READY_FOR_DATA) || (fileSize==0)) {
					    c=buffer[0];
					    if (c==0xFF)
					         c=8;
                        printf(" End of operation reply: %s \n",XSVF_ERROR[c]);
                        switch (buffer[0]) {
                            case  XSVF_ERROR_NONE :
                                printf(" Success!\n");
                                break;
                            case XSVF_ERROR_UNKNOWN:
                             printf(" Unknown error: XSVF_ERROR_UNKNOWN \n");
                                break;
                            case XSVF_ERROR_TDOMISMATCH:
                             printf(" Device did not respond as expected: XSVF_ERROR_TDOMISMATCH \n");
                                break;
                            case XSVF_ERROR_MAXRETRIES:
                             printf(" Device did not respond: XSVF_ERROR_MAXRETRIES \n");
                                break;
                            case XSVF_ERROR_ILLEGALCMD :
                             printf(" Unknown XSVF command: XSVF_ERROR_ILLEGALCMD \n");
                                break;
                            case XSVF_ERROR_ILLEGALSTATE:
                             printf(" Unknown JTAG state: XSVF_ERROR_ILLEGALSTATE \n");
                                break;
                            case XSVF_ERROR_DATAOVERFLOW :
                             printf(" Error, data overflow: XSVF_ERROR_DATAOVERFLOW \n");
                                break;
                            case XSVF_ERROR_LAST:
                             printf(" Some other error I don't remember, probably isn't active: XSVF_ERROR_LAST \n");
                                break;
                            case XSVF_READY_FOR_DATA:
                                if (fileSize==0) {
                                    printf(" End of file reached. \n");
                                } else {
									printf(" Programmer says more data: XSVF_READY_FOR_DATA \n");
                                }
                                break;
                            default:
                             printf(" Unknown error\n ");

                         }

                     }
                     break; //break loop and send data
				}else{
					printf("\n Waiting for reply...");
				//	Sleep(1);
					timeout_counter++;
					if(timeout_counter > 4){
						printf("\n No reply.... Quitting.\n ");
						timeout_counter=0;
						timer_out=-1;
						break;
					}
				}
			}
            if (fileSize==0) {
			       break;
			}

            if (timer_out==-1)
                break;
            //send data
            if(fileSize<MAX_BUFFER){
                readSize=fileSize;
            }
			//send to bp
			temp[0]=(readSize>>8);
			temp[1]=readSize;
			cnt=cnt+readSize;

			printf(" Sending %i Bytes (%04X)...",readSize, cnt);
			serial_write( fd, (char *)temp,2 );
			serial_write( fd, (char *) &bin_buf[bytePointer],readSize );
			bytePointer=bytePointer+readSize;//start 1 chunk in next itme
			fileSize=fileSize-readSize; //deincrement the remaining byte count

	}

    printf(" Thank you for playing! :-)\n\n");
#ifdef WIN32
    fclose(XSVF);
	FREE(param_port);
 	FREE(param_speed);
    FREE(param_bytechunks);
    FREE(param_XSVF);
    FREE( bin_buf);
#endif
    return 0;
 }  //end main()