fhemdb_get.pl 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/perl
  2. #
  3. ################################################################
  4. #
  5. # Copyright notice
  6. #
  7. # (c) 2007 Copyright: Dr. Boris Neubert (omega at online dot de)
  8. # All rights reserved
  9. #
  10. # This script free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # The GNU General Public License can be found at
  16. # http://www.gnu.org/copyleft/gpl.html.
  17. # A copy is found in the textfile GPL.txt and important notices to the license
  18. # from the author is found in LICENSE.txt distributed with these scripts.
  19. #
  20. # This script is distributed in the hope that it will be useful,
  21. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. # GNU General Public License for more details.
  24. #
  25. # This copyright notice MUST APPEAR in all copies of the script!
  26. #
  27. ################################################################
  28. #
  29. # this script returns the current reading for a device stored in
  30. # the fhem logging database
  31. #
  32. # Usage:
  33. # fhemdb_get.pl <device> <reading> [<reading> ...]
  34. # Example:
  35. # fhemdb_get.pl ext.ks300 temperature humidity
  36. #
  37. #
  38. #
  39. # global configuration
  40. #
  41. my $dbconn = "mysql:database=fhem;host=db;port=3306";
  42. my $dbuser = "fhemuser";
  43. my $dbpassword = "fhempassword";
  44. #
  45. # nothing to change below this line
  46. #
  47. use strict;
  48. use warnings;
  49. use DBI;
  50. (@ARGV>=2) || die "Usage: fhemdb_get.pl <device> <reading> [<reading> ... ]";
  51. my $device= $ARGV[0];
  52. my @readings=@ARGV; shift @readings;
  53. my $set= join(",", map({"\'" . $_ . "\'"} @readings));
  54. my $dbh= DBI->connect_cached("dbi:$dbconn", $dbuser, $dbpassword) ||
  55. die "Cannot connect to $dbconn: $DBI::errstr";
  56. my $stm= "SELECT READING, VALUE FROM current WHERE
  57. (DEVICE='$device') AND
  58. (READING IN ($set))";
  59. my $sth= $dbh->prepare($stm) ||
  60. die "Cannot prepare statement $stm: $DBI::errstr";
  61. my $rc= $sth->execute() ||
  62. die "Cannot execute statement $stm: $DBI::errstr";
  63. my %rs;
  64. my $reading;
  65. my $value;
  66. while( ($reading,$value)= $sth->fetchrow_array) {
  67. $rs{$reading}= $value;
  68. }
  69. foreach $reading (@readings) {
  70. $value= $rs{$reading};
  71. $value= "NULL" if(!defined($value));
  72. print "$reading:$value ";
  73. }
  74. print "\n";
  75. die $sth->errstr if $sth->err;
  76. $dbh->disconnect();