;
close FILE;
$log .= "--- AVRDUDE ---------------------------------------------------------------------------------\n";
$log .= $logText;
$log .= "--- AVRDUDE ---------------------------------------------------------------------------------\n\n";
}
else {
$log .= "WARNING: avrdude created no log file\n\n";
}
ArduCounter_Open($hash, 0); # new open
$log .= "$name open called.\n";
delete $hash->{Initialized};
}
return $log;
}
# SET command
#########################################################################
sub ArduCounter_Set($@)
{
my ($hash, @a) = @_;
return "\"set ArduCounter\" needs at least one argument" if ( @a < 2 );
# @a is an array with DeviceName, SetName, Rest of Set Line
my $name = shift @a;
my $attr = shift @a;
my $arg = join(" ", @a);
if(!defined($ArduCounter_sets{$attr})) {
my @cList = keys %ArduCounter_sets;
return "Unknown argument $attr, choose one of " . join(" ", @cList);
}
if ($attr eq "disable") {
Log3 $name, 4, "$name: set disable called";
CommandAttr(undef, "$name disable 1");
return;
} elsif ($attr eq "enable") {
Log3 $name, 4, "$name: set enable called";
CommandAttr(undef, "$name disable 0");
return;
} elsif ($attr eq "reconnect") {
Log3 $name, 4, "$name: set reconnect called";
DevIo_CloseDev($hash);
ArduCounter_Open($hash);
return;
} elsif ($attr eq "clearLevels") {
delete $hash->{analogLevels};
return;
} elsif ($attr eq "flash") {
return ArduCounter_Flash($hash, @a);
}
if(!$hash->{FD}) {
Log3 $name, 4, "$name: Set $attr $arg called but device is disconnected";
return ("Set called but device is disconnected", undef);
}
if (IsDisabled($name)) {
Log3 $name, 4, "$name: set $attr $arg called but device is disabled";
return;
}
if ($attr eq "raw") {
Log3 $name, 4, "$name: set raw $arg called";
ArduCounter_Write($hash, "$arg");
} elsif ($attr eq "saveConfig") {
Log3 $name, 4, "$name: set saveConfig called";
ArduCounter_Write($hash, "e");
} elsif ($attr eq "reset") {
Log3 $name, 4, "$name: set reset called";
DevIo_CloseDev($hash);
ArduCounter_Open($hash);
if (ArduCounter_Write($hash, "r")) {
delete $hash->{Initialized};
return "sent (r)eset command to device - waiting for its setup message";
}
}
return undef;
}
# GET command
#########################################################################
sub ArduCounter_Get($@)
{
my ( $hash, @a ) = @_;
return "\"set ArduCounter\" needs at least one argument" if ( @a < 2 );
my $name = shift @a;
my $attr = shift @a;
my $opt = shift @a;
if(!defined($ArduCounter_gets{$attr})) {
my @cList = keys %ArduCounter_gets;
return "Unknown argument $attr, choose one of " . join(" ", @cList);
}
if ($attr eq "levels") {
my $msg = "";
foreach my $level (sort {$a <=> $b} keys %{$hash->{analogLevels}}) {
$msg .= "$level: $hash->{analogLevels}{$level}\n";
}
return "observed levels from analog input:\n$msg\n";
}
if(!$hash->{FD}) {
Log3 $name, 4, "$name: Get called but device is disconnected";
return ("Get called but device is disconnected", undef);
}
if (IsDisabled($name)) {
Log3 $name, 4, "$name: get called but device is disabled";
return;
}
if ($attr eq "info") {
Log3 $name, 3, "$name: Sending info command to device";
ArduCounter_Write( $hash, "s");
my ($err, $msg) = ArduCounter_ReadAnswer($hash, 'Next report in.*seconds');
return ($err ? $err : $msg);
} elsif ($attr eq "history") {
Log3 $name, 3, "$name: get history";
$hash->{HistIdx} = 0 if (!defined($hash->{HistIdx}));
my $idx = $hash->{HistIdx}; # HistIdx points to the next slot to be overwritten
my $ret = "";
my $count = 0;
my $histLine;
while ($count < AttrVal($name, "maxHist", 1000)) {
if (defined ($hash->{History}[$idx])) {
if (!$opt || !$hash->{HistoryPin} || $hash->{HistoryPin}[$idx] eq $opt) {
$ret .= $hash->{History}[$idx] . "\n";
}
}
$idx++;
$count++;
$idx = 0 if ($idx > AttrVal($name, "maxHist", 1000));
}
if (!$hash->{runningCfg}{V} || $hash->{runningCfg}{V} < 5) {
$ret = "Make sure that devVerbose is set to 5 or higher to get pin history data\n" .
"current devVerbose at device is " . ($hash->{runningCfg}{V} ? $hash->{runningCfg}{V} : "undef") . "\n\n" .
$ret;
}
return ($ret ? $ret : "no history data so far");
}
return undef;
}
######################################
sub ArduCounter_HandleDeviceTime($$$$)
{
my ($hash, $deTi, $deTiW, $now) = @_;
my $name = $hash->{NAME};
my $deviceNowSecs = ($deTi/1000) + ((0xFFFFFFFF / 1000) * $deTiW);
Log3 $name, 5, "$name: Device Time $deviceNowSecs";
if (defined ($hash->{'.DeTOff'}) && $hash->{'.LastDeT'}) {
if ($deviceNowSecs >= $hash->{'.LastDeT'}) {
$hash->{'.Drift2'} = ($now - $hash->{'.DeTOff'}) - $deviceNowSecs;
} else {
$hash->{'.DeTOff'} = $now - $deviceNowSecs;
Log3 $name, 4, "$name: device did reset (now $deviceNowSecs, before $hash->{'.LastDeT'}). New offset is $hash->{'.DeTOff'}";
}
} else {
$hash->{'.DeTOff'} = $now - $deviceNowSecs;
$hash->{'.Drift2'} = 0;
$hash->{'.DriftStart'} = $now;
Log3 $name, 5, "$name: Initialize device clock offset to $hash->{'.DeTOff'}";
}
$hash->{'.LastDeT'} = $deviceNowSecs;
my $drTime = ($now - $hash->{'.DriftStart'});
#Log3 $name, 5, "$name: Device Time $deviceNowSecs" .
#", Offset " . sprintf("%.3f", $hash->{'.DeTOff'}/1000) .
", Drift " . sprintf("%.3f", $hash->{'.Drift2'}) .
"s in " . sprintf("%.3f", $drTime) . "s" .
($drTime > 0 ? ", " . sprintf("%.2f", $hash->{'.Drift2'} / $drTime * 100) . "%" : "");
}
######################################
sub ArduCounter_ParseHello($$$)
{
my ($hash, $line, $now) = @_;
my $name = $hash->{NAME};
if ($line =~ /^ArduCounter V([\d\.]+) on ([^\ ]+)( ?[^\ ]*) compiled (.*) Hello(, pins ([0-9\,]+) available)? ?(T([\d]+),([\d]+) B([\d]+),([\d]+))?/) { # setup / hello message
$hash->{VersionFirmware} = ($1 ? $1 : 'unknown');
$hash->{Board} = ($2 ? $2 : 'unknown');
$hash->{BoardDet} = ($3 ? $3 : '');
$hash->{SketchCompile} = ($4 ? $4 : 'unknown');
$hash->{allowedPins} = $6 if ($6);
my $mNow = ($8 ? $8 : 0);
my $mNowW = ($9 ? $9 : 0);
my $mBoot = ($10 ? $10 : 0);
my $mBootW = ($11 ? $11 : 0);
if ($hash->{VersionFirmware} < "2.36") {
$hash->{VersionFirmware} .= " - not compatible with this Module version - please flash new sketch";
Log3 $name, 3, "$name: device reported outdated Arducounter Firmware ($hash->{VersionFirmware}) - please update!";
delete $hash->{Initialized};
} else {
Log3 $name, 3, "$name: device sent hello: $line";
$hash->{Initialized} = 1; # now device has finished its boot and reported its version
delete $hash->{runningCfg};
my $cft = AttrVal($name, "configDelay", 1); # wait for device to send cfg before reconf.
RemoveInternalTimer ("cmpCfg:$name");
InternalTimer($now+$cft, "ArduCounter_ConfigureDevice", "cmpCfg:$name", 0);
my $deviceNowSecs = ($mNow/1000) + ((0xFFFFFFFF / 1000) * $mNowW);
my $deviceBootSecs = ($mBoot/1000) + ((0xFFFFFFFF / 1000) * $mBootW);
my $bootTime = $now - ($deviceNowSecs - $deviceBootSecs);
$hash->{deviceBooted} = $bootTime; # for estimation of missed pulses up to now
my $boardAttr = AttrVal($name, 'board', '');
if ($hash->{Board} && $boardAttr && ($hash->{Board} ne $boardAttr)) {
Log3 $name, 3, "attribute board is set to $boardAttr and is overwriting board $hash->{Board} reported by device";
$hash->{Board} = $boardAttr;
}
# now enrich $hash->{allowedPins} with $rAnalogPinMap{$hash->{Board}}{$pin}
if ($hash->{allowedPins} && $hash->{Board}) {
my $newAllowed;
my $first = 1;
foreach my $pin (split (/,/, $hash->{allowedPins})) {
$newAllowed .= ($first ? '' : ','); # separate by , if not empty anymore
$newAllowed .= $pin;
if ($rAnalogPinMap{$hash->{Board}}{$pin}) {
$newAllowed .= ",$rAnalogPinMap{$hash->{Board}}{$pin}";
}
$first = 0;
}
$hash->{allowedPins} = $newAllowed;
}
}
delete $hash->{WaitForHello};
RemoveInternalTimer ("hwait:$name"); # dont wait for hello reply if already sent
RemoveInternalTimer ("sendHello:$name"); # Hello not needed anymore if not sent yet
} else {
Log3 $name, 4, "$name: probably wrong firmware version - cannot parse line $line";
}
}
######################################
# $hash->{Board} wird in parseHello gesetzt und ggf. dort gleich durch das Attribut Board überschrieben
# called from Attr and ConfigureDevice.
# in all cases Board and AllowedPins have been received with hello before
sub ArduCounter_PinNumber($$)
{
my ($hash, $pinName) = @_;
my $name = $hash->{NAME};
my $boardAttr = AttrVal($name, "board", "");
my $board = ($boardAttr ? $boardAttr : $hash->{Board});
my $pin;
if (!$board) { # maybe no hello received yet and no Board-attr set (should never be the case)
my @boardOptions = keys %AnalogPinMap;
my $count = 0;
foreach my $candidate (@boardOptions) {
if ($AnalogPinMap{$candidate}{$pinName}) {
$board = $AnalogPinMap{$candidate}{$pinName};
$count++;
}
}
if ($count > 1) {
Log3 $name, 3, "$name: PinNumber called from " . ArduCounter_Caller() . " can not determine internal pin number for $pinName, board type is not known (yet) and attribute Board is also not set";
} elsif (!$count) {
Log3 $name, 3, "$name: PinNumber called from " . ArduCounter_Caller() . " can not determine internal pin number for $pinName. No known board seems to support it";
}
}
$pin = $AnalogPinMap{$board}{$pinName} if ($board);
if ($pin) {
Log3 $name, 5, "$name: PinNumber called from " . ArduCounter_Caller() . " returns $pin for $pinName";
} else {
Log3 $name, 5, "$name: PinNumber called from " . ArduCounter_Caller() . " returns unknown for $pinName";
}
return $pin # might be undef
}
######################################
sub ArduCounter_PinName($$)
{
my ($hash, $pin) = @_;
my $name = $hash->{NAME};
my $pinName = $pin; # start assuming that attrs are set as pinX
if (!AttrVal($name, "pin$pinName", 0)) { # if not
if (AttrVal($name, "pinD$pin", 0)) {
$pinName = "D$pin"; # maybe pinDX?
#Log3 $name, 5, "$name: using attrs with pin name D$pin";
} elsif ($hash->{Board}) {
my $aPin = $rAnalogPinMap{$hash->{Board}}{$pin};
if ($aPin) { # or pinAX?
$pinName = "$aPin";
#Log3 $name, 5, "$name: using attrs with pin name $pinName instead of $pin or D$pin (Board $hash->{Board})";
}
}
}
return $pinName;
}
sub AduCounter_AttrVal($$$;$$$)
{
my ($hash, $default, $a1, $a2, $a3, $a4) = @_;
my $name = $hash->{NAME};
return AttrVal($name, $a1, undef) if (defined (AttrVal($name, $a1, undef)));
return AttrVal($name, $a2, undef) if (defined ($a2) && defined (AttrVal($name, $a2, undef)));
return AttrVal($name, $a3, undef) if (defined ($a3) && defined (AttrVal($name, $a3, undef)));
return AttrVal($name, $a4, undef) if (defined ($a4) && defined (AttrVal($name, $a4, undef)));
return $default;
}
######################################
sub ArduCounter_LogPinDesc($$)
{
my ($hash, $pin) = @_;
my $pinName = ArduCounter_PinName ($hash, $pin);
return AduCounter_AttrVal($hash, "pin$pin", "readingNameCount$pinName", "readingNameCount$pin", "readingNamePower$pinName", "readingNamePower$pin");
}
#########################################################################
sub ArduCounter_HandleCounters($$$$$$$$)
{
my ($hash, $pin, $seq, $count, $time, $diff, $rDiff, $now) = @_;
my $name = $hash->{NAME};
my $pinName = ArduCounter_PinName ($hash, $pin);
my $rcname = AduCounter_AttrVal($hash, "pin$pinName", "readingNameCount$pinName", "readingNameCount$pin");
my $rlname = AduCounter_AttrVal($hash, "long$pinName", "readingNameLongCount$pinName", "readingNameLongCount$pin");
my $riname = AduCounter_AttrVal($hash, "interpolatedLong$pinName", "readingNameInterpolatedCount$pinName", "readingNameInterpolatedCount$pin");
my $rccname = AduCounter_AttrVal($hash, "calcCounter$pinName", "readingNameCalcCount$pinName", "readingNameCalcCount$pin");
my $ppk = AduCounter_AttrVal($hash, 0, "readingPulsesPerKWh$pin", "readingPulsesPerKWh$pinName", "pulsesPerKWh");
my $lName = ArduCounter_LogPinDesc($hash, $pin);
my $longCount = ReadingsVal($name, $rlname, 0); # alter long count Wert
my $intpCount = ReadingsVal($name, $riname, 0); # alter interpolated count Wert
my $lastCount = ReadingsVal($name, $rcname, 0);
my $cCounter = ReadingsVal($name, $rccname, 0); # calculated counter
my $iSum = ReadingsVal($name, $rccname . "_i", 0); # interpolation sum
my $lastSeq = ReadingsVal($name, "seq".$pinName, 0);
my $intrCount = 0; # interpolated count to be added
my $lastCountTS = ReadingsTimestamp ($name, $rlname, 0); # last time long count reading was set as string
my $lastCountTNum = time_str2num($lastCountTS); # time as number
my $fLastCTim = FmtTime($lastCountTNum); # formatted for logging
my $pLog = "$name: pin $pinName ($lName)"; # start of log lines
my $fBootTim;
my $deviceBooted;
if ($hash->{deviceBooted} && $lastCountTS && $hash->{deviceBooted} > $lastCountTNum) {
$deviceBooted = 1; # first report for this pin after a restart
$fBootTim = FmtTime($hash->{deviceBooted}) ; # time device booted
} # without old readings, interpolation makes no sense anyway
my $countStart = $count - $rDiff; # count at start of this reported interval
$countStart = 0 if ($countStart < 0);
my $timeGap = ($now - $time/1000 - $lastCountTNum); # time between last report and start of currently reported interval
$timeGap = 0 if ($timeGap < 0 || !$lastCountTS);
my $seqGap = $seq - ($lastSeq + 1); # gap of reporting sequences if any
$seqGap = 0 if (!$lastCountTS); # readings didn't exist yet
if ($seqGap < 0) { # new sequence number is smaller than last
$seqGap %= 256; # correct seq gap
Log3 $name, 5, "$pLog sequence wrapped from $lastSeq to $seq, set seqGap to $seqGap" if (!$deviceBooted);
}
my $pulseGap = $countStart - $lastCount; # gap of missed pulses if any
$pulseGap = 0 if (!$lastCountTS); # readings didn't exist yet
if ($pulseGap < 0) { # pulseGap < 0 should not happen
$pulseGap = 0;
Log3 $name, 3, "$pLog seems to have missed $seqGap reports in $timeGap seconds. " .
"Last reported sequence was $lastSeq, now $seq. " .
"Device count before was $lastCount, now $count with rDiff $rDiff " .
"but pulseGap is $pulseGap. this is probably wrong and should not happen" if (!$deviceBooted);
}
if ($deviceBooted) { # first report for this pin after a restart -> do interpolation
# interpolate for period between last report before boot and boot time.
Log3 $name, 5, "$pLog device restarted at $fBootTim, last reported at $fLastCTim, " .
"count changed from $lastCount to $count, sequence from $lastSeq to $seq";
$seqGap = $seq - 1; # $seq should be 1 after restart
$pulseGap = $countStart; # we missed everything up to the count at start of the reported interval
my $lastInterval = ReadingsVal ($name, "timeDiff$pinName", 0); # time diff of last interval (old reading)
my $lastCDiff = ReadingsVal ($name, "countDiff$pinName", 0); # count diff of last interval (old reading)
my $offlTime = sprintf ("%.2f", $hash->{deviceBooted} - $lastCountTNum); # estimated offline time (last report in readings until boot)
if ($lastInterval && ($offlTime > 0) && ($offlTime < 12*60*60)) { # offline > 0 and < 12h
my $lastRatio = $lastCDiff / $lastInterval;
my $curRatio = $diff / $time;
my $intRatio = 1000 * ($lastRatio + $curRatio) / 2;
$intrCount = int(($offlTime * $intRatio)+0.5);
Log3 $name, 3, "$pLog interpolating for $offlTime secs until boot, $intrCount estimated pulses (before $lastCDiff in $lastInterval ms, now $diff in $time ms, avg ratio $intRatio p/s)";
} else {
Log3 $name, 4, "$pLog interpolation of missed pulses for pin $pinName ($lName) not possible - no valid historic data.";
}
}
Log3 $name, 3, "$pLog missed $seqGap reports in $timeGap seconds. Last reported sequence was $lastSeq, " .
"now $seq. Device count before was $lastCount, now $count with rDiff $rDiff. " .
"Adding $pulseGap to long count and intpolated count readings" if ($pulseGap > 0);
Log3 $name, 5, "$pLog adding rDiff $rDiff to long count $longCount and interpolated count $intpCount";
Log3 $name, 5, "$pLog adding interpolated $intrCount to interpolated count $intpCount" if ($intrCount);
$intpCount += ($rDiff + $pulseGap + $intrCount);
$longCount += ($rDiff + $pulseGap);
if ($ppk) {
$cCounter += ($rDiff + $pulseGap + $intrCount) / $ppk; # add to calculated counter
$iSum += $intrCount / $ppk; # sum of interpolation kWh
}
readingsBulkUpdate($hash, $rcname, $count); # device internal counter
readingsBulkUpdate($hash, $rlname, $longCount); # Fhem long counterr
readingsBulkUpdate($hash, $riname, $intpCount); # Fhem interpolated counter
if ($ppk) {
readingsBulkUpdate($hash, $rccname, $cCounter); # Fhem calculated / interpolated counter
readingsBulkUpdate($hash, $rccname . "_i", $iSum); # Fhem interpolation sum
}
readingsBulkUpdate($hash, "seq".$pinName, $seq); # Sequence number
}
#########################################################################
sub ArduCounter_ParseReport($$)
{
my ($hash, $line) = @_;
my $name = $hash->{NAME};
my $now = gettimeofday();
if ($line =~ '^R([\d]+) C([\d]+) D([\d]+) ?[\/R]([\d]+) T([\d]+) N([\d]+),([\d]+) X([\d]+)( S[\d]+)?( A[\d]+)?')
{
# new count is beeing reported
my $pin = $1;
my $count = $2; # internal counter at device
my $diff = $3; # delta during interval
my $rDiff = $4; # real delta including the first pulse after a restart
my $time = $5; # interval in ms
my $deTime = $6;
my $deTiW = $7;
my $reject = $8;
my $seq = ($9 ? substr($9, 2) : "");
my $avgLen = ($10 ? substr($10, 2) : "");
my $pinName = ArduCounter_PinName($hash, $pin);
# now get pin specific reading names and options - first try with pinName, then pin Number, then generic fallback for all pins
my $factor = AduCounter_AttrVal($hash, 1000, "readingFactor$pinName", "readingFactor$pin", "factor");
my $ppk = AduCounter_AttrVal($hash, 0, "readingPulsesPerKWh$pinName", "readingPulsesPerKWh$pin", "pulsesPerKWh");
my $rpname = AduCounter_AttrVal($hash, "power$pinName", "readingNamePower$pinName", "readingNamePower$pin");
my $lName = ArduCounter_LogPinDesc($hash, $pin);
my $pLog = "$name: pin $pinName ($lName)"; # start of log lines
my $sTime = $now - $time/1000; # start of observation interval (~first pulse) in secs (floating point)
my $fSTime = FmtDateTime($sTime); # formatted
my $fSdTim = FmtTime($sTime); # only time formatted for logging
my $fEdTim = FmtTime($now); # end of Interval - only time formatted for logging
ArduCounter_HandleDeviceTime($hash, $deTime, $deTiW, $now);
if (!$time || !$factor) {
Log3 $name, 3, "$pLog skip line because time or factor is 0: $line";
return;
}
my $power;
if ($ppk) { # new calculation with pulsee or rounds per unit (kWh)
$power = sprintf ("%.3f", ($time ? ($diff/$time) * (3600000 / $ppk) : 0));
} else { # old calculation with a factor that is hard to understand
$power = sprintf ("%.3f", ($time ? $diff/$time/1000*3600*$factor : 0));
}
Log3 $name, 4, "$pLog Cnt $count " .
"(diff $diff/$rDiff) in " . sprintf("%.3f", $time/1000) . "s" .
" from $fSdTim until $fEdTim, seq $seq" .
((defined($reject) && $reject ne "") ? ", Rej $reject" : "") .
(defined($avgLen) ? ", Avg ${avgLen}ms" : "") .
", result $power";
if (AttrVal($name, "readingStartTime$pinName", AttrVal($name, "readingStartTime$pin", 0))) {
readingsBeginUpdate($hash); # special block: use time of interval start as reading time
Log3 $name, 5, "$pLog readingStartTime$pinName specified: setting timestamp to $fSdTim";
my $chIdx = 0;
$hash->{".updateTime"} = $sTime;
$hash->{".updateTimestamp"} = $fSTime;
readingsBulkUpdate($hash, $rpname, $power) if ($time);
$hash->{CHANGETIME}[$chIdx++] = $fSTime; # Intervall start
readingsEndUpdate($hash, 1); # end of special block
readingsBeginUpdate($hash); # start regular update block
} else {
# normal way to set readings
readingsBeginUpdate($hash); # start regular update block
readingsBulkUpdate($hash, $rpname, $power) if ($time);
}
if (defined($reject) && $reject ne "") {
my $rejCount = ReadingsVal($name, "reject$pinName", 0); # alter reject count Wert
readingsBulkUpdate($hash, "reject$pinName", $reject + $rejCount);
}
readingsBulkUpdate($hash, "timeDiff$pinName", $time); # these readings are used internally for calculations
readingsBulkUpdate($hash, "countDiff$pinName", $diff); # these readings are used internally for calculations
if (AttrVal($name, "verboseReadings$pinName", AttrVal($name, "verboseReadings$pin", 0))) {
readingsBulkUpdate($hash, "lastMsg$pinName", $line);
}
ArduCounter_HandleCounters($hash, $pin, $seq, $count, $time, $diff, $rDiff, $now);
readingsEndUpdate($hash, 1);
if (!$hash->{Initialized}) { # device has sent count but not Started / hello after reconnect
Log3 $name, 3, "$name: device is still counting";
if (!$hash->{WaitForHello}) { # if hello not already sent, send it now
ArduCounter_AskForHello("direct:$name");
}
RemoveInternalTimer ("sendHello:$name"); # don't send hello again
}
}
}
sub ArduCounter_HandleHistory($$$$)
{
my ($hash, $now, $pinName, $hist) = @_;
my $name = $hash->{NAME};
my @hList = split(/[, ]/, $hist);
Log3 $name, 5, "$name: HandleHistory " . ($hash->{CL} ? "client $hash->{CL}{NAME}" : "no CL");
foreach my $he (@hList) {
if ($he) {
if ($he =~ /([\d]+)s([\d-]+)\/([\d]+)@([01])(.)/) {
my ($seq, $time, $len, $level, $act) = ($1, $2, $3, $4, $5);
my $fTime = FmtDateTime($now + ($time/1000));
my $action ="";
if ($act eq "C") {$action = "count"}
elsif ($act eq "G") {$action = "gap"}
elsif ($act eq "R") {$action = "reject"}
elsif ($act eq "X") {$action = "ignore spike"}
elsif ($act eq "P") {$action = "ignore drop"}
my $histLine = sprintf ("%6s", $seq) . ' ' . $fTime . " $pinName " .
sprintf ("%7s", sprintf("%.3f", $len/1000)) . " seconds at $level -> $action";
Log3 $name, 5, "$name: HandleHistory $histLine ($he)";
$hash->{LastHistSeq} = $seq -1 if (!defined($hash->{LastHistSeq}));
$hash->{HistIdx} = 0 if (!defined($hash->{HistIdx}));
if ($seq > $hash->{LastHistSeq} || $seq < ($hash->{LastHistSeq} - 10000)) {
$hash->{History}[$hash->{HistIdx}] = $histLine;
$hash->{HistoryPin}[$hash->{HistIdx}] = $pinName;
$hash->{LastHistSeq} = $seq;
$hash->{HistIdx}++;
}
$hash->{HistIdx} = 0 if ($hash->{HistIdx} > AttrVal($name, "maxHist", 1000));
} else {
Log3 $name, 5, "$name: HandleHistory - no match for $he";
}
}
}
}
#########################################################################
sub ArduCounter_Parse($)
{
my ($hash) = @_;
my $name = $hash->{NAME};
my $retStr = "";
my @lines = split /\n/, $hash->{buffer};
my $now = gettimeofday();
foreach my $line (@lines) {
#Log3 $name, 5, "$name: Parse line: $line";
if ($line =~ /^R([\d]+)/) {
ArduCounter_ParseReport($hash, $line);
} elsif ($line =~ /^H([\d]+) (.+)/) { # pin pulse history as separate line
my $pin = $1;
my $hist = $2;
my $pinName = ArduCounter_PinName($hash, $pin);
ArduCounter_HandleHistory($hash, $now, $pinName, $hist);
if (AttrVal($name, "verboseReadings$pinName", AttrVal($name, "verboseReadings$pin", 0))) {
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "pinHistory$pinName", $hist);
readingsEndUpdate($hash, 1);
}
} elsif ($line =~ /^M Next report in ([\d]+)/) { # end of report tells when next
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 4, "$name: device: $line";
} elsif ($line =~ /^I(.*)/) { # interval config report after show/hello
$hash->{runningCfg}{I} = $1; # save for later compare
$hash->{runningCfg}{I} =~ s/\s+$//; # remove spaces at end
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 4, "$name: device sent interval config $hash->{runningCfg}{I}";
} elsif ($line =~ /^T(.*)/) { # analog threshold config report after show/hello
$hash->{runningCfg}{T} = $1; # save for later compare
$hash->{runningCfg}{T} =~ s/\s+$//; # remove spaces at end
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 4, "$name: device sent analog threshold config $hash->{runningCfg}{T}";
} elsif ($line =~ /^V(.*)/) { # devVerbose
$hash->{runningCfg}{V} = $1; # save for later compare
$hash->{runningCfg}{V} =~ s/\s+$//; # remove spaces at end
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 4, "$name: device sent devVerbose $hash->{runningCfg}{V}";
} elsif ($line =~ /^P([\d]+) (falling|rising|-) ?(pullup)? ?min ([\d]+)/) { # pin configuration at device
my $p = ($3 ? $3 : "nop");
$hash->{runningCfg}{$1} = "$2 $p $4"; # save for later compare
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 4, "$name: device sent config for pin $1: $2 $p min $4";
} elsif ($line =~ /^alive( ?RSSI ([\-\d]+))?/) { # alive response
Log3 $name, 5, "$name: device sent alive response: $line";
RemoveInternalTimer ("alive:$name");
$hash->{WaitForAlive} = 0;
delete $hash->{KeepAliveRetries};
if ($2) {
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "RSSI", $2);
readingsEndUpdate($hash, 1);
}
} elsif ($line =~ /^ArduCounter V([\d\.]+).*(Started|Hello)/) { # setup message
ArduCounter_ParseHello($hash, $line, $now);
} elsif ($line =~ /^Status: ArduCounter V([\d\.]+)/) { # response to s(how)
$retStr .= ($retStr ? "\n" : "") . $line;
} elsif ($line =~ /connection already busy/) {
my $now = gettimeofday();
my $delay = AttrVal($name, "nextOpenDelay", 60);
Log3 $name, 4, "$name: _Parse: primary tcp connection seems busy - delay next open";
ArduCounter_Disconnected($hash); # set to disconnected (state), remove timers
DevIo_CloseDev($hash); # close, remove from readyfnlist so _ready is not called again
RemoveInternalTimer ("delayedopen:$name");
InternalTimer($now+$delay, "ArduCounter_DelayedOpen", "delayedopen:$name", 0);
} elsif ($line =~ /^D (.*)/) { # debug / info Message from device
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 4, "$name: device: $1";
} elsif ($line =~ /^L *([\d]+) ?, ?([\d]+) ?, ?-> *([\d]+)/) { # analog level difference reported with details
if ($hash->{analogLevels}{$3}) {
$hash->{analogLevels}{$3}++;
} else {
$hash->{analogLevels}{$3} = 1;
}
} elsif ($line =~ /^L *([\d]+)/) { # analog level difference reported
if ($hash->{analogLevels}{$1}) {
$hash->{analogLevels}{$1}++;
} else {
$hash->{analogLevels}{$1} = 1;
}
} elsif ($line =~ /^M (.*)/) { # other Message from device
$retStr .= ($retStr ? "\n" : "") . $line;
Log3 $name, 3, "$name: device: $1";
} elsif ($line =~ /^[\s\n]*$/) {
# blank line - ignore
} else {
Log3 $name, 3, "$name: unparseable message from device: $line";
}
}
$hash->{buffer} = "";
return $retStr;
}
#########################################################################
# called from the global loop, when the select for hash->{FD} reports data
sub ArduCounter_Read($)
{
my ($hash) = @_;
my $name = $hash->{NAME};
my ($pin, $count, $diff, $power, $time, $reject, $msg);
# read from serial device
my $buf = DevIo_SimpleRead($hash);
return if (!defined($buf) );
$hash->{buffer} .= $buf;
my $end = chop $buf;
#Log3 $name, 5, "$name: Read: current buffer content: " . $hash->{buffer};
# did we already get a full frame?
return if ($end ne "\n");
ArduCounter_Parse($hash);
}
#####################################
# Called from get / set to get a direct answer
# called with logical device hash
sub ArduCounter_ReadAnswer($$)
{
my ($hash, $expect) = @_;
my $name = $hash->{NAME};
my $rin = '';
my $msgBuf = '';
my $to = AttrVal($name, "timeout", 2);
my $buf;
Log3 $name, 5, "$name: ReadAnswer called";
for(;;) {
if($^O =~ m/Win/ && $hash->{USBDev}) {
$hash->{USBDev}->read_const_time($to*1000); # set timeout (ms)
$buf = $hash->{USBDev}->read(999);
if(length($buf) == 0) {
Log3 $name, 3, "$name: Timeout in ReadAnswer";
return ("Timeout reading answer", undef)
}
} else {
if(!$hash->{FD}) {
Log3 $name, 3, "$name: Device lost in ReadAnswer";
return ("Device lost when reading answer", undef);
}
vec($rin, $hash->{FD}, 1) = 1; # setze entsprechendes Bit in rin
my $nfound = select($rin, undef, undef, $to);
if($nfound < 0) {
next if ($! == EAGAIN() || $! == EINTR() || $! == 0);
my $err = $!;
ArduCounter_Disconnected($hash); # set to disconnected, remove timers, let _ready try to reopen
Log3 $name, 3, "$name: ReadAnswer error: $err";
return("ReadAnswer error: $err", undef);
}
if($nfound == 0) {
Log3 $name, 3, "$name: Timeout2 in ReadAnswer";
return ("Timeout reading answer", undef);
}
$buf = DevIo_SimpleRead($hash);
if(!defined($buf)) {
Log3 $name, 3, "$name: ReadAnswer got no data";
return ("No data", undef);
}
}
if($buf) {
#Log3 $name, 5, "$name: ReadAnswer got: $buf";
$hash->{buffer} .= $buf;
}
my $end = chop $buf;
#Log3 $name, 5, "$name: Current buffer content: " . $hash->{buffer};
next if ($end ne "\n");
$msgBuf .= "\n" if ($msgBuf);
$msgBuf .= ArduCounter_Parse($hash);
#Log3 $name, 5, "$name: ReadAnswer msgBuf: " . $msgBuf;
if ($msgBuf =~ $expect) {
Log3 $name, 5, "$name: ReadAnswer matched $expect";
return (undef, $msgBuf);
}
}
return ("no Data", undef);
}
1;
=pod
=item device
=item summary Module for counters based on arduino / ESP8266 board
=item summary_DE Modul für Strom / Wasserzähler mit Arduino- oder ESP8266
=begin html
ArduCounter
This module implements an Interface to an Arduino or ESP8266 based counter for pulses on any input pin of an Arduino Uno, Nano, Jeenode, NodeMCU, Wemos D1 or similar device. The device connects to Fhem either through USB / serial or via tcp if an ESP board is used.
The typical use case is an S0-Interface on an energy meter or water meter, but also reflection light barriers to monitor old ferraris counters are supported
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.
The Arduino sketch that works with this module uses pin change interrupts so it can efficiently count pulses on all available input pins.
The module creates readings for pulse counts, consumption and optionally also a pin history with pulse lengths and gaps of the last pulses.
Prerequisites
-
This module requires an Arduino Uno, Nano, Jeenode, NodeMCU, Wemos D1 or similar device based on an Atmel 328p or ESP8266 running the ArduCounter sketch provided with this module
In order to flash an arduino board with the corresponding ArduCounter firmware from within Fhem, avrdude needs to be installed.
For old ferraris counters an Arduino Uno or Nano or ESP8266 board needs to be connected to a reflection light barrier
which consists simply of an infra red photo transistor (connected to A7 on Arduinos and A0 on ESP8266) and an infra red led (connected to D2 on Arduinos and to D6 on ESP8266), both with a resistor in line.
Define
define <name> ArduCounter <device>
or
define <name> ArduCounter <ip:port>
<device> specifies the serial port to communicate with the Arduino.
<ip:port> specifies the ip address and tcp port to communicate with an esp8266 where port is typically 80.
The name of the serial-device depends on your distribution.
You can also specify a baudrate for serial connections if the device name contains the @
character, e.g.: /dev/ttyUSB0@38400
The default baudrate of the ArduCounter firmware is 38400 since Version 1.4
Example:
define AC ArduCounter /dev/ttyUSB2@38400
define AC ArduCounter 192.168.1.134:80
Configuration of ArduCounter digital counters
Specify the pins where impulses should be counted e.g. as attr AC pinX falling pullup 30
The X in pinX can be an Arduino / ESP pin number with or without the letter D e.g. pin4, pinD5, pin6, pinD7 ...
After the pin you can use the keywords falling or rising to define if a logical one / 5V (rising) or a logical zero / 0V (falling) should be treated as pulse.
The optional keyword pullup activates the pullup resistor for the given Pin.
The last argument is also optional but recommended and specifies a minimal pulse length in milliseconds.
An energy meter with S0 interface is typically connected to GND and an input pin like D4.
The S0 pulse then pulls the input to 0V.
Since the minimal pulse lenght of the s0 interface is specified to be 30ms, the typical configuration for an s0 interface is
attr AC pinX falling pullup 30
Specifying a minimal pulse length is recommended since it filters bouncing of reed contacts or other noise.
Example:
define AC ArduCounter /dev/ttyUSB2
attr AC pulsesPerKWh 1000
attr AC interval 60 300
attr AC pinD4 falling pullup 5
attr AC pinD5 falling pullup 30
attr AC verboseReadingsD5
attr AC pinD6 rising
This defines three counters connected to the pins D4, D5 and D5.
D4 and D5 have their pullup resistors activated and the impulse draws the pins to zero.
For D4 and D5 the arduino measures the time in milliseconds between the falling edge and the rising edge. If this time is longer than the specified 5 or 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.
verboseReadings5 causes the module to create additional readings like the pin history which shows length and gaps between the last pulses.
For pin D6 the arduino does not check pulse lengths and counts every time when the signal changes from 0 to 1.
The ArduCounter sketch which must be loaded on the Arduino or ESP implements this using pin change interrupts,
so all avilable input pins can be used, not only the ones that support normal interrupts.
The module has been tested with 14 inputs of an Arduino Uno counting in parallel and pulses as short as 3 milliseconds.
Configuration of ArduCounter analog counters
this module and the corresponding sketch can be used to read out old analog ferraris energy counters. Therefore for an Arduino Uno or Nano board (the ESP version does not yet support analog measurements) needs to be connected to a reflection light barrier which consists simply of an infra red photo transistor (connected to A7 on Arduinos and A0 on ESP8266) and an infra red led (connected to D2 on Arduinos and to D6 on ESP8266), both with a resistor in line. The idea comes from Martin Kompf (https://www.kompf.de/tech/emeir.html) and has been adopted for ArduCounter to support old ferraris energy counters.
To support this mode, the sketch has to be compiled with analogIR defined.
The configuration is then similar to the one for digital counters:
define ACF ArduCounter /dev/ttyUSB4
attr ACF analogThresholds 100 110
attr ACF flashCommand avrdude -p atmega328P -b57600 -c arduino -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]
attr ACF interval 60 300 2 2
attr ACF pinA7 rising 20
attr ACF pulsesPerKWh 75
attr ACF stateFormat {sprintf("%.3f kW", ReadingsVal($name,"powerA7",0))}
To find out the right analog thresholds you can set devVerbose to 20 which will ask the firmware of your conting board to report every analog measurement. The ArduCounter module will count how often each value is reported and you can then query these analog level counts with get levels
. After a few turns of the ferraris disc the result of get levels
might look like this:
observed levels from analog input:
94: 21
95: 79
96: 6
97: 2
98: 3
99: 2
100: 2
101: 1
102: 3
105: 2
106: 1
108: 2
109: 1
110: 1
112: 1
113: 3
115: 4
116: 9
117: 14
118: 71
119: 103
120: 118
121: 155
122: 159
123: 143
124: 147
125: 158
126: 198
127: 249
128: 220
129: 230
130: 201
131: 140
132: 147
133: 153
134: 141
135: 119
136: 105
137: 109
138: 114
139: 83
140: 33
141: 14
142: 1
This shows the measured values together with the frequency how often the individual value has been measured. It is obvious that most measurements result in values between 120 and 135, very few values are betweem 96 and 115 and another peak is around the value 95.
It means that the when the red mark of the ferraris disc is under the sensor, the value is around 95 and while the blank disc is under the sensor, the value is typically between 120 and 135. So a good upper threshold would be 120 and a good lower threshold would be for example 96.
Set-Commands
- raw
send the value to the board so you can directly talk to the sketch using its commands.
This is not needed for normal operation but might be useful sometimes for debugging
- flash
flashes the ArduCounter firmware ArduCounter.hex from the fhem subdirectory FHEM/firmware
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]
This setting should work for a standard installation and the placeholders are automatically replaced when
the command is used. So normally there is no need to modify this attribute.
Depending on your specific Arduino board however, you might need to insert -b 57600
in the flash Command. (e.g. for an Arduino Nano)
ESP boards so far have to be fashed from the Arduino IDE. In a future version flashing over the air sould be supported.
- reset
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.
- saveConfig
stores the current interval, analog threshold and pin configuration to be stored in the EEPROM of the counter device so it can be retrieved after a reset.
- enable
sets the attribute disable to 0
- disable
sets the attribute disable to 1
- reconnect
closes the tcp connection to an ESP based counter board that is conected via TCP/IP and reopen the connection
Get-Commands
- info
send a command to the Arduino board to get current counts.
This is not needed for normal operation but might be useful sometimes for debugging
- levels
show the count for the measured levels if an analog pin is used to measure e.g. the red mark of a ferraris counter disc. This is useful for setting the thresholds for analog measurements.
- history
shows details regarding all the level changes that the counter device (Arduino or ESP) has detected and how they were used (counted or rejected)
If get history is issued with a pin name (e.g. get history D5) then only the history entries concerning D5 will be shown.
This information is sent from the device to Fhem when it reports the current count but only if devVerbose is equal or greater than 5.
The maximum number of lines that the Arducounter module stores in a ring buffer is defined by the attribute maxHist and defaults to 1000.
Attributes
- do_not_notify
- readingFnAttributes
- pin[AD]?[0-9]+
Define a pin of the Arduino or ESP board as input. This attribute expects either
rising
, falling
or change
, followed by an optional pullup
and an optional number as value.
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.
Example:
attr MyCounter pinD4 falling pullup 30
- interval normal max min mincout
Defines the parameters that affect the way counting and reporting works.
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.
In the usual operation mode (when the normal interval is smaller than the maximum interval),
the Arduino board just counts and remembers the time between the first impulse and the last impulse for each pin.
After the normal interval is elapsed the Arduino board reports the count and time for those pins where impulses were encountered.
This means that even though the normal interval might be 10 seconds, the reported time difference can be
something different because it observed impulses as starting and ending point.
The Power (e.g. for energy meters) is then calculated based of the counted impulses and the time between the first and the last impulse.
For the next interval, the starting time will be the time of the last impulse in the previous reporting period and the time difference will be taken up to the last impulse before the reporting interval has elapsed.
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.
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.
By adjusting the other numbers of this attribute this can be avoided.
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 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.
This way the counter will report a higher number of pulses counted and a larger time difference back to fhem.
Example:
attr myCounter interval 60 600 5 2
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.
- factor
Define a multiplicator for calculating the power from the impulse count and the time between the first and the last impulse.
This attribute is outdated and unintuitive so you should avoid it.
Instead you should specify the attribute pulsesPerKWh or readingPulsesPerKWh[0-9]+ (where [0-9]+ stands for the pin number).
- readingFactor[0-9]+
Override the factor attribute for this individual pin.
Just like the attribute factor, this is a rather cumbersome way to specify the pulses per kWh.
Instaed it is advised to use the attribute pulsesPerKWh or readingPulsesPerKWh[0-9]+ (where [0-9]+ stands for the pin number).
- pulsesPerKWh
specify the number of pulses that the meter is giving out per unit that sould be displayed (e.g. per kWh energy consumed). For many S0 counters this is 1000, for old ferraris counters this is 75 (rounds per kWh).
Example:
attr myCounter pulsesPerKWh 75
- readingPulsesPerKWh[0-9]+
is the same as pulsesPerKWh but specified per pin individually in case you have multiple counters with different settings at the same time
Example:
attr myCounter readingPulsesPerKWhA7 75
attr myCounter readingPulsesPerKWhD4 1000
- readingNameCount[AD]?[0-9]+
Change the name of the counter reading pinX to something more meaningful.
Example:
attr myCounter readingNameCountD4 CounterHaus_internal
- readingNameLongCount[AD]?[0-9]+
Change the name of the long counter reading longX to something more meaningful.
Example:
attr myCounter readingNameLongCountD4 CounterHaus_long
- readingNameInterpolatedCount[AD]?[0-9]+
Change the name of the interpolated long counter reading InterpolatedlongX to something more meaningful.
Example:
attr myCounter readingNameInterpolatedCountD4 CounterHaus_interpolated
- readingNameCalcCount[AD]?[0-9]+
Change the name of the real unit counter reading CalcCounterX to something more meaningful.
Example:
attr myCounter readingNameCalcCountD4 CounterHaus_kWh
- readingNamePower[AD]?[0-9]+
Change the name of the power reading powerX to something more meaningful.
Example:
attr myCounter readingNamePowerD4 PowerHaus
- readingStartTime[AD]?[0-9]+
Allow the reading time stamp to be set to the beginning of measuring intervals.
- verboseReadings[AD]?[0-9]+
create readings timeDiff, countDiff, lastMsg and pinHistory for each pin
Example:
attr myCounter verboseReadingsD4 1
- devVerbose
set the verbose level in the counting board. This defaults to 0.
If the value is >0, then the firmware will echo all commands sent to it by the Fhem module.
If the value is >=5, then the firmware will report the pin history (assuming that the firmware has been compiled with this feature enabled)
If the value is >=10, then the firmware will report every level change of a pin
If the value is >=20, then the firmware will report every analog measurement (assuming that the firmware has been compiled with analog measurements for old ferraris counters or similar).
- maxHist
specifies how many pin history lines hould be buffered for "get history".
This attribute defaults to 1000.
- analogThresholds
this Attribute is necessary when you use an arduino nano with connected reflection light barrier (photo transistor and led) to detect the red mark of an old ferraris energy counter. In this case the firmware uses an upper and lower threshold which can be set here.
Example:
attr myCounter analogThresholds 90 110
In order to find out the right threshold values you can set devVerbose to 20, wait for several turns of the ferraris disc and then use get levels
to see the typical measurements for the red mark and the blank disc.
- flashCommand
sets the command to call avrdude and flash the onnected arduino with an updated hex file (by default it looks for ArduCounter.hex in the FHEM/firmware subdirectory.
This attribute contains avrdude -p atmega328P -c arduino -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]
by default.
For an Arduino Nano based counter you should add -b 57600
e.g. between the -P and -D options.
Example:
attr myCounter flashCommand avrdude -p atmega328P -c arduino -b 57600 -P [PORT] -D -U flash:w:[HEXFILE] 2>[LOGFILE]
- keepAliveDelay
defines an interval in which the module sends keepalive messages to a counter device that is conected via tcp.
This attribute is ignored if the device is connected via serial port.
If the device doesn't reply within a defined timeout then the module closes and tries to reopen the connection.
The module tells the device when to expect the next keepalive message and the device will also close the tcp connection if it doesn't see a keepalive message within the delay multiplied by 3
The delay defaults to 10 seconds.
Example:
attr myCounter keepAliveDelay 30
- keepAliveTimeout
defines the timeout when wainting for a keealive reply (see keepAliveDelay)
The timeout defaults to 2 seconds.
Example:
attr myCounter keepAliveTimeout 3
- keepAliveRetries
defines how often sending a keepalive is retried before the connection is closed and reopened.
It defaults to 2.
Example:
attr myCounter keepAliveRetries 3
- nextOpenDelay
defines the time that the module waits before retrying to open a disconnected tcp connection.
This defaults to 60 seconds.
Example:
attr myCounter nextOpenDelay 20
- openTimeout
defines the timeout after which tcp open gives up trying to establish a connection to the counter device.
This timeout defaults to 3 seconds.
Example:
attr myCounter openTimeout 5
- silentReconnect
if set to 1, then it will set the loglevel for "disconnected" and "reappeared" messages to 4 instead of 3
Example:
attr myCounter silentReconnect 1
- disable
if set to 1 then the module closes the connection to a counter device.
Readings / Events
The module creates at least the following readings and events for each defined pin:
- pin.* e.g. pinD4
the current internal count at this pin (internal to the Arduino / ESP device, starts at 0 when the device restarts).
The name of this reading can be changed with the attribute readingNameCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
- long.* e.g. longD5
long count which keeps on counting up after fhem restarts whereas the pin.* count is only a temporary internal count that starts at 0 when the arduino board starts.
The name of this reading can be changed with the attribute readingNameLongCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
- interpolatedLong.*
like long.* but when the Arduino restarts the potentially missed pulses are interpolated based on the pulse rate before the restart and after the restart.
The name of this reading can be changed with the attribute readingNameInterpolatedCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
- reject.*
counts rejected pulses that are shorter than the specified minimal pulse length.
- power.*
the current calculated power at this pin.
The name of this reading can be changed with the attribute readingNamePower[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
- calcCounter.*
similar to long count which keeps on counting up after fhem restarts but this counter will take the pulses per kWh setting into the calculation und thus not count count pulses but real kWh (or some other unit that is applicable)
The name of this reading can be changed with the attribute readingNameCalcCount[AD]?[0-9]+ where [AD]?[0-9]+ stands for the pin description e.g. D4
- pinHistory.*
shows detailed information of the last pulses. This is only available when a minimal pulse length is specified for this pin. Also the total number of impulses recorded here is limited to 20 for all pins together. The output looks like -36/7:0C, -29/7:1G, -22/8:0C, -14/7:1G, -7/7:0C, 0/7:1G
The first number is the relative time in milliseconds when the input level changed, followed by the length in milliseconds, the level and the internal action.
-36/7:0C for example means that 36 milliseconds before the reporting started, the input changed to 0V, stayed there for 7 milliseconds and this was counted.
- countDiff.*
delta of the current count to the last reported one. This is used together with timeDiff.* to calculate the power consumption.
- timeDiff.*
time difference between the first pulse in the current observation interval and the last one. Used togehter with countDiff to calculate the power consumption.
- seq.*
internal sequence number of the last report from the board to Fhem.
=end html
=cut