def setNeoPixel(self, doChase, input_queue, *args): light_arg = 0 if args is not None: for arg in args: light_arg = arg logger = logging.getLogger("main.max.setNeoPixel") logger.info("Setting NeoPixel Lights") cube_state, vera_state, boiler_enabled, interval, boiler_override, rooms_Ok = Variables( ).readVariables([ 'CubeOK', 'VeraOK', 'BoilerEnabled', 'Interval', 'BoilerOverride', 'RoomsCorrect' ]) heating_state = DbUtils().getBoiler()[2] # overide CubeState if rooms wrong if not rooms_Ok: cube_state = 2 sendString = '%s,%s,%s,%s,%s,%s,%s,%s\n\r' % ( doChase, heating_state, interval, boiler_enabled, cube_state, vera_state, boiler_override, light_arg) logger.info("Sending NeoPixel %s" % sendString) input_queue.put(sendString)
def maxCmd_H(self, line): """ process H response """ line = line.split(',') serialNumber = line[0][2:] rfChannel = line[1] maxId = line[2] dutyCycle = int(line[5], 16) maxDetails['serialNumber'] = serialNumber maxDetails['rfChannel'] = rfChannel maxDetails['maxId'] = maxId msg = (maxId, serialNumber, rfChannel, dutyCycle) DbUtils().updateCube(msg)
def __init__(self): #Initialise the Logger logLevel = Variables().readVariables(['LoggingLevel']).rstrip('\r') useNeoPixel = Variables().readVariables(['UseNeoPixel']) self.logger = logging.getLogger("main") level = logging.getLevelName(logLevel) self.logger.setLevel(level) fh = RotatingFileHandler("heating.log", maxBytes=1000000, # 1Mb I think backupCount=5) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) self.logger.addHandler(fh) self.logger.info("Main has started __init__ has run logger level is %s" % logLevel) try: cube = DbUtils().getCubes() self.logger.info("Database OK cube %s found" % (cube[1])) except Exception, err: DbUtils().initialiseDB() self.logger.exception("Database Initialised %s" % err)
def updateRoom(self, roomData): self.logger = logging.getLogger("main.sendmessage.updateRoom") self.logger.info("Updating rooms") roomList = DbUtils().getRooms() self.logger.debug("roomList %s" % roomList) self.logger.debug("roomData %s" % roomData) roomSplit = roomData.split('?') mode = roomSplit[1].replace('%20', ' ') room = roomSplit[2].replace('%20', ' ') temp = roomSplit[3].replace('%20', ' ') self.logger.debug("room %s mode %s temp %s" % (room, mode, temp)) if mode == 'eco': for rooms in roomList: sCommand = self.s_Command(rooms[2], rooms[0], 'none', 0.0) self.logger.debug("eco sCommand %s" % sCommand) self.sendMAX(sCommand) time.sleep(0.8) if mode == 'ECO': for rooms in roomList: if room == rooms[1]: sCommand = self.s_Command(rooms[2], rooms[0], 'none', 0.0) self.logger.debug("ECO sCommand %s" % sCommand) self.sendMAX(sCommand) elif mode == 'auto': for rooms in roomList: sCommand = self.s_Command(rooms[2], rooms[0], 'AUTO', 0.0) self.logger.debug("auto sCommand %s" % sCommand) self.sendMAX(sCommand) time.sleep(0.8) else: # For standard room change for rooms in roomList: if room == rooms[1]: sCommand = self.s_Command( rooms[2], rooms[0], mode, temp) # rf address,room Number, mode, temp self.logger.debug("standard sCommand %s" % sCommand) self.sendMAX(sCommand) CreateUIPage().updateWebUI()
def setStatusLights(): cube_state, vera_state, boiler_enabled, local_relay = Variables( ).readVariables( ['CubeOK', 'VeraOK', 'BoilerEnabled', 'ManualHeatingSwitch']) heating_state = DbUtils().getBoiler()[2] module_logger.info("setting status lights") if cube_state: GPIO.output(C_OK, GPIO.HIGH) GPIO.output(C_ERR, GPIO.LOW) else: GPIO.output(C_OK, GPIO.LOW) GPIO.output(C_ERR, GPIO.HIGH) # Set Vera Lights if vera_state: GPIO.output(V_OK, GPIO.HIGH) GPIO.output(V_ERR, GPIO.LOW) else: GPIO.output(V_OK, GPIO.LOW) GPIO.output(V_ERR, GPIO.HIGH) # Set Heating State if heating_state: GPIO.output(H_ON, GPIO.HIGH) GPIO.output(H_OFF, GPIO.LOW) if local_relay: module_logger.info("Switching local relay") GPIO.output(BOILER_SW, GPIO.LOW) # Pull down Relay to switch on. else: GPIO.output(H_ON, GPIO.LOW) GPIO.output(H_OFF, GPIO.HIGH) if local_relay: module_logger.info("Switching local relay") GPIO.output(BOILER_SW, GPIO.HIGH) # Set Boiler State if boiler_enabled: GPIO.output(B_OFF, GPIO.LOW) else: GPIO.output(B_OFF, GPIO.HIGH) module_logger.info("Starting flashing boiler light")
import sys #for exit import base64 import datetime import time import requests import threading from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from webtest import MyRequestHandler from database import DbUtils from kioskui import CreateUIPage CUI = CreateUIPage() DB = DbUtils() maxDetails = {} rooms = {} devices = {} valves = {} valveList = [] message = "" validData = False veraControl = "{}/data_request?id=lu_action&output_format=xml&DeviceNum={}&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue={}" boilerOn = 0 weekDays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ]
def switchHeat(self): module_logger.info("main.max.switchHeat running") logTime = time.time() boilerEnabled, veraControl, Vera_Address, Vera_Port, \ Vera_Device, singleRadThreshold, multiRadThreshold, \ multiRadCount, AllValveTotal, ManualHeatingSwitch, boilerOverride = Variables().readVariables(['BoilerEnabled', 'VeraControl', 'VeraIP', 'VeraPort', 'VeraDevice', 'SingleRadThreshold', 'MultiRadThreshold', 'MultiRadCount', 'AllValveTotal', 'ManualHeatingSwitch', 'BoilerOverride']) roomTemps = CreateUIPage().createRooms() outsideTemp = self.getCurrentOutsidetemp() # Add outside temp to each rooms information for i in range(len(roomTemps)): roomTemps[i] = roomTemps[i] + (str(outsideTemp), ) # Calculate if heat is required valveList = [] for room in roomTemps: valveList.append(room[4]) singleRadOn = sum(i >= singleRadThreshold for i in valveList) multiRadOn = sum(i >= multiRadThreshold for i in valveList) totalRadOn = sum(valveList) if singleRadOn >= 1 or multiRadOn >= multiRadCount or totalRadOn >= AllValveTotal: boilerState = 1 else: boilerState = 0 # Boiler Override if boilerOverride == 1: module_logger.info('Boiler overridden ON') boilerState = 1 if boilerOverride == 0: boilerState = 0 module_logger.info('Boiler overridden OFF') module_logger.info("main.max.switchHeat Boiler is %s, Heating is %s" % (boilerEnabled, boilerState)) # Update Temps database DbUtils().insertTemps(roomTemps) if boilerEnabled: try: _ = requests.get(veraControl.format(Vera_Address, Vera_Port, Vera_Device, str(boilerState)), timeout=5) Variables().writeVariable([['VeraOK', 1]]) module_logger.info('message sent to Vera') except: Variables().writeVariable([['VeraOK', 0]]) module_logger.info("vera is unreachable") # Set Manual Boiler Switch if enabled # if ManualHeatingSwitch: # module_logger.info("Switching local Relay %s" %boilerState) # relayHeating(boilerState) else: boilerState = 0 try: _ = requests.get(veraControl.format(Vera_Address, Vera_Port, Vera_Device, boilerState), timeout=5) Variables().writeVariable([['VeraOK', 1]]) module_logger.info("Boiler is Disabled") except: Variables().writeVariable([['VeraOK', 0]]) module_logger.info("vera is unreachable") # Set Manual Boiler Switch if enabled # if ManualHeatingSwitch: # module_logger.info("Switching local Relay %s" %boilerState) # relayHeating(boilerState) try: boilerOn = DbUtils().getBoiler()[2] except: boilerOn = 9 if boilerState != boilerOn: msg = (logTime, boilerState) DbUtils().updateBoiler(msg) boilerOn = boilerState # Create UI Pages CreateUIPage().saveUI(roomTemps)
def maxCmd_L(self, line): """ process L response """ line = line.split(":") # print line es = base64.b64decode(line[1]) es_pos = 0 # print "hex ", self.hexify(es) while (es_pos < len(es)): dev_len = ord(es[es_pos]) + 1 # print "Dev Len ", dev_len valve_adr = self.hexify(es[es_pos + 1:es_pos + 4]) # print valve_adr valve_status = ord(es[es_pos + 0x05]) # print valve_status valve_info = ord(es[es_pos + 0x06]) valve_temp = 0xFF valve_curtemp = 0xFF valve_info_string = '{0}{{:{1}>{2}}}'.format('ob', 0, 8).format( bin(valve_info)[2:]) valve_mode = str(valve_info_string[8:]) if valve_mode == '00': valve_MODE = 'AUTO' elif valve_mode == '01': valve_MODE = 'MANUAL' elif valve_mode == '11': valve_MODE = 'BOOST' elif valve_mode == '10': valve_MODE = 'VACATION' link_status = int(valve_info_string[3:4]) battery_status = int(valve_info_string[2:3]) # WallMountedThermostat (dev_type 3) if dev_len == 13: # print "WALL THERMOSTAT" valve_pos = 999 if valve_info & 3 != 2: # valve_temp = float(int(self.hexify(es[es_pos + 0x08]), # 16)) / 2 # set temp # Get Binary at offset 8 valve_binary = "{0:08b}".format( int(self.hexify(es[es_pos + 0x08]), 16)) # print "Valve Binary ", valve_binary # Use msb of offset 8 for msb or actual temperature if valve_binary[0:1] == "1": temp_headder = "01" else: temp_headder = "00" # Just use last 6 bits for set temp valve_binary = valve_binary[-6:] # print "Valve Binary after trim", valve_binary valve_temp = float(int(valve_binary, 2)) / 2 # set temp # print "Valve Set temp ", valve_temp # print "Offset 12 Binary : # {0:08b}".format(int(self.hexify(es[es_pos + 0x0C]), 16)) curr_binary = "{0}{1:08b}".format( temp_headder, int(self.hexify(es[es_pos + 0x0C]), 16)) # print "Current Temp Binary ", curr_binary valve_curtemp = float(int(curr_binary, 2)) / 10 # measured temp # print "Valve Current Temp ", valve_curtemp # HeatingThermostat (dev_type 1 or 2) elif dev_len == 12: valve_pos = ord(es[es_pos + 0x07]) if valve_info & 3 != 2: valve_temp = float(int(self.hexify(es[es_pos + 0x08]), 16)) / 2 valve_curtemp = float(ord(es[es_pos + 0x0A])) / 10 # WindowContact elif dev_len == 7: pass valves.update({ valve_adr: [ valve_pos, valve_temp, valve_curtemp, valve_MODE, link_status, battery_status ] }) # save status and info #devices[valve_adr][6] = valve_status #devices[valve_adr][7] = valve_info es_pos += dev_len dbMessage = [] for keys in valves: dbList = keys, valves[keys][0], valves[keys][1], valves[keys][ 2], valves[keys][3], valves[keys][4], valves[keys][5] dbMessage.append(dbList) # print dbList DbUtils().updateValves(dbMessage)
def maxCmd_M(self, line, refresh): """ process M response Rooms and Devices""" logger = logging.getLogger("main.max.maxCmd_M") expectedRoomNo = int(Variables().readVariables(['ExpectedNoOfRooms'])) line = line.split(",") es = base64.b64decode(line[2]) room_num = ord(es[2]) logger.info("Number of rooms found : {}".format(room_num)) # Check number of rooms if room_num != expectedRoomNo: Variables().writeVariable([['RoomsCorrect', 0]]) logger.info("RoomsCorrect set to : {}".format(0)) else: Variables().writeVariable([['RoomsCorrect', 1]]) logger.info("RoomsCorrect set to : {}".format(1)) es_pos = 3 this_now = datetime.datetime.now() for _ in range(0, room_num): room_id = str(ord(es[es_pos])) room_len = ord(es[es_pos + 1]) es_pos += 2 room_name = es[es_pos:es_pos + room_len] es_pos += room_len room_adr = es[es_pos:es_pos + 3] es_pos += 3 if room_id not in rooms or refresh: # id :0room_name, 1room_address, 2is_win_open rooms.update( {room_id: [room_name, self.hexify(room_adr), False]}) dev_num = ord(es[es_pos]) es_pos += 1 for _ in range(0, dev_num): dev_type = ord(es[es_pos]) es_pos += 1 dev_adr = self.hexify(es[es_pos:es_pos + 3]) es_pos += 3 dev_sn = es[es_pos:es_pos + 10] es_pos += 10 dev_len = ord(es[es_pos]) es_pos += 1 dev_name = es[es_pos:es_pos + dev_len] es_pos += dev_len dev_room = ord(es[es_pos]) es_pos += 1 if dev_adr not in devices or refresh: # 0type 1serial 2name 3room 4OW,5OW_time, 6status, # 7info, 8temp offset devices.update({ dev_adr: [ dev_type, dev_sn, dev_name, dev_room, 0, this_now, 0, 0, 7 ] }) dbMessage = [] for keys in rooms: roomText = str(rooms[keys][0]) # For testing ' in names # if roomText == "Bathroom": # roomText = "Bathroom's" dbList = keys, roomText, rooms[keys][1] dbMessage.append(dbList) print dbMessage DbUtils().updateRooms(dbMessage) dbMessage = [] for keys in devices: dbList = keys, devices[keys][0], devices[keys][1], devices[keys][ 2], devices[keys][3], devices[keys][5] dbMessage.append(dbList) DbUtils().updateDevices(dbMessage)