s7_plc.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "s7_plc.h"
  2. S7PLC::S7PLC() : bConnected_(false) {
  3. }
  4. S7PLC::~S7PLC() {
  5. disconnect();
  6. }
  7. bool S7PLC::getConnection() {
  8. return bConnected_;
  9. }
  10. bool S7PLC::connect(std::string ip) {
  11. std::lock_guard<std::mutex> lck(mutex_);
  12. int ret = client_.ConnectTo(ip.c_str(), 0, 1);
  13. bConnected_ = (ret == 0);
  14. return bConnected_;
  15. }
  16. bool S7PLC::ReadShorts(int DBNumber, int start, int size, short *pdata) {
  17. short *plc_data = (short *) malloc(size * sizeof(short));
  18. bool ret = read_dbs(DBNumber, start * sizeof(short), size * sizeof(short), pdata);
  19. if (ret) {
  20. reverse_byte(pdata, size * sizeof(short), plc_data);
  21. for (int i = 0; i < size; ++i)
  22. pdata[i] = plc_data[size - i - 1];
  23. }
  24. free(plc_data);
  25. return ret;
  26. }
  27. bool S7PLC::WriteShorts(int DBNumber, int start, int size, short *pdata) {
  28. short *plc_data = (short *) malloc(size * sizeof(short));
  29. memcpy(plc_data, pdata, size * sizeof(short));
  30. for (int i = 0; i < size; ++i)
  31. plc_data[i] = HTON(plc_data[i]);
  32. bool ret = write_dbs(DBNumber, start * sizeof(short), size * sizeof(short), plc_data);
  33. free(plc_data);
  34. return ret;
  35. }
  36. bool S7PLC::read_dbs(int DBNumber, int start, int size, void *pdata) {
  37. std::lock_guard<std::mutex> lck(mutex_);
  38. usleep(1000 * 50);
  39. if (bConnected_ == false)
  40. return false;
  41. int ret = client_.AsDBRead(DBNumber, start, size, pdata);
  42. return ret == 0;
  43. }
  44. bool S7PLC::write_dbs(int DBNumber, int start, int size, void *pdata) {
  45. std::lock_guard<std::mutex> lck(mutex_);
  46. usleep(1000 * 50);
  47. if (bConnected_ == false)
  48. return false;
  49. int ret = client_.AsDBWrite(DBNumber, start, size, pdata);
  50. return ret == 0;
  51. }
  52. void S7PLC::disconnect() {
  53. std::lock_guard<std::mutex> lck(mutex_);
  54. client_.Disconnect();
  55. }
  56. void S7PLC::reverse_byte(void *pdata, int num_byte, void *out) {
  57. char *pin = (char *) pdata;
  58. char *pout = (char *) out;
  59. for (int i = 0; i < num_byte; ++i) {
  60. pout[i] = pin[num_byte - i - 1];
  61. }
  62. }