Browse Source

Added dryrun mode (don't insert to SQL, do everything else as usual) and try_db_cleanup() function to try and cleanly shutdown the SQL connection [==[[=

Wazakindjes 1 year ago
parent
commit
4ea3a0881c
1 changed files with 36 additions and 8 deletions
  1. 36 8
      temps.py

+ 36 - 8
temps.py

@@ -23,6 +23,19 @@ def printem(txt):
 	print txt
 	sys.stdout.flush()
 
+def try_db_cleanup(db, cursor):
+	# Some objects may not exist and perhaps db does but not cursor, hence 2 different try blocks ;]
+	# It shouldn't really be a problem if we quit before closing the connection, but it *is* good practice to close em cleanly
+	try:
+		cursor.close()
+	except:
+		pass
+
+	try:
+		db.close()
+	except:
+		pass
+
 def show_version():
 	printem("temps v{0}, written by: {1}".format(__version__, __author__))
 
@@ -35,7 +48,7 @@ def readem_conf():
 
 		### [main] section BEGIN
 		# Booleans first
-		for main_boolopt in ["debug"]:
+		for main_boolopt in ["debug", "dryrun"]:
 			muhconf[main_boolopt] = cfg.getboolean("main", main_boolopt)
 
 		# Integers next
@@ -101,16 +114,19 @@ def readem_conf():
 def readem_temp():
 	avgtemperatures = []
 
+	db = None
+	cursor = None
+
 	try:
 		if muhconf["debug"]:
 			printem("Connecting to MySQL 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'})
+			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()
+		cursor = db.cursor()
 		if muhconf["debug"]:
 			printem("Connected y0")
 
@@ -119,7 +135,6 @@ def readem_temp():
 				printem("\tSensor: {0}".format(sensor))
 
 			temperatures = []
-			text = '';
 			for i in range(1, 6): # Goes _up to_ 6 so the last iteration is i == 5 ;]
 				text = '';
 				attempts = 0
@@ -134,6 +149,7 @@ def readem_temp():
 						sys.exit(RET_ERR_SENSOR)
 
 					if attempts > 0:
+						# The sensor needs a 1 second recalibration time
 						time.sleep(1)
 
 					# Contents of the file should be something leik dis:
@@ -154,18 +170,26 @@ def readem_temp():
 
 			avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
 
-		cur.execute("INSERT INTO `{0}` (`{1}`) VALUES ({2})".format(muhconf["table"], muhconf["column"], avgtemperatures[0]))
-		db.commit()
+		if not muhconf["dryrun"]:
+			if muhconf["debug"]:
+				printem("\t\tInserting average: {0}".format(avgtemperatures[0]))
+			cursor.execute("INSERT INTO `{0}` (`{1}`) VALUES ({2})".format(muhconf["table"], muhconf["column"], avgtemperatures[0]))
+			db.commit()
+
+		try_db_cleanup(db, cursor)
 
 	except KeyboardInterrupt:
 		printem("\nCTRL + C")
+		try_db_cleanup(db, cursor)
 		sys.exit(RET_GUCCI)
 
 	except SystemExit:
+		try_db_cleanup(db, cursor)
 		pass
 
 	except:
 		printem("\nFAT RIP: {0}".format(sys.exc_info()[0]))
+		try_db_cleanup(db, cursor)
 		sys.exit(RET_ERR_SENSOR)
 
 if __name__ == "__main__":
@@ -174,8 +198,9 @@ if __name__ == "__main__":
 
 	# Then parse args imo tbh
 	p = argparse.ArgumentParser()
-	p.add_argument('--debug', help='force debug mode (current setting from config: {0})'.format(muhconf["debug"]), action='store_true')
-	p.add_argument('--version', help='print version and exit lol', action='store_true')
+	p.add_argument("--debug", help="force debug mode (current setting from config: {0})".format(muhconf["debug"]), action="store_true")
+	p.add_argument("--dryrun", help="do almost everything as usual (connect to SQL, read temperature) but don't actually insert into the database (current setting from config: {0})".format(muhconf["dryrun"]), action="store_true")
+	p.add_argument("--version", help="print version and exit lol", action="store_true")
 	args, noargs = p.parse_known_args() # noargs contains the 'topkek' in: ./temps.py --debug topkek
 
 	if args.version:
@@ -185,6 +210,9 @@ if __name__ == "__main__":
 	if args.debug:
 		muhconf["debug"] = True
 
+	if args.dryrun:
+		muhconf["dryrun"] = True
+
 	if muhconf["debug"]:
 		printem("Reading em temp")
 	readem_temp()