21_OWCOUNT.pm 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. ########################################################################################
  2. #
  3. # OWCOUNT.pm
  4. #
  5. # FHEM module to commmunicate with 1-Wire Counter/RAM DS2423
  6. #
  7. # Prof. Dr. Peter A. Henning
  8. # Norbert Truchsess
  9. #
  10. # $Id: 21_OWCOUNT.pm 15339 2017-10-29 08:14:07Z phenning $
  11. #
  12. ########################################################################################
  13. #
  14. # This programm is free software; you can redistribute it and/or modify
  15. # it under the terms of the GNU General Public License as published by
  16. # the Free Software Foundation; either version 2 of the License, or
  17. # (at your option) any later version.
  18. #
  19. # The GNU General Public License can be found at
  20. # http://www.gnu.org/copyleft/gpl.html.
  21. # A copy is found in the textfile GPL.txt and important notices to the license
  22. # from the author is found in LICENSE.txt distributed with these scripts.
  23. #
  24. # This script is distributed in the hope that it will be useful,
  25. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. # GNU General Public License for more details.
  28. #
  29. ########################################################################################
  30. package main;
  31. use vars qw{%attr %defs %modules $readingFnAttributes $init_done};
  32. use strict;
  33. use warnings;
  34. #add FHEM/lib to @INC if it's not already included. Should rather be in fhem.pl than here though...
  35. BEGIN {
  36. if (!grep(/FHEM\/lib$/,@INC)) {
  37. foreach my $inc (grep(/FHEM$/,@INC)) {
  38. push @INC,$inc."/lib";
  39. };
  40. };
  41. };
  42. use ProtoThreads;
  43. no warnings 'deprecated';
  44. sub Log3($$$);
  45. my $owx_version="7.01";
  46. #-- fixed raw channel name, flexible channel name
  47. my @owg_fixed = ("A","B");
  48. my @owg_channel = ("A","B");
  49. my @owg_rate = ("A_rate","B_rate");
  50. #-- initially assume that both memory types (low, high) are present
  51. my @owg_memory = (1,1,0);
  52. my $owgmodel;
  53. my $owgauto = 0;
  54. my %gets = (
  55. "id" => ":noArg",
  56. "mcache" => "",
  57. "memory" => "",
  58. "midnight" => "",
  59. "raw" => "",
  60. "counters" => ":noArg",
  61. "month" => ":noArg",
  62. "year" => ":noArg",
  63. "version" => ":noArg"
  64. );
  65. my %sets = (
  66. "interval" => "",
  67. "memory" => "",
  68. "midnight" => "",
  69. "counter" => ""
  70. );
  71. my %updates = (
  72. "present" => "",
  73. "counter" => ""
  74. );
  75. ########################################################################################
  76. #
  77. # The following subroutines are independent of the bus interface
  78. #
  79. # Prefix = OWCOUNT
  80. #
  81. ########################################################################################
  82. #
  83. # OWCOUNT_Initialize
  84. #
  85. # Parameter hash = hash of device addressed
  86. #
  87. ########################################################################################
  88. sub OWCOUNT_Initialize ($) {
  89. my ($hash) = @_;
  90. $hash->{DefFn} = "OWCOUNT_Define";
  91. $hash->{UndefFn} = "OWCOUNT_Undef";
  92. $hash->{GetFn} = "OWCOUNT_Get";
  93. $hash->{SetFn} = "OWCOUNT_Set";
  94. $hash->{NotifyFn}= "OWCOUNT_Notify";
  95. $hash->{InitFn} = "OWCOUNT_Init";
  96. $hash->{AttrFn} = "OWCOUNT_Attr";
  97. #-- see header for attributes
  98. my $attlist = "IODev do_not_notify:0,1 showtime:0,1 model:DS2423,DS2423enew,DS2423eold LogM LogY ".
  99. "nomemory:1,0 interval ".
  100. $readingFnAttributes;
  101. for( my $i=0;$i<int(@owg_fixed);$i++ ){
  102. $attlist .= " ".$owg_fixed[$i]."Name";
  103. $attlist .= " ".$owg_fixed[$i]."Rate";
  104. $attlist .= " ".$owg_fixed[$i]."Offset";
  105. $attlist .= " ".$owg_fixed[$i]."Factor";
  106. $attlist .= " ".$owg_fixed[$i]."Unit";
  107. $attlist .= " ".$owg_fixed[$i]."Mode:normal,daily";
  108. $attlist .= " ".$owg_fixed[$i]."Period:hour,minute,second";
  109. }
  110. $hash->{AttrList} = $attlist;
  111. #-- make sure OWX is loaded so OWX_CRC is available if running with OWServer
  112. main::LoadModule("OWX");
  113. }
  114. #########################################################################################
  115. #
  116. # OWCOUNT_Define - Implements DefFn function
  117. #
  118. # Parameter hash = hash of device addressed, def = definition string
  119. #
  120. #########################################################################################
  121. sub OWCOUNT_Define ($$) {
  122. my ($hash, $def) = @_;
  123. my @a = split("[ \t][ \t]*", $def);
  124. my ($name,$model,$fam,$id,$crc,$interval,$scale,$ret);
  125. #-- default
  126. $name = $a[0];
  127. $interval = 300;
  128. $scale = "";
  129. $ret = "";
  130. #-- check syntax
  131. return "OWCOUNT: Wrong syntax, must be define <name> OWCOUNT [<model>] <id> [interval] or OWCOUNT <fam>.<id> [interval]"
  132. if(int(@a) < 2 || int(@a) > 5);
  133. #-- different types of definition allowed
  134. my $a2 = $a[2];
  135. my $a3 = defined($a[3]) ? $a[3] : "";
  136. #-- The model may be DS2423 or DS2423emu. Some weird people are violating 1-Wire integrity by using the
  137. # the same family ID although the DS2423emu does not fully support the DS2423 commands.
  138. # Model attribute will be modified later when memory is checked
  139. #-- no model, 12 characters
  140. if( $a2 =~ m/^[0-9|a-f|A-F]{12}$/ ) {
  141. $model = "DS2423";
  142. $owgauto =1;
  143. #CommandAttr (undef,"$name model DS2423");
  144. $fam = "1D";
  145. $id = $a[2];
  146. if(int(@a)>=4) { $interval = $a[3]; }
  147. #-- no model, 2+12 characters
  148. } elsif( $a2 =~ m/^[0-9|a-f|A-F]{2}\.[0-9|a-f|A-F]{12}$/ ) {
  149. $fam = substr($a[2],0,2);
  150. $id = substr($a[2],3);
  151. if(int(@a)>=4) { $interval = $a[3]; }
  152. if( $fam eq "1D" ){
  153. $model = "DS2423";
  154. $owgauto =1;
  155. #CommandAttr (undef,"$name model DS2423");
  156. }else{
  157. return "OWCOUNT: Wrong 1-Wire device family $fam";
  158. }
  159. #-- model, 12 characters
  160. } elsif( $a3 =~ m/^[0-9|a-f|A-F]{12}$/ ) {
  161. $model = $a[2];
  162. $id = $a[3];
  163. if(int(@a)>=5) { $interval = $a[4]; }
  164. if( $model eq "DS2423" ){
  165. $fam = "1D";
  166. #CommandAttr (undef,"$name model DS2423");
  167. #-- Check, if name might be from autocreate -> checking memory
  168. if( $name =~ /OWX\_$fam\_$id/ ){
  169. $owgauto=1;
  170. }
  171. @owg_memory = (1,1,0);
  172. }elsif( $model eq "DS2423enew" ){
  173. $fam = "1D";
  174. @owg_memory = (1,1,0);
  175. #CommandAttr (undef,"$name model DS2423enew");
  176. }elsif( $model eq "DS2423eold" ){
  177. $fam = "1D";
  178. #CommandAttr (undef,"$name model DS2423eold");
  179. #CommandAttr (undef,"$name nomemory 1");
  180. @owg_memory = (0,0,0);
  181. }else{
  182. return "OWCOUNT: Wrong 1-Wire device model $model";
  183. }
  184. } else {
  185. return "OWCOUNT: $a[0] ID $a[2] invalid, specify a 12 or 2.12 digit value";
  186. }
  187. $owgmodel=$model;
  188. # determine CRC Code - only if this is a direct interface
  189. $crc = sprintf("%02x",OWX_CRC($fam.".".$id."00"));
  190. #-- Define device internals
  191. $hash->{ROM_ID} = "$fam.$id.$crc";
  192. $hash->{OW_ID} = $id;
  193. $hash->{OW_FAMILY} = $fam;
  194. $hash->{ERRCOUNT} = 0;
  195. $hash->{PRESENT} = 0;
  196. $hash->{INTERVAL} = $interval;
  197. #-- Couple to I/O device
  198. AssignIoPort($hash);
  199. if( !defined($hash->{IODev}) or !defined($hash->{IODev}->{NAME}) ){
  200. return "OWCOUNT: Warning, no 1-Wire I/O device found for $name.";
  201. } else {
  202. $hash->{ASYNC} = $hash->{IODev}->{TYPE} eq "OWX_ASYNC" ? 1 : 0; #-- false for now
  203. }
  204. $modules{OWCOUNT}{defptr}{$id} = $hash;
  205. #--
  206. readingsSingleUpdate($hash,"state","defined",1);
  207. Log3 $name, 3, "OWCOUNT: Device $name defined.";
  208. $hash->{NOTIFYDEV} = "global";
  209. if ($init_done) {
  210. OWCOUNT_Init($hash);
  211. }
  212. return undef;
  213. }
  214. #######################################################################################
  215. #
  216. # OWCOUNT_Notify - Implements Notify function
  217. #
  218. # Parameter hash = hash of device addressed
  219. # dev = device
  220. #
  221. ########################################################################################
  222. sub OWCOUNT_Notify ($$) {
  223. my ($hash,$dev) = @_;
  224. if( grep(m/^(INITIALIZED|REREADCFG)$/, @{$dev->{CHANGED}}) ) {
  225. OWCOUNT_Init($hash);
  226. } elsif( grep(m/^SAVE$/, @{$dev->{CHANGED}}) ) {
  227. }
  228. }
  229. #######################################################################################
  230. #
  231. # OWCOUNT_Init - Implements Init function
  232. #
  233. # Parameter hash = hash of device addressed
  234. #
  235. ########################################################################################
  236. sub OWCOUNT_Init ($) {
  237. my ($hash)=@_;
  238. #-- Start timer for updates
  239. RemoveInternalTimer($hash);
  240. InternalTimer(gettimeofday()+10, "OWCOUNT_GetValues", $hash, 0);
  241. return undef;
  242. }
  243. ########################################################################################
  244. #
  245. # OWCOUNT_InitializeDevice - delayed setting of initial readings and channel names
  246. #
  247. # Parameter hash = hash of device addressed
  248. #
  249. ########################################################################################
  250. sub OWCOUNT_InitializeDevice($) {
  251. my ($hash) = @_;
  252. my $name = $hash->{NAME};
  253. #-- get memory page/counter according to interface type
  254. my $master= $hash->{IODev};
  255. my $interface= $hash->{IODev}->{TYPE};
  256. my $olddata = "";
  257. my ($olddata1,$olddata2);
  258. my $newdata = "OWCOUNT ".$owx_version;
  259. my $ret;
  260. #-- post-define: check model
  261. if( !defined($attr{$hash->{NAME}}{"model"}) ){
  262. CommandAttr (undef,$hash->{NAME}." model $owgmodel");
  263. }
  264. #-- initial values
  265. for( my $i=0;$i<int(@owg_fixed);$i++) {
  266. #-- initial readings
  267. $hash->{owg_val}->[$i] = "";
  268. $hash->{owg_midnight}->[$i] = "";
  269. $hash->{owg_str}->[$i] = "";
  270. }
  271. $hash->{DATA}{memory} = "";
  272. #-- Set state to initialized
  273. readingsSingleUpdate($hash,"state","initialized",1);
  274. return undef;
  275. }
  276. #######################################################################################
  277. #
  278. # OWCOUNT_Attr - Set one attribute value for device
  279. #
  280. # Parameter hash = hash of device addressed
  281. # a = argument array
  282. #
  283. #######################################################################################
  284. sub OWCOUNT_Attr(@) {
  285. my ($do,$name,$key,$value) = @_;
  286. my $hash = $defs{$name};
  287. my $ret;
  288. if ( $do eq "set") {
  289. ARGUMENT_HANDLER: {
  290. #-- interval modified at runtime
  291. $key eq "interval" and do {
  292. #-- check value
  293. return "OWCOUNT: set $name interval must be >= 0" if(int($value) < 0);
  294. #-- update timer
  295. $hash->{INTERVAL} = int($value);
  296. if ($init_done) {
  297. RemoveInternalTimer($hash);
  298. InternalTimer(gettimeofday()+$hash->{INTERVAL}, "OWCOUNT_GetValues", $hash, 0);
  299. }
  300. last;
  301. };
  302. $key eq "IODev" and do {
  303. AssignIoPort($hash,$value);
  304. if( defined($hash->{IODev}) ) {
  305. $hash->{ASYNC} = $hash->{IODev}->{TYPE} eq "OWX_ASYNC" ? 1 : 0;
  306. if ($init_done) {
  307. OWCOUNT_Init($hash);
  308. }
  309. }
  310. last;
  311. };
  312. }
  313. }
  314. return $ret;
  315. }
  316. ########################################################################################
  317. #
  318. # OWCOUNT_ChannelNames - find the real channel names
  319. #
  320. # Parameter hash = hash of device addressed
  321. #
  322. ########################################################################################
  323. sub OWCOUNT_ChannelNames($) {
  324. my ($hash) = @_;
  325. my $name = $hash->{NAME};
  326. my $state = $hash->{READINGS}{"state"}{VAL};
  327. my ($cname,@cnama,$unit,@unarr,$runit,$period);
  328. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  329. $gets{"memory"} = ($nomemory) ? ":noArg" : ":0,1,2,3,4,5,6,7,8,9,10,11,12,13";
  330. $gets{"mcache"} = $gets{"memory"};
  331. $gets{"midnight"}=":";
  332. for (my $i=0;$i<int(@owg_fixed);$i++){
  333. #-- name
  334. $cname = defined($attr{$name}{$owg_fixed[$i]."Name"}) ? $attr{$name}{$owg_fixed[$i]."Name"} : "$owg_fixed[$i]";
  335. @cnama = split(/\|/,$cname);
  336. if( int(@cnama)!=2){
  337. push(@cnama,$cnama[0]);
  338. }
  339. #-- unit
  340. $unit = defined($attr{$name}{$owg_fixed[$i]."Unit"}) ? $attr{$name}{$owg_fixed[$i]."Unit"} : "cts";
  341. if( $unit eq "none" ){
  342. $unit = "";
  343. }else{
  344. $unit = " ".$unit;
  345. }
  346. #-- put into readings
  347. $owg_channel[$i]=$cnama[0];
  348. $hash->{READINGS}{$owg_channel[$i]}{ABBR} = $cnama[1];
  349. $gets{"midnight"} .= $cnama[0];
  350. $gets{"midnight"} .= ","
  351. if ($i<(int(@owg_fixed)-1))
  352. ;
  353. $hash->{READINGS}{$owg_channel[$i]}{UNIT} = $unit;
  354. $period = defined($attr{$name}{$owg_fixed[$i]."Period"}) ? $attr{$name}{$owg_fixed[$i]."Period"} : "hour";
  355. #-- put into readings
  356. $hash->{READINGS}{$owg_channel[$i]}{PERIOD} = $period;
  357. #-- rate
  358. $cname = defined($attr{$name}{$owg_fixed[$i]."Rate"}) ? $attr{$name}{$owg_fixed[$i]."Rate"} :
  359. (defined($attr{$name}{$owg_fixed[$i]."Name"}) ? "$cnama[0]_rate|$cnama[1]_r" : "$owg_fixed[$i]_rate|$owg_fixed[$i]_r");
  360. @cnama = split(/\|/,$cname);
  361. if( int(@cnama)!=2){
  362. push(@cnama,$cnama[0]);
  363. }
  364. #-- rate unit
  365. if( $unit ne " " ){
  366. if( $period eq "hour" ){
  367. $unit .= "/h";
  368. }elsif( $period eq "minute" ){
  369. $unit .= "/min";
  370. } else {
  371. $unit .= "/s";
  372. }
  373. }
  374. #-- some special cases
  375. # Energy/Power
  376. $unit = " kW"
  377. if ($unit eq " kWh/h" );
  378. #-- put into readings
  379. $owg_rate[$i]=$cnama[0];
  380. $hash->{READINGS}{$owg_rate[$i]}{ABBR} = $cnama[1];
  381. $hash->{READINGS}{$owg_rate[$i]}{UNIT} = $unit;
  382. }
  383. $gets{"raw"} = $gets{"midnight"};
  384. }
  385. ########################################################################################
  386. #
  387. # OWCOUNT_FormatValues - put together various format strings and assemble STATE variable
  388. #
  389. # Parameter hash = hash of device addressed
  390. #
  391. ########################################################################################
  392. sub OWCOUNT_FormatValues($) {
  393. my ($hash) = @_;
  394. my $name = $hash->{NAME};
  395. my ($offset,$factor,$period,$unit,$runit,$vval,$vrate);
  396. my ($svalue,$dvalue,$mvalue) = ("","","");
  397. my $galarm = 0;
  398. my ($sec, $min, $hour, $day, $month, $year, $wday,$yday,$isdst) = localtime(time);
  399. my ($seco,$mino,$houro,$dayo,$montho,$yearo,$dayrest);
  400. my ($daily, $dt,$dval,$dval2,$deltim,$delt,$delf);
  401. my ($total,$total0,$total1,$total2,$total3,@monthv,@yearv);
  402. my $daybreak = 0;
  403. my $monthbreak = 0;
  404. #-- no change in any value if invalid reading
  405. for (my $i=0;$i<int(@owg_fixed);$i++){
  406. return if( $hash->{owg_val}->[$i] eq "");
  407. }
  408. #-- obtain channel names
  409. OWCOUNT_ChannelNames($hash);
  410. #-- Check, whether we have a new day at the next reading
  411. $deltim = $hour*60.0+$min+$sec/60.0 + $hash->{INTERVAL}/60.0 - 1440;
  412. #$deltim = $min+$sec/60.0 - 55;
  413. if( $deltim>=0 ){
  414. $daybreak = 1;
  415. $monthbreak = 0;
  416. #-- Timer data from tomorrow
  417. my ($secn,$minn,$hourn,$dayn,$monthn,$yearn,$wdayn,$ydayn,$isdstn) = localtime(time() + $hash->{INTERVAL} + 3600);
  418. #-- Check, whether we have a new month
  419. if( $dayn == 1 ){
  420. $monthbreak = 1;
  421. }
  422. }
  423. #-- put into READING
  424. readingsBeginUpdate($hash);
  425. #-- Check memory string only if model is defined automatically
  426. # TODO: REMOVE THIS TAKES TOO MUCH TIME IN FORMAT
  427. if( $owgauto ){
  428. my $msg = "OWCOUNT: In device $name, ";
  429. if( $owg_memory[2]==1 ){
  430. if( ($owg_memory[0]==1) && ($owg_memory[1]==1) ){
  431. Log 1, $msg."memory pages 0..13 and midnight store present, model should be DS2423"
  432. if( $attr{$name}{"model"} ne "DS2423");
  433. }elsif( ($owg_memory[0]==0) && ($owg_memory[1]==1) ){
  434. Log 1, $msg."midnight store only, model should be DS2423enew"
  435. if( $attr{$name}{"model"} ne "DS2423enew");
  436. }else{
  437. Log 1, $msg."no memory pages and no midnight store found, model should be DS2423eold"
  438. if( $attr{$name}{"model"} ne "DS2423eold");
  439. }
  440. $owg_memory[2]=0;
  441. }
  442. $owgauto=0;
  443. }
  444. #-- formats for output
  445. for (my $i=0;$i<int(@owg_fixed);$i++){
  446. #-- mode normal or daily
  447. $daily = 0;
  448. if( defined($attr{$name}{$owg_fixed[$i]."Mode"} )){
  449. if( $attr{$name}{$owg_fixed[$i]."Mode"} eq "daily"){
  450. $daily = 1;
  451. }
  452. }
  453. #-- offset and scale factor
  454. $offset = defined($attr{$name}{$owg_fixed[$i]."Offset"}) ? $attr{$name}{$owg_fixed[$i]."Offset"} : 0;
  455. $factor = defined($attr{$name}{$owg_fixed[$i]."Factor"}) ? $attr{$name}{$owg_fixed[$i]."Factor"} : 1;
  456. #-- put into READINGS
  457. $hash->{READINGS}{$owg_channel[$i]}{OFFSET} = $offset;
  458. $hash->{READINGS}{$owg_channel[$i]}{FACTOR} = $factor;
  459. $unit = $hash->{READINGS}{$owg_channel[$i]}{UNIT};
  460. $period = $hash->{READINGS}{$owg_channel[$i]}{PERIOD};
  461. $runit = $hash->{READINGS}{$owg_rate[$i]}{UNIT};
  462. #-- skip some things if undefined
  463. if( $hash->{owg_val}->[$i] eq ""){
  464. $svalue .= $owg_channel[$i]." ???";
  465. }else{
  466. #-- only if attribute value mode=daily, take the midnight value from memory
  467. if( $daily == 1){
  468. $vval = int( (($hash->{owg_val}->[$i] + $offset)*$factor - $hash->{owg_midnight}->[$i])*10000+0.5)/10000;
  469. } else {
  470. $vval = int( ($hash->{owg_val}->[$i] + $offset)*$factor*10000+0.5)/10000;
  471. }
  472. #-- rate calculation: get the old values
  473. my $oldval = $hash->{READINGS}{$owg_channel[$i]}{VAL};
  474. my $oldtim = $hash->{READINGS}{$owg_channel[$i]}{TIME};
  475. $oldtim = "" if(!defined($oldtim));
  476. #-- safeguard against the case where no previous measurement
  477. if( length($oldtim) > 0 ){
  478. #-- correct counter wraparound since last reading
  479. if( $vval < $oldval) {
  480. $oldval -= (65536*$factor);
  481. }
  482. #-- previous measurement time
  483. ($yearo,$montho,$dayrest) = split(/-/,$oldtim);
  484. $dayo = substr($dayrest,0,2);*60=
  485. ($houro,$mino,$seco) = split(/:/,substr($dayrest,3));
  486. #-- time difference to previous measurement and to midnight
  487. $delt = ($hour-$houro)*3600 + ($min-$mino)*60 + ($sec-$seco);
  488. $delf = $hour *3600 + $min *60 + $sec - 86400;
  489. #-- rate
  490. if( $delt > 0.0){
  491. $vrate = ($vval-$oldval)/$delt;
  492. } else {
  493. $vrate = 0.0;
  494. }
  495. #-- correct rate for period setting
  496. if( $period eq "hour" ){
  497. $vrate*=3600;
  498. }elsif( $period eq "minute" ){
  499. $vrate*=60;
  500. }
  501. $vrate = int($vrate * 10000+0.5)/10000;
  502. #--midnight extrapolation only possible if previous measurement
  503. if( $daybreak==1 ){
  504. #-- linear extrapolation
  505. if( $delt > 0.0 ){
  506. $dt = -$delf/$delt;
  507. $dval = int(($vval+($vval-$oldval)*$dt)*10000+0.5)/10000;
  508. Log3 $name,5,"OWCOUNT: midnight exploration $name channel ".$owg_channel[$i]." with time delta $delt, dt $dt and dval=$dval";
  509. }else{
  510. Log3 $name,5,"OWCOUNT: midnight exploration $name channel ".$owg_channel[$i]." fails because of zero time delta. dval=$dval";
  511. }
  512. if( $daily == 1 ){
  513. $dval2 = $dval+$hash->{owg_midnight}->[$i];
  514. } else {
  515. $dval2 = $dval;
  516. }
  517. #-- in any mode store the interpolated value in the midnight store
  518. my $msg = sprintf("%4d-%02d-%02d midnight %7.2f ",
  519. $year+1900,$month+1,$day,$dval2);
  520. Log3 $name,5,"OWCOUNT: measured $name value $vval (midnight ".$hash->{owg_midnight}->[$i].") => extrapolated midnight $dval2";
  521. OWCOUNT_SetPage($hash,14+$i,$msg);
  522. #-- string buildup for monthly and yearly logging
  523. $dvalue .= sprintf( " %s: %5.2f %s %sM: %%5.2f %s", $owg_channel[$i],$dval,$unit,$owg_channel[$i],$unit);
  524. $mvalue .= sprintf( " %sM: %%5.2f %s %sY: %%5.2f %s", $owg_channel[$i],$unit,$owg_channel[$i],$unit);
  525. } #-- end daybreak
  526. #-- string buildup for return value and STATE
  527. #-- 1 or 3 decimals
  528. my $fs = ( $factor == 1.0 )? "%s: %5.2f %s %s: %5.2f %s" : "%s: %5.3f %s %s: %5.3f %s";
  529. $svalue .= sprintf( $fs, $hash->{READINGS}{$owg_channel[$i]}{ABBR}, $vval,$unit,$hash->{READINGS}{$owg_rate[$i]}{ABBR},$vrate,$runit);
  530. #-- 3 decimals
  531. }
  532. readingsBulkUpdate($hash,$owg_channel[$i],$vval);
  533. readingsBulkUpdate($hash,$owg_rate[$i],$vrate);
  534. }
  535. #-- insert space
  536. if( $i<int(@owg_fixed)-1 ){
  537. $svalue .= " ";
  538. $dvalue .= " ";
  539. }
  540. }#-- end channel loop
  541. #-- daybreak postprocessing
  542. if( $daybreak == 1 ){
  543. #-- daily/monthly accumulated value
  544. @monthv = OWCOUNT_GetMonth($hash);
  545. @yearv = OWCOUNT_GetYear($hash);
  546. #-- put in monthly and yearly sums
  547. if( int(@monthv) == 2 ){
  548. $total0 = $monthv[0]->[1];
  549. $total1 = ($day==1)?$total0:$monthv[1]->[1];
  550. $dvalue = sprintf("D%02d ",$day).$dvalue;
  551. $dvalue = sprintf($dvalue,$total0,$total1);
  552. readingsBulkUpdate($hash,"day",$dvalue);
  553. }else{
  554. Log3 $name,5,"OWCOUNT: No monthly summary possible, ".$monthv[0]." for device $name";
  555. $total0 = 0;
  556. $total1 = 0;
  557. }
  558. if( int(@yearv) == 2 ){
  559. $total2 = $yearv[0]->[1];
  560. $total3 = ($month==0)?$total2: $yearv[1]->[1];
  561. if ( $monthbreak == 1){
  562. $mvalue = sprintf("M%02d ",$month+1).$mvalue;
  563. $mvalue = sprintf($mvalue,$total0,$total2,$total1,$total3);
  564. readingsBulkUpdate($hash,"month",$mvalue);
  565. }
  566. }else{
  567. Log3 $name,5,"OWCOUNT: No yearly summary possible, ".$yearv[0]." for device $name";
  568. $total2 = 0;
  569. $total3 = 0;
  570. }
  571. }
  572. #--- memory most recently read
  573. readingsBulkUpdate($hash,"memory",$hash->{DATA}{memory});
  574. #-- STATE
  575. readingsBulkUpdate($hash,"state",$svalue);
  576. readingsEndUpdate($hash,1);
  577. return $svalue;
  578. }
  579. ########################################################################################
  580. #
  581. # OWCOUNT_Get - Implements GetFn function
  582. #
  583. # Parameter hash = hash of device addressed, a = argument array
  584. #
  585. ########################################################################################
  586. sub OWCOUNT_Get($@) {
  587. my ($hash, @a) = @_;
  588. my $reading = $a[1];
  589. my $name = $hash->{NAME};
  590. my $model = $hash->{OW_MODEL};
  591. my $master = $hash->{IODev};
  592. my $value = undef;
  593. my $ret = "";
  594. my $page;
  595. my ($unit,$daily);
  596. my ($ret1,$ret2);
  597. #-- check syntax
  598. return "OWCOUNT: get $name argument is missing @a"
  599. if(int(@a) < 2);
  600. #-- check argument
  601. my $msg = "OWCOUNT: Get with unknown argument $a[1], choose one of ";
  602. $msg .= "$_$gets{$_} " foreach (keys%gets);
  603. return $msg
  604. if(!defined($gets{$a[1]}));
  605. #-- get id
  606. if($a[1] eq "id") {
  607. $value = $hash->{ROM_ID};
  608. return "$name.id => $value";
  609. }
  610. #-- get version
  611. if( $a[1] eq "version") {
  612. return "$name.version => $owx_version";
  613. }
  614. #-- get channel names
  615. OWCOUNT_ChannelNames($hash);
  616. #-- get month
  617. if($a[1] eq "month") {
  618. $value="$name.month =>\n";
  619. my @month2 = OWCOUNT_GetMonth($hash);
  620. #-- error case
  621. if( int(@month2) != 2 ){
  622. return $value." no monthly summary possible, ".$month2[0];
  623. }
  624. #-- 3 entries for each day
  625. for(my $i=0;$i<int(@month2);$i++){
  626. $unit = $hash->{READINGS}{$owg_channel[$i]}{UNITABBR};
  627. #-- mode = daily ?
  628. $daily = 0;
  629. if( defined($attr{$name}{$owg_fixed[$i]."Mode"} )){
  630. if( $attr{$name}{$owg_fixed[$i]."Mode"} eq "daily"){
  631. $daily = 1;
  632. }
  633. }
  634. if( $daily==1){
  635. $value .= $owg_channel[$i]."M: ".$month2[$i]->[1]." ".$unit.
  636. " (monthly sum until now, average ".$month2[$i]->[2]." ".$unit."/d)\n";
  637. }else{
  638. $value .= $owg_channel[$i]."M: ".$month2[$i]->[1]." ".$unit." (last midnight)\n";
  639. }
  640. }
  641. return $value;
  642. }
  643. #-- get year
  644. if($a[1] eq "year") {
  645. $value="$name.year =>\n";
  646. my @year2 = OWCOUNT_GetYear($hash);
  647. #-- error case
  648. if( int(@year2) != 2 ){
  649. return $value." no yearly summary possible, ".$year2[0];
  650. }
  651. #-- 3 entries for each month
  652. for(my $i=0;$i<int(@year2);$i++){
  653. $unit = $hash->{READINGS}{$owg_channel[$i]}{UNITABBR};
  654. #-- mode = daily ?
  655. $daily = 0;
  656. if( defined($attr{$name}{$owg_fixed[$i]."Mode"} )){
  657. if( $attr{$name}{$owg_fixed[$i]."Mode"} eq "daily"){
  658. $daily = 1;
  659. }
  660. }
  661. if( $daily==1){
  662. $value .= $owg_channel[$i]."Y: ".$year2[$i]->[1]." ".$unit.
  663. " (yearly sum until now, average ".$year2[$i]->[2]." ".$unit."/d)\n";
  664. }else{
  665. $value .= $owg_channel[$i]."Y: ".$year2[$i]->[1]." ".$unit."\n";
  666. }
  667. }
  668. return $value;
  669. }
  670. #-- get memory page/counter according to interface type
  671. my $interface= $hash->{IODev}->{TYPE};
  672. #-- check syntax for getting memory page 0..13 or midnight A/B
  673. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  674. if( ($reading eq "memory") || ($reading eq "mcache") ){
  675. return "OWCOUNT: Memory usage disabled in $name"
  676. if( $nomemory==1 );
  677. return "OWCOUNT: get $name memory/mcache: needs parameter <page>"
  678. if( int(@a)<2 );
  679. $page=int($a[2]);
  680. if( ($page<0) || ($page>13) ){
  681. return "OWCOUNT: get $name memory/mcache requested wrong page $page";
  682. }
  683. if( $reading eq "memory" ){
  684. $ret = OWCOUNT_GetPage($hash,$page,1,1);
  685. #-- process result
  686. if( $master->{ASYNCHRONOUS} ){
  687. #return "OWCOUNT: $name getting memory $page, please wait for completion";
  688. return undef;
  689. }else{
  690. #-- when we have a return code, we have an error
  691. if( $ret ){
  692. return "OWCOUNT: get $name failed, reason: ".$ret;
  693. }else{
  694. return "OWCOUNT: $name.$reading [$page] =>".$hash->{owg_str}->[$page];
  695. }
  696. }
  697. }else{
  698. return "OWCOUNT: $name.$reading [$page] =>".$hash->{owg_str}->[$page];
  699. }
  700. }
  701. #-- get midnight value
  702. if( $reading eq "midnight" ){
  703. return "OWCOUNT: get $name midnight needs parameter <channel>"
  704. if( int(@a)<3 );
  705. #-- find out which channel we have
  706. if( ($a[2] eq $owg_channel[0]) || ($a[2] eq "A") ){
  707. $page=14;
  708. }elsif( ($a[2] eq $owg_channel[1]) || ($a[2] eq "B") ){
  709. $page=15;
  710. } else {
  711. return "OWCOUNT: get $name midnight has invalid counter address, must be A, B or defined channel name"
  712. }
  713. $ret = OWCOUNT_GetPage($hash,$page,1,1);
  714. #-- process result
  715. if( $master->{ASYNCHRONOUS} ){
  716. return undef;
  717. }else{
  718. #-- when we have a return code, we have an error
  719. if( $ret ){
  720. return "OWCOUNT: get $name midnight failed, reason: ".$ret;
  721. }else{
  722. return "OWCOUNT: $name.$reading [$page] =>".$hash->{owg_midnight}->[$page-14];
  723. }
  724. }
  725. }
  726. #-- check syntax for getting counter
  727. if( $reading eq "raw" ){
  728. return "OWCOUNT: get $name raw needs parameter <channel>"
  729. if( int(@a)<2 );
  730. #-- find out which channel we have
  731. if( ($a[2] eq $owg_channel[0]) || ($a[2] eq "A") ){
  732. $page=14;
  733. }elsif( ($a[2] eq $owg_channel[1]) || ($a[2] eq "B") ){
  734. $page=15;
  735. } else {
  736. return "OWCOUNT: get $name raw has invalid counter address, must be A, B or defined channel name"
  737. }
  738. $ret = OWCOUNT_GetPage($hash,$page,1,1);
  739. #-- process result
  740. if( $master->{ASYNCHRONOUS} ){
  741. return undef;
  742. }else{
  743. #-- when we have a return code, we have an error
  744. if( $ret ){
  745. return "OWCOUNT: get $name raw failed, reason: ".$ret;
  746. }
  747. #-- only one counter will be returned
  748. return "OWCOUNT: $name.raw $a[2] => ".$hash->{owg_val}->[$page-14];
  749. }
  750. #-- check syntax for getting counters
  751. }elsif( $reading eq "counters" ){
  752. return "OWCOUNT: get $name counters needs no parameter"
  753. if( int(@a)==1 );
  754. $ret1 = OWCOUNT_GetPage($hash,14,0,1);
  755. $ret2 = OWCOUNT_GetPage($hash,15,1,1);
  756. #-- process result
  757. if( $master->{ASYNCHRONOUS} ){
  758. return undef;
  759. }else{
  760. $ret .= $ret1
  761. if( defined($ret1) );
  762. $ret .= $ret2
  763. if( defined($ret2) );
  764. if( defined($ret1) || defined($ret2) ){
  765. return "OWCOUNT: get $name counters failed, reason: ".$ret;
  766. }
  767. #-- both counters will be returned
  768. return "OWCOUNT: $name.counters => ".$hash->{READINGS}{"state"}{VAL};
  769. }
  770. }
  771. }
  772. #######################################################################################
  773. #
  774. # OWCOUNT_GetPage - Get a memory page
  775. #
  776. # Parameter hash = hash of device addressed
  777. # page = page addressed
  778. # final= 1 if FormatValues is to be called
  779. #
  780. ########################################################################################
  781. sub OWCOUNT_GetPage ($$$@) {
  782. my ($hash, $page,$final,$sync) = @_;
  783. #-- get memory page/counter according to interface type
  784. my $master= $hash->{IODev};
  785. my $interface= $hash->{IODev}->{TYPE};
  786. my $name = $hash->{NAME};
  787. my $ret;
  788. #-- check if memory usage has been disabled
  789. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  790. #-- even if memory usage has been disabled, we need to read the page because it contains the counter values
  791. if( ($nomemory==0) || ($nomemory==1 && (($page==14)||($page==15))) ){
  792. #-- OWX interface
  793. if( $interface eq "OWX" ){
  794. $ret = OWXCOUNT_GetPage($hash,$page,$final);
  795. }elsif( $interface eq "OWX_ASYNC" ){
  796. eval {
  797. if ($sync) {
  798. $ret = OWX_ASYNC_RunToCompletion($hash,OWXCOUNT_PT_GetPage($hash,$page,$final));
  799. } else {
  800. OWX_ASYNC_Schedule( $hash, OWXCOUNT_PT_GetPage($hash,$page,$final) );
  801. }
  802. };
  803. $ret = GP_Catch($@) if $@;
  804. #-- OWFS interface
  805. }elsif( $interface eq "OWServer" ){
  806. $ret = OWFSCOUNT_GetPage($hash,$page,$final);
  807. #-- Unknown interface
  808. }else{
  809. return "OWCOUNT: GetPage with wrong IODev type $interface";
  810. }
  811. #-- process results
  812. if( defined($ret) ){
  813. return "OWCOUNT: Could not get values from device $name, reason: ".$ret;
  814. }
  815. }
  816. return undef
  817. }
  818. ########################################################################################
  819. #
  820. # OWCOUNT_GetMonth Read monthly data from a file
  821. #
  822. # Parameter hash
  823. #
  824. # Returns total value up to last day, including this day and average including this day
  825. #
  826. ########################################################################################
  827. sub OWCOUNT_GetMonth($) {
  828. my ($hash) = @_;
  829. my $name = $hash->{NAME};
  830. my $regexp = ".*$name.*";
  831. my $val;
  832. my @month = ();
  833. my @month2 = ();
  834. my @mchannel;
  835. my @linarr;
  836. my $day;
  837. my $line;
  838. my ($total,$total2,$daily,$deltim,$av);
  839. #-- Check current logfile
  840. my $ln = $attr{$name}{"LogM"};
  841. if( !(defined($ln))){
  842. return "attribute LogM is missing";
  843. }
  844. #-- get channel names
  845. OWCOUNT_ChannelNames($hash);
  846. my $lf = $defs{$ln}{currentlogfile};
  847. if( !(defined($lf))){
  848. return "logfile of LogM is missing";
  849. }
  850. #-- current date
  851. my ($csec,$cmin,$chour,$cday,$cmonth,$cyear,$cwday,$cyday,$cisdst) = localtime(time);
  852. my $ret = open(OWXFILE, "< $lf" );
  853. if( $ret) {
  854. while( <OWXFILE> ){
  855. #-- line looks as
  856. # 2013-06-25_23:57:57 DG.CT1 day: D25 W: 42.2 kWh Wm: 84.4 kWh B: 2287295.7 cts Bm: 2270341.0 cts
  857. $line = $_;
  858. chomp($line);
  859. if ( $line =~ m/$regexp/i){
  860. @linarr = split(' ',$line);
  861. if( int(@linarr)==4+6*int(@owg_fixed) ){
  862. $day = $linarr[3];
  863. $day =~ s/D_+0+//;
  864. @mchannel = ();
  865. for (my $i=0;$i<int(@owg_fixed);$i++){
  866. $val = $linarr[5+6*$i];
  867. push(@mchannel,$val);
  868. }
  869. push(@month,[@mchannel]);
  870. }
  871. }
  872. }
  873. if( int(@month)<($cday-1) ){
  874. Log3 $name,3, "OWCOUNT: warning, found only ".int(@month)." lines in logfile $lf of LogM";
  875. }
  876. } else {
  877. return "cannot open logfile of LogM";
  878. }
  879. #-- sum and average
  880. for (my $i=0;$i<int(@owg_fixed);$i++){
  881. $total = 0.0;
  882. #-- summing only if mode daily (means daily reset !)
  883. $daily = 0;
  884. if( defined($attr{$name}{$owg_fixed[$i]."Mode"} )){
  885. if( $attr{$name}{$owg_fixed[$i]."Mode"} eq "daily"){
  886. $daily = 1;
  887. }
  888. }
  889. if( $daily==1){
  890. for (my $j=0;$j<int(@month);$j++){
  891. $total += $month[$j][$i];
  892. }
  893. }
  894. #-- add data from current day also for non-summed mode
  895. $total = int($total*100)/100;
  896. $total2 = int(100*($total+$hash->{READINGS}{$owg_channel[$i]}{VAL}))/100;
  897. #-- number of days so far, including the present day
  898. my $deltim = int(@month)+($chour+$cmin/60.0 + $csec/3600.0)/24.0;
  899. my $av = $deltim>0 ? int(100*$total2/$deltim)/100 : -1;
  900. #-- output format
  901. push(@month2,[($total,$total2,$av)]);
  902. }
  903. return @month2;
  904. }
  905. ########################################################################################
  906. #
  907. # OWCOUNT_GetYear Read yearly data from a file
  908. #
  909. # Parameter hash
  910. #
  911. # Returns total value up to last month including this month and average including this day
  912. #
  913. ########################################################################################
  914. sub OWCOUNT_GetYear($) {
  915. my ($hash) = @_;
  916. my $name = $hash->{NAME};
  917. my $regexp = ".*$name.*";
  918. my $val;
  919. my @year = ();
  920. my @year2 = ();
  921. my @mchannel;
  922. my @linarr;
  923. my $month;
  924. my $line;
  925. my ($total,$total2,$daily,$deltim,$av);
  926. #-- Check current logfile
  927. my $ln = $attr{$name}{"LogY"};
  928. if( !(defined($ln))){
  929. return "attribute LogY is missing";
  930. }
  931. #-- get channel names
  932. OWCOUNT_ChannelNames($hash);
  933. #-- current date
  934. my ($csec,$cmin,$chour,$cday,$cmonth,$cyear,$cwday,$cyday,$cisdst) = localtime(time);
  935. my $lf = $defs{$ln}{currentlogfile};
  936. if( !(defined($lf))){
  937. return "logfile of LogY is missing";
  938. }
  939. my $ret = open(OWXFILE, "< $lf" );
  940. if( $ret) {
  941. while( <OWXFILE> ){
  942. #-- line looks as
  943. # 2013-05-31_23:57:57 DG.CT1 month: M05 W: 42.2 kWh Wy: 84.4 kWh B: 2287295.7 cts By: 2270341.0 cts
  944. $line = $_;
  945. chomp($line);
  946. if ( $line =~ m/$regexp/i){
  947. @linarr = split(' ',$line);
  948. if( int(@linarr)==4+6*int(@owg_fixed) ){
  949. $month = $linarr[3];
  950. $month =~ s/M_+0+//;
  951. @mchannel = ();
  952. for (my $i=0;$i<int(@owg_fixed);$i++){
  953. $val = $linarr[5+6*$i];
  954. push(@mchannel,$val);
  955. }
  956. push(@year,[@mchannel]);
  957. }
  958. }
  959. }
  960. if( int(@year)<($cmonth-1) ){
  961. Log3 $name,3, "OWCOUNT: warning, found only ".int(@year)." lines in logfile $lf of LogY";
  962. }
  963. } else {
  964. return "cannot open logfile of LogY";
  965. }
  966. #-- sum and average
  967. my @month2 = OWCOUNT_GetMonth($hash);
  968. for (my $i=0;$i<int(@owg_fixed);$i++){
  969. $total = 0.0;
  970. $daily = 0;
  971. if( defined($attr{$name}{$owg_fixed[$i]."Mode"} )){
  972. if( $attr{$name}{$owg_fixed[$i]."Mode"} eq "daily"){
  973. $daily = 1;
  974. }
  975. }
  976. #-- sum previous months only in daily mode
  977. if( $daily==1){
  978. for (my $j=0;$j<int(@year);$j++){
  979. $total += $year[$j][$i];
  980. }
  981. }else{
  982. $total = $year[int(@year)-1][$i]
  983. if (int(@year)>0);
  984. };
  985. $total = int($total*100)/100;
  986. #-- data from this month is
  987. $total2 = int(100*($month2[$i]->[1]))/100;
  988. #-- add data from this month and previous months in daily mode
  989. $total2+=$total
  990. if( $daily==1 );
  991. #-- number of days so far, including the present day
  992. my $deltim = $cyday+($chour+$cmin/60.0 + $csec/3600.0)/24.0;
  993. my $av = $deltim>0 ? int(100*$total2/$deltim)/100 : -1;
  994. #-- output format
  995. push(@year2,[($total,$total2,$av)]);
  996. }
  997. return @year2;
  998. }
  999. #######################################################################################
  1000. #
  1001. # OWCOUNT_GetValues - Updates the reading from one device
  1002. #
  1003. # Parameter hash = hash of device addressed
  1004. #
  1005. ########################################################################################
  1006. sub OWCOUNT_GetValues($) {
  1007. my $hash = shift;
  1008. my $name = $hash->{NAME};
  1009. my $model = $hash->{OW_MODEL};
  1010. my $value = "";
  1011. my $ret = "";
  1012. my ($ret1,$ret2);
  1013. #-- check if device needs to be initialized
  1014. OWCOUNT_InitializeDevice($hash)
  1015. if( $hash->{READINGS}{"state"}{VAL} eq "defined");
  1016. RemoveInternalTimer($hash);
  1017. #-- auto-update for device disabled;
  1018. return undef
  1019. if( $hash->{INTERVAL} == 0 );
  1020. #-- restart timer for updates
  1021. InternalTimer(time()+$hash->{INTERVAL}, "OWCOUNT_GetValues", $hash, 0);
  1022. #-- Get readings
  1023. $ret1 = OWCOUNT_GetPage($hash,14,0);
  1024. $ret2 = OWCOUNT_GetPage($hash,15,1);
  1025. #-- process results
  1026. $ret .= $ret1
  1027. if( defined($ret1) );
  1028. $ret .= $ret2
  1029. if( defined($ret2) );
  1030. if( $ret ne "" ){
  1031. return "OWCOUNT: Could not get values from device $name, reason: ".$ret;
  1032. }
  1033. return undef;
  1034. }
  1035. #######################################################################################
  1036. #
  1037. # OWCOUNT_ParseMidnight - Read the stored midnight value
  1038. #
  1039. # Parameter hash = hash of device addressed
  1040. # strval = data string
  1041. # page = page number
  1042. #
  1043. ########################################################################################
  1044. sub OWCOUNT_ParseMidnight($$$) {
  1045. my ($hash,$strval,$page) = @_;
  1046. my $name = $hash->{NAME};
  1047. #-- midnight value
  1048. #-- new format
  1049. if ( defined $strval and $strval =~ /^\d\d\d\d-\d\d-\d\d.*/ ) {
  1050. my @data=split(' ',$strval);
  1051. $strval = $data[2];
  1052. }
  1053. if ( defined $strval ) {
  1054. #-- parse float from midnight
  1055. $strval =~ s/[^-\d\.]+//g;
  1056. $strval = 0.0 if($strval !~ /^-?\d+\.\d*$/);
  1057. $strval = int($strval*100)/100;
  1058. } else {
  1059. $strval = 0.0;
  1060. }
  1061. $hash->{owg_midnight}->[$page-14] = $strval;
  1062. }
  1063. #######################################################################################
  1064. #
  1065. # OWCOUNT_Set - Set one value for device
  1066. #
  1067. # Parameter hash = hash of device addressed
  1068. # a = argument array
  1069. #
  1070. ########################################################################################
  1071. sub OWCOUNT_Set($@) {
  1072. my ($hash, @a) = @_;
  1073. my $name = $hash->{NAME};
  1074. my $model = $hash->{OW_MODEL};
  1075. my $ret = undef;
  1076. my $page;
  1077. my $data;
  1078. my $key = $a[1];
  1079. my $value = $a[2];
  1080. my ($cname,@cnama,@channel);
  1081. #-- for the selector: which values are possible
  1082. if (@a == 2){
  1083. my $newkeys = join(" ", keys %sets);
  1084. return $newkeys ;
  1085. }
  1086. #-- check syntax
  1087. return "OWCOUNT: set $name needs at least one parameter"
  1088. if( int(@a)<3 );
  1089. #-- check argument
  1090. if( !defined($sets{$a[1]}) ){
  1091. return "OWCOUNT: set $name with unknown argument $a[1]";
  1092. }
  1093. #-- set new timer interval
  1094. if($key eq "interval") {
  1095. # check value
  1096. return "OWCOUNT: set $name interval must be >= 0"
  1097. if(int($value) < 0);
  1098. # update timer
  1099. $hash->{INTERVAL} = int($value);
  1100. RemoveInternalTimer($hash);
  1101. InternalTimer(gettimeofday()+$hash->{INTERVAL}, "OWCOUNT_GetValues", $hash, 0);
  1102. return undef;
  1103. }
  1104. #-- get channel names
  1105. OWCOUNT_ChannelNames($hash);
  1106. #-- set memory page/counter according to interface type
  1107. my $interface= $hash->{IODev}->{TYPE};
  1108. #-- check syntax for setting memory page 0..13
  1109. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  1110. if( $key eq "memory" ){
  1111. return "OWCOUNT: set $name memory usage disabled"
  1112. if( $nomemory==1 );
  1113. return "OWCOUNT: set $name memory needs parameter <page>"
  1114. if( int(@a)<2 );
  1115. $page=int($a[2]);
  1116. if( ($page<0) || ($page>13) ){
  1117. return "OWXCOUNT: set $name memory with wrong page $page attempted";
  1118. }
  1119. $data=$a[3];
  1120. for( my $i=4;$i<int(@a);$i++){
  1121. $data.=" ".$a[$i];
  1122. }
  1123. $ret = OWCOUNT_SetPage($hash,$page,$data);
  1124. }
  1125. #-- other commands are per channel
  1126. if( ($key eq "midnight") || ($key eq "counter" )){
  1127. return "OWCOUNT: set $name $key needs parameter: <channel>"
  1128. if( int(@a)<2 );
  1129. #-- find out which channel we have
  1130. if( ($a[2] eq $owg_channel[0]) || ($a[2] eq "A") ){
  1131. $page=14;
  1132. }elsif( ($a[2] eq $owg_channel[1]) || ($a[2] eq "B") ){
  1133. $page=15;
  1134. } else {
  1135. return "OWCOUNT: set $name $key has invalid counter address, must be A, B or defined channel name"
  1136. }
  1137. #-- mode normal or daily
  1138. my $daily = 0;
  1139. if( defined($attr{$name}{$owg_fixed[$page-14]."Mode"} )){
  1140. if( $attr{$name}{$owg_fixed[$page-14]."Mode"} eq "daily"){
  1141. $daily = 1;
  1142. }
  1143. }
  1144. return "OWCOUNT: set $name $key for channel $a[2] not possible, is not in daily mode"
  1145. if( $daily==0 );
  1146. my ($sec, $min, $hour, $day, $month, $year, $wday,$yday,$isdst) = localtime(time);
  1147. if( $key eq "midnight" ){
  1148. $data = sprintf("%4d-%02d-%02d midnight %7.2f ",
  1149. $year+1900,$month+1,$day,$a[3]);
  1150. $ret = OWCOUNT_SetPage($hash,$page,$data);
  1151. }
  1152. #--
  1153. if( $key eq "counter" ){
  1154. my $midnew=($hash->{owg_val}->[$page-14] + $hash->{READINGS}{$owg_channel[$page-14]}{OFFSET})*
  1155. $hash->{READINGS}{$owg_channel[$page-14]}{FACTOR} - $a[3];
  1156. $data = sprintf("%4d-%02d-%02d midnight %7.2f ",
  1157. $year+1900,$month+1,$day,$midnew);
  1158. Log3 $name,1,"OWCOUNT: old midnight value for device $name ".$hash->{owg_midnight}->[$page-14].", replaced by $midnew";
  1159. $ret = OWCOUNT_SetPage($hash,$page,$data);
  1160. }
  1161. }
  1162. #-- process results - we have to reread the device
  1163. if( defined($ret) && ($ret ne "") ){
  1164. return "OWCOUNT: set $name $key failed, reason: ".$ret;
  1165. }
  1166. #-- Took this out, not possible in asynchronoues mode
  1167. #OWCOUNT_GetValues($hash);
  1168. Log3 $name,5, "OWCOUNT: set $name $key $value";
  1169. }
  1170. #######################################################################################
  1171. #
  1172. # OWCOUNT_SetPage - Set one value for device
  1173. #
  1174. # Parameter hash = hash of device addressed
  1175. # page = page addressed
  1176. # data = data
  1177. #
  1178. ########################################################################################
  1179. sub OWCOUNT_SetPage ($$$) {
  1180. my ($hash, $page, $data) = @_;
  1181. #-- set memory page/counter according to interface type
  1182. my $interface= $hash->{IODev}->{TYPE};
  1183. my $name = $hash->{NAME};
  1184. my $ret;
  1185. #-- check if memory usage has been disabled
  1186. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  1187. $data=sprintf("%-32s",$data);
  1188. if( $nomemory==0 ){
  1189. #-- OWX interface
  1190. if( $interface eq "OWX" ){
  1191. $ret = OWXCOUNT_SetPage($hash,$page,$data);
  1192. }elsif( $interface eq "OWX_ASYNC" ){
  1193. eval {
  1194. OWX_ASYNC_Schedule( $hash, OWXCOUNT_PT_SetPage($hash,$page,$data) );
  1195. };
  1196. $ret = GP_Catch($@) if $@;
  1197. #-- OWFS interface
  1198. }elsif( $interface eq "OWServer" ){
  1199. $ret = OWFSCOUNT_SetPage($hash,$page,$data);
  1200. #-- Unknown interface
  1201. }else{
  1202. return "OWCOUNT: SetPage $name with wrong IODev type $interface";
  1203. }
  1204. #-- process results
  1205. if( defined($ret) && ($ret ne "") ){
  1206. return "OWCOUNT: SetPage $name failed, reason: ".$ret;
  1207. }
  1208. }else{
  1209. if( $page==14 ){
  1210. return OWCOUNT_store($hash,"OWCOUNT_".$name."_14.dat",$data);
  1211. }elsif( $page==15 ){
  1212. return OWCOUNT_store($hash,"OWCOUNT_".$name."_15.dat",$data);
  1213. } else {
  1214. return "OWCOUNT: file store with wrong page number";
  1215. }
  1216. }
  1217. }
  1218. ########################################################################################
  1219. #
  1220. # Store daily start value in a file
  1221. #
  1222. # Parameter hash, filename
  1223. #
  1224. ########################################################################################
  1225. sub OWCOUNT_store($$$) {
  1226. my ($hash,$filename,$data) = @_;
  1227. my $name = $hash->{NAME};
  1228. my $mp = AttrVal("global", "modpath", ".");
  1229. my $ret = open(OWXFILE, "> $mp/FHEM/$filename" );
  1230. if( $ret) {
  1231. print OWXFILE $data;
  1232. Log3 $name,1, "OWCOUNT_store: $name $data";
  1233. close(OWXFILE);
  1234. return undef;
  1235. } else {
  1236. Log3 $name,1,"OWCOUNT_store: Cannot open $filename for writing!";
  1237. return $ret;
  1238. }
  1239. }
  1240. ########################################################################################
  1241. #
  1242. # OWCOUNT_recall Recall daily start value from a file
  1243. #
  1244. # Parameter hash,filename
  1245. #
  1246. ########################################################################################
  1247. sub OWCOUNT_recall($$) {
  1248. my ($hash,$filename) = @_;
  1249. my $name= $hash->{NAME};
  1250. my $mp = AttrVal("global", "modpath", ".");
  1251. my $ret = open(OWXFILE, "< $mp/FHEM/$filename" );
  1252. if( $ret ){
  1253. my $line = readline OWXFILE;
  1254. close(OWXFILE);
  1255. return $line;
  1256. }
  1257. Log3 $name,1, "OWCOUNT_recall: Cannot open $filename for reading, 2nd attempt";
  1258. $ret = OWCOUNT_store($hash,$filename,0);
  1259. if (!$ret){
  1260. $ret = open(OWXFILE, "< $mp/FHEM/$filename" );
  1261. if( $ret ){
  1262. my $line = readline OWXFILE;
  1263. close(OWXFILE);
  1264. return $line;
  1265. }
  1266. Log3 $name,1, "OWCOUNT_recall: Cannot open $filename for reading - tried twice";
  1267. return "error";
  1268. }
  1269. }
  1270. ########################################################################################
  1271. #
  1272. # OWCOUNT_Undef - Implements UndefFn function
  1273. #
  1274. # Parameter hash = hash of device addressed
  1275. #
  1276. ########################################################################################
  1277. sub OWCOUNT_Undef ($) {
  1278. my ($hash) = @_;
  1279. delete($modules{OWCOUNT}{defptr}{$hash->{OW_ID}});
  1280. RemoveInternalTimer($hash);
  1281. return undef;
  1282. }
  1283. ########################################################################################
  1284. #
  1285. # The following subroutines in alphabetical order are only for a 1-Wire bus connected
  1286. # via OWFS
  1287. #
  1288. # TODO: So far no automatic recognition of DS2423 / Emulator
  1289. #
  1290. # Prefix = OWFSCOUNT
  1291. #
  1292. ########################################################################################
  1293. #
  1294. # OWFSCOUNT_GetPage - Get page from device
  1295. #
  1296. # Parameter hash = hash of device addressed
  1297. # page = page to be read
  1298. # final= 1 if FormatValues is to be called
  1299. #
  1300. ########################################################################################
  1301. sub OWFSCOUNT_GetPage($$$) {
  1302. my ($hash,$page,$final) = @_;
  1303. #-- ID of the device
  1304. my $owx_add = substr($hash->{ROM_ID},0,15);
  1305. #-- hash of the busmaster
  1306. my $master = $hash->{IODev};
  1307. my $name = $hash->{NAME};
  1308. #-- reset presence
  1309. $hash->{PRESENT} = 0;
  1310. my $vval;
  1311. my $strval;
  1312. #=============== wrong value requested ===============================
  1313. if( ($page<0) || ($page>15) ){
  1314. return "wrong memory page requested";
  1315. }
  1316. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  1317. #-- get values - or shoud we rather get the uncached ones ?
  1318. if( $page == 14 || $page == 15 ) {
  1319. $vval = OWServer_Read($master,"/$owx_add/counters.$owg_fixed[$page-14]");
  1320. return "no return from OWServer for counter.$owg_fixed[$page-14]" unless defined $vval;
  1321. return "empty return from OWServer for counter.$owg_fixed[$page-14]" if($vval eq "");
  1322. if ($nomemory == 0) {
  1323. $strval = OWServer_Read($master,"/$owx_add/pages/page.$page");
  1324. return "no return from OWServer for page.$page" unless defined $strval;
  1325. return "empty return from OWServer for page.$page" if($strval eq "");
  1326. } else {
  1327. $strval = OWCOUNT_recall($hash,"OWCOUNT_".$hash->{NAME}."_".$page.".dat");
  1328. }
  1329. $hash->{owg_val}->[$page-14] = $vval;
  1330. $hash->{owg_str}->[$page] = defined $strval ? $strval : "";
  1331. #-- midnight value
  1332. OWCOUNT_ParseMidnight($hash,$strval,$page);
  1333. }else {
  1334. $strval = OWServer_Read($master,"/$owx_add/pages/page.".$page);
  1335. return "no return from OWServer"
  1336. if( !defined($strval) );
  1337. return "empty return from OWServer"
  1338. if( $strval eq "" );
  1339. $hash->{owg_str}->[$page] = $strval;
  1340. }
  1341. #-- and now from raw to formatted values
  1342. $hash->{PRESENT} = 1;
  1343. if($final==1){
  1344. my $value = OWCOUNT_FormatValues($hash);
  1345. Log3 $name,5, $value;
  1346. }
  1347. return undef;
  1348. }
  1349. ########################################################################################
  1350. #
  1351. # OWFSCOUNT_SetPage - Set page in device
  1352. #
  1353. # Parameter hash = hash of device addressed
  1354. #
  1355. ########################################################################################
  1356. sub OWFSCOUNT_SetPage($$$) {
  1357. my ($hash,$page,$data) = @_;
  1358. #-- ID of the device
  1359. my $owx_add = substr($hash->{ROM_ID},0,15);
  1360. #-- hash of the busmaster
  1361. my $master = $hash->{IODev};
  1362. my $name = $hash->{NAME};
  1363. #=============== wrong page requested ===============================
  1364. if( ($page<0) || ($page>15) ){
  1365. return "wrong memory page write attempt";
  1366. }
  1367. #=============== midnight value =====================================
  1368. if( ($page==14) || ($page==15) ){
  1369. OWCOUNT_ParseMidnight($hash,$data,$page);
  1370. }
  1371. OWServer_Write($master, "/$owx_add/pages/page.".$page,$data );
  1372. return undef
  1373. }
  1374. ########################################################################################
  1375. #
  1376. # The following subroutines in alphabetical order are only for a 1-Wire bus connected
  1377. # directly to the FHEM server
  1378. #
  1379. # Prefix = OWXCOUNT
  1380. #
  1381. ########################################################################################
  1382. #
  1383. # OWXCOUNT_BinValues - Process reading from one device - translate binary into raw
  1384. #
  1385. # Parameter hash = hash of device addressed
  1386. # context = mode for evaluating the binary data
  1387. # proc = processing instruction, also passed to OWX_Read.
  1388. # bitwise interpretation !!
  1389. # if 0, nothing special
  1390. # if 1 = bit 0, a reset will be performed not only before, but also after
  1391. # the last operation in OWX_Read
  1392. # if 2 = bit 1, the initial reset of the bus will be suppressed
  1393. # if 8 = bit 3, the fillup of the data with 0xff will be suppressed
  1394. # if 16= bit 4, the insertion will be at the top of the queue
  1395. # owx_dev = ROM ID of slave device
  1396. # crcpart = part of the data that needs to be part of the CRC check
  1397. # numread = number of bytes to receive
  1398. # res = result string
  1399. #
  1400. #
  1401. #######################################################################################
  1402. sub OWXCOUNT_BinValues($$$$$$$) {
  1403. my ($hash, $context, $proc, $owx_dev, $crcpart, $numread, $res) = @_;
  1404. #-- hash of the busmaster
  1405. my $master = $hash->{IODev};
  1406. my $name = $hash->{NAME};
  1407. my $error = 0;
  1408. my @data = [];
  1409. my $value;
  1410. my $msg;
  1411. OWX_WDBGL($name,4,"OWXCOUNT_BinValues called for device $name in context $context with data ",$res);
  1412. return undef unless (defined $context and $context =~ /^(get|set|check)page\.([\d]+)(\.final|)$/);
  1413. my $cmd = $1;
  1414. my $page = $2;
  1415. my $final = $3;
  1416. #=============== get memory + counter ===============================
  1417. if ($cmd eq "get") {
  1418. my (@data,$strval,$value);
  1419. my $change = 0;
  1420. #-- we have to get rid of the first 12 bytes
  1421. if( length($res) == 54 ){
  1422. $res=substr($res,12);
  1423. }
  1424. @data=split(//,$res);
  1425. $crcpart = $crcpart.substr($res,0,40);
  1426. #-- process results
  1427. if( int(@data) != 42){
  1428. $error = 1;
  1429. $msg = "$name: invalid data length, ".int(@data)." instead of 42 bytes ";
  1430. }elsif (OWX_CRC16($crcpart,$data[40],$data[41]) == 0){
  1431. $error = 1;
  1432. $msg = "$name: invalid CRC, ".ord($data[40])." ".ord($data[41])." ";
  1433. }else{
  1434. $msg = "$name: no error ";
  1435. }
  1436. OWX_WDBGL($name,5-$error*4,"OWXCOUNT_BinValues getpage: ".$msg,$res);
  1437. #--
  1438. my $nomemory = defined($attr{$name}{"nomemory"}) ? $attr{$name}{"nomemory"} : 0;
  1439. if( $nomemory==0 ){
  1440. #-- memory part, treated as string
  1441. $strval=substr($res,0,32);
  1442. } else {
  1443. $strval = OWCOUNT_recall($hash,"OWCOUNT_".$hash->{NAME}."_".$page.".dat");
  1444. }
  1445. $hash->{owg_str}->[$page] = defined $strval ? $strval : "";
  1446. $hash->{DATA}{memory} = defined $strval ? $strval : "";
  1447. #-- counter part
  1448. if( ($page == 14) || ($page == 15) ){
  1449. @data=split(//,substr($res,32));
  1450. #-- does not work with old emulator devices
  1451. #if ( ($data[4] | $data[5] | $data[6] | $data[7]) ne "\x00" ){
  1452. # $error = 1;
  1453. # my $msg = "$name: invalid data in counter page ".ord($data[4])." ".ord($data[5])." ".ord($data[6])." ".ord($data[7]);
  1454. # OWX_WDBGL($name,1,"OWXCOUNT_BinValues getpage counter: ".$msg,"")
  1455. #}
  1456. if( !$error ){
  1457. #-- counter value
  1458. $value = (ord($data[3])<<24) + (ord($data[2])<<16) +(ord($data[1])<<8) + ord($data[0]);
  1459. $hash->{owg_val}->[$page-14] = $value;
  1460. #-- midnight value
  1461. OWCOUNT_ParseMidnight($hash,$strval,$page);
  1462. }
  1463. }
  1464. if( $error ){
  1465. $hash->{ERRCOUNT}=$hash->{ERRCOUNT}+1;
  1466. }else{
  1467. $hash->{PRESENT} = 1;
  1468. #-- and now from raw to formatted values
  1469. OWCOUNT_FormatValues($hash)
  1470. if( $final );
  1471. }
  1472. #=============== set memory ===============================
  1473. #-- for setting a page we need a second step where the scratchpad is copied into memory
  1474. }elsif (($cmd eq "set") && !$final ) {
  1475. if( length($res) != 45){
  1476. $error = 1;
  1477. $msg = "$name: invalid data length, ".length($res)." instead of 45 bytes ";
  1478. }else{
  1479. $msg = "$name: no error ";
  1480. }
  1481. OWX_WDBGL($name,5-$error*4,"OWXCOUNT_BinValues: setpage ".$msg,$res);
  1482. #-- process results
  1483. my $select="\x5A".substr($res,10,3);
  1484. #### master slave context proc owx_dev data crcpart numread startread callback delay
  1485. # 16 inserts at top of queue
  1486. OWX_Qomplex($master, $hash, "setpage.$page.final", 16, $owx_dev, $select, 0, 16, 0, \&OWXCOUNT_BinValues, undef);
  1487. #-- and a third step where this is finalized
  1488. }elsif (($cmd eq "set") && $final ) {
  1489. #-- we have to get rid of the first 10 bytes
  1490. if( length($res) == 16 ){
  1491. $res=substr($res,10);
  1492. }
  1493. #-- process results
  1494. if( substr($res,4,1) ne "\xAA"){
  1495. $error = 1;
  1496. $msg = "$name: copy scratchpad to memory not successful ";
  1497. }else{
  1498. $msg = "$name: no error ";
  1499. }
  1500. OWX_WDBGL($name,5-$error*4,"OWXCOUNT_BinValues: setpage.$page.final ".$msg,$res);
  1501. }
  1502. return undef;
  1503. }
  1504. ########################################################################################
  1505. #
  1506. # OWXCOUNT_GetPage - Get one memory page + counter from device
  1507. #
  1508. # Parameter hash = hash of device addressed
  1509. # page = 0..15
  1510. # final= 1 if FormatValues is to be called
  1511. #
  1512. ########################################################################################
  1513. sub OWXCOUNT_GetPage($$$) {
  1514. my ($hash,$page,$final) = @_;
  1515. my ($select, $res, $res2, $res3, @data);
  1516. #-- ID of the device, hash of the busmaster
  1517. my $owx_dev = $hash->{ROM_ID};
  1518. my $master = $hash->{IODev};
  1519. #-- reset presence
  1520. $hash->{PRESENT} = 0;
  1521. #=============== wrong value requested ===============================
  1522. if( ($page<0) || ($page>15) ){
  1523. return "wrong memory page requested from $owx_dev";
  1524. }
  1525. #=============== get memory + counter ===============================
  1526. #-- issue the match ROM command \x55 and the read memory + counter command
  1527. # \xA5 TA1 TA2 reading 40 data bytes and 2 CRC bytes
  1528. my $ta2 = ($page*32) >> 8;
  1529. my $ta1 = ($page*32) & 255;
  1530. $select=sprintf("\xA5%c%c",$ta1,$ta2);
  1531. my $context = "getpage.".$page.($final ? ".final" : "");
  1532. #-- OLD OWX interface
  1533. if( !$master->{ASYNCHRONOUS} ){
  1534. #-- reset the bus
  1535. OWX_Reset($master);
  1536. #-- reading 9 + 3 + 40 data bytes (32 byte memory, 4 byte counter + 4 byte zeroes) and 2 CRC bytes = 54 bytes
  1537. $res=OWX_Complex($master,$owx_dev,$select,42);
  1538. if( $res eq 0 ){
  1539. return "$owx_dev not accessible in reading page $page";
  1540. }
  1541. #-- process results
  1542. if( length($res) < 54 ) {
  1543. #-- read the data in a second step
  1544. $res.=OWX_Complex($master,"","",0);
  1545. #-- process results
  1546. if( length($res) < 54 ) {
  1547. #-- read the data in a third step
  1548. $res.=OWX_Complex($master,"","",0);
  1549. }
  1550. }
  1551. #-- reset the bus (needed to stop receiving data ?)
  1552. OWX_Reset($master);
  1553. #-- for processing we need 45 bytes
  1554. return "$owx_dev not accessible in reading"
  1555. if( $res eq 0 );
  1556. return "$owx_dev has returned invalid data of length ".length($res)
  1557. if( length($res)!=54);
  1558. return OWXCOUNT_BinValues($hash,$context,0,$owx_dev,$select,44,substr($res,12));
  1559. #-- NEW OWX interface
  1560. }else{
  1561. #### master slave context proc owx_dev data crcpart numread startread callback delay
  1562. # 1 additional reset after last action
  1563. OWX_Qomplex($master, $hash, $context, 0, $owx_dev, $select, $select, 54, 0, \&OWXCOUNT_BinValues, undef);
  1564. return undef;
  1565. }
  1566. }
  1567. ########################################################################################
  1568. #
  1569. # OWXCOUNT_SetPage - Set one memory page of device
  1570. #
  1571. # Parameter hash = hash of device addressed
  1572. # page = 0..15
  1573. # data = string to set into memory
  1574. #
  1575. ########################################################################################
  1576. sub OWXCOUNT_SetPage($$$) {
  1577. my ($hash,$page,$data) = @_;
  1578. my ($select, $res, $res2, $res3);
  1579. #-- ID of the device, hash of the busmaster
  1580. my $owx_dev = $hash->{ROM_ID};
  1581. my $master = $hash->{IODev};
  1582. #=============== wrong page requested ===============================
  1583. if( ($page<0) || ($page>15) ){
  1584. return "OWCOUNT: device $owx_dev wrong memory page write attempt";
  1585. }
  1586. #=============== midnight value =====================================
  1587. if( ($page==14) || ($page==15) ){
  1588. OWCOUNT_ParseMidnight($hash,$data,$page);
  1589. }
  1590. #=============== set memory =========================================
  1591. #-- issue the match ROM command \x55 and the write scratchpad command
  1592. # \x0F TA1 TA2 followed by the data
  1593. my $ta2 = ($page*32) >> 8;
  1594. my $ta1 = ($page*32) & 255;
  1595. $select=sprintf("\x0F%c%c",$ta1,$ta2).$data;
  1596. #-- OLD OWX interface
  1597. if( !$master->{ASYNCHRONOUS} ){
  1598. #-- reset the bus
  1599. OWX_Reset($master);
  1600. $res=OWX_Complex($master,$owx_dev,$select,0);
  1601. if( $res eq 0 ){
  1602. return "OWCOUNT: device $owx_dev not accessible in writing scratchpad";
  1603. }
  1604. #-- issue the match ROM command \x55 and the read scratchpad command
  1605. # \xAA, receiving 2 address bytes, 1 status byte and scratchpad content
  1606. $select = "\xAA";
  1607. #-- reset the bus
  1608. OWX_Reset($master);
  1609. #-- reading 9 + 3 + up to 32 bytes
  1610. # TODO: sometimes much less than 28
  1611. $res=OWX_Complex($master,$owx_dev,$select,28);
  1612. if( length($res) < 13 ){
  1613. return "OWCOUNT: device $owx_dev not accessible in reading scratchpad";
  1614. }
  1615. #-- issue the match ROM command \x55 and the copy scratchpad command
  1616. # \x5A followed by 3 byte authentication code obtained in previous read
  1617. $select="\x5A".substr($res,10,3);
  1618. #-- reset the bus
  1619. OWX_Reset($master);
  1620. $res=OWX_Complex($master,$owx_dev,$select,6);
  1621. #-- process results
  1622. if( $res eq 0 ){
  1623. return "OWCOUNT: device $owx_dev not accessible for copying scratchpad";
  1624. }
  1625. return undef;
  1626. #-- NEW OWX interface
  1627. }else{
  1628. #### master slave context proc owx_dev data crcpart numread startread callback delay
  1629. # 8 prevents from filling up with 0xFF
  1630. OWX_Qomplex($master, $hash, "setscratch", 8, $owx_dev, $select, 0, 40, 0, undef, 0.05);
  1631. #-- The third step of copying the scratchpad into memory can be scheduled only when the authorization code has been received
  1632. # will be done in the callback of the following line
  1633. OWX_Qomplex($master, $hash, "setpage.".$page, 0, $owx_dev, "\xAA", 0, 45, 0, \&OWXCOUNT_BinValues, undef);
  1634. }
  1635. return undef;
  1636. }
  1637. ########################################################################################
  1638. #
  1639. # OWXCOUNT_PT_GetPage - Get one memory page + counter from device async
  1640. #
  1641. # Parameter hash = hash of device addressed
  1642. # page = 0..15
  1643. # final= 1 if FormatValues is to be called
  1644. #
  1645. ########################################################################################
  1646. sub OWXCOUNT_PT_GetPage($$$) {
  1647. my ($hash,$page,$final) = @_;
  1648. return PT_THREAD(sub {
  1649. my ($thread) = @_;
  1650. #-- ID of the device, hash of the busmaster
  1651. my $owx_dev = $hash->{ROM_ID};
  1652. my $master = $hash->{IODev};
  1653. PT_BEGIN($thread);
  1654. #=============== wrong value requested ===============================
  1655. if( ($page<0) || ($page>15) ){
  1656. die("wrong memory page requested");
  1657. }
  1658. #=============== get memory + counter ===============================
  1659. #-- issue the match ROM command \x55 and the read memory + counter command
  1660. # \xA5 TA1 TA2 reading 40 data bytes and 2 CRC bytes
  1661. my $ta2 = ($page*32) >> 8;
  1662. my $ta1 = ($page*32) & 255;
  1663. $thread->{'select'}=sprintf("\xA5%c%c",$ta1,$ta2);
  1664. #-- reading 9 + 3 + 40 data bytes (32 byte memory, 4 byte counter + 4 byte zeroes) and 2 CRC bytes = 54 bytes
  1665. $thread->{pt_execute} = OWX_ASYNC_PT_Execute($master,1,$owx_dev, $thread->{'select'}, 42 );
  1666. PT_WAIT_THREAD($thread->{pt_execute});
  1667. die $thread->{pt_execute}->PT_CAUSE() if ($thread->{pt_execute}->PT_STATE() == PT_ERROR);
  1668. $thread->{response} = $thread->{pt_execute}->PT_RETVAL();
  1669. #-- reset the bus (needed to stop receiving data ?)
  1670. $thread->{pt_execute} = OWX_ASYNC_PT_Execute($master,1,undef,undef,undef);
  1671. PT_WAIT_THREAD($thread->{pt_execute});
  1672. die $thread->{pt_execute}->PT_CAUSE() if ($thread->{pt_execute}->PT_STATE() == PT_ERROR);
  1673. if (my $ret = OWXCOUNT_BinValues($hash,"getpage.".$page.($final ? ".final" : ""),0,$owx_dev,$thread->{'select'},0,$thread->{response})) {
  1674. die $ret;
  1675. }
  1676. PT_END;
  1677. });
  1678. }
  1679. ########################################################################################
  1680. #
  1681. # OWXCOUNT_PT_SetPage - Set one memory page of device async
  1682. #
  1683. # Parameter hash = hash of device addressed
  1684. # page = "alarm" or "status"
  1685. #
  1686. ########################################################################################
  1687. sub OWXCOUNT_PT_SetPage($$$) {
  1688. my ($hash,$page,$data) = @_;
  1689. return PT_THREAD(sub {
  1690. my ($thread) = @_;
  1691. my ($res, $response);
  1692. #-- ID of the device, hash of the busmaster
  1693. my $owx_dev = $hash->{ROM_ID};
  1694. my $master = $hash->{IODev};
  1695. PT_BEGIN($thread);
  1696. #=============== wrong page requested ===============================
  1697. if( ($page<0) || ($page>15) ){
  1698. PT_EXIT("wrong memory page write attempt");
  1699. }
  1700. #=============== midnight value =====================================
  1701. if( ($page==14) || ($page==15) ){
  1702. OWCOUNT_ParseMidnight($hash,$data,$page);
  1703. }
  1704. #=============== set memory =========================================
  1705. #-- issue the match ROM command \x55 and the write scratchpad command
  1706. # \x0F TA1 TA2 followed by the data
  1707. my $ta2 = ($page*32) >> 8;
  1708. my $ta1 = ($page*32) & 255;
  1709. #Log 1, "OWXCOUNT: setting page Nr. $ta2 $ta1 $data";
  1710. $thread->{'select'}=sprintf("\x0F%c%c",$ta1,$ta2).$data;
  1711. #"setpage.1"
  1712. $thread->{pt_execute} = OWX_ASYNC_PT_Execute($master,1,$owx_dev, $thread->{'select'}, 0 );
  1713. PT_WAIT_THREAD($thread->{pt_execute});
  1714. die $thread->{pt_execute}->PT_CAUSE() if ($thread->{pt_execute}->PT_STATE() == PT_ERROR);
  1715. #-- issue the match ROM command \x55 and the read scratchpad command
  1716. # \xAA, receiving 2 address bytes, 1 status byte and scratchpad content
  1717. $thread->{'select'} = "\xAA";
  1718. #-- reading 9 + 3 + up to 32 bytes
  1719. # TODO: sometimes much less than 28
  1720. #"setpage.2"
  1721. $thread->{pt_execute} = OWX_ASYNC_PT_Execute($master,1,$owx_dev, $thread->{'select'}, 28 );
  1722. PT_WAIT_THREAD($thread->{pt_execute});
  1723. die $thread->{pt_execute}->PT_CAUSE() if ($thread->{pt_execute}->PT_STATE() == PT_ERROR);
  1724. $res = $thread->{pt_execute}->PT_RETVAL();
  1725. if( length($res) < 13 ){
  1726. PT_EXIT("device $owx_dev not accessible in reading scratchpad");
  1727. }
  1728. #-- issue the match ROM command \x55 and the copy scratchpad command
  1729. # \x5A followed by 3 byte authentication code obtained in previous read
  1730. $thread->{'select'}="\x5A".substr($res,0,3);
  1731. #-- first command, next 2 are address, then data
  1732. #"setpage.3"
  1733. $thread->{pt_execute} = OWX_ASYNC_PT_Execute($master,1,$owx_dev, $thread->{'select'}, 6 );
  1734. PT_WAIT_THREAD($thread->{pt_execute});
  1735. die $thread->{pt_execute}->PT_CAUSE() if ($thread->{pt_execute}->PT_STATE() == PT_ERROR);
  1736. $res = $thread->{pt_execute}->PT_RETVAL();
  1737. #TODO validate whether testing '0' is appropriate with async interface
  1738. #-- process results
  1739. if( $res eq 0 ){
  1740. PT_EXIT("device $owx_dev error copying scratchpad");
  1741. }
  1742. PT_END;
  1743. });
  1744. }
  1745. sub OWXCOUNT_PT_InitializeDevicePage($$$) {
  1746. my ($hash,$page,$newdata) = @_;
  1747. return PT_THREAD(sub {
  1748. my ($thread) = @_;
  1749. my $ret;
  1750. PT_BEGIN($thread);
  1751. $thread->{task} = OWXCOUNT_PT_GetPage($hash,$page,0);
  1752. PT_WAIT_THREAD($thread->{task});
  1753. $ret = $thread->{task}->PT_RETVAL();
  1754. if ($ret) {
  1755. PT_EXIT($ret);
  1756. }
  1757. $thread->{olddata} = $hash->{owg_str}->[14];
  1758. $thread->{task} = OWXCOUNT_PT_SetPage($hash,$page,$newdata);
  1759. PT_WAIT_THREAD($thread->{task});
  1760. $ret = $thread->{task}->PT_RETVAL();
  1761. if ($ret) {
  1762. PT_EXIT($ret);
  1763. }
  1764. $thread->{task} = OWXCOUNT_PT_GetPage($hash,$page,0);
  1765. PT_WAIT_THREAD($thread->{task});
  1766. $ret = $thread->{task}->PT_RETVAL();
  1767. if ($ret) {
  1768. PT_EXIT($ret);
  1769. }
  1770. $thread->{task} = OWXCOUNT_PT_SetPage($hash,$page,$thread->{olddata});
  1771. PT_WAIT_THREAD($thread->{task});
  1772. $ret = $thread->{task}->PT_RETVAL();
  1773. if ($ret) {
  1774. PT_EXIT($ret);
  1775. }
  1776. PT_END;
  1777. });
  1778. }
  1779. 1;
  1780. =pod
  1781. =item device
  1782. =item summary to commmunicate with 1-Wire Counter/RAM DS2423
  1783. =begin html
  1784. <a name="OWCOUNT"></a>
  1785. <h3>OWCOUNT</h3>
  1786. <p>FHEM module to commmunicate with 1-Wire Counter/RAM DS2423 or its emulation DS2423emu <br />
  1787. <br />This 1-Wire module works with the OWX interface module or with the OWServer interface module
  1788. (prerequisite: Add this module's name to the list of clients in OWServer).
  1789. Please define an <a href="#OWX">OWX</a> device or <a href="#OWServer">OWServer</a> device first. <br/><p/>
  1790. <br /><h4>Example</h4><br />
  1791. <code>define OWC OWCOUNT 1D.CE780F000000 60</code>
  1792. <br />
  1793. <code>attr OWC AName energy|W</code>
  1794. <br />
  1795. <code>attr OWC AUnit kWh</code>
  1796. <br />
  1797. <code>attr OWC APeriod hour</code>
  1798. <br />
  1799. <code>attr OWC ARate power|P</code>
  1800. <br />
  1801. <code>attr OWX_AMode daily</code>
  1802. <br />
  1803. <br />
  1804. <a name="OWCOUNTdefine"></a>
  1805. <h4>Define</h4>
  1806. <p>
  1807. <code>define &lt;name&gt; OWCOUNT [&lt;model&gt;] &lt;id&gt; [&lt;interval&gt;]</code> or <br/>
  1808. <code>define &lt;name&gt; OWCOUNT &lt;fam&gt;.&lt;id&gt; [&lt;interval&gt;]</code>
  1809. <br /><br /> Define a 1-Wire counter.<br /><br /></p>
  1810. <ul>
  1811. <li>
  1812. <code>[&lt;model&gt;]</code><br /> Defines the counter model (and thus 1-Wire family
  1813. id), currently the following values are permitted: <ul>
  1814. <li>model DS2423 with family id 1D (default if the model parameter is
  1815. omitted)</li>
  1816. <li>model DS2423enew with family id 1D - emulator, works like DS2423</li>
  1817. <li>model DS2423eold with family id 1D - emulator, works like DS2423 except that the internal memory is not present</li>
  1818. </ul>
  1819. </li>
  1820. <li>
  1821. <code>&lt;fam&gt;</code>
  1822. <br />2-character unique family id, see above
  1823. </li>
  1824. <li>
  1825. <code>&lt;id&gt;</code>
  1826. <br />12-character unique ROM id of the converter device without family id and CRC
  1827. code </li>
  1828. <li>
  1829. <code>&lt;interval&gt;</code>
  1830. <br />Measurement interval in seconds. The default is 300 seconds, a value of 0 disables the automatic update. </li>
  1831. </ul>
  1832. <br />
  1833. <a name="OWCOUNTset"></a>
  1834. <h4>Set</h4>
  1835. <ul>
  1836. <li><a name="owcount_interval">
  1837. <code>set &lt;name&gt; interval &lt;int&gt;</code></a><br /> Measurement
  1838. interval in seconds. The default is 300 seconds, a value of 0 disables the automatic update.
  1839. Log line after each interval &lt;date&gt; &lt;name&gt; &lt;channel&gt;: &lt;value&gt; &lt;unit&gt; &lt;value&gt; /
  1840. &lt;unit&gt;/&lt;period&gt; &lt;channel&gt;: &lt;value&gt; &lt;unit&gt; / &lt;value&gt; &lt;unit&gt;/&lt;period&gt; <br />
  1841. example: 2012-07-30_00:07:55 OWX_C Taste: 17.03 p 28.1 p/h B: 7.0 cts 0.0 cts/min
  1842. </li>
  1843. <li><a name="owcount_memory">
  1844. <code>set &lt;name&gt; memory &lt;page&gt; &lt;string&gt;</code></a><br />Write 32 bytes to
  1845. memory page 0..13 </li>
  1846. <li><a name="owcount_midnight">
  1847. <code>set &lt;name&gt; midnight &lt;channel-name&gt; &lt;val&gt;</code></a><br />Write the
  1848. day's starting value for counter &lt;channel&gt; (A, B or named channel, see
  1849. below)</li>
  1850. <li><a name="owcount_counter">
  1851. <code>set &lt;name&gt; counter &lt;channel-name&gt; &lt;val&gt;</code></a><br />Correct the midnight
  1852. value such that counter &lt;channel&gt; (A, B or named channel, see
  1853. below) displays value &lt;val&gt;</li>
  1854. </ul>
  1855. <br />
  1856. <a name="OWCOUNTget"></a>
  1857. <h4>Get</h4>
  1858. <ul>
  1859. <li><a name="owcount_id">
  1860. <code>get &lt;name&gt; id</code></a>
  1861. <br /> Returns the full 1-Wire device id OW_FAMILY.ROM_ID.CRC </li>
  1862. <li><a name="owcount_memory2">
  1863. <code>get &lt;name&gt; memory &lt;page&gt;</code></a><br />Obtain 32 bytes from
  1864. memory page 0..13 and store in cache <i>$hash->{owg_str}->[page]</i> as well as in reading "memory"</li>
  1865. <li><a name="owcount_mcache">
  1866. <code>get &lt;name&gt; mcache &lt;page&gt;</code></a><br />Obtain 32 bytes from
  1867. cache <i>$hash->{owg_str}->[page]</i> and display.</li>
  1868. <li><a name="owcount_midnight2">
  1869. <code>get &lt;name&gt; midnight &lt;channel-name&gt;</code></a><br />Obtain the
  1870. day's starting value for counter &lt;channel&gt; (A, B or named channel, see
  1871. below)</li>
  1872. <li><a name="owcount_month">
  1873. <code>get &lt;name&gt; month</code></a><br />Returns cumulated and averaged monthly value if mode=daily, otherwise last day's and averaged value </li>
  1874. <li><a name="owcount_year">
  1875. <code>get &lt;name&gt; year</code></a><br />Returns cumulated and averaged yearly value if mode=daily, otherwise last months's and averaged value </li>
  1876. <li><a name="owcount_raw">
  1877. <code>get &lt;name&gt; raw &lt;channel-name&gt;</code></a><br />Obtain the
  1878. current raw value for counter &lt;channel&gt; (A, B or named channel, see below)</li>
  1879. <li><a name="owcount_counters">
  1880. <code>get &lt;name&gt; counters</code></a><br />Obtain the current value both
  1881. counters</li>
  1882. </ul>
  1883. <br />
  1884. <a name="OWCOUNTattr"></a>
  1885. <h4>Attributes</h4>
  1886. <ul>
  1887. <li><a name="owcount_logm"><code>attr &lt;name&gt; LogM
  1888. &lt;string&gt;</code></a>
  1889. <br />device name (not file name) of monthly log file.
  1890. Log line after midnight &lt;new date&gt; &lt;name&gt; &lt;old day&gt; &lt;old date&gt; &lt;channel&gt;: &lt;value&gt; &lt;unit&gt; &lt;channel&gt;: &lt;value&gt; &lt;unit&gt;
  1891. <br /> example: 2012-07-30_00:00:57 OWX_C D29: 2012-7-29_23:59:59 Taste: 110.0 p, B: 7.0 cts
  1892. </li>
  1893. <li><a name="owcount_logy"><code>attr &lt;name&gt; LogY
  1894. &lt;string&gt;</code></a>
  1895. <br />device name (not file name) of yearly log file.</li>
  1896. <li><a name="owcount_interval2">
  1897. <code>attr &lt;name&gt; interval &lt;int&gt;</code></a>
  1898. <br /> Measurement
  1899. interval in seconds. The default is 300 seconds, a value of 0 disables the automatic update. </li>
  1900. <li><a name="owcount_nomemory"><code>attr &lt;name&gt; nomemory
  1901. 0|1</code></a>
  1902. <br />when set to 1, midnight values will be stored in files instead of the internal memory.</li>
  1903. </ul>
  1904. <p>For each of the following attributes, the channel identification A,B may be used.</p>
  1905. <ul>
  1906. <li><a name="owcount_cname"><code>attr &lt;name&gt; &lt;channel&gt;Name
  1907. &lt;string&gt;[|&lt;string&gt;]</code></a>
  1908. <br />name for the channel [|short name used in state reading]. </li>
  1909. <li><a name="owcount_cunit"><code>attr &lt;name&gt; &lt;channel&gt;Unit
  1910. &lt;string&</code></a>
  1911. <br />unit of measurement used in state reading (default "cts", set to "none" for empty).</li>
  1912. <li><a name="owcount_crate"><code>attr &lt;name&gt; &lt;channel&gt;Rate
  1913. &lt;string&gt;[|&lt;string&gt;]</code></a>
  1914. <br />name for the channel rate [|short name used in state reading]</li>
  1915. <li><a name="owcount_coffset"><code>attr &lt;name&gt; &lt;channel&gt;Offset
  1916. &lt;float&gt;</code></a>
  1917. <br />offset added to the reading in this channel. </li>
  1918. <li><a name="owcount_cfactor"><code>attr &lt;name&gt; &lt;channel&gt;Factor
  1919. &lt;float&gt;</code></a>
  1920. <br />factor multiplied to (reading+offset) in this channel. </li>
  1921. <li><a name="owcount_cmode"><code>attr &lt;name&gt; &lt;channel&gt;Mode daily |
  1922. normal</code></a>
  1923. <br />determines whether counter is nulled at start of day or running continuously </li>
  1924. <li><a name="owcount_cperiod"><code>attr &lt;name&gt; &lt;channel&gt;Period hour(default) | minute |
  1925. second</code></a>
  1926. <br />period for rate calculation </li>
  1927. <li><a href="#readingFnAttributes">readingFnAttributes</a></li>
  1928. </ul>
  1929. =end html
  1930. =cut