File modules/modbusy/ModbusTcpClient.class.php

Last commit: Thu Dec 26 19:50:18 2024 +0100	Jan Dankert	New: ModbusTCP for later use in the scriptbox.
1 <?php 2 3 namespace modbusy; 4 5 6 use modbusy\request\MultibyteRequest; 7 use modbusy\request\MultipleHoldingRegistersReader; 8 use modbusy\request\MultipleHoldingRegistersWriter; 9 use modbusy\request\Request; 10 11 /** 12 */ 13 class ModbusTcpClient 14 { 15 protected $host = 'localhost'; 16 protected $port = 502; 17 protected $socket; 18 protected $timeout = 2; 19 protected $log; 20 21 public function __construct() 22 { 23 $this->log = function ($log) {}; 24 } 25 26 public function setTimeout( $timeoutInSeconds) 27 { 28 $this->timeout = $timeoutInSeconds; 29 return $this; 30 } 31 32 /** 33 * Setting the host. 34 * Default: localhost. 35 * @param $host 36 * @return $this 37 */ 38 public function setHost( $host ) { 39 $this->host = $host; 40 return $this; 41 } 42 43 /** 44 * Setting the TCP Port. Default: 502 (Modbus TCP standard port) 45 * @param $port 46 * @return $this 47 */ 48 public function setPort( $port ) 49 { 50 $this->port = $port; 51 return $this; 52 } 53 54 55 /** 56 * @return \Closure 57 */ 58 public function getLog(): \Closure 59 { 60 return $this->log; 61 } 62 63 64 65 public function setLog( $log ) 66 { 67 $this->log = $log; 68 return $this; 69 } 70 71 72 /** 73 * @return MultipleHoldingRegistersReader 74 */ 75 public function readMultipleHoldingRegisters() { 76 return $this->initializeRequest(new MultipleHoldingRegistersReader()); 77 } 78 79 /** 80 * @return MultipleHoldingRegistersWriter 81 */ 82 public function writeMultipleHoldingRegisters() { 83 return $this->initializeRequest( new MultipleHoldingRegistersWriter()); 84 } 85 86 87 public function open() 88 { 89 $this->socket = fsockopen($this->host,$this->port); 90 socket_set_timeout($this->socket,$this->timeout); 91 if ( $this->socket === false ) 92 throw new \InvalidArgumentException("no socket to host"); 93 return $this; 94 } 95 96 97 protected function initializeRequest(Request $request) 98 { 99 $request->setSocket($this->socket ); 100 $request->setLog( $this->log ); 101 return $request; 102 } 103 104 105 public function close() 106 { 107 if ( $this->socket ) { 108 fclose($this->socket); 109 $this->socket = null; 110 } 111 return $this; 112 113 } 114 115 public function __destruct() 116 { 117 if ( $this->socket ) { 118 119 fclose($this->socket); 120 $this->socket = null; 121 } 122 } 123 }
Download modules/modbusy/ModbusTcpClient.class.php
History Thu, 26 Dec 2024 19:50:18 +0100 Jan Dankert New: ModbusTCP for later use in the scriptbox.