import os import requests from configparser import ConfigParser class GarageUpdater: def __init__(self, configFile): config = ConfigParser() config.read(configFile) self.uri = config['garage'].get('uri') self.garageTempFile = 'garage.tmp' self.garageFile = 'garage.json' self.persistGarageState('{"error": "init"}') def updateGarageState(self): try: state = self.getGarageState() self.persistGarageState(state) except Exception as e: print(e, flush=True) self.persistGarageState('{"error": "exception"}') def clearGarageState(self): self.persistGarageState('{"error": "halted"}') def getGarageState(self): return requests.get(self.uri, timeout=3).text def persistGarageState(self, state): with open(self.garageTempFile, 'w') as file: file.write(state) os.replace(self.garageTempFile, self.garageFile)