12_HProtocolGateway.pm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. # $Id: 12_HProtocolGateway.pm 17509 2018-10-11 13:53:45Z eisler $
  2. ####################################################################################################
  3. #
  4. # 12_HProtocolGateway.pm
  5. #
  6. # Copyright: Stephan Eisler
  7. # Email: fhem.dev@hausautomatisierung.co
  8. #
  9. # This file is part of fhem.
  10. #
  11. # Fhem is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation, either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # Fhem is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License
  22. # along with fhem. If not, see <http://www.gnu.org/licenses/>.
  23. #
  24. ####################################################################################################
  25. package main;
  26. use strict;
  27. use warnings;
  28. use DevIo;
  29. use Math::Round qw/round/;
  30. my @tankList = undef;
  31. my %sets = (
  32. 'readValues' => 1,
  33. );
  34. sub HProtocolGateway_Initialize($) {
  35. my ($hash) = @_;
  36. $hash->{Clients} = "HProtocolTank";
  37. $hash->{DefFn} = "HProtocolGateway_Define";
  38. $hash->{InitFn} = "HProtocolGateway_Init";
  39. $hash->{GetFn} = "HProtocolGateway_Get";
  40. $hash->{SetFn} = "HProtocolGateway_Set";
  41. $hash->{AttrFn} = "HProtocolGateway_Attr";
  42. $hash->{AttrList} = "device " .
  43. "baudrate:300,600,1200,2400,4800,9600 " .
  44. "parityBit:N,E,O " .
  45. "databitsLength:5,6,7,8 " .
  46. "stopBit:0,1 " .
  47. "pollIntervalMins " .
  48. "path";
  49. }
  50. sub HProtocolGateway_Define($$) {
  51. my ($hash, $def) = @_;
  52. my @a = split("[ \t][ \t]*", $def);
  53. my $name = $hash->{NAME};
  54. return "Wrong syntax: use define <name> HProtocolGateway </dev/tty???>" if(int(@a) != 3);
  55. $hash->{helper}{DeviceName} = $a[2];
  56. $hash->{Clients} = "HProtocolTank";
  57. $hash->{STATE} = "Initialized";
  58. $attr{$name}{room} = "HProtocol";
  59. HProtocolGateway_DeviceConfig($hash);
  60. HProtocolGateway_Poll($hash) if defined(AttrVal($hash->{NAME}, 'pollIntervalMins', undef)); # if pollIntervalMins defind -> start timer
  61. return undef;
  62. }
  63. sub HProtocolGateway_Get($$@) {
  64. my ($hash, $name, $opt, @args) = @_;
  65. return "\"get $name\" needs at least one argument" unless(defined($opt));
  66. if ($opt eq "update") {
  67. HProtocolGateway_GetUpdate($hash);
  68. return "Done.";
  69. } else {
  70. # IMPORTANT! This defines the list of possible commands
  71. my $list = "update:noArg";
  72. return "Unknown argument $opt, choose one of $list";
  73. }
  74. return -1;
  75. }
  76. sub HProtocolGateway_Set($@) {
  77. my ($hash, @a) = @_;
  78. my $name = $a[0];
  79. my $cmd = $a[1];
  80. if(!defined($sets{$cmd})) {
  81. return 'Unknown argument ' . $cmd . ', choose one of ' . join(' ', keys %sets) . ":noArg"
  82. }
  83. if ($cmd eq 'readValues') {
  84. RemoveInternalTimer($hash);
  85. InternalTimer(gettimeofday() + 1, 'HProtocolGateway_GetUpdate', $hash, 0);
  86. }
  87. return undef
  88. }
  89. sub HProtocolGateway_GetUpdate($) {
  90. my ($hash) = @_;
  91. my $name = $hash->{NAME};
  92. foreach (@tankList) {
  93. my $tankHash = $_;
  94. my $mode = AttrVal($tankHash->{NAME},"mode","");
  95. my $command = "\$A";
  96. if ($mode eq "Volume") {
  97. $command = "\$B";
  98. } elsif ($mode eq "Ullage") {
  99. $command = "\$C";
  100. }
  101. my $hID = AttrVal($tankHash->{NAME},"hID","");
  102. my $msg = $command . $hID . "\r\n";
  103. DevIo_SimpleWrite($hash, $msg , 2);
  104. my ($err, $data) = HProtocolGateway_ReadAnswer($hash,$tankHash);
  105. Log3 $name, 5, "err:". $err;
  106. Log3 $name, 5, "data:". $data;
  107. }
  108. my $pollInterval = AttrVal($hash->{NAME}, 'pollIntervalMins', 0); #restore pollIntervalMins Timer
  109. InternalTimer(gettimeofday() + ($pollInterval * 60), 'HProtocolGateway_Poll', $hash, 0) if ($pollInterval > 0);
  110. }
  111. sub HProtocolGateway_ReadAnswer($$) {
  112. my ($hash,$tankHash) = @_;
  113. my $name = $hash->{NAME};
  114. return ("No FD (dummy device?)", undef)
  115. if(!$hash || ($^O !~ /Win/ && !defined($hash->{FD})));
  116. for(;;) {
  117. return ("Device lost when reading answer", undef)
  118. if(!$hash->{FD});
  119. my $rin = '';
  120. vec($rin, $hash->{FD}, 1) = 1;
  121. my $nfound = select($rin, undef, undef, 3);
  122. if($nfound <= 0) {
  123. next if ($! == EAGAIN() || $! == EINTR());
  124. my $err = ($! ? $! : "Timeout");
  125. return("ProtocolGateway_ReadAnswer $err", undef);
  126. }
  127. my $buf = DevIo_SimpleRead($hash);
  128. return ("No data", undef) if(!defined($buf));
  129. my $ret = HProtocolGateway_Read($hash, $buf,$tankHash);
  130. return (undef, $ret) if(defined($ret));
  131. }
  132. }
  133. sub HProtocolGateway_Read($@) {
  134. my ($hash, $data, $tankHash) = @_;
  135. my $name = $hash->{NAME};
  136. my $buffer = $hash->{PARTIAL};
  137. Log3 $name, 5, "HProtocolGateway ($name) - received $data (buffer contains: $buffer)";
  138. $buffer .= $data;
  139. my $msg;
  140. # as long as the buffer contains CR (complete datagramm)
  141. while($buffer =~ m/\r/)
  142. {
  143. ($msg, $buffer) = split("\r", $buffer, 2);
  144. chomp $msg;
  145. HProtocolGateway_ParseMessage($hash, $msg, $tankHash);
  146. }
  147. $hash->{PARTIAL} = $buffer;
  148. return $msg if(defined($data));
  149. return undef;
  150. }
  151. sub HProtocolGateway_ParseMessage($$) {
  152. my ($hash, $data, $tankHash) = @_;
  153. my $name = $hash->{NAME};
  154. $data =~ s/^.//; # remove #
  155. my ($tankdata,$water,$temperature,$probe_offset,$version,$error,$checksum)=split(/@/,$data);
  156. my $test = "#".$tankdata.$water.$temperature.$probe_offset.$version.$error;
  157. # calculate XOR CRC
  158. my $check = 0;
  159. $check ^= $_ for unpack 'C*', $test;
  160. # convert to HEX
  161. $check = sprintf '%02X', $check;
  162. # Unitronics
  163. if ($version == 0 && $error == 0 && $checksum == 0) {
  164. $check = 0;
  165. }
  166. return if($check ne $checksum);
  167. my ($filllevel,$volume,$ullage) = (0,0,0);
  168. my $mode = AttrVal($tankHash->{NAME},"mode","");
  169. if ($mode eq "FillLevel") {
  170. $filllevel = $tankdata/100;
  171. $volume = HProtocolGateway_Tank($hash,$tankHash,$filllevel);
  172. } elsif ($mode eq "Volume") {
  173. $volume = $tankdata;
  174. } elsif ($mode eq "Ullage") {
  175. $ullage = $tankdata;
  176. }
  177. my $sign = substr($temperature,0,1);
  178. $temperature =~ s/^.//;
  179. if ($sign eq "-") { $temperature = int($temperature) * -1 };
  180. $temperature = $temperature / 10;
  181. $sign = substr($probe_offset,0,1);
  182. $probe_offset =~ s/^.//;
  183. if ($sign eq "-") { $probe_offset = int($probe_offset) * -1 };
  184. my $volume_15C = $volume * (1 + 0.00084 * ( 15 - $temperature ));
  185. $volume_15C = Math::Round::nearest('0.01',$volume_15C);
  186. # Update all received readings
  187. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "ullage", $ullage);
  188. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "filllevel", $filllevel);
  189. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "volume", $volume);
  190. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "volume_15C", $volume_15C);
  191. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "temperature", $temperature);
  192. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "waterlevel", $water);
  193. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "probe_offset", $probe_offset);
  194. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "version", $version);
  195. HProtocolGateway_UpdateTankDevice($hash, $tankHash->{NAME}, "error", $error);
  196. }
  197. sub HProtocolGateway_UpdateTankDevice($$$$) {
  198. my ($hash, $tankName, $reading, $value) = @_;
  199. my $message = $tankName . " " . $reading . " " . $value;
  200. my $success = Dispatch($hash, $message, undef);
  201. if (!$success) {
  202. my $name = $hash->{NAME};
  203. Log3 $name, 1, "$name: failed to update tank device";
  204. }
  205. }
  206. sub HProtocolGateway_RegisterTank($) {
  207. my ($tankHash) = @_;
  208. # Remove undefined elements of empty array
  209. @tankList = grep defined, @tankList;
  210. @tankList = (@tankList, $tankHash);
  211. }
  212. # called when definition is undefined
  213. # (config reload, shutdown or delete of definition)
  214. sub HProtocolGateway_Undef($$)
  215. {
  216. my ($hash, $name) = @_;
  217. # close the connection
  218. DevIo_CloseDev($hash);
  219. return undef;
  220. }
  221. # called repeatedly if device disappeared
  222. sub HProtocolGateway_Ready($)
  223. {
  224. my ($hash) = @_;
  225. # try to reopen the connection in case the connection is lost
  226. return DevIo_OpenDev($hash, 1, "HProtocolGateway_Init");
  227. }
  228. # will be executed upon successful connection establishment (see DevIo_OpenDev())
  229. sub HProtocolGateway_Init($)
  230. {
  231. my ($hash) = @_;
  232. # send a status request to the device
  233. # DevIo_SimpleWrite($hash, "get_status\r\n", 2);
  234. return undef;
  235. }
  236. # Called during attribute create/change
  237. sub HProtocolGateway_Attr (@) {
  238. my ($command, $name, $attr, $val) = @_;
  239. my $hash = $defs{$name};
  240. my $msg = '';
  241. if ($attr eq 'poll_interval') {
  242. if (defined($val)) {
  243. if ($val =~ m/^(0*[1-9][0-9]*)$/) {
  244. RemoveInternalTimer($hash);
  245. HProtocolGateway_Poll($hash) if ($main::init_done);
  246. } else {
  247. $msg = 'Wrong poll intervall defined. pollIntervalMins must be a number > 0';
  248. }
  249. } else {
  250. RemoveInternalTimer($hash);
  251. }
  252. } elsif ($attr eq 'path') {
  253. $attr{$name}{path} = $val;
  254. } elsif ($attr eq 'baudrate') {
  255. $attr{$name}{baudrate} = $val;
  256. HProtocolGateway_DeviceConfig($hash);
  257. } elsif ($attr eq 'databitsLength') {
  258. $attr{$name}{databitsLength} = $val;
  259. HProtocolGateway_DeviceConfig($hash);
  260. } elsif ($attr eq 'parityBit') {
  261. $attr{$name}{parityBit} = $val;
  262. HProtocolGateway_DeviceConfig($hash);
  263. } elsif ($attr eq 'stopBit') {
  264. $attr{$name}{stopBit} = $val;
  265. HProtocolGateway_DeviceConfig($hash);
  266. }
  267. }
  268. sub HProtocolGateway_DeviceConfig($) {
  269. my ($hash) = @_;
  270. my $name = $hash->{NAME};
  271. my $deviceName = $hash->{helper}{DeviceName};
  272. $hash->{DeviceName} = $deviceName."@".$attr{$name}{baudrate}.",".$attr{$name}{databitsLength}.",".$attr{$name}{parityBit}.",".$attr{$name}{stopBit};
  273. DevIo_CloseDev($hash) if(DevIo_IsOpen($hash));
  274. my $ret = DevIo_OpenDev($hash, 0, "HProtocolGateway_Init");
  275. return $ret
  276. }
  277. # Request measurements regularly
  278. sub HProtocolGateway_Poll($) {
  279. my ($hash) = @_;
  280. my $name = $hash->{NAME};
  281. HProtocolGateway_Set($hash, ($name, 'readValues'));
  282. my $pollInterval = AttrVal($hash->{NAME}, 'pollIntervalMins', 0);
  283. if ($pollInterval > 0) {
  284. InternalTimer(gettimeofday() + ($pollInterval * 60), 'HProtocolGateway_Poll', $hash, 0);
  285. }
  286. }
  287. sub HProtocolGateway_Tank($$$) {
  288. my ($hash,$tankHash,$filllevel) = @_;
  289. my $name = $hash->{NAME};
  290. my $path = AttrVal($name,"path","");
  291. my $type = AttrVal($tankHash->{NAME},"type","");
  292. my %TankChartHash;
  293. open my $fh, '<', $path.$type or die "Cannot open: $!";
  294. while (my $line = <$fh>) {
  295. $line =~ s/\s*\z//;
  296. my @array = split /,/, $line;
  297. my $key = shift @array;
  298. $TankChartHash{$key} = $array[0];
  299. }
  300. close $fh;
  301. my $volume = 0;
  302. my $volume1 = 0;
  303. my $level1 = 0;
  304. foreach my $level (sort keys %TankChartHash) {
  305. if ($level ne "level" && $filllevel <= $level) {
  306. $volume = $volume1 + ($TankChartHash{$level} - $volume1) / ($level - $level1) * ($filllevel-$level1);
  307. $volume = Math::Round::nearest('0.01',$volume);
  308. last;
  309. }
  310. $level1 = $level;
  311. $volume1 = $TankChartHash{$level};
  312. }
  313. return $volume;
  314. }
  315. 1;
  316. =pod
  317. =item summary support for the HLS 6010 Probes
  318. =begin html
  319. <a name="HProtocolGateway"></a>
  320. <h3>HProtocolGateway</h3>
  321. <ul>
  322. The HProtocolGateway is a fhem module for the RS232 standard interface for HLS 6010 Probes connected to a Hectronic OPTILEVEL Supply.
  323. <br /><br /><br />
  324. <a name="HProtocolGateway"></a>
  325. <b>Define</b>
  326. <ul>
  327. <code>define &lt;name&gt; HProtocolGateway /dev/tty???<br />
  328. attr &lt;name&gt; pollIntervalMins 2<br />
  329. attr &lt;name&gt; path /opt/fhem/<br />
  330. attr &lt;name&gt; baudrate 1200<br />
  331. attr &lt;name&gt; databitsLength 8<br />
  332. attr &lt;name&gt; parityBit N<br />
  333. attr &lt;name&gt; stopBit 1</code>
  334. <br />
  335. <br />
  336. Defines an HProtocolGateway connected to RS232 serial standard interface.<br /><br />
  337. path is the path for tank&lt;01&gt;.csv strapping table files.<br /><br />
  338. <code>
  339. level,volume<br />
  340. 10,16<br />
  341. 520,7781<br />
  342. 1330,29105<br />
  343. 1830,43403<br />
  344. 2070,49844<br />
  345. 2220,53580<br />
  346. 2370,57009<br />
  347. 2400,57650<br />
  348. 2430,58275<br />
  349. 2370,57009<br />
  350. 2400,57650<br />
  351. 2430,58275<br />
  352. </code>
  353. <br /><br />
  354. <a name="HProtocolGateway"></a>
  355. <b>Attributes</b>
  356. <ul>
  357. <li>pollIntervalMins<br />
  358. poll Interval in Mins</li>
  359. <li>path<br />
  360. Strapping Table csv file path</li>
  361. <li>baudrate<br />
  362. Baudrate / 300, 600, 1200, 2400, 4800, 9600</li>
  363. <li>databitsLength<br />
  364. Databits Length / 5, 6, 7, 8</li>
  365. <li>parityBit<br />
  366. Parity Bit / N, E, O</li>
  367. <li>stopBit<br />
  368. Stop Bit / 0, 1</li>
  369. </ul><br />
  370. </ul><br />
  371. </ul><br />
  372. =end html
  373. =cut