コード例 #1
0
ファイル: MODBUSPuerto.cpp プロジェクト: batela/Gaypu-Src
	int MODBUSPuerto::abrir(){
		log.info("%s: %s %s",__FILE__, "Comienza abrir puerto..",this->getName().data());
		int res = 1 ;
		//struct timeval response_timeout;
		//response_timeout.tv_sec = 1;
		//response_timeout.tv_usec = 0;
		errno= 0;
		if ((ctx = modbus_new_rtu(this->getName().data(), baudrate, 'N', 8, 1)) != NULL){
			log.error("%s: %s %s",__FILE__, "Set slave error: ",modbus_strerror(errno));
			modbus_set_slave(ctx, 0x01);
			//log.error("%s: %s %s",__FILE__, "Set slave error: ",modbus_strerror(errno));
			//modbus_set_response_timeout(ctx, &response_timeout);
			if (errno != 0) log.error("%s: %s %s",__FILE__, "Set timeout error",modbus_strerror(errno));
			if (modbus_connect(ctx) == -1) {
				log.error("%s: %s %s",__FILE__, "Error al abrir puerto!",modbus_strerror(errno));
				modbus_free(ctx);
				res = 1;
				this->isOpen = false ;
			}
			else {
				this->isOpen = true ;
				res = 0 ;
				log.info("%s: %s",__FILE__, "Puerto abierto!!");
			}
		}
		return res ;
	}
コード例 #2
0
ファイル: mainform.cpp プロジェクト: kyyblabla/gas_check
bool MainForm::checkModbus(){

    if(m_modbus!=NULL){

        modbus_close(  m_modbus);
        modbus_free(  m_modbus );
        m_modbus = NULL;

    }

    char parity;
    if(Config::serialParity=="even"){
        parity = 'E';
    }else if(Config::serialParity=="odd"){
        parity = 'O';
    }else{
        parity = 'N';
    }

    m_modbus = modbus_new_rtu(Config::serialinterface.toAscii().constData(), Config::serialBaudRate,  parity,Config::serialDatabits,Config::serialStopbits );

    int re=  modbus_connect( m_modbus );

   // qDebug()<<"re:"<<re<<endl;

    return re != -1;
}
コード例 #3
0
ModbusClientV1::ModbusClientV1(char* device)
{
	ctx = modbus_new_rtu(device, 115200, 'E', 8, 1); // Port_name, Speed, Parity, Data_bits, Stop_bits
	if (ctx == NULL)
	{
		fprintf(stderr, "Unable to create the libmodbus context\n");
		return;
	}

	if (verbose > 4)
	{
		modbus_set_debug(ctx, 1);
	}

	int rc = modbus_set_slave(ctx, 1);

	// Connecting to existing modbus socket
	rc = modbus_connect(ctx);
	if (rc == -1)
	{
		fprintf(stderr, "Connection failed [%s]\n", modbus_strerror(errno));
		modbus_free(ctx);
		return;
	}

	// Change bytes and response timeouts for connections
	change_byte_timeout(0, 10000); /* 10 ms */
	change_response_timeout(0, 100000); /* 100 ms */

	isInitialized = true;
}
コード例 #4
0
ファイル: energycam.c プロジェクト: gedankennebel/ecpi
//open serial port
bool EnergyCamOpen(unsigned int dwPort ){
  m_dwPort=dwPort;
  char comDeviceName[100];
      
  sprintf(comDeviceName, "/dev/ttyUSB%d", dwPort);
  m_ctx = (modbus_t* )modbus_new_rtu(comDeviceName, m_dwBaud, 'E', 8, 1); // parity 'E'ven used by EnergyCam's freemodbus implementation
    
  if(NULL == m_ctx)
    return false;

  modbus_set_debug( m_ctx, false);
  modbus_set_slave( m_ctx, 1);

  if (modbus_connect(m_ctx) == -1) {
    fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));

    modbus_free(m_ctx);
    m_ctx = NULL;
    return false; 
  } 
  else{
    printf,( "Connection OK: \n");
  }

  return true;
}
コード例 #5
0
ファイル: modbus.c プロジェクト: mleinart/collectd
/* Version 2.9.2 */
static int mb_init_connection (mb_host_t *host) /* {{{ */
{
  int status;

  if (host == NULL)
    return (EINVAL);

  if (host->connection != NULL)
    return (0);

  if (host->conntype == MBCONN_TCP)
  {
    if ((host->port < 1) || (host->port > 65535))
      host->port = MODBUS_TCP_DEFAULT_PORT;

    DEBUG ("Modbus plugin: Trying to connect to \"%s\", port %i.",
        host->node, host->port);

    host->connection = modbus_new_tcp (host->node, host->port);
    if (host->connection == NULL)
    {
      ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
      return (-1);
    }
  }
  else
  {
    DEBUG ("Modbus plugin: Trying to connect to \"%s\", baudrate %i.",
        host->node, host->baudrate);

    host->connection = modbus_new_rtu (host->node, host->baudrate, 'N', 8, 1);
    if (host->connection == NULL)
    {
      ERROR ("Modbus plugin: Creating new Modbus/RTU object failed.");
      return (-1);
    }
  }

#if COLLECT_DEBUG
  modbus_set_debug (host->connection, 1);
#endif

  /* We'll do the error handling ourselves. */
  modbus_set_error_recovery (host->connection, 0);

  status = modbus_connect (host->connection);
  if (status != 0)
  {
    ERROR ("Modbus plugin: modbus_connect (%s, %i) failed with status %i.",
        host->node, host->port ? host->port : host->baudrate, status);
    modbus_free (host->connection);
    host->connection = NULL;
    return (status);
  }

  return (0);
} /* }}} int mb_init_connection */
コード例 #6
0
ファイル: hello.c プロジェクト: crised/electrical
int main()
{
modbus_t *ctx;
uint16_t tab_reg[64];
int rc;
int i;

ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8,1);
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}

rc = modbus_set_slave(ctx, 1);
if (rc == -1) {
fprintf(stderr, "%s\n", modbus_strerror(errno));
return -1;
}

struct timeval response_timeout;
response_timeout.tv_sec = 5;
response_timeout.tv_usec = 0;

modbus_set_response_timeout(ctx, &response_timeout);

while(1){

	modbus_connect(ctx);
	rc = modbus_read_registers(ctx, 13952, 1, &tab_reg[0]);
	if (rc == -1) {
	fprintf(stderr, "%s\n", modbus_strerror(errno));
	return -1;
	}
	usleep(17000); //max transaction timing.

	rc = modbus_read_registers(ctx, 13954, 1, &tab_reg[1]);
	if (rc == -1) {
	fprintf(stderr, "%s\n", modbus_strerror(errno));
	return -1;
	}

	for (i=0; i < 2; i++) {
	printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
	}
	//modbus_flush(ctx);
	//modbus_close(ctx);
	usleep(10000);
	modbus_close(ctx);

}

modbus_free(ctx);
return 0;
}
コード例 #7
0
  virtual int MainSetup()
  {
    this->ctx = modbus_new_rtu(this->port, this->baud, 'N', 8, 1);
    modbus_set_slave(this->ctx, this->uid);
    if (modbus_connect(this->ctx) == -1) {
      fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
      return -1;
    }

    printf("Initialising modbus master on port=%s on speed=%d\n", this->port, this->baud);
    return(0);
  }
コード例 #8
0
ファイル: main.cpp プロジェクト: pillo79/home-control
static int openSerial(const char *device, int baudrate, char parity, int data_bits, int stop_bits)
{
	int ret = 0;
	if (!mb) {
		mb = modbus_new_rtu(device, baudrate, parity, data_bits, stop_bits);
		struct timeval tv = { 0, 100000 };
		modbus_set_response_timeout(mb, &tv);
		modbus_set_debug(mb, 1);
		ret = modbus_connect(mb);
		if (ret < 0)
			closeSerial();
	}
	return ret;
}
コード例 #9
0
ファイル: serial_port.cpp プロジェクト: Perfy/wb-homa-drivers
TLibModbusContext::TLibModbusContext(const TSerialPortSettings& settings)
    : Inner(modbus_new_rtu(settings.Device.c_str(), settings.BaudRate,
                           settings.Parity, settings.DataBits, settings.StopBits))
{
    modbus_set_error_recovery(Inner, MODBUS_ERROR_RECOVERY_PROTOCOL); // FIXME

    if (settings.ResponseTimeout.count() > 0) {
        std::chrono::milliseconds response_timeout = settings.ResponseTimeout;
        struct timeval tv;
        tv.tv_sec = response_timeout.count() / 1000;
        tv.tv_usec = (response_timeout.count() % 1000) * 1000;
        modbus_set_response_timeout(Inner, &tv);
    }
}
コード例 #10
0
ファイル: vrpn_OmegaTemperature.C プロジェクト: ASPePeX/vrpn
vrpn_OmegaTemperature::vrpn_OmegaTemperature (const char * name, vrpn_Connection * c,
			const char * port, float temp1, float temp2, bool control_on):
	vrpn_Serial_Analog(name, c, port, 115200, 8, vrpn_SER_PARITY_NONE, true),
    vrpn_Analog_Output(name, c),
    vrpn_Button_Filter(name, c)
{
  // XXX Make this configurable?
  int baud = 38400;
  char parity = 'n';  // XXX What should this be?
  int stop_bits = 1;
  d_modbus = modbus_new_rtu(port, baud, parity, 8, stop_bits);
  // XXX No code below has been changed yet.

  num_channel = 6;
  o_num_channel = 3;
  num_buttons = 1;
  buttons[0] = control_on;

  // Fill in the arguments to send to the device at reset time.
  o_channel[0] = temp1;
  o_channel[1] = temp2;
  o_channel[2] = control_on;

  // Set the mode to reset
  status = STATUS_RESETTING;

  // Register to receive the message to request changes and to receive connection
  // messages.
  if (d_connection != NULL) {
    if (register_autodeleted_handler(request_m_id, handle_request_message,
      this, d_sender_id)) {
	  fprintf(stderr,"vrpn_OmegaTemperature: can't register handler\n");
	  d_connection = NULL;
    }
    if (register_autodeleted_handler(request_channels_m_id, handle_request_channels_message,
      this, d_sender_id)) {
	  fprintf(stderr,"vrpn_OmegaTemperature: can't register handler\n");
	  d_connection = NULL;
    }
    if (register_autodeleted_handler(d_ping_message_id, handle_connect_message,
      this, d_sender_id)) {
	  fprintf(stderr,"vrpn_OmegaTemperature: can't register handler\n");
	  d_connection = NULL;
    }
  } else {
	  fprintf(stderr,"vrpn_OmegaTemperature: Can't get connection!\n");
  }

}
コード例 #11
0
TDefaultModbusContext::TDefaultModbusContext(const TModbusConnectionSettings& settings)
{
    InnerContext = modbus_new_rtu(settings.Device.c_str(), settings.BaudRate,
                                  settings.Parity, settings.DataBits, settings.StopBits);
    if (!InnerContext)
        throw TModbusException("failed to create modbus context");
    modbus_set_error_recovery(InnerContext, MODBUS_ERROR_RECOVERY_PROTOCOL); // FIXME

    if (settings.ResponseTimeoutMs > 0) {
        struct timeval tv;
        tv.tv_sec = settings.ResponseTimeoutMs / 1000;
        tv.tv_usec = (settings.ResponseTimeoutMs % 1000) * 1000;
        modbus_set_response_timeout(InnerContext, &tv);
    }
}
コード例 #12
0
int initialiseRTU(void){
ctx = modbus_new_rtu("/dev/ttyUSB0", 19200, 'E',8,1);
if (ctx == NULL) {
#ifdef DEBUG_ENABLED
    qWarning() << "Modbus failed to initialise";
#endif
    return 0;
}
else {
#ifdef DEBUG_ENABLED
    qWarning() << "Modbus Initialised";

#endif
    return 1;
    }
}
コード例 #13
0
static int libmodbus_new_rtu(lua_State *L)
{
	const char *device = luaL_checkstring(L, 1);
	int baud = luaL_optnumber(L, 2, 19200);
	const char *parityin = luaL_optstring(L, 3, "EVEN");
	int databits = luaL_optnumber(L, 4, 8);
	int stopbits = luaL_optnumber(L, 5, 1);

	/* just accept baud as is */
	/* parity must be one of a few things... */
	char parity;
	switch (parityin[0]) {
	case 'e':
	case 'E':
		parity = 'E';
		break;
	case 'n':
	case 'N':
		parity = 'N';
		break;
	case 'o':
	case 'O':
		parity = 'O';
		break;
	default:
		return luaL_argerror(L, 3, "Unrecognised parity");
	}

	ctx_t *ctx = (ctx_t *) lua_newuserdata(L, sizeof(ctx_t));

	ctx->modbus = modbus_new_rtu(device, baud, parity, databits, stopbits);
	ctx->max_len = MODBUS_RTU_MAX_ADU_LENGTH;

	if (ctx->modbus == NULL) {
		return luaL_error(L, modbus_strerror(errno));
	}

	ctx->L = L;

	luaL_getmetatable(L, MODBUS_META_CTX);
	// Can I put more functions in for rtu here? maybe?
	lua_setmetatable(L, -2);

	return 1;
}
コード例 #14
0
ファイル: test_rpi.c プロジェクト: dhruvvyas90/Scratch
int main(int argc, char *argv[])
{
    uint16_t *tab_rp_registers = NULL;
    modbus_t *ctx = NULL;
    uint32_t sec_to = 1;
    uint32_t usec_to = 0;
    int i;
    int rc;
    int nb_points = 1;
    ctx = modbus_new_rtu(SERIAL_PORT, BAUD_RATE, PARITY, BYTE_SIZE, STOP_BITS);
    if (ctx == NULL) {
        fprintf(stderr, "Unable to allocate libmodbus context\n");
        return -1;
    }
    modbus_set_debug(ctx, TRUE);
    modbus_set_error_recovery(ctx, MODBUS_ERROR_RECOVERY_LINK | MODBUS_ERROR_RECOVERY_PROTOCOL);
    modbus_set_slave(ctx, SERVER_ID);
    modbus_get_response_timeout(ctx, &sec_to, &usec_to);
    modbus_enable_rpi(ctx,TRUE);
    modbus_configure_rpi_bcm_pin(ctx,RPI_PIN);
    modbus_rpi_pin_export_direction(ctx);


    //modbus_get_response_timeout(ctx, &old_response_to_sec, &old_response_to_usec);
    if (modbus_connect(ctx) == -1)
    {
        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }
    // modbus_get_response_timeout(ctx, &new_response_to_sec, &new_response_to_usec);
    /* Allocate and initialize the memory to store the registers */
    tab_rp_registers = (uint16_t *) malloc(nb_points * sizeof(uint16_t));
    memset(tab_rp_registers, 0, nb_points * sizeof(uint16_t));
    rc = modbus_read_registers(ctx, 97,1, tab_rp_registers);
    printf("Date received is : %d\n",tab_rp_registers[0]);
    free(tab_rp_registers);

    /* Close the connection */
    modbus_rpi_pin_unexport_direction(ctx);
    modbus_close(ctx);
    modbus_free(ctx);
}
コード例 #15
0
void ModBusReader::connect()
{
	this->mb = modbus_new_rtu(this->_address, this->baud, 'N', 8, 2);
	if (this->mb == NULL) {
		throw "Unable to allocate libmodbus context";
	}

	//modbus_set_debug(this->mb, TRUE);
	modbus_set_error_recovery(this->mb,
	                         (modbus_error_recovery_mode)(MODBUS_ERROR_RECOVERY_LINK |
	                         MODBUS_ERROR_RECOVERY_PROTOCOL));

	modbus_set_slave(mb, this->slave_id);

	if (modbus_connect(mb) == -1) {
		modbus_free(mb);
		throw modbus_strerror(errno);
	}
}
コード例 #16
0
modbus_t* RbCtrlIface::initializeSerialModbus( const char *device,
                                               int baud, char parity, int data_bit,
                                               int stop_bit )
{
    // >>>>> Simulation?
    if(mSimulActive)
        return NULL;
    // <<<<< Simulation?

    if( mModbus )
    {
        modbus_close( mModbus );
        modbus_free( mModbus );
    }

    mModbus = modbus_new_rtu( device, baud, parity,
                              data_bit, stop_bit );

    return mModbus;
}
コード例 #17
0
/*
 * @brief Reads a modbus RTU device's registers in an uint16_t array
 * @param const uint16_t *tab_reg, const unsigned int mb_slave_address, const unsigned int mb_reg_address, const unsigned int mb_reg_count
 * @return Number of uint16_t registers read, -1 if error
 */
int read_modbus_rtu_device(uint16_t tab_reg[],
	const unsigned int mb_slave_address,
	const unsigned int mb_reg_address,
	const unsigned int mb_reg_count)
{
	int rc = 0;
	int ret = -1;
	if (tab_reg <= 0)
		return -1;

	modbus_t *ctx;
	ctx = modbus_new_rtu(MB_DEVICE_NAME,
		MB_BITRATE,
		MB_PARITY,
		MB_DATABITS,
		MB_STOPBITS);

	if (ctx == 0)
		goto ERROR_DATA;

	if (modbus_set_slave(ctx,mb_slave_address) != 0)
		goto ERROR_DATA;

	if (modbus_connect(ctx) != 0)
		goto ERROR_CONNECTION;

	/* since here the modbus connection is established successfully */

	rc = modbus_read_registers(ctx,mb_reg_address,mb_reg_count,tab_reg);
	if (rc > 0)
		ret = rc;

ERROR_CONNECTION:
	modbus_close(ctx);
ERROR_DATA:
	modbus_free(ctx);

	return ret;
}
コード例 #18
0
ファイル: modbus.c プロジェクト: 8bitgeek/libzbxmodbus
void create_modbus_context(char *con_string, modbus_t **ctx_out, int *lock_required_out) {

    char first_char = con_string[0];
    
    if (first_char == '/') {//then its rtu(serial con)
        // -- next code is to parse first arg and find all required to connect to rtu successfully
        char rtu_port[100];
        int rtu_speed = 9600;
        char rtu_parity = 'N';
        int rtu_bits = 8;
        int rtu_stop_bit = 1;

        sscanf(con_string,"%s %d %c %d %d",rtu_port,&rtu_speed,&rtu_parity,&rtu_bits,&rtu_stop_bit);
        *lock_required_out = 1;
        *ctx_out = modbus_new_rtu(rtu_port, rtu_speed, rtu_parity, rtu_bits, rtu_stop_bit);
    }
    else {//try modbus_tcp
        *lock_required_out = 0;
        *ctx_out = modbus_new_tcp(con_string, MODBUS_TCP_DEFAULT_PORT );
    }
    
    return;
}
コード例 #19
0
ファイル: modbusdevice.c プロジェクト: steventian163/m2b
modbus_t* modbus_new_rtu_device(const char* serial_port, int slaveAddr)
{
	modbus_t* context = modbus_new_rtu(serial_port, 
		modbus_baud_rate_device_water_cool_boxihua,
		modbus_parity_device_water_cool_boxihua,
		modbus_databit_device_water_cool_boxihua,
		modbus_stopbit_device_water_cool_boxihua);

	if (context == NULL)
	{
		my_log_error("modbus_new_rtu");
		return NULL;
	}

#ifdef HAVE_DECL_TIOCSRS485
	if (modbus_rtu_set_serial_mode(context, modbus_serial_mode_device_water_cool_boxihua) < 0)
	{
		my_log_error("modbus_rtu_set_serial_mode");
		return NULL;
	}

#endif 

	if (modbus_set_slave(context, slaveAddr) < 0)
	{
		my_log_error("modbus_set_slave");
		return NULL;
	}

	if (modbus_connect(context) < 0)
	{
		my_log_error("modbus_connect");
		return NULL;
	}

	return context;
}
コード例 #20
0
ファイル: moddiag.c プロジェクト: mryndzionek/moddiag
modbus_t* modbus_init_con(options_t *opt)
{
	modbus_t *ctx;

	switch(opt->connection_type)
	{
		case _TCP:
			ctx = modbus_new_tcp(opt->ip, opt->port);
			DBG_ASSERT(ctx != NULL,"Unable to allocate libmodbus TCP context");
			modbus_set_slave(ctx, 1);
		break;

		case _RTU:
			ctx = modbus_new_rtu(opt->device, opt->baud, opt->parity, opt->data_bit, opt->stop_bit); 
			DBG_ASSERT(ctx != NULL,"Unable to allocate libmodbus RTU context");
		break;

		default:
			DBG_ASSERT(0,"Unhandled connection type %d", opt->connection_type);
	}

	return ctx;

}
コード例 #21
0
int open_modbus(unsigned short slave_address, unsigned short baud_rate)
{
ctx = modbus_new_rtu("/dev/ttyUSB0", baud_rate, 'N', 8, 1);

if (ctx == NULL) {
    fprintf(stderr, "Unable to create the libmodbus context\n");
    return -1;
}

if (modbus_connect(ctx) == -1) {
    fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
}

printf("Modbus RTU context created at %u, N, 8bit, 1\n", baud_rate);

modbus_set_slave(ctx,slave_address);

printf("Set comm slave address: %u\n", slave_address);

return 0;

}  // end open_modbus
コード例 #22
0
ファイル: unit-test-client.c プロジェクト: eliafino/mbtools
int main(int argc, char *argv[])
{
    modbus_t *ctx;
    uint16_t *tab_reg;
    int rc;
    int use_backend;
    const uint16_t values[] = {5678, 9012};

    if (argc > 1) {
        if (strcmp(argv[1], "tcp") == 0) {
            use_backend = TCP;
        } else if (strcmp(argv[1], "rtu") == 0) {
            use_backend = RTU;
        } else {
            printf("Usage:\n  %s [tcp|rtu] - Modbus client for unit testing\n\n", argv[0]);
            exit(1);
        }
    } else {
        /* By default */
        use_backend = TCP;
    }

    if (use_backend == TCP) {
        ctx = modbus_new_tcp("127.0.0.1", 1502);
    } else {
        ctx = modbus_new_rtu("/dev/ttyUSB1", 115200, 'N', 8, 1);
    }
    if (ctx == NULL) {
        fprintf(stderr, "Unable to allocate libmodbus context\n");
        return -1;
    }
    modbus_set_debug(ctx, TRUE);
    modbus_set_error_recovery(ctx,
                              MODBUS_ERROR_RECOVERY_LINK |
                              MODBUS_ERROR_RECOVERY_PROTOCOL);

    if (use_backend == RTU) {
        modbus_set_slave(ctx, SERVER_ID);
    }

    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    /* Allocate and initialize the memory to store the registers */
    tab_reg = (uint16_t *) malloc(10 * sizeof(uint16_t));

    /* Single register */
    printf("1/2 modbus_write_register");
    rc = modbus_write_register(ctx, 0, 1234);
    if (rc != 1) {
        goto close;
    }

    printf("2/2 modbus_read_registers");
    rc = modbus_read_registers(ctx, 0, 1, tab_reg);
    if (rc != 1) {
        goto close;
    }

    if (tab_reg[0] != 1234) {
        goto close;
    }

    /* Many registers */
    printf("1/2 modbus_write_registers");
    rc = modbus_write_registers(ctx, 1, 2, values);
    if (rc != 2) {
        goto close;
    }

    printf("2/2 modbus_read_registers");
    rc = modbus_read_registers(ctx, 1, 2, tab_reg);
    if (rc != 2) {
        goto close;
    }

close:
    /* Free the memory */
    free(tab_reg);

    /* Close the connection */
    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}
コード例 #23
0
ファイル: unit-test-server.c プロジェクト: octo/libmodbus
int main(int argc, char*argv[])
{
    int socket;
    modbus_t *ctx;
    modbus_mapping_t *mb_mapping;
    int rc;
    int i;
    int use_backend;
    uint8_t *query;
    int header_length;

    if (argc > 1) {
        if (strcmp(argv[1], "tcp") == 0) {
            use_backend = TCP;
        } else if (strcmp(argv[1], "rtu") == 0) {
            use_backend = RTU;
        } else {
            printf("Usage:\n  %s [tcp|rtu] - Modbus server for unit testing\n\n", argv[0]);
            return -1;
        }
    } else {
        /* By default */
        use_backend = TCP;
    }

    if (use_backend == TCP) {
        ctx = modbus_new_tcp("127.0.0.1", 1502);
        query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
    } else {
        ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
        modbus_set_slave(ctx, SERVER_ID);
        query = malloc(MODBUS_RTU_MAX_ADU_LENGTH);
    }
    header_length = modbus_get_header_length(ctx);

    modbus_set_debug(ctx, TRUE);
    modbus_set_error_recovery(ctx, TRUE);

    mb_mapping = modbus_mapping_new(
        UT_BITS_ADDRESS + UT_BITS_NB_POINTS,
        UT_INPUT_BITS_ADDRESS + UT_INPUT_BITS_NB_POINTS,
        UT_REGISTERS_ADDRESS + UT_REGISTERS_NB_POINTS,
        UT_INPUT_REGISTERS_ADDRESS + UT_INPUT_REGISTERS_NB_POINTS);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    /* Examples from PI_MODBUS_300.pdf.
       Only the read-only input values are assigned. */

    /** INPUT STATUS **/
    modbus_set_bits_from_bytes(mb_mapping->tab_input_bits,
                               UT_INPUT_BITS_ADDRESS, UT_INPUT_BITS_NB_POINTS,
                               UT_INPUT_BITS_TAB);

    /** INPUT REGISTERS **/
    for (i=0; i < UT_INPUT_REGISTERS_NB_POINTS; i++) {
        mb_mapping->tab_input_registers[UT_INPUT_REGISTERS_ADDRESS+i] =
            UT_INPUT_REGISTERS_TAB[i];;
    }

    if (use_backend == TCP) {
        socket = modbus_tcp_listen(ctx, 1);
        modbus_tcp_accept(ctx, &socket);
    } else {
        rc = modbus_connect(ctx);
        if (rc == -1) {
            fprintf(stderr, "Unable to connect %s\n", modbus_strerror(errno));
            modbus_free(ctx);
            return -1;
        }
    }

    for (;;) {
        rc = modbus_receive(ctx, -1, query);
        if (rc == -1) {
            /* Connection closed by the client or error */
            break;
        }

        /* Read holding registers */
        if (query[header_length] == 0x03) {
            if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 3)
                == UT_REGISTERS_NB_POINTS_SPECIAL) {
                printf("Set an incorrect number of values\n");
                MODBUS_SET_INT16_TO_INT8(query, header_length + 3,
                                         UT_REGISTERS_NB_POINTS);
            } else if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1)
                == UT_REGISTERS_ADDRESS_SPECIAL) {
                modbus_reply_exception(ctx, query,
                                       MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY);
                continue;
            }
        }

        rc = modbus_reply(ctx, query, rc, mb_mapping);
        if (rc == -1) {
            break;
        }
    }

    printf("Quit the loop: %s\n", modbus_strerror(errno));

    if (use_backend == TCP) {
        close(socket);
    }
    modbus_mapping_free(mb_mapping);
    free(query);
    modbus_free(ctx);

    return 0;
}
コード例 #24
0
int main(int argc, char *argv[])
{
    int s = -1;
    modbus_t *ctx = NULL;
    modbus_mapping_t *mb_mapping = NULL;
    int rc;
    int use_backend;

     /* TCP */
    if (argc > 1) {
        if (strcmp(argv[1], "tcp") == 0) {
            use_backend = TCP;
        } else if (strcmp(argv[1], "rtu") == 0) {
            use_backend = RTU;
        } else {
            printf("Usage:\n  %s [tcp|rtu] - Modbus client to measure data bandwith\n\n", argv[0]);
            exit(1);
        }
    } else {
        /* By default */
        use_backend = TCP;
    }

    if (use_backend == TCP) {
        ctx = modbus_new_tcp("127.0.0.1", 1502);
        s = modbus_tcp_listen(ctx, 1);
        modbus_tcp_accept(ctx, &s);

    } else {
        ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
        modbus_set_slave(ctx, 1);
        modbus_connect(ctx);
    }

    mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
                                    MODBUS_MAX_READ_REGISTERS, 0);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    for(;;) {
        uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];

        rc = modbus_receive(ctx, query);
        if (rc > 0) {
            modbus_reply(ctx, query, rc, mb_mapping);
        } else if (rc  == -1) {
            /* Connection closed by the client or error */
            break;
        }
    }

    printf("Quit the loop: %s\n", modbus_strerror(errno));

    modbus_mapping_free(mb_mapping);
    if (s != -1) {
        close(s);
    }
    /* For RTU, skipped by TCP (no TCP connect) */
    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}
コード例 #25
0
/* At each loop, the program works in the range ADDRESS_START to
 * ADDRESS_END then ADDRESS_START + 1 to ADDRESS_END and so on.
 */
int main(void)
{
    modbus_t *ctx;
    int rc;
    int nb_fail;
    int nb_loop;
    int addr;
    int nb;
    uint16_t *tab_rp_registers;
    char query[100];
    int reg_address;


    /* RTU */
    ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8, 1);
    modbus_set_slave(ctx, SERVER_ID);

    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection failed: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }


     MYSQL *con = mysql_init(NULL);
    
	if (con == NULL) 
	  {
	      fprintf(stderr, "%s\n", mysql_error(con));
	      exit(1);
	  }

	  if (mysql_real_connect(con, "localhost", "root", "root", 
	          NULL, 0, NULL, 0) == NULL) 
	  {
	      fprintf(stderr, "%s\n", mysql_error(con));
	      mysql_close(con);
	      exit(1);
	  }  

	if(mysql_select_db(con, "embedded")==0)/*success*/
	    printf( "Database Selected\n");
	else
	    printf( "Failed to connect to Database: Error: \n");

	if (mysql_query(con, "select address from configuration")) {
	      fprintf(stderr, "%s\n", mysql_error(con));
	      exit(1);
	   }

	MYSQL_RES * res = mysql_use_result(con);
	
	 nb =  mysql_num_rows(res);
         tab_rp_registers = (uint16_t *) malloc(nb * sizeof(uint16_t));
	 memset(tab_rp_registers, 0, nb * sizeof(uint16_t));

	 MYSQL_ROW row;
	   /* output table name */
	   printf("Addresses from database:\n");
   	   while ((row = mysql_fetch_row(res)) != NULL) {

		reg_address = atoi(row[0]);
                addr = reg_address - 30000;
      		printf("%i \n", addr);
 		rc = modbus_read_input_registers(ctx, addr, 1, tab_rp_registers);

                if (rc == -1) {
                    printf("ERROR modbus_read_input_registers (%d)\n", rc);
                    nb_fail++;
                } else{
                    printf("Address = %d, value %d \n",addr, tab_rp_registers[0]);
                }

		sprintf(query, "INSERT INTO solar_panel_data (address, value) VALUES (%i, %d)", reg_address, tab_rp_registers[0]);
		printf("%s\n", query);
/*		if (mysql_query(con, "INSERT INTO solar_panel_data (address, value) VALUES (30001, 65273)")) {
			printf("ERROR writing to database");
  		}
*/	   }
	   mysql_free_result(res);
//do the queries in to matrix
 if (mysql_query(con, "INSERT INTO solar_panel_data (address, value) VALUES (30001, 65273)")) {
                        printf("ERROR writing to database");
                }

 
    /* Free the memory */
    free(tab_rp_registers);

    /* Close the connection */
    modbus_close(ctx);
    modbus_free(ctx);
    mysql_close(con);

    return 0;
}
コード例 #26
0
int main(int argc, char **argv)
{
    int retval = 0;
    modbus_t *mb_ctx;
    haldata_t *haldata;
    slavedata_t slavedata;
    int slave;
    int hal_comp_id;
    struct timespec loop_timespec, remaining;
    int baud, bits, stopbits, verbose;
    char *device, *endarg;
    char parity;
    int opt;
    int argindex, argvalue;
    done = 0;

    // assume that nothing is specified on the command line
    baud = 38400;
    bits = 8;
    stopbits = 1;
    verbose = 0;
    device = "/dev/ttyS0";
    parity = 'O';

    /* slave / register info */
    slave = 1;
    slavedata.read_reg_start = START_REGISTER_R;
    slavedata.read_reg_count = NUM_REGISTERS_R;
    slavedata.write_reg_start = START_REGISTER_W;
    slavedata.write_reg_count = NUM_REGISTERS_R;

    // process command line options
    while ((opt=getopt_long(argc, argv, option_string, long_options, NULL)) != -1) {
        switch(opt) {
            case 'b':   // serial data bits, probably should be 8 (and defaults to 8)
                argindex=match_string(optarg, bitstrings);
                if (argindex<0) {
                    printf("gs2_vfd: ERROR: invalid number of bits: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                bits = atoi(bitstrings[argindex]);
                break;
            case 'd':   // device name, default /dev/ttyS0
                // could check the device name here, but we'll leave it to the library open
                if (strlen(optarg) > FILENAME_MAX) {
                    printf("gs2_vfd: ERROR: device node name is too long: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                device = strdup(optarg);
                break;
            case 'g':
            case 'v':
                verbose = 1;
                break;
            case 'n':   // module base name
                if (strlen(optarg) > HAL_NAME_LEN-20) {
                    printf("gs2_vfd: ERROR: HAL module name too long: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                modname = strdup(optarg);
                break;
            case 'p':   // parity, should be a string like "even", "odd", or "none"
                argindex=match_string(optarg, paritystrings);
                if (argindex<0) {
                    printf("gs2_vfd: ERROR: invalid parity: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                parity = paritychars[argindex];
                break;
            case 'r':   // Baud rate, 38400 default
                argindex=match_string(optarg, ratestrings);
                if (argindex<0) {
                    printf("gs2_vfd: ERROR: invalid baud rate: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                baud = atoi(ratestrings[argindex]);
                break;
            case 's':   // stop bits, defaults to 1
                argindex=match_string(optarg, stopstrings);
                if (argindex<0) {
                    printf("gs2_vfd: ERROR: invalid number of stop bits: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                stopbits = atoi(stopstrings[argindex]);
                break;
            case 't':   // target number (MODBUS ID), default 1
                argvalue = strtol(optarg, &endarg, 10);
                if ((*endarg != '\0') || (argvalue < 1) || (argvalue > 254)) {
                    printf("gs2_vfd: ERROR: invalid slave number: %s\n", optarg);
                    retval = -1;
                    goto out_noclose;
                }
                slave = argvalue;
                break;
            case 'h':
            default:
                usage(argc, argv);
                exit(0);
                break;
        }
    }

    printf("%s: device='%s', baud=%d, parity='%c', bits=%d, stopbits=%d, address=%d, verbose=%d\n",
           modname, device, baud, parity, bits, stopbits, slave, verbose);
    /* point TERM and INT signals at our quit function */
    /* if a signal is received between here and the main loop, it should prevent
            some initialization from happening */
    signal(SIGINT, quit);
    signal(SIGTERM, quit);

    /* Assume 38.4k O-8-1 serial settings, device 1 */
    mb_ctx = modbus_new_rtu(device, baud, parity, bits, stopbits);
    if (mb_ctx == NULL) {
        printf("%s: ERROR: couldn't open modbus serial device: %s\n", modname, modbus_strerror(errno));
        goto out_noclose;
    }

    /* the open has got to work, or we're out of business */
    if (((retval = modbus_connect(mb_ctx))!=0) || done) {
        printf("%s: ERROR: couldn't open serial device: %s\n", modname, modbus_strerror(errno));
        goto out_noclose;
    }

    modbus_set_debug(mb_ctx, verbose);

    modbus_set_slave(mb_ctx, slave);

    /* create HAL component */
    hal_comp_id = hal_init(modname);
    if ((hal_comp_id < 0) || done) {
        printf("%s: ERROR: hal_init failed\n", modname);
        retval = hal_comp_id;
        goto out_close;
    }

    /* grab some shmem to store the HAL data in */
    haldata = (haldata_t *)hal_malloc(sizeof(haldata_t));
    if ((haldata == 0) || done) {
        printf("%s: ERROR: unable to allocate shared memory\n", modname);
        retval = -1;
        goto out_close;
    }

    retval = hal_pin_s32_newf(HAL_OUT, &(haldata->stat1), hal_comp_id, "%s.status-1", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_s32_newf(HAL_OUT, &(haldata->stat2), hal_comp_id, "%s.status-2", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_cmd), hal_comp_id, "%s.frequency-command", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->freq_out), hal_comp_id, "%s.frequency-out", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->curr_out), hal_comp_id, "%s.output-current", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->DCBusV), hal_comp_id, "%s.DC-bus-volts", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->outV), hal_comp_id, "%s.output-voltage", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->RPM), hal_comp_id, "%s.motor-RPM", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->scale_freq), hal_comp_id, "%s.scale-frequency", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->power_factor), hal_comp_id, "%s.power-factor", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_float_newf(HAL_OUT, &(haldata->load_pct), hal_comp_id, "%s.load-percentage", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_s32_newf(HAL_OUT, &(haldata->FW_Rev), hal_comp_id, "%s.firmware-revision", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_s32_newf(HAL_RW, &(haldata->errorcount), hal_comp_id, "%s.error-count", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_float_newf(HAL_RW, &(haldata->looptime), hal_comp_id, "%s.loop-time", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_s32_newf(HAL_RW, &(haldata->retval), hal_comp_id, "%s.retval", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_bit_newf(HAL_OUT, &(haldata->at_speed), hal_comp_id, "%s.at-speed", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_bit_newf(HAL_OUT, &(haldata->is_stopped), hal_comp_id, "%s.is-stopped", modname); // JET
    if (retval!=0) goto out_closeHAL; 
    retval = hal_pin_float_newf(HAL_IN, &(haldata->speed_command), hal_comp_id, "%s.speed-command", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_on), hal_comp_id, "%s.spindle-on", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_fwd), hal_comp_id, "%s.spindle-fwd", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_bit_newf(HAL_IN, &(haldata->spindle_rev), hal_comp_id, "%s.spindle-rev", modname); //JET
    if (retval!=0) goto out_closeHAL;
    retval = hal_pin_bit_newf(HAL_IN, &(haldata->err_reset), hal_comp_id, "%s.err-reset", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_float_newf(HAL_RW, &(haldata->speed_tolerance), hal_comp_id, "%s.tolerance", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_float_newf(HAL_RW, &(haldata->motor_hz), hal_comp_id, "%s.nameplate-HZ", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_float_newf(HAL_RW, &(haldata->motor_RPM), hal_comp_id, "%s.nameplate-RPM", modname);
    if (retval!=0) goto out_closeHAL;
    retval = hal_param_s32_newf(HAL_RW, &(haldata->ack_delay), hal_comp_id, "%s.ack-delay", modname);
    if (retval!=0) goto out_closeHAL;

    /* make default data match what we expect to use */
    *(haldata->stat1) = 0;
    *(haldata->stat2) = 0;
    *(haldata->freq_cmd) = 0;
    *(haldata->freq_out) = 0;
    *(haldata->curr_out) = 0;
    *(haldata->DCBusV) = 0;
    *(haldata->outV) = 0;
    *(haldata->RPM) = 0;
    *(haldata->scale_freq) = 0;
    *(haldata->power_factor) = 0;
    *(haldata->load_pct) = 0;
    *(haldata->FW_Rev) = 0;
    haldata->errorcount = 0;
    haldata->looptime = 0.1;
    haldata->motor_RPM = 1730;
    haldata->motor_hz = 60;
    haldata->speed_tolerance = 0.01;
    haldata->ack_delay = 2;
    *(haldata->err_reset) = 0;
    *(haldata->spindle_on) = 0;
    *(haldata->spindle_fwd) = 1;
    *(haldata->spindle_rev) = 0;
    haldata->old_run = -1;		// make sure the initial value gets output
    haldata->old_dir = -1;
    haldata->old_err_reset = -1;
    hal_ready(hal_comp_id);
    
    /* here's the meat of the program.  loop until done (which may be never) */
    while (done==0) {
        read_data(mb_ctx, &slavedata, haldata);
        write_data(mb_ctx, &slavedata, haldata);
        /* don't want to scan too fast, and shouldn't delay more than a few seconds */
        if (haldata->looptime < 0.001) haldata->looptime = 0.001;
        if (haldata->looptime > 2.0) haldata->looptime = 2.0;
        loop_timespec.tv_sec = (time_t)(haldata->looptime);
        loop_timespec.tv_nsec = (long)((haldata->looptime - loop_timespec.tv_sec) * 1000000000l);
        nanosleep(&loop_timespec, &remaining);
    }
    
    retval = 0;	/* if we get here, then everything is fine, so just clean up and exit */
out_closeHAL:
    hal_exit(hal_comp_id);
out_close:
    modbus_close(mb_ctx);
    modbus_free(mb_ctx);
out_noclose:
    return retval;
}
コード例 #27
0
int main(int argc, char*argv[])
{
    int s = -1;
    modbus_t *ctx;
    modbus_mapping_t *mb_mapping;
    int rc;
    int i;
    int use_backend;
    uint8_t *query;
    int header_length;

    if (argc > 1) {
        if (strcmp(argv[1], "tcp") == 0) {
            use_backend = TCP;
        } else if (strcmp(argv[1], "tcppi") == 0) {
            use_backend = TCP_PI;
        } else if (strcmp(argv[1], "rtu") == 0) {
            use_backend = RTU;
        } else {
            printf("Usage:\n  %s [tcp|tcppi|rtu] - Modbus server for unit testing\n\n", argv[0]);
            return -1;
        }
    } else {
        /* By default */
        use_backend = TCP;
    }

    if (use_backend == TCP) {
        ctx = modbus_new_tcp("127.0.0.1", 1502);
        query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
    } else if (use_backend == TCP_PI) {
        ctx = modbus_new_tcp_pi("::0", "1502");
        query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
    } else {
        ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
        modbus_set_slave(ctx, SERVER_ID);
        query = malloc(MODBUS_RTU_MAX_ADU_LENGTH);
    }
    header_length = modbus_get_header_length(ctx);

    modbus_set_debug(ctx, TRUE);

    mb_mapping = modbus_mapping_new(
        UT_BITS_ADDRESS + UT_BITS_NB,
        UT_INPUT_BITS_ADDRESS + UT_INPUT_BITS_NB,
        UT_REGISTERS_ADDRESS + UT_REGISTERS_NB,
        UT_INPUT_REGISTERS_ADDRESS + UT_INPUT_REGISTERS_NB);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    /* Unit tests of modbus_mapping_new (tests would not be sufficient if two
       nb_* were identical) */
    if (mb_mapping->nb_bits != UT_BITS_ADDRESS + UT_BITS_NB) {
        printf("Invalid nb bits (%d != %d)\n", UT_BITS_ADDRESS + UT_BITS_NB, mb_mapping->nb_bits);
        modbus_free(ctx);
        return -1;
    }

    if (mb_mapping->nb_input_bits != UT_INPUT_BITS_ADDRESS + UT_INPUT_BITS_NB) {
        printf("Invalid nb input bits: %d\n", UT_INPUT_BITS_ADDRESS + UT_INPUT_BITS_NB);
        modbus_free(ctx);
        return -1;
    }

    if (mb_mapping->nb_registers != UT_REGISTERS_ADDRESS + UT_REGISTERS_NB) {
        printf("Invalid nb registers: %d\n", UT_REGISTERS_ADDRESS + UT_REGISTERS_NB);
        modbus_free(ctx);
        return -1;
    }

    if (mb_mapping->nb_input_registers != UT_INPUT_REGISTERS_ADDRESS + UT_INPUT_REGISTERS_NB) {
        printf("Invalid nb input registers: %d\n", UT_INPUT_REGISTERS_ADDRESS + UT_INPUT_REGISTERS_NB);
        modbus_free(ctx);
        return -1;
    }

    /* Examples from PI_MODBUS_300.pdf.
       Only the read-only input values are assigned. */

    /** INPUT STATUS **/
    modbus_set_bits_from_bytes(mb_mapping->tab_input_bits,
                               UT_INPUT_BITS_ADDRESS, UT_INPUT_BITS_NB,
                               UT_INPUT_BITS_TAB);

    /** INPUT REGISTERS **/
    for (i=0; i < UT_INPUT_REGISTERS_NB; i++) {
        mb_mapping->tab_input_registers[UT_INPUT_REGISTERS_ADDRESS+i] =
            UT_INPUT_REGISTERS_TAB[i];;
    }

    if (use_backend == TCP) {
        s = modbus_tcp_listen(ctx, 1);
        modbus_tcp_accept(ctx, &s);
    } else if (use_backend == TCP_PI) {
        s = modbus_tcp_pi_listen(ctx, 1);
        modbus_tcp_pi_accept(ctx, &s);
    } else {
        rc = modbus_connect(ctx);
        if (rc == -1) {
            fprintf(stderr, "Unable to connect %s\n", modbus_strerror(errno));
            modbus_free(ctx);
            return -1;
        }
    }

    for (;;) {
        do {
            rc = modbus_receive(ctx, query);
            /* Filtered queries return 0 */
        } while (rc == 0);

        /* The connection is not closed on errors which require on reply such as
           bad CRC in RTU. */
        if (rc == -1 && errno != EMBBADCRC) {
            /* Quit */
            break;
        }

        /* Special server behavior to test client */
        if (query[header_length] == 0x03) {
            /* Read holding registers */

            if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 3)
                == UT_REGISTERS_NB_SPECIAL) {
                printf("Set an incorrect number of values\n");
                MODBUS_SET_INT16_TO_INT8(query, header_length + 3,
                                         UT_REGISTERS_NB_SPECIAL - 1);
            } else if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1)
                       == UT_REGISTERS_ADDRESS_SPECIAL) {
                printf("Reply to this special register address by an exception\n");
                modbus_reply_exception(ctx, query,
                                       MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY);
                continue;
            } else if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1)
                       == UT_REGISTERS_ADDRESS_INVALID_TID_OR_SLAVE) {
                const int RAW_REQ_LENGTH = 5;
                uint8_t raw_req[] = {
                    (use_backend == RTU) ? INVALID_SERVER_ID : 0xFF,
                    0x03,
                    0x02, 0x00, 0x00
                };

                printf("Reply with an invalid TID or slave\n");
                modbus_send_raw_request(ctx, raw_req, RAW_REQ_LENGTH * sizeof(uint8_t));
                continue;
            } else if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1)
                       == UT_REGISTERS_ADDRESS_SLEEP_500_MS) {
                printf("Sleep 0.5 s before replying\n");
                usleep(500000);
            } else if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1)
                       == UT_REGISTERS_ADDRESS_BYTE_SLEEP_5_MS) {
                /* Test low level only available in TCP mode */
                /* Catch the reply and send reply byte a byte */
                uint8_t req[] = "\x00\x1C\x00\x00\x00\x05\xFF\x03\x02\x00\x00";
                int req_length = 11;
                int w_s = modbus_get_socket(ctx);

                /* Copy TID */
                req[1] = query[1];
                for (i=0; i < req_length; i++) {
                    printf("(%.2X)", req[i]);
                    usleep(5000);
                    send(w_s, (const char*)(req + i), 1, MSG_NOSIGNAL);
                }
                continue;
            }
        }

        rc = modbus_reply(ctx, query, rc, mb_mapping);
        if (rc == -1) {
            break;
        }
    }

    printf("Quit the loop: %s\n", modbus_strerror(errno));

    if (use_backend == TCP) {
        if (s != -1) {
            close(s);
        }
    }
    modbus_mapping_free(mb_mapping);
    free(query);
    /* For RTU */
    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}
コード例 #28
0
ファイル: bandwidth-server-one.c プロジェクト: peterax/hallon
int main(int argc, char *argv[])
{
    int socket;
    modbus_t *ctx;
    modbus_mapping_t *mb_mapping;
    int rc;
    int use_backend;
    int justacounter;
    
    justacounter = 0;

while (TRUE) {
	
	
     /* TCP */
    if (argc > 1) {
        if (strcmp(argv[1], "tcp") == 0) {
            use_backend = TCP;
        } else if (strcmp(argv[1], "rtu") == 0) {
            use_backend = RTU;
        } else {
            printf("Usage:\n  %s [tcp|rtu] - Modbus client to measure data bandwith\n\n", argv[0]);
            exit(1);
        }
    } else {
        /* By default */
        use_backend = TCP;
	printf("bandwidth-server-one:\n Running in tcp mode - Modbus client to measure data bandwith\n\n");
    }

    if (use_backend == TCP) {
        printf("Waiting for TCP connection\n");
        ctx = modbus_new_tcp("127.0.0.1", 502);
        socket = modbus_tcp_listen(ctx, 1);
        modbus_tcp_accept(ctx, &socket);
        modbus_set_debug(ctx, TRUE);
	printf("TCP connection started!\n");
    } else {
	printf("Waiting for Serial connection\n");
        ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
        modbus_set_slave(ctx, 1);
        modbus_connect(ctx);
	printf("Serial connection started!\n");
    }

    mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 22,
                                    MODBUS_MAX_READ_REGISTERS, 22);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    for(;;) {
        uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];

        rc = modbus_receive(ctx, query);
        if (rc >= 0) {
		mb_mapping->tab_input_registers[0] = justacounter++;	
	    printf("Replying to request.\n");
            modbus_reply(ctx, query, rc, mb_mapping);
        } else {
            /* Connection closed by the client or server */
           break;
        }
    }

    printf("Quit the loop: %s\n", modbus_strerror(errno));

    modbus_mapping_free(mb_mapping);
    close(socket);
    modbus_free(ctx);
}
    return 0;
}
コード例 #29
0
int main(int argc, char *argv[])
{
	srand((unsigned)time(NULL));
	int ctxnum = 0;
	int i;
	int sel = 1;

	modbus_t *ctx[SLAVE_NUM];			// modbus structure, save connect data
	char portName[SLAVE_NUM][100];	// for save port name
	int slaveID[SLAVE_NUM];			// for save slave id
	int bitRate[SLAVE_NUM];			// for save bit rate
	char parity[SLAVE_NUM];			// for save parity option

	for ( i=0 ; i<SLAVE_NUM ; i++ )
		ctx[i] = NULL;

	if ( argc != 1 )
	{
		printf("Usage : %s\n", argv[0] );
		exit(1);
	}
/*
	if ( argc == 2 )
		if ( !strcmp( argv[1], "ON" ))
			modbus_set_debug(ctx, TRUE);
*/
	while ( sel != -2 )
	{
		for ( i=0 ; i<ctxnum ; i++ )
			printf("%4d. %s	%d	%d	%c\n", i, portName[i], slaveID[i], bitRate[i], parity[i] );
		printf("  -1. make new connect\n");
		printf("  -2. quit\n");
		printf(" sel	: ");
		scanf("%d", &sel);

		switch ( sel )
		{
			case -1 :
				{
					if ( ctxnum == 246 )
						printf("\nconnection is full!!!\n\n");
					printf("\n\tinput port name : ");
					scanf("%s", portName[ctxnum]);
					printf("\tinput slave ID	: ");
					scanf("%d", &slaveID[ctxnum]);
					printf("\tinput bit rate : ");
					scanf("%d", &bitRate[ctxnum]);
					printf("\tinput parity : ");
					fgetc(stdin);
					parity[ctxnum] = fgetc(stdin);

					ctx[ctxnum] = modbus_new_rtu(portName[ctxnum], bitRate[ctxnum], parity[ctxnum], 8, 1);
					// make rtu connection

					if (ctx[ctxnum] == NULL) {          // error
						fprintf(stderr, "Unable to allocate libmodbus context\n");
						return -1;
					}

					modbus_set_error_recovery(ctx[ctxnum],
							MODBUS_ERROR_RECOVERY_LINK |
							MODBUS_ERROR_RECOVERY_PROTOCOL);

					modbus_set_slave(ctx[ctxnum], slaveID[ctxnum]);       // set slave number

					if (modbus_connect(ctx[ctxnum]) == -1) {
						fprintf(stderr, "Connection failed: %s\n",
								modbus_strerror(errno));
						modbus_free(ctx[ctxnum]);
						return -1;
					}
					ctxnum++;
					printf("\n");
				}
			break;
		case -2 :
			printf("exit client module (master)\n");
			break;
		default :
			if ( ctx[sel] == NULL || sel <-2 || sel>246  )
				printf("\ninput correct number.\n\n");		// error input
			else
				connectToSlave(ctx[sel]);	// cennect to slave
		}
	}

	/* Close the connection */
	for ( i=0 ; i<SLAVE_NUM; i++ )
	{
		if ( ctx[i] != NULL )
		{
			modbus_close(ctx[i]);
			modbus_free(ctx[i]);
		}
	}
	return 0;
}
コード例 #30
0
ファイル: client_serial2.c プロジェクト: csts0090/modbus
int main(int argc, char *argv[])
{
    modbus_t            *ctx;
    struct timeval      timeout;
    int                 ret, i, rc, ii,iii;
    int nb_pointers;
   // unit16_t *tab_rp_registers;
    uint16_t        regs[MODBUS_MAX_READ_REGISTERS] = {0}; 
    uint16_t        regs2[MODBUS_MAX_READ_REGISTERS] = {0};
    char            regs3[MODBUS_MAX_READ_REGISTERS] = {0};
    FILE *fp = NULL;
 

    if(argc < 3){
        printf("INsufficient argument");
        return -1;
    }


    ctx = modbus_new_rtu(MODBUS_SERIAL_DEV,
            MODBUS_SERIAL_BAUDRATE,
            MODBUS_SERIAL_PARITY,
            MODBUS_SERIAL_DATABITS,
            MODBUS_SERIAL_STOPBITS);
 
    if (ctx == NULL) {
        fprintf(stderr, "Unable to create the libmodbus context\n");
        exit(-1);
    }
 
    
    i = modbus_rtu_get_serial_mode(ctx);
    if( i == MODBUS_RTU_RS232)
    {
	printf("Serial mode = RS232\n");
	ret = modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS232);
	if(ret < 0)
	    fprintf(stderr, "modbus_rtu_set_serial_mode() error: %s\n", strerror(errno));
    }
    else if(i == MODBUS_RTU_RS485)
    {
	printf("Serial mode = RS485\n");
	ret = modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485);
	if(ret < 0)
	    fprintf(stderr, "modbus_rtu_set_serial_mode() error: %s\n", strerror(errno));
    }
    else
    {
	printf("Serial mode = RS485\n");
	ret = modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485);
	if(ret < 0)
	    fprintf(stderr, "modbus_rtu_set_serial_mode() error: %s\n", strerror(errno));
    }

    /* set slave device ID */
    modbus_set_slave(ctx, MODBUS_DEVICE_ID);
 
    /* Debug mode */
    modbus_set_debug(ctx, MODBUS_DEBUG);

    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection failed: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }


    /* Allocate and initialize the memory to store the registers */
  /*  nb_points = (UT_REGISTERS_NB > UT_INPUT_REGISTERS_NB) ?
        UT_REGISTERS_NB : UT_INPUT_REGISTERS_NB;
    tab_rp_registers = (uint16_t *) malloc(nb_points * sizeof(uint16_t));
    memset(tab_rp_registers, 0, nb_points * sizeof(uint16_t));
    */

     /* write data in test.txt */
    fp = fopen("test2.txt", "w");
    if(fp == NULL)
    {
        printf("fail to open file!\n");
        return -1;
    }


    for( iii=1; iii <= strtol(argv[2],NULL, 10);iii++)
        {
                regs[iii] = strtol(argv[iii+2], NULL, 10);
        }

        rc = modbus_write_registers(ctx, strtol(argv[1], NULL, 16), strtol(argv[2], NULL, 10), &regs[1]);
         if (rc < 0) {
                fprintf(stderr, "%s\n", modbus_strerror(errno));
         }


    /* read holding registers (0x03 function code) */

   rc = modbus_read_registers(ctx, strtol(argv[1], NULL, 16), strtol(argv[2], NULL, 10), regs2);
    if (rc < 0) {
        fprintf(stderr, "%s\n", modbus_strerror(errno));
    }
    else {
            printf("HOLDING REGISTERS:\n");
            for (ii=0; ii < rc; ii++) {
                sprintf(regs3, "%d", regs2[ii]);
                fputs(regs3, fp);
                fputs("\n", fp);
                printf("[%d]=%d\n", ii, regs2[ii]);
            }
    }


    fclose(fp);

    /* Close the connection */
    modbus_close(ctx);

    modbus_free(ctx);
 
    return 0;
}