Browse Source

Added config file shit lol

Wazakindjes 1 year ago
parent
commit
e68d879102
2 changed files with 139 additions and 34 deletions
  1. 17 0
      muhconf.ini.example
  2. 122 34
      temps.py

+ 17 - 0
muhconf.ini.example

@@ -0,0 +1,17 @@
+[main]
+debug = false
+
+# Specify the sensor's sysfs directory (should be /sys/bus/w1/devices/<SENSOR>/w1_slave)
+# If you have multiple sensors simply specify multuple "sensor = xxx" lines ;]
+sensor = 28-02155265b0ff
+
+[mysql]
+# Should be obvious lmao
+host = 127.0.0.1
+port = 3306
+user = ayylmao
+pass = gottem
+db = turds
+table = temperature
+column = temp
+tls = true

+ 122 - 34
temps.py

@@ -1,43 +1,131 @@
 #!/usr/bin/python
+import ConfigParser
 import MySQLdb
+import os
+import sys
 import time
-#import sys
-
-sensorids = ["28-02155265b0ff"]
-avgtemperatures = []
-
-try:
-	#print 'Connecting.'
-	#sys.stdout.flush()
-	db = MySQLdb.connect(host='topkeks',
-						 port=3306,
-						 user='topkeks',
-						 passwd='topkeks',
-						 db='topkeks',
-						 ssl={'cipher': 'AES256-SHA'})
-	cur = db.cursor()
-	#print 'Connected.'
-	#sys.stdout.flush()
-	
-	for sensor in range(len(sensorids)):
-		temperatures = []
-		for i in range(0,5):
+
+muhconf = {}
+
+def printem(txt):
+	print txt
+	sys.stdout.flush()
+
+def readem_conf():
+	err = False
+
+	try:
+		cfg = ConfigParser.ConfigParser()
+		cfg.read("{0}/muhconf.ini".format(os.path.dirname(os.path.realpath(__file__))))
+
+		### [main] section
+		for main_boolopt in ["debug"]:
+			muhconf[main_boolopt] = cfg.getboolean("main", main_boolopt)
+
+
+		for main_stropt_multi in ["sensor"]:
+			optval_multi = cfg.get("main", main_stropt_multi).split("\n")
+
+			for optval in optval_multi:
+				if main_stropt_multi == "sensor" and "/" in optval:
+					printem("Invalid value '{0}' for option '{1}': may not contain a slash".format(optval, main_stropt_multi))
+					err = True
+					continue
+
+			muhconf[main_stropt_multi] = optval_multi
+
+
+		### [mysql] section
+		for mysql_boolopt in ["tls"]:
+			muhconf[mysql_boolopt] = cfg.getboolean("mysql", mysql_boolopt)
+
+		for mysql_intopt in ["port"]:
+			optval = cfg.getint("mysql", mysql_intopt)
+
+			if mysql_intopt == "port" and (optval <= 0 or optval > 65535):
+				printem("Invalid value '{0}' for option '{1}': must be in the range of 1-65535".format(optval, mysql_intopt))
+				err = True
+				continue
+
+			muhconf[mysql_intopt] = optval
+
+		for mysql_stropt in ["host", "user", "pass", "db", "table", "column"]:
+			muhconf[mysql_stropt] = cfg.get("mysql", mysql_stropt)
+
+
+	except KeyboardInterrupt:
+		printem("CTRL + C")
+
+	except:
+		exc_info = sys.exc_info()
+		printem("RIP config ({0}): {1}".format(exc_info[0], exc_info[1]))
+		sys.exit(1)
+
+	if err:
+		printem("Invalid config, not proceeding")
+		sys.exit(1)
+
+def readem_temp():
+	avgtemperatures = []
+
+	try:
+		if muhconf["debug"]:
+			printem("Connecting lol")
+
+		if muhconf["tls"]:
+			db = MySQLdb.connect(host=muhconf["host"], port=muhconf["port"], user=muhconf["user"], passwd=muhconf["pass"], db=muhconf["db"], ssl={'cipher': 'AES256-SHA'})
+		else:
+			db = MySQLdb.connect(host=muhconf["host"], port=muhconf["port"], user=muhconf["user"], passwd=muhconf["pass"], db=muhconf["db"])
+
+		cur = db.cursor()
+		if muhconf["debug"]:
+			printem("Connected y0")
+
+		for sensor in muhconf["sensor"]:
+			if muhconf["debug"]:
+				printem("\tSensor: {0}".format(sensor))
+			temperatures = []
+			text = '';
+			for i in range(1, 6):
+				if muhconf["debug"]:
+					printem("\t\tPass: {0}".format(i))
 				text = '';
+				attempts = 0
 				while text.split("\n")[0].find("YES") == -1:
-						tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave")
-						text = tfile.read()
-						tfile.close()
-						time.sleep(1)
-						
+					# Contents of the file should be something leik dis:
+					# 79 01 80 80 7f ff 7f 80 02 : crc=02 YES
+					# 79 01 80 80 7f ff 7f 80 02 t=23562
+
+					tfile = open("/sys/bus/w1/devices/{0}/w1_slave".format(sensor))
+					text = tfile.read()
+					tfile.close()
+
+					attempts += 1
+					if attempts == 30:
+						printem("\nAyyy rip readem_temp(): unable to read temperature (pass #{0}) after {1} attempts".format(i, attempts))
+						sys.exit(2)
+
+					time.sleep(1)
+
 				secondline = text.split("\n")[1]
 				temperaturedata = secondline.split(" ")[9]
 				temperature = float(temperaturedata[2:])
 				temperatures.append(temperature / 1000)
-				
-		avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
-
-	cur.execute("INSERT INTO `topkeks` (temp) VALUES ({0})".format(avgtemperatures[0]))
-	db.commit()
-	
-except KeyboardInterrupt:
-	print '\nCTRL + C'
+
+			avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
+
+		cur.execute("INSERT INTO `{0}` (`{1}`) VALUES ({2})".format(muhconf["table"], muhconf["column"], avgtemperatures[0]))
+		db.commit()
+
+	except KeyboardInterrupt:
+		printem("\nCTRL + C")
+
+	except:
+		printem("\nFAT RIP: {0}".format(sys.exc_info()[0]))
+		sys.exit(2)
+
+if __name__ == "__main__":
+	readem_conf()
+	if muhconf["debug"]:
+		printem("Reading em temp")
+	readem_temp()