s7_plc.cpp 2.0 KB

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