Beispiel #1
0
void upsdrv_initups(void)
{
	const char *val = getval("baudrate");
	speed_t baudrate = B2400;

	if (val) {
		switch (atoi(val))
		{
		case 1200:
			baudrate = B1200;
			break;
		case 2400:
			baudrate = B2400;
			break;
		case 4800:
			baudrate = B4800;
			break;
		case 9600:
			baudrate = B9600;
			break;
		case 19200:
			baudrate = B19200;
			break;
		default:
			fatalx(EXIT_FAILURE, "Baudrate [%s] unsupported", val);
		}
	}

	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, baudrate);
}
Beispiel #2
0
void upsdrv_initups(void)
{
	char	*version;

	version = getval("protocol");
	upsfd = ser_open(device_path);

	ser_set_rts(upsfd, 0);

	/*
	 * Try to autodetect which UPS is connected.
	 */
	for (mode = 0; subdriver[mode] != NULL; mode++) {

		if ((version != NULL) && strcasecmp(version, subdriver[mode]->version)) {
			continue;
		}

		ser_set_dtr(upsfd, 1);
		usleep(10000);

		if (subdriver[mode]->initups() > 0) {
			upslogx(LOG_INFO, "CyberPower UPS with %s protocol on %s detected", subdriver[mode]->version, device_path);
			return;
		}

		ser_set_dtr(upsfd, 0);
		usleep(10000);
	}

	fatalx(EXIT_FAILURE, "CyberPower UPS not found on %s", device_path);
}
Beispiel #3
0
void openPort(QString port)
{
#ifndef Q_OS_WIN32
    int tries=MAX_RETRIES;
    int i;

    //repeatedly open the port until there are no errors
    QByteArray ba = port.toLocal8Bit();
    for(i=0;i<tries;i++) {
       if (ser_open(ba.data(), 38400, &portFD) != -1) {
          break;
       } else {
          std::cout << "Error opening serial port\n";
          SLEEP(250);
       }
    }

    if (i==tries) {
       exit(1);
    }

    //reconfigure the device for Mac
    _portName = port;
    //std::cout << "Reconfiguring device\n";
    ser_setspeed(&portFD, 38400);
#else
    _portName = port;
    _port = new QextSerialPort(port);
    _port->setBaudRate(BAUD9600);
    _port->setTimeout(1000);
    if (!_port->open(QextSerialPort::ReadWrite))
        error("Could not open serial port.");
#endif
}
Beispiel #4
0
//-----------------------------------------------------------------------------
int main ( int argc, char *argv[] )
{
    unsigned int ra;
    unsigned int rb;

    if(argc<2)
    {
        fprintf(stderr,"progpluto /dev/ttySOMETHING\n");
        return(1);
    }
    if(ser_open(argv[1])) return(1);


    while(1)
    {
        rb=ser_copystring(rdata);
        for(ra=0;ra<rb;ra++)
        {
            printf("0x%02X ",rdata[ra]);
            if((rdata[ra]>=0x20)&&(rdata[ra]<127)) printf("[%c]",rdata[ra]);
            printf("\n");
        }
        ser_dump(rb);
    }


    ser_close();
    return(0);
}
Beispiel #5
0
/**
 * Reopen serial port.
 */
static struct KFile *ser_reopen(struct KFile *fd)
{
	Serial *fds = SERIAL_CAST(fd);

	ser_close(fd);
	ser_open(fds, fds->unit);
	return (KFile *)fds;
}
Beispiel #6
0
int upsdrv_initups(void)
{
	upsfd = ser_open(device_path); 
	ser_set_speed(upsfd, device_path, B2400); 
	send_zeros();

	return 1;
}
Beispiel #7
0
void upsdrv_initups(void)
{
	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, B19200);

	/* dtr and rts setting */
	ser_set_dtr(upsfd, 1);
	ser_set_rts(upsfd, 0);
	
}
int main()
{	
	union filedescriptor fd;
	union pinfo pinfo;
	pinfo.baud = 115200;
	
	ser_open("/dev/ttyO4",pinfo,&fd);
	ser_close(&fd);
	return 0;
}
Beispiel #9
0
int main( int argc, const char **argv )
{
  long serspeed;
  
  if( argc < 4 )
  {
    fprintf( stderr, "Usage: %s <port> <speed> <dirname> [-v]\n", argv[ 0 ] );
    fprintf( stderr, "(use -v for verbose output).\n");
    return 1;
  }
  if( secure_atoi( argv[ SPEED_ARG_IDX ], &serspeed ) == 0 )
  {
    fprintf( stderr, "Invalid speed\n" );
    return 1;
  } 
  if( !os_isdir( argv[ DIRNAME_ARG_IDX ] ) )
  {
    fprintf( stderr, "Invalid directory %s\n", argv[ DIRNAME_ARG_IDX ] );
    return 1;
  }
  if( ( argc >= 5 ) && !strcmp( argv[ VERBOSE_ARG_IDX ], "-v" ) )
    log_init( LOG_ALL );
  else
    log_init( LOG_NONE );

  // Setup RFS server
  server_setup( argv[ DIRNAME_ARG_IDX ] );

  // Setup serial port
  if( ( ser = ser_open( argv[ PORT_ARG_IDX ] ) ) == ( ser_handler )-1 )
  {
    fprintf( stderr, "Cannot open port %s\n", argv[ PORT_ARG_IDX ] );
    return 1;
  }
  if( ser_setup( ser, ( u32 )serspeed, SER_DATABITS_8, SER_PARITY_NONE, SER_STOPBITS_1 ) != SER_OK )
  {
    fprintf( stderr, "Unable to initialize serial port\n" );
    return 1;
  }
  flush_serial();
  
  // User report
  printf( "Running RFS server on port %s (%u baud) in directory %s\n", argv[ PORT_ARG_IDX ], ( unsigned )serspeed, argv[ DIRNAME_ARG_IDX ] );  

  // Enter the server endless loop
  while( 1 )
  {
    read_request_packet();
    server_execute_request( rfs_buffer );
    send_response_packet();
  }

  ser_close( ser );
  return 0;
}
Beispiel #10
0
int upsdrv_initups(void)
{
	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, B9600);

	/*get the UPS in the right frame of mind*/
	ser_send_pace(upsfd, 100, "%s", COMMAND_END);
	ser_send_pace(upsfd, 100, "%s", COMMAND_END);
	sleep (1);

	return 1;
}
Beispiel #11
0
void upsdrv_initups(void)
{
	upsfd = ser_open(device_path);

	/* Speed should not matter (see comments in upsdrv_updateinfo),
	 * but set it relatively low in case there are problems with higher
	 * speeds. */
	ser_set_speed(upsfd, device_path, B9600);

	/* raise RTS */
	ser_set_rts(upsfd, 1);
}
Beispiel #12
0
int upsdrv_initups(void)
{
	struct termios	tio;
	const char	*val;

	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, B1200);

	if (tcgetattr(upsfd, &tio)) {
		fatal_with_errno(EXIT_FAILURE, "tcgetattr");
	}

	/*
	 * Use canonical mode input processing (to read reply line)
	 */
	tio.c_lflag |= ICANON;	/* Canonical input (erase and kill processing) */
	tio.c_iflag |= IGNCR;	/* Ignore CR */
	tio.c_iflag |= IGNBRK;	/* Ignore break condition */
	tio.c_oflag |= ONLCR;	/* Map NL to CR-NL on output */

	tio.c_cc[VEOF] = _POSIX_VDISABLE;
	tio.c_cc[VEOL] = _POSIX_VDISABLE;
	tio.c_cc[VERASE] = _POSIX_VDISABLE;
	tio.c_cc[VINTR]  = _POSIX_VDISABLE;
	tio.c_cc[VKILL]  = _POSIX_VDISABLE;
	tio.c_cc[VQUIT]  = _POSIX_VDISABLE;
	tio.c_cc[VSUSP]  = _POSIX_VDISABLE;
	tio.c_cc[VSTART] = _POSIX_VDISABLE;
	tio.c_cc[VSTOP]  = _POSIX_VDISABLE;

	if (tcsetattr(upsfd, TCSANOW, &tio)) {
		fatal_with_errno(EXIT_FAILURE, "tcsetattr");
	}

	/*
	 * Set DTR and clear RTS to provide power for the serial interface.
	 */
	ser_set_dtr(upsfd, 1);
	ser_set_rts(upsfd, 0);

	val = dstate_getinfo("battery.voltage.nominal");
	battery.voltage.nom = (val) ? strtod(val, NULL) : 12.00;

	val = dstate_getinfo("battery.voltage.low");
	battery.voltage.low = (val) ? strtod(val, NULL) : 10.80;

	if (battery.voltage.nom <= battery.voltage.low) {
		fatalx(EXIT_FAILURE, "Nominal battery voltage must be higher than low battery voltage!");
	}

	return 1;
}
Beispiel #13
0
void upsdrv_initups(void)
{
	int fdm, fds;
//	char *slavename;                       //only for ptmx
//	extern char *ptsname();                //only for ptmx
     
	upsfd = ser_open(device_path);
//	grantpt(upsfd);                        /* change permission of slave , only for ptmx*/
//	unlockpt(upsfd);                       /* unlock slave ,only for ptmx */
//	slavename = ptsname(upsfd);           //only for ptmx
//	printf("the slave name is %s\n",slavename);
	printf("driver initups is running");
	ser_set_speed(upsfd, device_path, BAUDRATE);
}
Beispiel #14
0
/**
 * Init serial driver for \a unit.
 *
 * Use values SER_UARTn as values for \a unit.
 */
void ser_init(struct Serial *fds, unsigned int unit)
{
	memset(fds, 0, sizeof(*fds));

	DB(fds->fd._type = KFT_SERIAL);
	fds->fd.reopen = ser_reopen;
	fds->fd.close = ser_close;
	fds->fd.read = ser_read;
	fds->fd.write = ser_write;
	fds->fd.flush = ser_flush;
	fds->fd.error = ser_error;
	fds->fd.clearerr = ser_clearerr;
	ser_open(fds, unit);
}
void transport_open( Transport *tpt, const char *path )
{
  struct exception e;
  
  tpt->fd = ser_open( path );

  if( tpt->fd == INVALID_TRANSPORT)
  {
    e.errnum = transport_errno;
    e.type = fatal;
    Throw( e );
  }
  
  ser_setup( tpt->fd, 115200, SER_DATABITS_8, SER_PARITY_NONE, SER_STOPBITS_1 );
  ser_set_timeout_ms( tpt->fd, 1000 );
}
Beispiel #16
0
static int transport_ser_init()
{
    TRANSPORT_SER *pser = ( TRANSPORT_SER* )transport_data;

    if( ( pser->fd = ser_open( pser->pname ) ) == ( ser_handler )-1 )
    {
        fprintf( stderr, "Unable to open %s\n", pser->pname );
        return 0;
    }
    if( ser_setup( pser->fd, pser->speed, 8, SER_PARITY_NONE, SER_STOPBITS_1 ) != SER_OK )
    {
        fprintf( stderr, "Unable to setup serial port %s\n", pser->pname );
        return 0;
    }
    while( ser_read_byte( pser->fd, SER_NO_TIMEOUT ) != -1 );
    printf( "Running serial transport on port %s at %u baud (8N1)\n", pser->pname, ( unsigned )pser->speed );
    return 1;
}
Beispiel #17
0
void upsdrv_initups(void)
{
	upsdebugx(2, "entering upsdrv_initups()");

	upsfd = ser_open(device_path);

	riello_comm_setup(device_path);

	/* probe ups type */

	/* to get variables and flags from the command line, use this:
	 *
	 * first populate with upsdrv_buildvartable above, then...
	 *
	 *	  				set flag foo : /bin/driver -x foo
	 * set variable 'cable' to '1234' : /bin/driver -x cable=1234
	 *
	 * to test flag foo in your code:
	 *
	 * 	if (testvar("foo"))
	 * 		do_something();
	 *
	 * to show the value of cable:
	 *
	 *	if ((cable = getval("cable")))
	 *		printf("cable is set to %s\n", cable);
	 *	else
	 *		printf("cable is not set!\n");
	 *
	 * don't use NULL pointers - test the return result first!
	 */

	/* the upsh handlers can't be done here, as they get initialized
	 * shortly after upsdrv_initups returns to main.
	 */

	/* don't try to detect the UPS here */

	/* initialise communication */
}
Beispiel #18
0
int upsdrv_initups(void)
{
	  upsfd = ser_open(device_path);
          setup_serial(device_path);
	/* upsfd = ser_open(device_path); */
	/* ser_set_speed(upsfd, device_path, B1200); */
   
	/* probe ups type */

	/* to get variables and flags from the command line, use this:
	 *
	 * first populate with upsdrv_buildvartable above, then...
	 *
	 *                   set flag foo : /bin/driver -x foo
	 * set variable 'cable' to '1234' : /bin/driver -x cable=1234
	 *
	 * to test flag foo in your code:
	 *
	 * 	if (testvar("foo"))
	 * 		do_something();
	 *
	 * to show the value of cable:
	 *
	 *      if ((cable == getval("cable")))
	 *		printf("cable is set to %s\n", cable);
	 *	else
	 *		printf("cable is not set!\n");
	 *
	 * don't use NULL pointers - test the return result first!
	 */

	/* the upsh handlers can't be done here, as they get initialized
	 * shortly after upsdrv_initups returns to main.
	 */


	  return 1;
}
Beispiel #19
0
/*-----------------------------------------------------------------------------------*/
void
rs232dev_init(void)
{
  char err;
  struct ser_params p;
  
  err = ser_load_driver("c64-swlink.ser");

  if(err != SER_ERR_OK) {
    asm("inc $d020");
    return;
  }
  
  p.baudrate = SER_BAUD_9600;
  p.databits = SER_BITS_8;
  p.stopbits = SER_STOP_1;
  p.parity = SER_PAR_NONE;
  p.handshake = SER_HS_HW;

  err = ser_open(&p);

  if(err != SER_ERR_OK) {
    asm("inc $d020");
    return;
  }
  

  loaded = 1;
  
  /*  err = rs232_init(0); */
  /*  rs232_err(err);*/
  /*  err = rs232_params(RS_BAUD_9600 | RS_BITS_8 | RS_STOP_1, RS_PAR_NONE);*/
  /*  rs232_err(err);*/

  len = 0;

  return;
}
Beispiel #20
0
static int parport_init(void)
{
    struct cable *cur_cable;
    cur_cable = cables;


    if(ser_open())
    {
        printf("ser_open failed\n");
    }


    parport_cable = "jtagproxy";

    while (cur_cable->name) {
        if (strcmp(cur_cable->name, parport_cable) == 0) {
            cable = cur_cable;
            break;
        }
        cur_cable++;
    }

    if (!cable) {
        LOG_ERROR("No matching cable found for %s", parport_cable);
        return ERROR_JTAG_INIT_FAILED;
    }

    dataport_value = cable->PORT_INIT;

    parport_reset(0, 0);
    parport_write(0, 0, 0);
    parport_led(1);

    bitbang_interface = &parport_bitbang;

    return ERROR_OK;
}
Beispiel #21
0
//-----------------------------------------------------------------------------
int main ( int argc, char *argv[] )
{
    unsigned int ra,rb,rc,rd;
    int ea;

    if(argc<3)
    {
        fprintf(stderr,"proglpc /dev/ttySOMETHING program.bin\n");
        fdatalen=0;
    }
    else
    {
        fp=fopen(argv[2],"rb");
        if(fp==NULL)
        {
            fprintf(stderr,"Error opening file [%s]\n",argv[2]);
            return(1);
        }
        memset(fdata,0xFF,sizeof(fdata));
        fdatalen=fread(fdata,1,sizeof(fdata),fp);
        fclose(fp);
        if(fdatalen&3) fdatalen+=4;
        fdatalen>>=2;
    }
    if(argc>3) ea=1; else ea=0;

    if(ser_open(argv[1]))
    {
        printf("ser_open(%s) failed\n",argv[1]);
        return(1);
    }
    printf("port opened\n");
    do_lpc_stuff(ea);
    ser_close();

    return(0);
}
Beispiel #22
0
//-----------------------------------------------------------------------------
int main ( int argc, char *argv[] )
{

    if(argc<3)
    {
        fprintf(stderr,"prognxp_sram /dev/ttySOMETHING program.bin\n");
        return(1);
    }
    fp=fopen(argv[2],"rb");
    if(fp==NULL)
    {
        fprintf(stderr,"Error opening file [%s]\n",argv[2]);
        return(1);
    }
    memset(fdata,0xFF,sizeof(fdata));
    fdatalen=fread(fdata,1,sizeof(fdata),fp);
    fclose(fp);
    printf("read %u bytes\n",fdatalen);

    if(fdatalen>0x800)
    {
        printf("Program too big\n");
        return(1);
    }

    if(ser_open(argv[1]))
    {
        printf("ser_open(%s) failed\n",argv[1]);
        return(1);
    }
    printf("port opened\n");
    do_nxp_stuff();
    ser_close();

    return(0);
}
Beispiel #23
0
//-----------------------------------------------------------------------------
int main ( int argc, char *argv[] )
{
  //struct termios newsettings;

    if(argc<2)
    {
        printf(".hex file not specified\n");
        return(1);
    }
    fp=fopen(argv[1],"rt");
    if(fp==NULL)
    {
        printf("error opening file %s\n",argv[1]);
        return(1);
    }
    if(readhex()) return(1);
    fclose(fp);

    pages=maxadd>>8;

        printf("pages %u maxadd %u\n",pages,maxadd);



    if(ser_open())
    {
        printf("ser_open() failed\n");
        return(1);
    }
    printf("port opened\n");


    if(get_sync())
    {
        ser_close();
        printf("\n\n");
        return(1);
    }

        sdata[0]=0x41;
        sdata[1]=0x81;
        sdata[2]=0x20;
        ser_senddata(sdata,3);
        while(1)
        {
            rb=ser_copystring(data);
            if(rb==3) break;
        }
        ser_dump(rb);
        showstring(rb);

        sdata[0]=0x41;
        sdata[1]=0x82;
        sdata[2]=0x20;
        ser_senddata(sdata,3);
        while(1)
        {
            rb=ser_copystring(data);
            if(rb==3) break;
        }
        ser_dump(rb);
        showstring(rb);


        sdata[0]=0x50;
        sdata[1]=0x20;
        ser_senddata(sdata,2);
        while(1)
        {
            rb=ser_copystring(data);
            if(rb==2) break;
        }
        ser_dump(rb);
        showstring(rb);

        if((data[0]==0x14)&&(data[1]==0x10))
        {
        }
        else
        {
            ser_close();
            printf("\n\n");
            return(1);
        }


        for(page=0;page<=maxadd;page+=256)
        {
            printf("set address 0x%04X\n",page);
            sdata[0]=0x55;
            sdata[1]=(page>>1)&0xFF;
            sdata[2]=(page>>9)&0xFF;
            sdata[3]=0x20;
            ser_senddata(sdata,4);
            while(1)
            {
                rb=ser_copystring(data);
                if(rb==2) break;
            }
            ser_dump(rb);
            showstring(rb);

            printf("write page\n");
            sdata[0]=0x64;
            sdata[1]=0x01;
            sdata[2]=0x00;
            sdata[3]='F';
            for(ra=0;ra<256;ra++) sdata[4+ra]=memory[ra+page];
            sdata[4+ra]=0x20;
            ser_senddata(sdata,ra+5);
            while(1)
            {
                rb=ser_copystring(data);
                if(rb==2) break;
            }
            ser_dump(rb);
            showstring(rb);

        }


        sdata[0]=0x51;
        sdata[1]=0x20;
        ser_senddata(sdata,2);
        while(1)
        {
            rb=ser_copystring(data);
            if(rb==2) break;
        }
        ser_dump(rb);
        showstring(rb);

        if((data[0]==0x14)&&(data[1]==0x10))
        {
        }
        else
        {
            ser_close();
            printf("\n\n");
            return(1);
        }



  ser_close();
  printf("\n\n");
  return(0);
}
Beispiel #24
0
void upsdrv_initups ()
{
  char	temp[256], fcstring[512];

  upsfd = ser_open(device_path);
  ser_set_speed(upsfd, device_path, B1200);
  setup_serial();
  ups_sync();

  fc.model = UNKNOWN;
  /* Obtain Model */
  if (execute("id\r", fcstring, sizeof(fcstring)) < 1) {
    fatalx(EXIT_FAILURE, "Failed execute in ups_ident()");
  }
  
  /* response is a one-line packed string starting with $ */
  if (memcmp(fcstring, "Unit", 4)) {
    fatalx(EXIT_FAILURE, 
	"Bad response from formatconfig command in ups_ident()\n"
	"id: %s\n", fcstring
    );
  }

  if (debugging)
    fprintf(stderr, "id: %s\n", fcstring);
  
  /* chars 4:2  are a two-digit ascii hex enumerated model code */
  memcpy(temp, fcstring+9, 2);
  temp[2] = '\0';

  if (memcmp(temp, "ME", 2) == 0)  {
    fc.model = ME3100;
  } else if ((memcmp(temp, "RE", 2) == 0)) {
    fc.model = RE1800;
  } else if (memcmp(temp, "C1", 2) == 0)  {
    /* Better way to identify unit is using "d 15\r", which results in
       "15 M#    MD1KVA", "id\r" yields "Unit ID "C1K03588"" */
    fc.model = MD1KVA;
  }
 
  switch(fc.model) {
    case ME3100:
      fc.va = 3100;
      fc.watts = 2200;
      /* determine shutdown battery voltage */
      if (execute("d 29\r", fcstring, sizeof(fcstring)) > 0) {
        sscanf(fcstring, "29 LowBat   %f", &fc.emptyvolts);
      }
      /* determine fully charged battery voltage */
      if (execute("d 31\r", fcstring, sizeof(fcstring)) > 0) {
        sscanf(fcstring, "31 HiBatt   %f", &fc.fullvolts);
      }
      fc.fullvolts = 54.20;
      /* determine "ideal" voltage by a guess */
      fc.idealbvolts = ((fc.fullvolts - fc.emptyvolts) * 0.7) + fc.emptyvolts;
      break;
    case RE1800:
      fc.va = 1800;
      fc.watts = 1200;
      /* determine shutdown battery voltage */
      if (execute("d 29\r", fcstring, sizeof(fcstring)) > 0) {
        sscanf(fcstring, "29 LowBat   %f", &fc.emptyvolts);
      }
      /* determine fully charged battery voltage */
      if (execute("d 31\r", fcstring, sizeof(fcstring)) > 0) {
        sscanf(fcstring, "31 HiBatt   %f", &fc.fullvolts);
      }
      fc.fullvolts = 54.20;
      /* determine "ideal" voltage by a guess */
      fc.idealbvolts = ((fc.fullvolts - fc.emptyvolts) * 0.7) + fc.emptyvolts;
      break;
    case MD1KVA:
      fc.va = 1100;
      fc.watts = 770; /* Approximate, based on 0.7 power factor */
      /* determine shutdown battery voltage */
      if (execute("d 27\r", fcstring, sizeof(fcstring)) > 0) {
        sscanf(fcstring, "27 LowBatt  %f", &fc.emptyvolts);
      }
      /* determine fully charged battery voltage */
      if (execute("d 28\r", fcstring, sizeof(fcstring)) > 0) {
        sscanf(fcstring, "28 Hi Batt  %f", &fc.fullvolts);
      }
      fc.fullvolts = 13.70;
      /* determine "ideal" voltage by a guess */
      fc.idealbvolts = ((fc.fullvolts - fc.emptyvolts) * 0.7) + fc.emptyvolts;
      break;
    default:
      fatalx(EXIT_FAILURE, "Uknown model %s in ups_ident()", temp);
  }

  fc.valid = 1;
  return;
}
Beispiel #25
0
int main( int argc, char **argv )
{
    unsigned i;
    THREAD_DATA *tdata;
    int c;
    int temp, sdata;
    int got_esc = 0;
    DATA data;

    // Interpret arguments
    if( argc < 4 )
    {
        fprintf( stderr, "Usage: %s <transport> <baud> <vcom1> [<vcom2>] ... [<vcomn>] [-v]\n", argv[ 0 ] );
        return 1;
    }
    i = argc - 1;
    if( !strcasecmp( argv[ i ], "-v" ) )
    {
        i --;
        log_init( LOG_ALL );
    }
    else
        log_init( LOG_NONE );
    if( ( vport_num = i - 2 ) > SERVICE_MAX )
    {
        fprintf( stderr, "Too many service ports, maximum is %d\n", SERVICE_MAX );
        return 1;
    }
    if( parse_transport( argv[ MAIN_TRANSPORT_IDX ] ) == 0 )
        return 1;
    if( secure_atoi( argv[ SERVICE_BAUD_IDX ], &service_baud ) == 0 )
    {
        fprintf( stderr, "Invalid service baud\n" );
        return 1;
    }
    if( transport_init() == 0 )
        return 1;

    // Create global sync objects
    sem_init( &mux_w_sem, 0, 1 );
    sem_init( &mux_r_sem, 0, 0 );

    // Open all the service ports and create their corresponding threads
    if( ( threads = ( THREAD_DATA* )malloc( sizeof( THREAD_DATA ) * ( vport_num + 1 ) ) ) == NULL )
    {
        fprintf( stderr, "Not enough memory\n" );
        return 1;
    }
    for( i = 0; i <= vport_num; i ++ )
    {
        tdata = threads + i;
        if( i < vport_num )
        {
            if( ( tdata->fd = ser_open( argv[ i + FIRST_SERVICE_IDX ] ) ) == ( ser_handler )-1 )
            {
                fprintf( stderr, "Unable to open port %s\n", argv[ i + FIRST_SERVICE_IDX ] );
                return 1;
            }
            if( ser_setup( tdata->fd, service_baud, SER_DATABITS_8, SER_PARITY_NONE, SER_STOPBITS_1 ) != SER_OK )
            {
                fprintf( stderr, "Unable to setup serial port %s\n", argv[ i + FIRST_SERVICE_IDX ] );
                return 1;
            }
            tdata->pname = argv[ i + FIRST_SERVICE_IDX ];
            tdata->service_id = i + SERVICE_ID_FIRST;
        }
        if( pthread_create( &tdata->tid, NULL, i == vport_num ? transport_thread : service_thread, ( void* )tdata ) )
        {
            fprintf( stderr, "Unable to create thread\n" );
            return 1;
        }
    }

    printf( "Starting service multiplexer on %u port(s)\n", vport_num );
    // Main service thread
    while( 1 )
    {
        sem_wait( &mux_r_sem );
        data = mux_data;
        sem_post( &mux_w_sem );
        if( data.id == TRANSPORT_SERVICE_ID )
        {
            // Read one byte, interpret it
            c = data.data;
            if( c != ESCAPE_CHAR )
            {
                if( c >= SERVICE_ID_FIRST && c <= SERVICE_ID_LAST )
                    service_id_in = c;
                else
                {
                    if( got_esc )
                    {
                        // Got an escape last time, check the char now (with the 5th bit flipped)
                        c ^= ESCAPE_XOR_MASK;
                        if( c != ESCAPE_CHAR && c < SERVICE_ID_FIRST && c > SERVICE_ID_LAST )
                        {
                            fprintf( stderr, "Protocol error: invalid escape sequence\n" );
                            return 1;
                        }
                        got_esc = 0;
                    }
                    if( service_id_in == -1 )
                    {
                        fprintf( stderr, "Protocol error: service ID not specified\n" );
                        return 1;
                    }
                    ser_write_byte( threads[ service_id_in - SERVICE_ID_FIRST ].fd, c );
                }
            }
            else
                got_esc = 1;
        }
        else
        {
            temp = data.id;
            sdata = data.data;
            if( temp != service_id_out )
                transport_send_byte( temp );
            // Then send the actual data byte, escaping it if needed
            if( sdata == ESCAPE_CHAR || ( sdata >= SERVICE_ID_FIRST && sdata <= SERVICE_ID_LAST ) )
            {
                transport_send_byte( ESCAPE_CHAR );
                transport_send_byte( ( u8 )sdata ^ ESCAPE_XOR_MASK );
            }
            else
                transport_send_byte( sdata );
            service_id_out = temp;
        }
    }

    return 0;
}
Beispiel #26
0
void upsdrv_initups(void)
{
#ifndef TESTING
	const struct {
		const char	*val;
		const int	dtr;
		const int	rts;
	} cablepower[] = {
		{ "normal",	1, 0 }, /* default */
		{ "reverse",	0, 1 },
		{ "both",	1, 1 },
		{ "none",	0, 0 },
		{ NULL }
	};

	int	i;

	const char	*val;

	struct termios		tio;

	/*
	 * Open and lock the serial port and set the speed to 2400 baud.
	 */
	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, B2400);

	if (tcgetattr(upsfd, &tio)) {
		fatal_with_errno(EXIT_FAILURE, "tcgetattr");
	}

	/*
	 * Use canonical mode input processing (to read reply line)
	 */
	tio.c_lflag |= ICANON;	/* Canonical input (erase and kill processing) */

	tio.c_cc[VEOF]   = _POSIX_VDISABLE;
	tio.c_cc[VEOL]   = '\r';
	tio.c_cc[VERASE] = _POSIX_VDISABLE;
	tio.c_cc[VINTR]  = _POSIX_VDISABLE;
	tio.c_cc[VKILL]  = _POSIX_VDISABLE;
	tio.c_cc[VQUIT]  = _POSIX_VDISABLE;
	tio.c_cc[VSUSP]  = _POSIX_VDISABLE;
	tio.c_cc[VSTART] = _POSIX_VDISABLE;
	tio.c_cc[VSTOP]  = _POSIX_VDISABLE;

	if (tcsetattr(upsfd, TCSANOW, &tio)) {
		fatal_with_errno(EXIT_FAILURE, "tcsetattr");
	}

	val = getval("cablepower");
	for (i = 0; val && cablepower[i].val; i++) {

		if (!strcasecmp(val, cablepower[i].val)) {
			break;
		}
	}

	if (!cablepower[i].val) {
		fatalx(EXIT_FAILURE, "Value '%s' not valid for 'cablepower'", val);
	}

	ser_set_dtr(upsfd, cablepower[i].dtr);
	ser_set_rts(upsfd, cablepower[i].rts);

	/*
	 * Allow some time to settle for the cablepower
	 */
	usleep(100000);
#endif
	blazer_initups();
}
Beispiel #27
0
void upsdrv_initups(void)
{
	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, B2400);
}
Beispiel #28
0
void upsdrv_initups(void)
{
	upsfd = ser_open(device_path);
	pw_comm_setup(device_path);
}
Beispiel #29
0
void upsdrv_initups(void)
{
	struct termios tio;
	int baud = B1200;
	char *str;

	if ((str = getval("baudrate")) != NULL) {
		int temp = atoi(str);
		switch (temp) {
		case   300:
			baud =   B300; break;
		case   600:
			baud =   B600; break;
		case  1200:
			baud =  B1200; break;
		case  2400:
			baud =  B2400; break;
		case  4800:
			baud =  B4800; break;
		case  9600:
			baud =  B9600; break;
		case 19200:
			baud = B19200; break;
		case 38400:
			baud = B38400; break;
		default:
			fatalx(EXIT_FAILURE, "Unrecognized baudrate: %s", str);
		}
		upsdebugx(1, "baud_rate = %d", temp);
	}
	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, baud);

	if (tcgetattr(upsfd, &tio) != 0)
		fatal_with_errno(EXIT_FAILURE, "tcgetattr(%s)", device_path);
	tio.c_lflag = ICANON;
	tio.c_iflag |= IGNCR;	/* Ignore CR */
	tio.c_cc[VMIN] = 0;
	tio.c_cc[VTIME] = 0;
	tcsetattr(upsfd, TCSANOW, &tio);

	if ((str = getval("input_timeout")) != NULL) {
		int temp = atoi(str);
		if (temp <= 0)
			fatalx(EXIT_FAILURE, "Bad input_timeout parameter: %s", str);
		input_timeout_sec = temp;
	}
	upsdebugx(1, "input_timeout = %d Sec", input_timeout_sec);

	if ((str = getval("output_pace")) != NULL) {
		int temp = atoi(str);
		if (temp <= 0)
			fatalx(EXIT_FAILURE, "Bad output_pace parameter: %s", str);
		output_pace_usec = temp;
	}
	upsdebugx(1, "output_pace = %d uSec", output_pace_usec);

	if ((str = getval("full_update_timer")) != NULL) {
		int temp = atoi(str);
		if (temp <= 0)
			fatalx(EXIT_FAILURE, "Bad full_update_timer parameter: %s", str);
		full_update_timer = temp;
	}
	upsdebugx(1, "full_update_timer = %d Sec", full_update_timer);

	use_crlf = testvar("use_crlf");
	upsdebugx(1, "use_crlf = %d", use_crlf);
	use_pre_lf = testvar("use_pre_lf");
	upsdebugx(1, "use_pre_lf = %d", use_pre_lf);
}
Beispiel #30
0
/* initialize UPS */
void upsdrv_initups(void)
{
	int tmp,model = 0;
	unsigned int i;
	static char buf[20];

	/* check manufacturer name from arguments */
	if (getval("manufacturer") != NULL) 
		manufacturer = getval("manufacturer");
	
	/* check model name from arguments */
	if (getval("modelname") != NULL) 
		modelname = getval("modelname");
	
	/* check serial number from arguments */
	if (getval("serialnumber") != NULL) 
		serialnumber = getval("serialnumber");
	
	/* get and check type */
	if (getval("type") != NULL) {
		for (i = 0; 
			 i < NUM_OF_SUBTYPES  &&  strcmp(types[i].name, getval("type"));
			 i++) ;
		if (i >= NUM_OF_SUBTYPES) {
			printf("Given UPS type '%s' isn't valid!\n", getval("type"));
			exit (1);
		}
		type = i;	
	};
	
	/* check line voltage from arguments */
	if (getval("linevoltage") != NULL) {
		tmp = atoi(getval("linevoltage"));
		if (! ( (tmp >= 200 && tmp <= 240) || (tmp >= 100 && tmp <= 120) ) ) {
			printf("Given line voltage '%d' is out of range (100-120 or 200-240 V)\n", tmp);
			exit (1);
		};
		linevoltage = (unsigned int) tmp;
	};

	if (getval("numOfBytesFromUPS") != NULL) {
		tmp = atoi(getval("numOfBytesFromUPS"));
		if (! (tmp > 0 && tmp <= MAX_NUM_OF_BYTES_FROM_UPS) ) {
			printf("Given numOfBytesFromUPS '%d' is out of range (1 to %d)\n",
	               tmp, MAX_NUM_OF_BYTES_FROM_UPS);
			exit (1);
		};
		types[type].num_of_bytes_from_ups = (unsigned char) tmp;
	}

	if (getval("methodOfFlowControl") != NULL) {
		for (i = 0; 
			 i < NUM_OF_SUBTYPES  &&  
					strcmp(types[i].flowControl.name,
							getval("methodOfFlowControl"));
			 i++) ;
		if (i >= NUM_OF_SUBTYPES) {
			printf("Given methodOfFlowControl '%s' isn't valid!\n", 
					getval("methodOfFlowControl"));
			exit (1);
		};
		types[type].flowControl = types[i].flowControl;	
	}

	if (getval("validationSequence")  &&
            sscanf(getval("validationSequence"),
					"{{%u,%x},{%u,%x},{%u,%x}}",
			                &types[type].validation[0].index_of_byte,
			                &types[type].validation[0].required_value,
			                &types[type].validation[1].index_of_byte,
			                &types[type].validation[1].required_value,
			                &types[type].validation[2].index_of_byte,
			                &types[type].validation[2].required_value
			      ) < 6
	   ) {
		printf("Given validationSequence '%s' isn't valid!\n", 
								         getval("validationSequence"));
		exit (1);
	}

	if (getval("shutdownArguments")  &&
	    sscanf(getval("shutdownArguments"), "{{%u,%u},%c}",
	                &types[type].shutdown_arguments.delay[0],
	                &types[type].shutdown_arguments.delay[1],
	                &types[type].shutdown_arguments.minutesShouldBeUsed 
	          ) < 3
	   ) {
	    printf("Given shutdownArguments '%s' isn't valid!\n", 
								         getval("shutdownArguments"));
		exit (1);
	} 

	if (getval("frequency")  &&
            sscanf(getval("frequency"), "{%f,%f}",
			                &types[type].freq[0], &types[type].freq[1]
	              ) < 2
	   ) {
		printf("Given frequency '%s' isn't valid!\n", 
										getval("frequency"));
		exit (1);
	}

	if (getval("loadPercentage")  && 
            sscanf(getval("loadPercentage"), "{%f,%f,%f,%f}",
	            &types[type].loadpct[0], &types[type].loadpct[1],
	            &types[type].loadpct[2], &types[type].loadpct[3]
	              ) < 4
	   ) {
		printf("Given loadPercentage '%s' isn't valid!\n", 
								         getval("loadPercentage"));
		exit (1);
	}

	if (getval("batteryPercentage")  && 
            sscanf(getval("batteryPercentage"), "{%f,%f,%f,%f,%f}",
	                &types[type].battpct[0], &types[type].battpct[1],
	                &types[type].battpct[2], &types[type].battpct[3],
	                &types[type].battpct[4]
	              ) < 5
	   ) {
		printf("Given batteryPercentage '%s' isn't valid!\n", 
								         getval("batteryPercentage"));
		exit (1);
	}

	if (getval("voltage")  &&
            sscanf(getval("voltage"), "{%f,%f,%f,%f}",
	            &types[type].voltage[0], &types[type].voltage[1],
	            &types[type].voltage[2], &types[type].voltage[3]
				  ) < 4
	   ) {
		printf("Given voltage '%s' isn't valid!\n", getval("voltage"));
		exit (1);
	}

	/* open serial port */
	upsfd = ser_open(device_path);
	ser_set_speed(upsfd, device_path, B1200);
	
	/* setup flow control */
	types[type].flowControl.setup_flow_control();

	/* Setup Model and LineVoltage */
	if (!strncmp(types[type].name, "BNT",3) || !strcmp(types[type].name, "KIN") || !strcmp(types[type].name, "IMP") || !strcmp(types[type].name, "OPTI")) {
		if (!ups_getinfo()) return;
		/* Give "BNT-other" a chance! */
		if (raw_data[MODELNAME]==0x42 || raw_data[MODELNAME]==0x4B || raw_data[MODELNAME]==0x4F){
			/* Give "IMP" a chance also! */
			if (raw_data[UPSVERSION]==0xFF){
				types[type].name="IMP";
				model=IMPmodels[raw_data[MODELNUMBER]/16];
			}
			else {
				model=BNTmodels[raw_data[MODELNUMBER]/16];
				if (!strcmp(types[type].name, "BNT-other"))
					types[type].name="BNT-other";
				else if (raw_data[MODELNAME]==0x42)
					types[type].name="BNT";
				else if (raw_data[MODELNAME]==0x4B){
					types[type].name="KIN";
					model=KINmodels[raw_data[MODELNUMBER]/16];
				} else if (raw_data[MODELNAME]==0x4F){
					types[type].name="OPTI";
					model=OPTImodels[raw_data[MODELNUMBER]/16];
				}
			}
		}
		else if (raw_data[UPSVERSION]==0xFF){
			types[type].name="IMP";
			model=IMPmodels[raw_data[MODELNUMBER]/16];
		}
		linevoltage=voltages[raw_data[MODELNUMBER]%16];
		if (!strcmp(types[type].name, "OPTI")) {
			snprintf(buf,sizeof(buf),"%s-%d",types[type].name,model);
		} else {
			snprintf(buf,sizeof(buf),"%s-%dAP",types[type].name,model);
		}
		if (!strcmp(modelname, "Unknown"))
			modelname=buf;
		upsdebugx(1,"Detected: %s , %dV",buf,linevoltage);
		if (ser_send_char (upsfd, BATTERY_TEST) != 1) {
			upslogx(LOG_NOTICE, "writing error");
			dstate_datastale();
			return;
		}
	}
	
	upsdebugx(1, "Values of arguments:");
	upsdebugx(1, " manufacturer            : '%s'", manufacturer);
	upsdebugx(1, " model name              : '%s'", modelname);
	upsdebugx(1, " serial number           : '%s'", serialnumber);
	upsdebugx(1, " line voltage            : '%u'", linevoltage);
	upsdebugx(1, " type                    : '%s'", types[type].name);
	upsdebugx(1, " number of bytes from UPS: '%u'", 
	                        types[type].num_of_bytes_from_ups);
	upsdebugx(1, " method of flow control  : '%s'", 
    	                    types[type].flowControl.name);
	upsdebugx(1, " validation sequence: '{{%u,%#x},{%u,%#x},{%u,%#x}}'",
			            types[type].validation[0].index_of_byte,
			            types[type].validation[0].required_value,
			            types[type].validation[1].index_of_byte,
			            types[type].validation[1].required_value,
			            types[type].validation[2].index_of_byte,
			            types[type].validation[2].required_value);
	upsdebugx(1, " shutdown arguments: '{{%u,%u},%c}'",
	                types[type].shutdown_arguments.delay[0],
	                types[type].shutdown_arguments.delay[1],
	                types[type].shutdown_arguments.minutesShouldBeUsed); 
	if ( strcmp(types[type].name, "KIN") && strcmp(types[type].name, "BNT") && strcmp(types[type].name, "IMP")) {
		upsdebugx(1, " frequency calculation coefficients: '{%f,%f}'",
								types[type].freq[0], types[type].freq[1]);
		upsdebugx(1, " load percentage calculation coefficients: "
					"'{%f,%f,%f,%f}'",
						types[type].loadpct[0], types[type].loadpct[1],
						types[type].loadpct[2], types[type].loadpct[3]);
		upsdebugx(1, " battery percentage calculation coefficients: " 
					"'{%f,%f,%f,%f,%f}'",
						types[type].battpct[0], types[type].battpct[1],
						types[type].battpct[2], types[type].battpct[3],
						types[type].battpct[4]);
		upsdebugx(1, " voltage calculation coefficients: '{%f,%f}'",
							types[type].voltage[2], types[type].voltage[3]);
	}

}