int main(int argc, char *argv[])
{
    uint16_t regs[1];
	float heaterTemp;
	float heaterSetPoint;
	char * heaterEnableState;
	char * heaterElementState;

	char * modbusClientIP = DEFAULT_CLIENT_IP;
	int modbusPort = DEFAULT_PORT;
    int packet_counter = 0;
	uint8_t *tab_bits;
	uint16_t *tab_input_value_registers;

	tab_bits = (uint8_t *)malloc(NO_BITS * sizeof(uint8_t));
	memset(tab_bits, 0, NO_BITS * sizeof(uint8_t));


	tab_input_value_registers = (uint16_t *)malloc(NO_REGS* sizeof(uint16_t));
	memset(tab_input_value_registers, 0, NO_REGS * sizeof(uint16_t));
        
    
        bool sts;
        int rc;
        uint8_t coils[2];
        ctx = modbus_new_tcp(modbusClientIP, modbusPort);
        if (ctx == NULL) {
            fprintf(stderr, "Unable to allocate libmodbus context\n");
            return -1;
        }
        
        if (modbus_connect(ctx) == -1) {
            sts = false;
        }
        
        rc = modbus_read_input_registers(ctx,0,1, regs);
        packet_counter++;
        printf("Packet No: %d, Value of current:%d\n",packet_counter, regs[0]);
        modbus_close(ctx);
		
     
        ctx = modbus_new_tcp(modbusClientIP, modbusPort);
        if (ctx == NULL) {
            fprintf(stderr, "Unable to allocate libmodbus context\n");
            return -1;
        }
        if (modbus_connect(ctx) == -1) {
            sts = false;
            
        }
        modbus_close(ctx);
        modbus_free(ctx);

    
    return 0;

}
示例#2
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;
}
示例#3
0
int _modbus_rtu_select(modbus_t *ctx, fd_set *rfds, struct timeval *tv, int length_to_read)
{
    int s_rc;
#if defined(_WIN32)
    s_rc = win32_ser_select(&(((modbus_rtu_t*)ctx->backend_data)->w_ser), length_to_read, tv);
    if (s_rc == 0) {
        errno = ETIMEDOUT;
        return -1;
    }

    if (s_rc < 0) {
        _error_print(ctx, "select");
        if (ctx->error_recovery && (errno == EBADF)) {
            modbus_close(ctx);
            modbus_connect(ctx);
            errno = EBADF;
            return -1;
        } else {
            return -1;
        }
    }
#else
    while ((s_rc = select(ctx->s+1, rfds, NULL, NULL, tv)) == -1) {
        if (errno == EINTR) {
            if (ctx->debug) {
                fprintf(stderr, "A non blocked signal was caught\n");
            }
            /* Necessary after an error */
            FD_ZERO(rfds);
            FD_SET(ctx->s, rfds);
        } else {
            _error_print(ctx, "select");
            if (ctx->error_recovery && (errno == EBADF)) {
                modbus_close(ctx);
                modbus_connect(ctx);
                errno = EBADF;
                return -1;
            } else {
                return -1;
            }
        }
    }

    if (s_rc == 0) {
        /* Timeout */
        errno = ETIMEDOUT;
        _error_print(ctx, "select");
        return -1;
    }
#endif

    return s_rc;
}
示例#4
0
void *poll_modbus(void *ctx_p) {
    int retval;
    modbus_t *ctx = (modbus_t *) ctx_p;

    /* Bring data into buffer */
    while (1) {
	/* TCP requests - may block */

	GET_REGS(826, 826);
	GET_REGS(352, 353);
	GET_REGS(902, 902);

	if (retval < 0) {
	    printf("modbus: Error on poll\n");
	    /* Attempt reconnect */
	    modbus_close(ctx);
	    if (modbus_connect(ctx) == -1) {
		/* Kill the process */
		exit(1);
	    }

	}

	pthread_mutex_lock(&modbus_lock);
	modbus_data = priv_modbus_data;
	pthread_mutex_unlock(&modbus_lock);

	usleep(MODBUS_POLL_INTERVAL_US);
    }
}
示例#5
0
//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;
}
    modbus_ctrl::modbus_ctrl(modbus_t* context) :
        next_write_time(0),
        shadow_registers()
    {
        this->context = context;
        if(context == NULL)
        {
            throw modbus_exception();
        }
        
        //set timeout
        struct timeval timeout_end;
        struct timeval timeout_begin;
        modbus_get_byte_timeout(context, &timeout_end);
        timeout_end.tv_usec = TIMEOUT_END;
        modbus_set_byte_timeout(context, &timeout_end);

        modbus_get_response_timeout(context, &timeout_begin);
        timeout_begin.tv_usec = TIMEOUT_BEGIN;
        modbus_set_response_timeout(context, &timeout_begin);
        
        //connect
        if(modbus_connect(context) == -1)
        {
            throw modbus_exception();
        }
    }
示例#7
0
int main(int argc, char *argv[])
{
	modbus_t *mb;
	uint16_t tab_reg[256];
	uint8_t bit_reg[256];
	int rc;
	int i;
	int actual;

	mb = modbus_new_tcp("192.168.1.120", 502);
	if (modbus_connect(mb) == -1)
	{
		fprintf(stderr, "modbus connect: %s\n", modbus_strerror(errno));
		modbus_free(mb);
		return -1;
	}

	sscanf(getenv("QUERY_STRING"),"%d",&actual);
	printf("Content-type: text/plain\n\n");

	/* Read 5 registers from the address 10 */
	//rc = modbus_read_registers(mb, 100, 10, tab_reg);
	rc = modbus_write_bit(mb,100,actual);
	if (rc == -1) {
		fprintf(stderr, "write bit: %s\n", modbus_strerror(errno));
		return -1;
	}

	modbus_close(mb);
	modbus_free(mb);
}
示例#8
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;
}
示例#9
0
int main(int argc, char *argv[])
{
	modbus_t *mb;
	uint16_t tab_reg[256];
	uint8_t bit_reg[256];
	int rc;
	int i;

	if (argc != 4)
	{
		printf("name ip adress register and value\n");
		exit(1);
	}
	int setvalue;
	sscanf(argv[3],"%d",&setvalue);
	int setregister;
	sscanf(argv[2],"%d",&setregister);

	mb = modbus_new_tcp(argv[1], 502);
	if (modbus_connect(mb) == -1)
	{
		fprintf(stderr, "modbus connect: %s\n", modbus_strerror(errno));
		modbus_free(mb);
		return -1;
	}
	printf("%d=%d\n",setregister, setvalue);
	rc = modbus_write_bit(mb,setregister,setvalue);
	if (rc == -1) {
		fprintf(stderr, "write registers: %s\n", modbus_strerror(errno));
		return -1;
	}

	modbus_close(mb);
	modbus_free(mb);
}
示例#10
0
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;
}
示例#11
0
modbus_t * ModbusMaster::openPort(QString ip, quint16 port)
{
    modbus_t * conn;

    conn = modbus_new_tcp(ip.toStdString().c_str(), port);
    if (conn)
    {
        if (modbus_connect(conn) == -1)
        {
#ifdef QT_DEBUG_OUTPUT
            qDebug() << "Connection failed: " << modbus_strerror(errno) << endl;
#endif
            modbus_free(conn);
            conn = 0;
        }
    }
    else
    {
#ifdef QT_DEBUG_OUTPUT
        qDebug() << "New TCP failed: " << modbus_strerror(errno) << endl;
#endif
        conn = 0;
    }

    return conn;
}
示例#12
0
	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 ;
	}
示例#13
0
void TSerialPort::Open()
{
    if (Fd >= 0)
        throw TSerialDeviceException("port already open");
    if (modbus_connect(Context->Inner) < 0)
        throw TSerialDeviceException("cannot open serial port");
    Fd = modbus_get_socket(Context->Inner);
}
示例#14
0
static int ctx_connect(lua_State *L)
{
	ctx_t *ctx = ctx_check(L, 1);

	int rc = modbus_connect(ctx->modbus);
	
	return libmodbus_rc_to_nil_error(L, rc, 0);
}
示例#15
0
/* 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 */
示例#16
0
文件: modbus.c 项目: rafa400/telepi
int main() {
  modbus_t *ctx;


uint16_t tab_reg[numero];
int rc;
int i;

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


struct timeval old_response_timeout;
struct timeval response_timeout;

/* Save original timeout */
//modbus_get_response_timeout(ctx, &old_response_timeout);

/* Define a new and too short timeout! */
//response_timeout.tv_sec = 2;
//response_timeout.tv_usec = 500000;
//modbus_set_response_timeout(ctx, &response_timeout);

//rc = modbus_set_slave(ctx, 49);

if (rc == -1) {
   fprintf(stderr, "SET: %s\n", modbus_strerror(errno));
    if (ctx!=NULL) {
      fprintf(stderr,"CLOSE\n");
      modbus_close(ctx);
      modbus_free(ctx);
    }
   return -1;
}
rc = modbus_read_input_registers(ctx, direccion, numero, tab_reg);
if (rc == -1) {
    fprintf(stderr, "HOLA: %s\n", modbus_strerror(errno));
    if (ctx!=NULL) {
      fprintf(stderr,"CLOSE\n");
      modbus_close(ctx);
      modbus_free(ctx);
    }
    return -1;
}

for (i=0; i < rc; i++) {
    printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
}

modbus_close(ctx);
modbus_free(ctx);
}
示例#17
0
int main(int argc, char **argv) {

    if (argc != 3) {
        fprintf(stdout, "\nUsage: %s <ip> <port>\n\n", argv[0]);
        return -1;
    }

    char *ip = argv[1];
    int port = atoi(argv[2]);
    int rc;    

    uint16_t *register_values = malloc(sizeof(*register_values));


    modbus_t *ctx = modbus_new_tcp(ip, port);
    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection to %s port %d failed: %s\n", ip, port, modbus_strerror(errno));
        modbus_end(ctx);
        return -1;
    }

    /* generate exception 02 (starting address out of range) */
    fprintf(stdout, "Test #1: Asking for out of bounds register (expected exception number 02)\n");
    rc = modbus_read_registers(ctx, MODBUS_MAX_READ_REGISTERS+1, 1, register_values);
    if (-1 == rc) {
        fprintf(stderr, "Reading registers failed (modbus protocol exception number = %d). %s\n", errno - MODBUS_ENOBASE, modbus_strerror(errno));
    }

    sleep(1);

    /* generate exception 02 (range of addresses requested out of range) */
    /* Note: if the range goes beyond the protocol maximum, the returned errno will be 16, which is not a 
     * protocol exception code */
    fprintf(stdout, "Test #2: Asking for out of bounds range of registers (expected exception number 02)\n");
    rc = modbus_read_registers(ctx, 0, MODBUS_MAX_READ_REGISTERS-1, register_values);
    if (-1 == rc) {
        fprintf(stderr, "Reading registers failed (modbus protocol exception number = %d). %s\n", errno - MODBUS_ENOBASE, modbus_strerror(errno));
    }

    sleep(1);

    /* generate exception 03 (quantity of registers out of bounds) */
    fprintf(stdout, "Test #3: Asking for zero registers (expected exception number 03)\n");
    rc = modbus_read_registers(ctx, 0, 0, register_values);
    if (-1 == rc) {
        fprintf(stderr, "Reading registers failed (modbus protocol exception number = %d). %s\n", errno - MODBUS_ENOBASE, modbus_strerror(errno));
    }

    sleep(1);

    modbus_end(ctx);
    free(register_values);

    return 0;
}
示例#18
0
static void *modbus_side (void *arg) 
{
	modbus_t *ctx;
	uint16_t tab_reg[64];
	int rc;
	int i;
modbus_side_restart:
	
	//ctx = modbus_new_tcp("127.0.0.1", 502);
	ctx = modbus_new_tcp("140.159.153.159", 502);
	// Use 140.159.153.159 for uni, 127.0.0.1 for home. Server port remains as 502 for both cases
	
	// Initialize connection to modbus server
	if(modbus_connect(ctx) == -1)  // Connection to server failed
	{
		fprintf(stderr, "Connection to server failed: %s\n", modbus_strerror(errno));
		modbus_free(ctx); 
		modbus_close(ctx);
		usleep(100000);  // Sleep for suggested delay time of 100ms
		// Closing connection to retry again
		goto modbus_side_restart;
	}

	else  // Connection to server successful
	{
		fprintf(stderr, "Connection to server successful\n");
	
	}

	// Read registers
	while(1)
	{
		rc = modbus_read_registers(ctx, 48, 2, tab_reg);  // Device 48 allocated for Nick Hodson

		if(rc == -1)  // Read of registers failed
		{
			fprintf(stderr, "Reading of registers has failed: %s\n", modbus_strerror(errno));

		// CLose modbus connection and start again (retry)
		modbus_free(ctx); 
		modbus_close(ctx);
		goto modbus_side_restart;
		}

		// not putting an else statement for succcessful read register as it will clog up the terminal window

		for(i = 0; i < rc; i++)  // Register display
		{
			add_to_list(&list_heads[i], tab_reg[i]);  // replacement for printf statement
			printf("register[%d] = %d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
		}	
		usleep(100000);  // Sleep for suggested delay time of 100ms
	}
}	
int RTU_connect(void){
  modbus_set_error_recovery(ctx, MODBUS_ERROR_RECOVERY_PROTOCOL);
if (modbus_connect(ctx)==0){
    return 1;
}else{
#ifdef DEBUG_ENABLED
    qWarning() << "Failed to Connect";
#endif
return 0;
    }
}
void TcpIpSettingsWidget::changeModbusInterface(const QString &address, int portNbr)
{
    releaseTcpModbus();

    m_tcpModbus = modbus_new_tcp( address.toLatin1().constData(), portNbr );
    if( modbus_connect( m_tcpModbus ) == -1 )
    {
        QMessageBox::critical( this, tr( "Connection failed" ),
            tr( "Could not connect tcp/ip port!" ) );
        ui->btnApply->setEnabled(true);
    }
}
示例#21
0
void ModBusTCP::Connect()
{
    if (ctx != NULL)
    {
        if (modbus_connect(ctx) == -1)
        {
            qDebug() << "Connection failed: " << modbus_strerror(errno);
            return;
        }
    }

}
示例#22
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);
  }
示例#23
0
//==========================================================================================
int MainWindow::ReadTimeFromICPDAS(QString IPaddr, QDateTime *icpDT)
{
    int res;

    modbus_t *mb;
    uint16_t tab_reg[200];
    const uint number_readed_registers=6;
    uint year=0;
    uint month=0;
    uint day=0;
    uint hour=0;
    uint minute=0;
    uint second=0;

                //inialized context
                mb = modbus_new_tcp(IPaddr.toStdString().c_str(), 502);
                if (mb==NULL) {return -1;}

                res=modbus_connect(mb);
                modbus_set_slave(mb, 1);


                if (res==-1) {modbus_free(mb); return -2;}


                res=modbus_read_registers(mb, 1, number_readed_registers, tab_reg);// 6 reg from 40002

                if (res!=number_readed_registers){modbus_close(mb);modbus_free(mb); return -3;}

        year=tab_reg[0];
        month=tab_reg[1];
        day=tab_reg[2];
        hour=tab_reg[3];
        minute=tab_reg[4];
        second=tab_reg[5];


        QDate dt;
        dt.setDate(year,month,day);
        QTime tm;
        tm.setHMS(hour,minute,second);

        icpDT->setDate(dt);
        icpDT->setTime(tm);

        modbus_close(mb);
        modbus_free(mb);


return 1;
}
示例#24
0
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;
}
示例#25
0
    /* bacnet_Analog_Input_Present_Value_Set(2, test_data[index++]); */
    
    if (index == NUM_TEST_DATA) index = 0;

not_pv:
    return bacnet_Analog_Input_Read_Property(rpdata);
}

static bacnet_object_functions_t server_objects[] = {
    {bacnet_OBJECT_DEVICE,
	    NULL,
	    bacnet_Device_Count,
	    bacnet_Device_Index_To_Instance,
	    bacnet_Device_Valid_Object_Instance_Number,
	    bacnet_Device_Object_Name,
	    bacnet_Device_Read_Property_Local,
	    bacnet_Device_Write_Property_Local,
	    bacnet_Device_Property_Lists,
	    bacnet_DeviceGetRRInfo,
	    NULL, /* Iterator */
	    NULL, /* Value_Lists */
	    NULL, /* COV */
	    NULL, /* COV Clear */
	    NULL  /* Intrinsic Reporting */
    },int main (void) {

  modbus_t *mb;
  uint16_t tab_reg[32];

  mb = modbus_new_tcp("127.0.0.1", 502);
  modbus_connect(mb);

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

  /* Read 5 registers from the address 0 */
  modbus_read_registers(mb, 0, 5, tab_reg);

  modbus_close(mb);
  modbus_free(mb);

return 0;
}
示例#26
0
modbus_t* modbus_new_tcp_device()
{
	// ignore this. IP address.
	modbus_t* pContext = modbus_new_tcp("192.168.1.12", 502);
	modbus_set_slave(pContext, 2);

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


	return pContext;

}
示例#27
0
/* Initializing and connecting modbus */
modbus_t *modbus_init(char *path_to_config)
{
    char ip[BUFFER_SIZE];
    int port;
    modbus_t *ctx = (modbus_t *) malloc(1);

    /* Set default values */
    sprintf(ip, "127.0.0.1");
    port = 502;

    /* Read Configuration */
    log_entry(APP_NAME, "Reading Modbus - Configuration");
    printf("\nReading Modbus - Configuration..\n");

    port = getIntFromFile(path_to_config, "modbus_port");
    if(getStringFromFile_n(path_to_config, "modbus_address", ip, BUFFER_SIZE) == -1) {
        log_entry(APP_NAME, "Error reading modbus address");
        printf("Error reading modbus_address..\n");
    }

    printf("IP-Address: %s\nport: %d\n", ip, port);

    /* Set up modbus */
    log_entry(APP_NAME, "Setting up and connecting Modbus");
    printf("\nSetting up and connecting Modbus..\n");
    ctx = modbus_new_tcp(ip, port);

    /* Check Setup */
    if(ctx == NULL) {
        log_entry(APP_NAME, "Error setting up modbus");
        printf("Error setting up modbus.\n");
        return NULL;
    }

    /* Connect and set slave */
    if(modbus_connect(ctx) != 0 || modbus_set_slave(ctx, MODBUS_SLAVE_ADDRESS) != 0) {
        log_entry(APP_NAME, "Error connecting modbus");
        printf("Error connecting modbus.\n");
        return NULL;
    }

    /* Message to user */
    log_entry(APP_NAME, "Setup and Connection successful");
    printf("Setup and Connection successful.\n\n");

    return ctx;
}
示例#28
0
/* Version 2.0.3 */
static int mb_init_connection (mb_host_t *host) /* {{{ */
{
  int status;

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

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

  /* We'll do the error handling ourselves. */
  modbus_set_error_handling (&host->connection, NOP_ON_ERROR);

  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);

    modbus_init_tcp (&host->connection,
        /* host = */ host->node,
        /* port = */ host->port);
  }
  else	/* MBCONN_RTU */
  {
    DEBUG ("Modbus plugin: Trying to connect to \"%s\".", host->node);

    modbus_init_rtu (&host->connection,
       /* device = */ host->node,
     /* baudrate = */ host->baudrate,
                      'N', 8, 1, 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);
    return (status);
  }

  host->is_connected = 1;
  return (0);
} /* }}} int mb_init_connection */
示例#29
0
文件: modbus.c 项目: kimor79/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);

  /* Only reconnect once per interval. */
  if (host->have_reconnected)
    return (-1);

  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)
  {
    host->have_reconnected = 1;
    ERROR ("Modbus plugin: Creating new Modbus/TCP object failed.");
    return (-1);
  }

  modbus_set_debug (host->connection, 1);

  /* 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, status);
    modbus_free (host->connection);
    host->connection = NULL;
    return (status);
  }

  host->have_reconnected = 1;
  return (0);
} /* }}} int mb_init_connection */
示例#30
0
int MeterModbus::open() {
	_mb = NULL;
	_mb = modbus_new_tcp(ip(), _port);
	
	if (_mb == NULL) {
		print(log_error, "Unable to allocate libmodbus context: %s, %i", ip(), _port);
		return ERR;
	}
	print(log_debug, "Connecting to %s:%i", name().c_str(), _ip.c_str(), _port);
	if (modbus_connect(_mb) == -1) {
		print(log_error, "Connection failed: %s",name().c_str(), modbus_strerror(errno));
		modbus_free(_mb);
		return ERR;
	}
	_reset_connection = false;
	return SUCCESS;
}