admin 管理员组

文章数量: 887006

Modbus封装库(Com,tcp,udp一应俱全)

自行封装在用的Modbus通迅库,集成了com,tcp,udp, 做个笔记吧, 以下头文件,

#pragma once
#include <functional>
#include <vector>
#include <string>
#include <memory>
#ifdef LIBMODBUS_EXPORTS
#define LIBMODBUS_EXPORT_API __declspec(dllexport)
#else
#define LIBMODBUS_EXPORT_API __declspec(dllimport)
#endif
class LIBMODBUS_EXPORT_API RTUModbus {

public:
    //devflag is 1 as default value
    RTUModbus();
    ~RTUModbus();
public:
    std::string getAddrPLC();
    uint16_t getDevflag();
    int getPort();
    void sendBit(uint16_t addrstart, bool mvalue);
    bool readBit(uint16_t addrstart, uint8_t* destBit);
    void sendDataRegister(uint16_t addrstart, uint16_t mvalue);
    void sendDataRegisters(uint16_t addrstart, uint16_t* mvalue);
    void sendDataRegisters(uint16_t addrstart,const int len, uint16_t* mvalue);

    bool readDataRegisters(uint16_t addrstart, uint16_t* destBit);

    bool readDataRegisters(uint16_t addrstart,const int len, uint16_t* destBit);
    bool isConnected();
    void setPLCParam(const int mport, std::string ipra);
    void disconnect();
    bool connectPLCbyNet(const int port, const int devflag, std::string addr);
    bool connectPLC(const int devflag);
    //mport :com1  ,flag:0 Rs232,1:RS485
    bool connectPLCbySerial(const char * mport, const int flag, const int baud = 115200,
        char parity = 'N', const int data_bit = 8, const int stopbit = 1);
    bool connectTo_UDP(std::string strIP, const int mport);

private:
    std::shared_ptr<void> _modClient;
};

应用标例:

RTUModbus* mBus=new RTUModbus();

网口连接:

//tcp:

bool res=mBus->connectPLCbyNet(9000,1,"192.168.3.58");

//udp

bool res=connectTo_UDP("192.168.3.58",9000);

串口:

bool res=connectPLCbySerial("com1",1,115200);

读写方式,三者(串口、网口tcp,udp)都是共用的

下载地址:

LibModbus库(udp,tcp)一应俱全

平台;VC++2015 ++

本文标签: Modbus封装库(Com TCP udp一应俱全)