temps.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/python
  2. __author__ = "Kruz, Wazakindjes"
  3. __copyright__ = "Jem0eder Inc."
  4. __version__ = "2.0.0"
  5. import argparse
  6. import ConfigParser
  7. import MySQLdb
  8. import os
  9. import sys
  10. import time
  11. # Some "constants" lol
  12. RET_GUCCI = 0
  13. RET_ERR_CONF = 1
  14. RET_ERR_SENSOR = 2
  15. # Globals y0
  16. muhconf = {}
  17. def printem(txt):
  18. # Because apparently we need to flush after every print to ensure it happens in real-time -.-
  19. print txt
  20. sys.stdout.flush()
  21. def show_version():
  22. printem("temps v{0}, written by: {1}".format(__version__, __author__))
  23. def readem_conf():
  24. err = False
  25. try:
  26. cfg = ConfigParser.ConfigParser()
  27. cfg.read("{0}/muhconf.ini".format(os.path.dirname(os.path.realpath(__file__))))
  28. ### [main] section BEGIN
  29. # Booleans first
  30. for main_boolopt in ["debug"]:
  31. muhconf[main_boolopt] = cfg.getboolean("main", main_boolopt)
  32. # Integers next
  33. for main_intopt in ["sample_maxattempts"]:
  34. optval = cfg.getint("main", main_intopt)
  35. # Should prolly restrict it to 30 attempts, anything more seems way too excessive ;];];]
  36. if main_intopt == "sample_maxattempts" and (optval <= 0 or optval > 30):
  37. printem("Invalid value '{0}' for option '{1}': must be in the range of 1-30".format(optval, main_intopt))
  38. err = True
  39. continue
  40. muhconf[main_intopt] = optval
  41. # Multiple string values last
  42. for main_stropt_multi in ["sensor"]:
  43. optval_multi = cfg.get("main", main_stropt_multi).split("\n")
  44. for optval in optval_multi:
  45. # Even though sensor is currently the only option, let's set it up for easy expansion laturd anyways ;]
  46. if main_stropt_multi == "sensor" and "/" in optval:
  47. printem("Invalid value '{0}' for option '{1}': may not contain a slash".format(optval, main_stropt_multi))
  48. err = True
  49. continue
  50. muhconf[main_stropt_multi] = optval_multi
  51. ### [main] section END
  52. ### [mysql] section BEGIN
  53. # Booleans first
  54. for mysql_boolopt in ["tls"]:
  55. muhconf[mysql_boolopt] = cfg.getboolean("mysql", mysql_boolopt)
  56. # Integers next
  57. for mysql_intopt in ["port"]:
  58. optval = cfg.getint("mysql", mysql_intopt)
  59. if mysql_intopt == "port" and (optval <= 0 or optval > 65535):
  60. printem("Invalid value '{0}' for option '{1}': must be in the range of 1-65535".format(optval, mysql_intopt))
  61. err = True
  62. continue
  63. muhconf[mysql_intopt] = optval
  64. # String values last
  65. for mysql_stropt in ["host", "user", "pass", "db", "table", "column"]:
  66. muhconf[mysql_stropt] = cfg.get("mysql", mysql_stropt)
  67. ### [mysql] section END
  68. except KeyboardInterrupt:
  69. printem("\nCTRL + C")
  70. sys.exit(RET_GUCCI)
  71. except:
  72. exc_info = sys.exc_info()
  73. printem("\nRIP config ({0}): {1}".format(exc_info[0], exc_info[1]))
  74. sys.exit(RET_ERR_CONF)
  75. if err:
  76. printem("Invalid config, not proceeding")
  77. sys.exit(RET_ERR_CONF)
  78. def readem_temp():
  79. avgtemperatures = []
  80. try:
  81. if muhconf["debug"]:
  82. printem("Connecting to MySQL lol")
  83. if muhconf["tls"]:
  84. db = MySQLdb.connect(host=muhconf["host"], port=muhconf["port"], user=muhconf["user"], passwd=muhconf["pass"], db=muhconf["db"], ssl={'cipher': 'AES256-SHA'})
  85. else:
  86. db = MySQLdb.connect(host=muhconf["host"], port=muhconf["port"], user=muhconf["user"], passwd=muhconf["pass"], db=muhconf["db"])
  87. cur = db.cursor()
  88. if muhconf["debug"]:
  89. printem("Connected y0")
  90. for sensor in muhconf["sensor"]:
  91. if muhconf["debug"]:
  92. printem("\tSensor: {0}".format(sensor))
  93. temperatures = []
  94. text = '';
  95. for i in range(1, 6): # Goes _up to_ 6 so the last iteration is i == 5 ;]
  96. text = '';
  97. attempts = 0
  98. while text.split("\n")[0].find("YES") == -1:
  99. if attempts >= muhconf["sample_maxattempts"]:
  100. plural = "s" if attempts > 1 else ""
  101. if muhconf["debug"]:
  102. printem("Ayyy rip readem_temp(): unable to read temperature after {0} attempt{1} (sample #{2})".format(attempts, plural, i))
  103. else:
  104. # Non-debug mode doesn't print the sensor name at an earlier point, so let's make it clear here ;;]];];
  105. printem("Ayyy rip readem_temp(): unable to read temperature for sensor {0} after {1} attempt{2} (sample #{3})".format(sensor, attempts, plural, i))
  106. sys.exit(RET_ERR_SENSOR)
  107. if attempts > 0:
  108. time.sleep(1)
  109. # Contents of the file should be something leik dis:
  110. # 79 01 80 80 7f ff 7f 80 02 : crc=02 YES
  111. # 79 01 80 80 7f ff 7f 80 02 t=23562
  112. tfile = open("/sys/bus/w1/devices/{0}/w1_slave".format(sensor))
  113. text = tfile.read()
  114. tfile.close()
  115. attempts += 1
  116. secondline = text.split("\n")[1]
  117. temperaturedata = secondline.split(" ")[9]
  118. temperature = float(temperaturedata[2:]) / 1000
  119. temperatures.append(temperature)
  120. if muhconf["debug"]:
  121. printem("\t\tSample #{0}: {1}".format(i, temperature))
  122. avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
  123. cur.execute("INSERT INTO `{0}` (`{1}`) VALUES ({2})".format(muhconf["table"], muhconf["column"], avgtemperatures[0]))
  124. db.commit()
  125. except KeyboardInterrupt:
  126. printem("\nCTRL + C")
  127. sys.exit(RET_GUCCI)
  128. except SystemExit:
  129. pass
  130. except:
  131. printem("\nFAT RIP: {0}".format(sys.exc_info()[0]))
  132. sys.exit(RET_ERR_SENSOR)
  133. if __name__ == "__main__":
  134. # Read config first lol
  135. readem_conf()
  136. # Then parse args imo tbh
  137. p = argparse.ArgumentParser()
  138. p.add_argument('--debug', help='force debug mode (current setting from config: {0})'.format(muhconf["debug"]), action='store_true')
  139. p.add_argument('--version', help='print version and exit lol', action='store_true')
  140. args, noargs = p.parse_known_args() # noargs contains the 'topkek' in: ./temps.py --debug topkek
  141. if args.version:
  142. show_version()
  143. sys.exit(RET_GUCCI)
  144. if args.debug:
  145. muhconf["debug"] = True
  146. if muhconf["debug"]:
  147. printem("Reading em temp")
  148. readem_temp()
  149. sys.exit(RET_GUCCI) # Let's do an explicit exit w/ code imo tbh famlamlaml