example_s7_315_2dp.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python3
  2. #
  3. # Simple pyprofibus example
  4. #
  5. # This example initializes an S7-315-2DP configured as slave,
  6. # reads its input data and writes the data back to the module.
  7. #
  8. import sys
  9. sys.path.insert(0, "..")
  10. import pyprofibus
  11. def main(confdir=".", watchdog=None):
  12. master = None
  13. try:
  14. # Parse the config file.
  15. config = pyprofibus.PbConf.fromFile(confdir + "/example_s7_315_2dp.conf")
  16. # Create a DP master.
  17. master = config.makeDPM()
  18. # Create the slave descriptions.
  19. outData = {}
  20. for slaveConf in config.slaveConfs:
  21. slaveDesc = slaveConf.makeDpSlaveDesc()
  22. # Register the S7-315-2DP slave at the DPM
  23. master.addSlave(slaveDesc)
  24. # Set initial output data.
  25. outData[slaveDesc.slaveAddr] = bytearray((0x00, ))
  26. # Initialize the DPM
  27. master.initialize()
  28. # Cyclically run Data_Exchange.
  29. while True:
  30. # Write the output data.
  31. for slaveDesc in master.getSlaveList():
  32. slaveDesc.setMasterOutData(outData[slaveDesc.slaveAddr])
  33. # Run slave state machines.
  34. handledSlaveDesc = master.run()
  35. # Get the in-data (receive) and set it as out-data (transmit).
  36. if handledSlaveDesc:
  37. inData = handledSlaveDesc.getMasterInData()
  38. if inData is not None:
  39. # In our example the output data shall be a mirror of the input.
  40. outData[handledSlaveDesc.slaveAddr] = inData
  41. # Feed the system watchdog, if it is available.
  42. if watchdog is not None:
  43. watchdog()
  44. except pyprofibus.ProfibusError as e:
  45. print("Terminating: %s" % str(e))
  46. return 1
  47. finally:
  48. if master:
  49. master.destroy()
  50. return 0
  51. if __name__ == "__main__":
  52. import sys
  53. sys.exit(main())