98_ArduCounter.pm 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. ############################################################################
  2. # $Id: 98_ArduCounter.pm 13345 2017-02-06 18:22:20Z StefanStrobel $
  3. # fhem Modul für Impulszähler auf Basis von Arduino mit ArduCounter Sketch
  4. #
  5. # This file is part of fhem.
  6. #
  7. # Fhem is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Fhem is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with fhem. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. # Changelog:
  22. #
  23. # 2014-2-4 initial version
  24. # 2014-3-12 added documentation
  25. # 2015-02-08 renamed ACNT to ArduCounter
  26. # 2016-01-01 added attributes for reading names
  27. # 2016-10-15 fixed bug in handling Initialized / STATE
  28. # added attribute for individual factor for each pin
  29. # 2016-10-29 added option to receive additional Message vom sketch and log it at level 4
  30. # added documentation, changed logging timestamp for power to begin of interval
  31. # 2016-11-02 Attribute to control timestamp backdating
  32. # 2016-11-04 allow number instead of rising etc. as change with min pulse length
  33. # 2016-11-10 finish parsing new messages
  34. # 2016-11-12 added attributes verboseReadings, readingStartTime
  35. # add readAnswer for get info
  36. # 2016-12-13 better logging, ignore empty lines from Ardiuno
  37. # change to new communication syntax of sketch version 1.6
  38. # 2016-12-24 add -b 57600 to flashCommand
  39. # 2016-12-25 check for old firmware and log error, better logging, disable attribute
  40. # 2017-01-01 improved logging
  41. # 2017-01-02 modification for sketch 1.7, monitor clock drift difference between ardino and Fhem
  42. # 2017-01-04 some more beatification in logging
  43. # 2017-01-06 avoid reopening when disable=0 is set during startup
  44. # ideas / todo:
  45. package main;
  46. use strict;
  47. use warnings;
  48. use Time::HiRes qw(gettimeofday);
  49. my %ArduCounter_sets = (
  50. "raw" => "",
  51. "reset" => "",
  52. "flash" => ""
  53. );
  54. my %ArduCounter_gets = (
  55. "info" => ""
  56. );
  57. my $ArduCounter_Version = '4.5 - 6.1.2017';
  58. #
  59. # FHEM module intitialisation
  60. # defines the functions to be called from FHEM
  61. #########################################################################
  62. sub ArduCounter_Initialize($)
  63. {
  64. my ($hash) = @_;
  65. require "$attr{global}{modpath}/FHEM/DevIo.pm";
  66. $hash->{ReadFn} = "ArduCounter_Read";
  67. $hash->{ReadyFn} = "ArduCounter_Ready";
  68. $hash->{DefFn} = "ArduCounter_Define";
  69. $hash->{UndefFn} = "ArduCounter_Undef";
  70. $hash->{GetFn} = "ArduCounter_Get";
  71. $hash->{SetFn} = "ArduCounter_Set";
  72. $hash->{AttrFn} = "ArduCounter_Attr";
  73. $hash->{NotifyFn} = "ArduCounter_Notify";
  74. $hash->{AttrList} =
  75. 'pin.* ' .
  76. "interval " .
  77. "factor " .
  78. "readingNameCount[0-9]+ " .
  79. "readingNamePower[0-9]+ " .
  80. "readingFactor[0-9]+ " .
  81. "readingStartTime[0-9]+ " .
  82. "verboseReadings[0-9]+ " .
  83. "flashCommand " .
  84. "helloSendDelay " .
  85. "helloWaitTime " .
  86. "disable:0,1 " .
  87. "do_not_notify:1,0 " .
  88. $readingFnAttributes;
  89. }
  90. #
  91. # Define command
  92. ##########################################################################
  93. sub ArduCounter_Define($$)
  94. {
  95. my ($hash, $def) = @_;
  96. my @a = split( "[ \t\n]+", $def );
  97. return "wrong syntax: define <name> ArduCounter devicename\@speed"
  98. if ( @a < 3 );
  99. DevIo_CloseDev($hash);
  100. my $name = $a[0];
  101. my $dev = $a[2];
  102. $dev .= '@38400' if ($dev !~ /.+@[0-9]+/);
  103. $hash->{buffer} = "";
  104. $hash->{DeviceName} = $dev;
  105. $hash->{VersionModule} = $ArduCounter_Version;
  106. $hash->{NOTIFYDEV} = "global"; # NotifyFn nur aufrufen wenn global events (INITIALIZED)
  107. $hash->{STATE} = "disconnected";
  108. delete $hash->{Initialized};
  109. if(!defined($attr{$name}{'flashCommand'})) {
  110. #$attr{$name}{'flashCommand'} = 'avrdude -p atmega328P -b 57600 -c arduino -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]';
  111. $attr{$name}{'flashCommand'} = 'avrdude -p atmega328P -c arduino -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]';
  112. }
  113. return;
  114. }
  115. #
  116. # Send config commands after Board reported it is ready or still counting
  117. ##########################################################################
  118. sub ArduCounter_ConfigureDevice($)
  119. {
  120. my ($hash) = @_;
  121. my $name = $hash->{NAME};
  122. # send attributes to arduino device. Just call ArduCounter_Attr again
  123. #Log3 $name, 3, "$name: sending configuration from attributes to device";
  124. while (my ($attr, $val) = each(%{$attr{$name}})) {
  125. if ($attr =~ "pin|interval") {
  126. Log3 $name, 3, "$name: ConfigureDevice calls Attr with $attr $val";
  127. ArduCounter_Attr("set", $name, $attr, $val);
  128. }
  129. }
  130. }
  131. #
  132. # undefine command when device is deleted
  133. #########################################################################
  134. sub ArduCounter_Undef($$)
  135. {
  136. my ( $hash, $arg ) = @_;
  137. DevIo_CloseDev($hash);
  138. }
  139. ########################################################
  140. # Notify for INITIALIZED
  141. sub ArduCounter_Notify($$)
  142. {
  143. my ($hash, $source) = @_;
  144. return if($source->{NAME} ne "global");
  145. my $events = deviceEvents($source, 1);
  146. return if(!$events);
  147. my $name = $hash->{NAME};
  148. # Log3 $name, 5, "$name: Notify called for source $source->{NAME} with events: @{$events}";
  149. return if (!grep(m/^INITIALIZED|REREADCFG|(MODIFIED $name)$/, @{$source->{CHANGED}}));
  150. if (AttrVal($name, "disable", undef)) {
  151. Log3 $name, 4, "$name: device is disabled - don't set timer to send hello";
  152. return;
  153. }
  154. Log3 $name, 5, "$name: Notify called with events: @{$events}, open device and set timer to send hello to device";
  155. DevIo_OpenDev( $hash, 0, 0);
  156. my $now = gettimeofday();
  157. RemoveInternalTimer ("sendHello:$name");
  158. my $helloDelay = AttrVal($name, "helloSendDelay", 3);
  159. InternalTimer($now+$helloDelay, "ArduCounter_SendHello", "sendHello:$name", 0);
  160. }
  161. ######################################
  162. # wrapper for DevIo write
  163. sub ArduCounter_Write ($$)
  164. {
  165. my ($hash, $line) = @_;
  166. my $name = $hash->{NAME};
  167. if ($hash->{STATE} eq "disconnected" || !$hash->{FD}) {
  168. Log3 $name, 4, "$name: Write: device is disconnected, dropping line to write";
  169. return 0;
  170. }
  171. if (AttrVal($name, "disable", undef)) {
  172. Log3 $name, 4, "$name: Write called but device is disabled, dropping line to send";
  173. return 0;
  174. }
  175. DevIo_SimpleWrite( $hash, "$line\n", 2);
  176. return 1;
  177. }
  178. #######################################
  179. # Aufruf aus InternalTimer
  180. sub ArduCounter_SendHello($)
  181. {
  182. my $param = shift;
  183. my (undef,$name) = split(':',$param);
  184. my $hash = $defs{$name};
  185. my $now = gettimeofday();
  186. Log3 $name, 3, "$name: sending h(ello) to device to ask for version";
  187. return if (!ArduCounter_Write( $hash, "h"));
  188. $hash->{WaitForHello} = 1;
  189. RemoveInternalTimer ("hwait:$name");
  190. my $helloWait= AttrVal($name, "helloWaitTime ", 3);
  191. InternalTimer($now+$helloWait, "ArduCounter_HelloTimeout", "hwait:$name", 0);
  192. }
  193. #######################################
  194. # Aufruf aus InternalTimer
  195. sub ArduCounter_HelloTimeout($)
  196. {
  197. my $param = shift;
  198. my (undef,$name) = split(':',$param);
  199. my $hash = $defs{$name};
  200. Log3 $name, 3, "$name: device didn't reply to h(ello). Is the right sketch flashed?";
  201. delete $hash->{WaitForHello};
  202. }
  203. # Attr command
  204. #########################################################################
  205. sub ArduCounter_Attr(@)
  206. {
  207. my ($cmd,$name,$aName,$aVal) = @_;
  208. # $cmd can be "del" or "set"
  209. # $name is device name
  210. # aName and aVal are Attribute name and value
  211. my $hash = $defs{$name};
  212. my $modHash = $modules{$hash->{TYPE}};
  213. #Log3 $name, 5, "$name: Attr called with @_";
  214. if ($cmd eq "set") {
  215. if ($aName =~ 'pin.*') {
  216. if ($aName !~ 'pin[dD]?(\d+)') {
  217. Log3 $name, 3, "$name: Invalid pin name in attr $name $aName $aVal";
  218. return "Invalid pin name $aName";
  219. }
  220. my $pin = $1;
  221. if ($aVal =~ /^(rising|falling|change) ?(pullup)? ?([0-9]+)?/) {
  222. my $opt = "";
  223. if ($1 eq 'rising') {$opt = "3"}
  224. elsif ($1 eq 'falling') {$opt = "2"}
  225. elsif ($1 eq 'change') {$opt = "1"}
  226. $opt .= ($2 ? ",1" : ",0"); # pullup
  227. $opt .= ($3 ? ",$3" : ""); # min length
  228. if ($hash->{Initialized}) {
  229. ArduCounter_Write( $hash, "${pin},${opt}a");
  230. } else {
  231. Log3 $name, 5, "$name: communication postponed until device is initialized";
  232. }
  233. } else {
  234. Log3 $name, 3, "$name: Invalid value in attr $name $aName $aVal";
  235. return "Invalid Value $aVal";
  236. }
  237. } elsif ($aName eq "interval") {
  238. if ($aVal =~ '^(\d+) (\d+) ?(\d+)? ?(\d+)?$') {
  239. my $min = $1;
  240. my $max = $2;
  241. my $sml = $3;
  242. my $cnt = $4;
  243. if ($min < 1 || $min > 3600 || $max < $min || $max > 3600) {
  244. Log3 $name, 3, "$name: Invalid value in attr $name $aName $aVal";
  245. return "Invalid Value $aVal";
  246. }
  247. if ($hash->{Initialized}) {
  248. $sml = 0 if (!$sml);
  249. $cnt = 0 if (!$cnt);
  250. ArduCounter_Write($hash, "${min},${max},${sml},${cnt}i");
  251. } else {
  252. Log3 $name, 5, "$name: communication postponed until device is initialized";
  253. }
  254. } else {
  255. Log3 $name, 3, "$name: Invalid value in attr $name $aName $aVal";
  256. return "Invalid Value $aVal";
  257. }
  258. } elsif ($aName eq "factor") {
  259. if ($aVal =~ '^(\d+)$') {
  260. } else {
  261. Log3 $name, 3, "$name: Invalid value in attr $name $aName $aVal";
  262. return "Invalid Value $aVal";
  263. }
  264. } elsif ($aName eq 'disable') {
  265. if ($aVal) {
  266. Log3 $name, 5, "$name: disable attribute set";
  267. DevIo_CloseDev($hash);
  268. return;
  269. } else {
  270. Log3 $name, 3, "$name: disable attribute cleared";
  271. DevIo_OpenDev( $hash, 0, 0) if ($hash->{Initialized});
  272. my $now = gettimeofday();
  273. RemoveInternalTimer ("sendHello:$name");
  274. my $helloDelay = AttrVal($name, "helloSendDelay", 1);
  275. InternalTimer($now+$helloDelay, "ArduCounter_SendHello", "sendHello:$name", 0);
  276. }
  277. }
  278. # handle wild card attributes -> Add to userattr to allow modification in fhemweb
  279. #Log3 $name, 3, "$name: attribute $aName checking ";
  280. if (" $modHash->{AttrList} " !~ m/ ${aName}[ :;]/) {
  281. # nicht direkt in der Liste -> evt. wildcard attr in AttrList
  282. foreach my $la (split " ", $modHash->{AttrList}) {
  283. $la =~ /([^:;]+)(:?.*)/;
  284. my $vgl = $1; # attribute name in list - probably a regex
  285. my $opt = $2; # attribute hint in list
  286. if ($aName =~ $vgl) { # yes - the name in the list now matches as regex
  287. # $aName ist eine Ausprägung eines wildcard attrs
  288. addToDevAttrList($name, "$aName" . $opt); # create userattr with hint to allow changing by click in fhemweb
  289. if ($opt) {
  290. # remove old entries without hint
  291. my $ualist = $attr{$name}{userattr};
  292. $ualist = "" if(!$ualist);
  293. my %uahash;
  294. foreach my $a (split(" ", $ualist)) {
  295. if ($a !~ /^${aName}$/) { # entry in userattr list is attribute without hint
  296. $uahash{$a} = 1;
  297. } else {
  298. Log3 $name, 3, "$name: added hint $opt to attr $a in userattr list";
  299. }
  300. }
  301. $attr{$name}{userattr} = join(" ", sort keys %uahash);
  302. }
  303. }
  304. }
  305. } else {
  306. # exakt in Liste enthalten -> sicherstellen, dass keine +* etc. drin sind.
  307. if ($aName =~ /\|\*\+\[/) {
  308. Log3 $name, 3, "$name: Atribute $aName is not valid. It still contains wildcard symbols";
  309. return "$name: Atribute $aName is not valid. It still contains wildcard symbols";
  310. }
  311. }
  312. } elsif ($cmd eq "del") {
  313. if ($aName =~ 'pin.*') {
  314. if ($aName !~ 'pin([dD]?\d+)') {
  315. Log3 $name, 3, "$name: Invalid pin name in attr $name $aName $aVal";
  316. return "Invalid pin name $aName";
  317. }
  318. my $pin = $1;
  319. # this cannot come from fhem.cfg and waiting for initialized doesnt help so send it
  320. ArduCounter_Write( $hash, "${pin}d");
  321. } elsif ($aName eq 'disable') {
  322. Log3 $name, 3, "$name: disable attribute removed";
  323. DevIo_OpenDev( $hash, 0, 0) if ($hash->{Initialized});
  324. my $now = gettimeofday();
  325. RemoveInternalTimer ("sendHello:$name");
  326. my $helloDelay = AttrVal($name, "helloSendDelay", 1);
  327. InternalTimer($now+$helloDelay, "ArduCounter_SendHello", "sendHello:$name", 0);
  328. }
  329. }
  330. return undef;
  331. }
  332. # SET command
  333. #########################################################################
  334. sub ArduCounter_Set($@)
  335. {
  336. my ( $hash, @a ) = @_;
  337. return "\"set ArduCounter\" needs at least one argument" if ( @a < 2 );
  338. # @a is an array with DeviceName, SetName, Rest of Set Line
  339. my $name = shift @a;
  340. my $attr = shift @a;
  341. my $arg = join(" ", @a);
  342. if(!defined($ArduCounter_sets{$attr})) {
  343. my @cList = keys %ArduCounter_sets;
  344. return "Unknown argument $attr, choose one of " . join(" ", @cList);
  345. }
  346. if(!$hash->{FD}) {
  347. Log3 $name, 4, "$name: Set called but device is disconnected";
  348. return ("Set called but device is disconnected", undef);
  349. }
  350. if (AttrVal($name, "disable", undef)) {
  351. Log3 $name, 4, "$name: set called but device is disabled";
  352. return;
  353. }
  354. if ($attr eq "raw") {
  355. ArduCounter_Write($hash, "$arg");
  356. } elsif ($attr eq "reset") {
  357. DevIo_CloseDev($hash);
  358. $hash->{buffer} = "";
  359. DevIo_OpenDev( $hash, 0, 0);
  360. if (ArduCounter_Write($hash, "r")) {
  361. delete $hash->{Initialized};
  362. return "sent (r)eset command to device - waiting for its setup message";
  363. }
  364. } elsif ($attr eq "flash") {
  365. my @args = split(' ', $arg);
  366. my $log = "";
  367. my @deviceName = split('@', $hash->{DeviceName});
  368. my $port = $deviceName[0];
  369. my $firmwareFolder = "./FHEM/firmware/";
  370. my $logFile = AttrVal("global", "logdir", "./log") . "/ArduCounterFlash.log";
  371. my $hexFile = $firmwareFolder . "ArduCounter.hex";
  372. return "The file '$hexFile' does not exist" if(!-e $hexFile);
  373. Log3 $name, 4, "$name: Flashing Aduino at $port with $hexFile. See $logFile for details";
  374. $log .= "flashing device as ArduCounter for $name\n";
  375. $log .= "hex file: $hexFile\n";
  376. $log .= "port: $port\n";
  377. $log .= "log file: $logFile\n";
  378. my $flashCommand = AttrVal($name, "flashCommand", "");
  379. if($flashCommand ne "") {
  380. if (-e $logFile) {
  381. unlink $logFile;
  382. }
  383. DevIo_CloseDev($hash);
  384. readingsSingleUpdate($hash, "state", "disconnected", 1);
  385. $log .= "$name closed\n";
  386. my $avrdude = $flashCommand;
  387. $avrdude =~ s/\Q[PORT]\E/$port/g;
  388. $avrdude =~ s/\Q[HEXFILE]\E/$hexFile/g;
  389. $avrdude =~ s/\Q[LOGFILE]\E/$logFile/g;
  390. $log .= "command: $avrdude\n\n";
  391. `$avrdude`;
  392. local $/=undef;
  393. if (-e $logFile) {
  394. open FILE, $logFile;
  395. my $logText = <FILE>;
  396. close FILE;
  397. $log .= "--- AVRDUDE ---------------------------------------------------------------------------------\n";
  398. $log .= $logText;
  399. $log .= "--- AVRDUDE ---------------------------------------------------------------------------------\n\n";
  400. }
  401. else {
  402. $log .= "WARNING: avrdude created no log file\n\n";
  403. }
  404. DevIo_OpenDev($hash, 0, 0);
  405. $log .= "$name opened\n";
  406. }
  407. return $log;
  408. }
  409. return undef;
  410. }
  411. # GET command
  412. #########################################################################
  413. sub ArduCounter_Get($@)
  414. {
  415. my ( $hash, @a ) = @_;
  416. return "\"set ArduCounter\" needs at least one argument" if ( @a < 2 );
  417. my $name = shift @a;
  418. my $attr = shift @a;
  419. if(!defined($ArduCounter_gets{$attr})) {
  420. my @cList = keys %ArduCounter_gets;
  421. return "Unknown argument $attr, choose one of " . join(" ", @cList);
  422. }
  423. if(!$hash->{FD}) {
  424. Log3 $name, 4, "$name: Get called but device is disconnected";
  425. return ("Get called but device is disconnected", undef);
  426. }
  427. if (AttrVal($name, "disable", undef)) {
  428. Log3 $name, 4, "$name: get called but device is disabled";
  429. return;
  430. }
  431. if ($attr eq "info") {
  432. Log3 $name, 3, "$name: Sending info command to device";
  433. ArduCounter_Write( $hash, "s");
  434. my ($err, $msg) = ArduCounter_ReadAnswer($hash, 'Next report in [0-9]+ Milliseconds');
  435. # todo: test adding \n to regex to make sure we got the whole respose string
  436. return ($err ? $err : $msg);
  437. }
  438. return undef;
  439. }
  440. ######################################
  441. sub ArduCounter_HandleVersion($$)
  442. {
  443. my ($hash, $line) = @_;
  444. my $name = $hash->{NAME};
  445. if ($line =~ / V([\d\.]+)/) {
  446. my $version = $1;
  447. if ($version < "1.7") {
  448. $version .= " - not compatible with this Module version - please flash new sketch";
  449. Log3 $name, 3, "$name: device reported outdated Arducounter Firmware - please update!";
  450. }
  451. $hash->{VersionFirmware} = $version;
  452. Log3 $name, 4, "$name: device reported firmware $version";
  453. }
  454. }
  455. #########################################################################
  456. sub ArduCounter_Parse($)
  457. {
  458. my ($hash) = @_;
  459. my $name = $hash->{NAME};
  460. my $retStr = "";
  461. my @lines = split /\n/, $hash->{buffer};
  462. foreach my $line (@lines) {
  463. # Log3 $name, 5, "$name: Parse line: $line";
  464. if ($line =~ 'R([\d]+) C([\d]+) D([\d]+) T([\d]+)( N[\d]+)?( X[\d]+)?( F[\d]+)?(L [\d]+)?( A[\d]+)?')
  465. {
  466. my $pin = $1;
  467. my $count = $2;
  468. my $diff = $3;
  469. my $time = $4;
  470. my $deTime = ($5 ? substr($5, 2) / 1000 : "");
  471. my $reject = ($6 ? substr($6, 2) : "");
  472. my $first = ($7 ? substr($7, 2) : "");
  473. my $last = ($8 ? substr($8, 2) : "");
  474. my $avgLen = ($9 ? substr($9, 2) : "");
  475. my $factor = AttrVal($name, "readingFactor$pin", AttrVal($name, "factor", 1000));
  476. my $rcname = AttrVal($name, "readingNameCount$pin", "pin$pin");
  477. my $rpname = AttrVal($name, "readingNamePower$pin", "power$pin");
  478. my $lName = AttrVal($name, "readingNamePower$pin", AttrVal($name, "readingNameCount$pin", "pin$pin"));
  479. my $chIdx = 0;
  480. my $now = gettimeofday();
  481. my $sTime = $now - $time/1000; # start of observation interval (~first pulse)
  482. my $fSTime = FmtDateTime($sTime); # formatted
  483. my $fSdTim = FmtTime($sTime); # only time formatted
  484. my $eTime = $now; # now / end of observation interval
  485. my $fETime = FmtDateTime($eTime); # formatted
  486. my $fEdTim = FmtTime($eTime); # only time formatted
  487. my $power = sprintf ("%.3f", ($time ? $diff/$time/1000*3600*$factor : 0));
  488. Log3 $name, 4, "$name: Pin $pin ($lName) count $count (diff $diff) in " .
  489. sprintf("%.3f", $time/1000) . "s" .
  490. ((defined($reject) && $reject ne "") ? ", reject $reject" : "") .
  491. ($avgLen ? ", Avg Len ${avgLen}ms" : "") .
  492. ", result $power";
  493. Log3 $name, 5, "$name: interval $fSdTim until $fEdTim" .
  494. ($first ? ", First at $first" : "") .
  495. ($last ? ", Last at $last" : "");
  496. readingsBeginUpdate($hash);
  497. if (AttrVal($name, "readingStartTime$pin", 0)) {
  498. $hash->{".updateTime"} = $sTime;
  499. $hash->{".updateTimestamp"} = $fSTime;
  500. Log3 $name, 5, "$name: readingStartTime$pin specified: setting reading timestamp to $fSdTim";
  501. Log3 $name, 5, "$name: set readings $rpname to $power, timeDiff$pin to $time and countDiff$pin to $diff";
  502. readingsBulkUpdate($hash, $rpname, $power) if ($time);
  503. $hash->{CHANGETIME}[$chIdx++] = $fSTime; # Intervall start
  504. $hash->{".updateTime"} = $eTime;
  505. $hash->{".updateTimestamp"} = $fETime;
  506. readingsBulkUpdate($hash, $rcname, $count);
  507. $hash->{CHANGETIME}[$chIdx++] = $fETime;
  508. if (AttrVal($name, "verboseReadings$pin", 0)) {
  509. readingsBulkUpdate($hash, "timeDiff$pin", $time);
  510. $hash->{CHANGETIME}[$chIdx++] = $fETime;
  511. readingsBulkUpdate($hash, "countDiff$pin", $diff);
  512. $hash->{CHANGETIME}[$chIdx++] = $fETime;
  513. readingsBulkUpdate($hash, "lastMsg$pin", $line);
  514. $hash->{CHANGETIME}[$chIdx++] = $fETime;
  515. if (defined($reject)) {
  516. readingsBulkUpdate($hash, "reject$pin", $reject);
  517. $hash->{CHANGETIME}[$chIdx++] = $fETime;
  518. }
  519. }
  520. } else {
  521. Log3 $name, 5, "$name: set readings $rpname to $power, timeDiff$pin to $time and countDiff$pin to $diff";
  522. readingsBulkUpdate($hash, $rpname, $power) if ($time);
  523. $eTime = time_str2num(ReadingsTimestamp ($name, $rpname, 0));
  524. readingsBulkUpdate($hash, $rcname, $count);
  525. if (AttrVal($name, "verboseReadings$pin", 0)) {
  526. readingsBulkUpdate($hash, "timeDiff$pin", $time);
  527. readingsBulkUpdate($hash, "countDiff$pin", $diff);
  528. readingsBulkUpdate($hash, "lastMsg$pin", $line);
  529. if (defined($reject)) {
  530. readingsBulkUpdate($hash, "reject$pin", $reject);
  531. }
  532. }
  533. }
  534. readingsEndUpdate($hash, 1);
  535. if ($deTime) {
  536. if (defined ($hash->{'.DeTOff'}) && $hash->{'.LastDeT'}) {
  537. if ($deTime >= $hash->{'.LastDeT'}) {
  538. $hash->{'.Drift2'} = ($now - $hash->{'.DeTOff'}) - $deTime;
  539. } else {
  540. $hash->{'.DeTOff'} = $now - $deTime;
  541. Log3 $name, 5, "$name: device clock wrapped (now $deTime, before $hash->{'.LastDeT'}). New offset is $hash->{'.DeTOff'}";
  542. }
  543. } else {
  544. $hash->{'.DeTOff'} = $now - $deTime;
  545. $hash->{'.Drift2'} = 0;
  546. $hash->{'.DriftStart'} = $now;
  547. Log3 $name, 5, "$name: Initialize clock offset to $hash->{'.DeTOff'}";
  548. }
  549. $hash->{'.LastDeT'} = $deTime;
  550. }
  551. my $drTime = ($now - $hash->{'.DriftStart'});
  552. Log3 $name, 5, "$name: Device Time $deTime" .
  553. #", Offset " . sprintf("%.3f", $hash->{'.DeTOff'}/1000) .
  554. ", Drift " . sprintf("%.3f", $hash->{'.Drift2'}) .
  555. "s in " . sprintf("%.3f", $drTime) . "s" .
  556. ($drTime > 0 ? ", " . sprintf("%.2f", $hash->{'.Drift2'} / $drTime * 100) . "%" : "");
  557. if (!$hash->{Initialized}) {
  558. Log3 $name, 3, "$name: device reported count";
  559. if (!$hash->{WaitForHello}) {
  560. ArduCounter_SendHello("direct:$name");
  561. }
  562. $hash->{Initialized} = 1;
  563. RemoveInternalTimer ("sendHello:$name");
  564. }
  565. } elsif ($line =~ /ArduCounter V([\d\.]+).?Hello/) { # response to h(ello)
  566. Log3 $name, 3, "$name: device replied to hello, V$1";
  567. ArduCounter_HandleVersion($hash, $line);
  568. $hash->{Initialized} = 1;
  569. ArduCounter_ConfigureDevice($hash) if ($hash->{WaitForHello});
  570. delete $hash->{WaitForHello};
  571. RemoveInternalTimer ("hwait:$name");
  572. RemoveInternalTimer ("sendHello:$name");
  573. } elsif ($line =~ /Status: ArduCounter V([\d\.]+)/) { # response to s(how)
  574. $retStr .= "\n" if ($retStr);
  575. $retStr .= $line;
  576. ArduCounter_HandleVersion($hash, $line);
  577. #todo: remove here?
  578. delete $hash->{WaitForHello};
  579. RemoveInternalTimer ("hwait:$name"); # dont wait for hello reply if already sent
  580. RemoveInternalTimer ("sendHello:$name"); # Hello not needed anymore if not sent yet
  581. } elsif ($line =~ /ArduCounter V([\d\.]+).?Started/) { # setup message
  582. Log3 $name, 3, "$name: device sent setup message, V$1";
  583. ArduCounter_HandleVersion($hash, $line);
  584. $hash->{Initialized} = 1;
  585. ArduCounter_ConfigureDevice($hash);
  586. delete $hash->{WaitForHello};
  587. RemoveInternalTimer ("hwait:$name"); # dont wait for hello reply if already sent
  588. RemoveInternalTimer ("sendHello:$name"); # Hello not needed anymore if not sent yet
  589. } elsif ($line =~ /V([\d\.]+).?Setup done/) { # old setup message
  590. Log3 $name, 3, "$name: device is flashed with an old and incompatible firmware : $1";
  591. Log3 $name, 3, "$name: please use set $name flash to update";
  592. ArduCounter_HandleVersion($hash, $line);
  593. } elsif ($line =~ /^M (.*)/) {
  594. $retStr .= "\n" if ($retStr);
  595. $retStr .= $1;
  596. Log3 $name, 3, "$name: device: $1";
  597. } elsif ($line =~ /^[\s\n]*$/) {
  598. # blank line - ignore
  599. } else {
  600. Log3 $name, 3, "$name: unparseable message from device: $line";
  601. }
  602. }
  603. $hash->{buffer} = "";
  604. return $retStr;
  605. }
  606. #########################################################################
  607. # called from the global loop, when the select for hash->{FD} reports data
  608. sub ArduCounter_Read($)
  609. {
  610. my ($hash) = @_;
  611. my $name = $hash->{NAME};
  612. my ($pin, $count, $diff, $power, $time, $reject, $msg);
  613. # read from serial device
  614. my $buf = DevIo_SimpleRead($hash);
  615. return if (!defined($buf) );
  616. $hash->{buffer} .= $buf;
  617. my $end = chop $buf;
  618. #Log3 $name, 5, "$name: Read: current buffer content: " . $hash->{buffer};
  619. # did we already get a full frame?
  620. return if ($end ne "\n");
  621. ArduCounter_Parse($hash);
  622. }
  623. #####################################
  624. # Called from get / set to get a direct answer
  625. # called with logical device hash
  626. sub
  627. ArduCounter_ReadAnswer($$)
  628. {
  629. my ($hash, $expect) = @_;
  630. my $name = $hash->{NAME};
  631. my $rin = '';
  632. my $msgBuf = '';
  633. my $to = AttrVal($name, "timeout", 2);
  634. my $buf;
  635. Log3 $name, 5, "$name: ReadAnswer called";
  636. for(;;) {
  637. if($^O =~ m/Win/ && $hash->{USBDev}) {
  638. $hash->{USBDev}->read_const_time($to*1000); # set timeout (ms)
  639. $buf = $hash->{USBDev}->read(999);
  640. if(length($buf) == 0) {
  641. Log3 $name, 3, "$name: Timeout in ReadAnswer";
  642. return ("Timeout reading answer", undef)
  643. }
  644. } else {
  645. if(!$hash->{FD}) {
  646. Log3 $name, 3, "$name: Device lost in ReadAnswer";
  647. return ("Device lost when reading answer", undef);
  648. }
  649. vec($rin, $hash->{FD}, 1) = 1; # setze entsprechendes Bit in rin
  650. my $nfound = select($rin, undef, undef, $to);
  651. if($nfound < 0) {
  652. next if ($! == EAGAIN() || $! == EINTR() || $! == 0);
  653. my $err = $!;
  654. DevIo_Disconnected($hash);
  655. Log3 $name, 3, "$name: ReadAnswer error: $err";
  656. return("ReadAnswer error: $err", undef);
  657. }
  658. if($nfound == 0) {
  659. Log3 $name, 3, "$name: Timeout2 in ReadAnswer";
  660. return ("Timeout reading answer", undef);
  661. }
  662. $buf = DevIo_SimpleRead($hash);
  663. if(!defined($buf)) {
  664. Log3 $name, 3, "$name: ReadAnswer got no data";
  665. return ("No data", undef);
  666. }
  667. }
  668. if($buf) {
  669. #Log3 $name, 5, "$name: ReadAnswer got: $buf";
  670. $hash->{buffer} .= $buf;
  671. }
  672. my $end = chop $buf;
  673. #Log3 $name, 5, "$name: Current buffer content: " . $hash->{buffer};
  674. next if ($end ne "\n");
  675. $msgBuf .= "\n" if ($msgBuf);
  676. $msgBuf .= ArduCounter_Parse($hash);
  677. #Log3 $name, 5, "$name: ReadAnswer msgBuf: " . $msgBuf;
  678. if ($msgBuf =~ $expect) {
  679. Log3 $name, 5, "$name: ReadAnswer matched $expect";
  680. return (undef, $msgBuf);
  681. }
  682. }
  683. return ("no Data", undef);
  684. }
  685. #
  686. # copied from other FHEM modules
  687. #########################################################################
  688. sub ArduCounter_Ready($)
  689. {
  690. my ($hash) = @_;
  691. my $name = $hash->{NAME};
  692. if (AttrVal($name, "disable", undef)) {
  693. return;
  694. }
  695. # try to reopen if state is disconnected
  696. if ( $hash->{STATE} eq "disconnected" ) {
  697. #Log3 $name, 3, "$name: ReadyFN tries to open"; # debug
  698. DevIo_OpenDev( $hash, 1, undef );
  699. if ($hash->{FD} && !$hash->{Initialized}) {
  700. Log3 $name, 3, "$name: device not initialized yet, set timer to send h(ello";
  701. my $now = gettimeofday();
  702. RemoveInternalTimer ("sendHello:$name");
  703. my $helloDelay = AttrVal($name, "helloSendDelay", 3);
  704. InternalTimer($now+$helloDelay, "ArduCounter_SendHello", "sendHello:$name", 0);
  705. }
  706. return;
  707. }
  708. # This is relevant for windows/USB only
  709. my $po = $hash->{USBDev};
  710. if ($po) {
  711. my ( $BlockingFlags, $InBytes, $OutBytes, $ErrorFlags ) = $po->status;
  712. return ( $InBytes > 0 );
  713. }
  714. }
  715. 1;
  716. =pod
  717. =item device
  718. =item summary Module for consumption counter based on an arduino with the ArduCounter sketch
  719. =item summary_DE Modul für Strom / Wasserzähler auf Arduino-Basis mit ArduCounter Sketch
  720. =begin html
  721. <a name="ArduCounter"></a>
  722. <h3>ArduCounter</h3>
  723. <ul>
  724. This module implements an Interface to an Arduino based counter for pulses on any input pin of an Arduino Uno, Nano or similar device like a Jeenode. The typical use case is an S0-Interface on an energy meter<br>
  725. Counters are configured with attributes that define which Arduino pins should count pulses and in which intervals the Arduino board should report the current counts.<br>
  726. The Arduino sketch that works with this module uses pin change interrupts so it can efficiently count pulses on all available input pins.
  727. <br><br>
  728. <b>Prerequisites</b>
  729. <ul>
  730. <br>
  731. <li>
  732. This module requires an Arduino uno, nano, Jeenode or similar device running the ArduCounter sketch provided with this module
  733. </li>
  734. </ul>
  735. <br>
  736. <a name="ArduCounterdefine"></a>
  737. <b>Define</b>
  738. <ul>
  739. <br>
  740. <code>define &lt;name&gt; ArduCounter &lt;device&gt;</code>
  741. <br>
  742. &lt;device&gt; specifies the serial port to communicate with the Arduino.<br>
  743. The name of the serial-device depends on your distribution.
  744. You can also specify a baudrate if the device name contains the @
  745. character, e.g.: /dev/ttyUSB0@38400<br>
  746. The default baudrate of the ArduCounter firmware is 38400 since Version 1.4
  747. <br>
  748. Example:<br>
  749. <br>
  750. <ul><code>define AC ArduCounter /dev/ttyUSB2@38400</code></ul>
  751. </ul>
  752. <br>
  753. <a name="ArduCounterconfiguration"></a>
  754. <b>Configuration of ArduCounter counters</b><br><br>
  755. <ul>
  756. Specify the pins where impulses should be counted e.g. as <code>attr AC pinX falling pullup 30</code> <br>
  757. The X in pinX can be an Arduino pin number with or without the letter D e.g. pin4, pinD5, pin6, pinD7 ...<br>
  758. After the pin you can define if rising or falling edges of the signals should be counted. The optional keyword pullup activates the pullup resistor for the given Arduino Pin.
  759. The last argument is also optional and specifies a minimal pulse length in milliseconds. In this case the first argument (e.g. falling) means that an impulse starts with a falling edge from 1 to 0 and ends when the signal changes back from 0 to 1.
  760. <br><br>
  761. Example:<br>
  762. <pre>
  763. define AC ArduCounter /dev/ttyUSB2
  764. attr AC factor 1000
  765. attr AC interval 60 300
  766. attr AC pinD4 falling pullup
  767. attr AC pinD5 falling pullup 30
  768. attr AC pinD6 rising
  769. </pre>
  770. this defines three counters connected to the pins D4, D5 and D5. <br>
  771. D4 and D5 have their pullup resistors activated and the impulse draws the pins to zero. <br>
  772. For D4 every falling edge of the signal (when the input changes from 1 to 0) is counted.<br>
  773. For D5 the arduino measures the time in milliseconds between the falling edge and the rising edge. If this time is longer than the specified 30 milliseconds then the impulse is counted. If the time is shorter then this impulse is regarded as noise and added to a separate reject counter.<br>
  774. For pin D6 the ardiono counts every time when the signal changes from 0 to 1. <br>
  775. The ArduCounter sketch which must be loaded on the Arduino implements this using pin change interrupts,
  776. so all avilable input pins can be used, not only the ones that support normal interrupts.
  777. </ul>
  778. <br>
  779. <a name="ArduCounterset"></a>
  780. <b>Set-Commands</b><br>
  781. <ul>
  782. <li><b>raw</b></li>
  783. send the value to the Arduino board so you can directly talk to the sketch using its commands.<br>
  784. This is not needed for normal operation but might be useful sometimes for debugging<br>
  785. <li><b>flash</b></li>
  786. flashes the ArduCounter firmware ArduCounter.hex from the fhem subdirectory FHEM/firmware
  787. onto the device. This command needs avrdude to be installed. The attribute flashCommand specidies how avrdude is called. If it is not modifed then the module sets it to avrdude -p atmega328P -c arduino -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]<br>
  788. This setting should work for a standard installation and the placeholders are automatically replaced when
  789. the command is used. So normally there is no need to modify this attribute.<br>
  790. Depending on your specific Arduino board however, you might need to insert <code>-b 57600</code> in the flash Command.<br>
  791. <br>
  792. <li><b>reset</b></li>
  793. reopens the arduino device and sends a command to it which causes a reinitialize and reset of the counters. Then the module resends the attribute configuration / definition of the pins to the device.
  794. </ul>
  795. <br>
  796. <a name="ArduCounterget"></a>
  797. <b>Get-Commands</b><br>
  798. <ul>
  799. <li><b>info</b></li>
  800. send a command to the Arduino board to get current counts.<br>
  801. This is not needed for normal operation but might be useful sometimes for debugging<br>
  802. </ul>
  803. <br>
  804. <a name="ArduCounterattr"></a>
  805. <b>Attributes</b><br><br>
  806. <ul>
  807. <li><a href="#do_not_notify">do_not_notify</a></li>
  808. <li><a href="#readingFnAttributes">readingFnAttributes</a></li>
  809. <br>
  810. <li><b>pin.*</b></li>
  811. Define a pin of the Arduino board as input. This attribute expects either
  812. <code>rising</code>, <code>falling</code> or <code>change</code>, followed by an optional <code>pullup</code> and an optional number as value.<br>
  813. If a number is specified, the arduino will track rising and falling edges of each impulse and measure the length of a pulse in milliseconds. The number specified here is the minimal length of a pulse and a pause before a pulse. If one is too small, the pulse is not counted but added to a separate reject counter.
  814. <li><b>interval</b> normal max min mincout</li>
  815. Defines the parameters that affect the way counting and reporting works.
  816. This Attribute expects at least two and a maximum of four numbers as value. The first is the normal interval, the second the maximal interval, the third is a minimal interval and the fourth is a minimal pulse count.
  817. In the usual operation mode (when the normal interval is smaller than the maximum interval),
  818. the Arduino board just counts and remembers the time between the first impulse and the last impulse for each pin.<br>
  819. After the normal interval is elapsed the Arduino board reports the count and time for those pins where impulses were encountered.<br>
  820. This means that even though the normal interval might be 10 seconds, the reported time difference can be
  821. something different because it observed impulses as starting and ending point.<br>
  822. The Power (e.g. for energy meters) is the calculated based of the counted impulses and the time between the first and the last impulse. <br>
  823. For the next interval, the starting time will be the time of the last impulse in the previous
  824. reporting period and the time difference will be taken up to the last impulse before the reporting
  825. interval has elapsed.
  826. <br><br>
  827. The second, third and fourth numbers (maximum, minimal interval and minimal count) exist for the special case when the pulse frequency is very low and the reporting time is comparatively short.<br>
  828. For example if the normal interval (first number) is 60 seconds and the device counts only one impulse in 90 seconds, the the calculated power reading will jump up and down and will give ugly numbers.
  829. By adjusting the other numbers of this attribute this can be avoided.<br>
  830. In case in the normal interval the observed impulses are encountered in a time difference that is smaller than the third number (minimal interval) or if the number of impulses counted is smaller than the
  831. fourth number (minimal count) then the reporting is delayed until the maximum interval has elapsed or the above conditions have changed after another normal interval.<br>
  832. This way the counter will report a higher number of pulses counted and a larger time difference back to fhem.
  833. <br><br>
  834. If this is seems too complicated and you prefer a simple and constant reporting interval, then you can set the normal interval and the mximum interval to the same number. This changes the operation mode of the counter to just count during this normal and maximum interval and report the count. In this case the reported time difference is always the reporting interval and not the measured time between the real impulses.
  835. <li><b>factor</b></li>
  836. Define a multiplicator for calculating the power from the impulse count and the time between the first and the last impulse
  837. <li><b>readingNameCount[0-9]+</b></li>
  838. Change the name of the counter reading pinX to something more meaningful.
  839. <li><b>readingNamePower[0-9]+</b></li>
  840. Change the name of the power reading powerX to something more meaningful.
  841. <li><b>readingFactor[0-9]+</b></li>
  842. Override the factor attribute for this individual pin.
  843. <li><b>readingStartTime[0-9]+</b></li>
  844. Allow the reading time stamp to be set to the beginning of measuring intervals
  845. <li><b>verboseReadings[0-9]+</b></li>
  846. create readings timeDiff, countDiff and lastMsg for each pin
  847. </ul>
  848. <br>
  849. <b>Readings / Events</b><br>
  850. <ul>
  851. The module creates at least the following readings and events for each defined pin:
  852. <li><b>pin.*</b></li>
  853. the current count at this pin
  854. <li><b>power.*</b></li>
  855. the current calculated power at this pin
  856. Most reading names can be customized with attribues and many more readings can be generated by setting the attribute verboseReadings[0-9]+ to 1.
  857. </ul>
  858. <br>
  859. </ul>
  860. =end html
  861. =cut