Added clockyconfig.py for better config file handling. (also conftest.py to test this)

This commit is contained in:
Jan
2019-09-25 11:28:03 +02:00
parent 930a517982
commit e65eadb2d0
2 changed files with 183 additions and 0 deletions

116
clockyconfig.py Normal file
View File

@@ -0,0 +1,116 @@
#!/usr/bin/python
import json
import os
import time
import copy
CONFIGFILEVERSION="1.0"
class ClockyConfig:
"""Read/write clocky config files."""
def __init__(self,filename,verbose=0):
"""Open existing Clocky config file and read config data. If no file can be found create a new one with default values."""
self.filename=filename
self.__verbose=verbose
if os.access(self.filename,os.R_OK):
self.__Read()
else:
self.__data={}
self.__data["clocky"]={}
self.__data["clocky"]["CONFIGFILEVERSION"]=CONFIGFILEVERSION
self.__data["clocky"]["settings"]={}
self.__data["clocky"]["settings"]["alarmtime"]="9:00"
self.__data["clocky"]["settings"]["alarmdisabled"]=0
self.__data["clocky"]["settings"]["maxalarmtime"]=30
self.__data["clocky"]["settings"]["snoozetime"]=9
self.__data["clocky"]["settings"]["playmode"]="random"
self.__data["clocky"]["tracks"]={}
self.__data["clocky"]["starttrack"]=0
self.__data["clocky"]["tracklist"]=[]
self.__data["clocky"]["tracksequence"]=[]
self.__Write()
if(self.__verbose):
print("Created new config file called \"%s\"" %self.filename)
def __Read(self):
"""Internal function to do the actual reading of file in to config"""
with open(self.filename) as json_data_file:
self.__data = json.load(json_data_file)
if(self.__data["clocky"]["version"] != CONFIGFILEVERSION):
print ("ERROR: configfile \""+self.filename+"\" CONFIGFILEVERSION ("+self.__data["clocky"]["version"]+") does not match program CONFIGFILEVERSION ("+CONFIGFILEVERSION+")!")
exit();
self.__readdata=copy.deepcopy(self.__data)
self.__timestamp=os.stat(self.filename).st_mtime
self.settings=self.__data["clocky"]["settings"]
self.starttrack=self.__data["clocky"]["starttrack"]
self.tracklist=self.__data["clocky"]["tracklist"]
self.sequence=self.__data["clocky"]["tracksequence"]
def __Write(self):
"""Internal function to do the actual writing of data into file"""
with open(self.filename,"w") as json_data_file:
json.dump(self.__data,json_data_file)
self.__readdata=copy.deepcopy(self.__data)
self.__timestamp=os.stat(self.filename).st_mtime
self.settings=self.__data["clocky"]["settings"]
self.starttrack=self.__data["clocky"]["starttrack"]
self.tracklist=self.__data["clocky"]["tracklist"]
self.sequence=self.__data["clocky"]["tracksequence"]
def Print(self):
"""Print current config data in human readable format"""
print("--ClockyConfig-------------")
print("filename =",self.filename)
print("CONFIGFILEVERSION =",self.__data["clocky"]["version"])
for x in self.__data["clocky"]["settings"].keys():
print("%-14s= %s" %(x,self.__data["clocky"]["settings"][x]))
print("...........................")
print("starttrack =",self.__data["clocky"]["starttrack"])
nrtracks=len(self.__data["clocky"]["tracklist"])
print ("%d Tracks:" %nrtracks)
for str in self.__data["clocky"]["tracklist"]:
print(" "+str)
print("%d sequence items:" %(len(self.__data["clocky"]["tracksequence"])) )
for num in self.__data["clocky"]["tracksequence"]:
if num<nrtracks:
print(" %d -> %s" %(num,self.__data["clocky"]["tracklist"][num]) )
else:
print(" %d UNKNOWN TRACK" %num)
print("---------------------------")
def Dump(self):
"""Dump current config data in json format"""
print(self.__data)
def CheckConfig(self):
"""Check if config file has changed or removed since reading, or if the settings have changed.
Re-write or Re-read when necessary"""
if not os.access(self.filename,os.R_OK):
self.__Write()
if(self.__verbose):
print("Re-write settings because of file removal!")
self.Print()
elif(os.stat(self.filename).st_mtime != self.__timestamp):
self.__Read()
if(self.__verbose):
print("Re-read settings because of config file change!")
self.Print()
if(self.__data != self.__readdata):
self.__Write()
if(self.__verbose):
print("Re-write settings because of settings change!")
self.Print()

67
conftest.py Normal file
View File

@@ -0,0 +1,67 @@
#!/usr/bin/python
import json
import os
import time
import copy
import clockyconfig
class Tracklist:
def __init__(self,path="."):
self.path=path
self.tracklist=[]
self.count=0
olddir=os.getcwd()
if(self.path != '.'):
if(not os.path.isdir(self.path)):
print("ERROR: \""+self.path+"\" is not an existing directory")
exit();
os.chdir(self.path)
for ent in os.listdir():
if ent.lower().endswith(".mp3") and os.access(ent,os.R_OK):
self.tracklist.append(ent)
self.count+=1
self.tracklist.sort()
os.chdir(olddir)
def Show(self):
print("Tracklist.path = %s" %self.path)
print("Tracklist.count= %d" %self.count)
print("Tracks:")
for track in self.tracklist:
print (" "+track)
config=clockyconfig.ClockyConfig("clocky.jso")
config.Print()
tl=Tracklist("m")
tl.Show()
if (tl.tracklist == config.tracklist):
print("Same!")
else:
print("diff")
a=0
t=0
while True:
t+=1
config.CheckConfig()
time.sleep(1)
a+=1
if(a>5):
config.settings["alarmdisabled"]=1-config.settings["alarmdisabled"]
print(config.settings["alarmdisabled"])
a=0
if(t>30):
break
tracklist=Tracklist()
#tracklist.Read("old")
#tracklist.Show()