예제 #1
0
    def generate(self, lower_t, upper_t) -> None:
        """Randomly generates home

        :param lower_t: lower temperature gradient (used for determining temperature color of home)
        :type lower_t: int
        :param upper_t: higher temperature gradient (used for determining temperature color of home)
        :type upper_t: int
        :return: Nothing
        """

        # convert sizes to m
        self.length = ft2m(self.length)
        self.width = ft2m(self.width)
        self.height = ft2m(self.height)

        self._lower_temp_grad = lower_t
        self._upper_temp_grad = upper_t

        # select wall material properties
        wall_type = random.randint(1, 3)
        if wall_type == 1:
            self.walls = material.LowEfficiency()
        elif wall_type == 2:
            self.walls = material.MedEfficiency()
        elif wall_type == 3:
            self.walls = material.HighEfficiency()
        else:
            self.walls = material.BrickWall()

        self.sharedInfo[0] = self.outside_temp.value
        self.sharedInfo[1] = 101325  # internal pressure, PA
        self.temp_history.append(self.sharedInfo[0])

        sizes = [self.length, self.width, self.height]
        self.thermostat = Thermostat(sizes, self.sharedInfo, self.world_clock, self.logger)
    def add_thermostat(self, location_id, location_name, thermostat, update):
        t_name = location_name + ' - ' + thermostat['userDefinedDeviceName']
        t_device_id = thermostat['deviceID']
        t_addr = thermostat['macID'].lower()
        use_celsius = thermostat['units'].lower() != 'fahrenheit'

        LOGGER.debug('Adding thermostat with id {0} and name {1} and addr {2}'.format(t_device_id, t_name, t_addr))
        self.addNode(Thermostat(self, t_addr, t_addr, t_name, self._api, location_id, t_device_id, use_celsius), update)

        if 'groups' not in thermostat:
            return

        for group in thermostat['groups']:
            group_id = group['id']

            sensors = self._api.get_sensors(location_id, t_device_id, group_id)
            for sensor in sensors.rooms:
                if len(sensor.accessories) == 0:
                    continue

                # TODO: Do we ever have to care about multiple accessory blocks?
                sensor_type = sensor.accessories[0].accessory_attribute.type
                sensor_name = sensor.name
                sensor_addr = t_addr + str(group_id) + str(sensor.id)

                if sensor_type == 'IndoorAirSensor' or sensor_type == 'Thermostat':
                    LOGGER.debug('Adding IndoorAirSensor with name {0} and addr {1} for thermostat {2}'.format(sensor_name, sensor_addr, t_addr))
                    self.addNode(IndoorAirSensor(self, t_addr, sensor_addr, sensor_name, self._api, location_id, t_device_id, group_id, sensor.id, use_celsius))
예제 #3
0
def open_thermostat(config):
    ip = config.get(
        'secret', {
            "ip": "192.168.0.100"}).get(
        'ip', '192.168.0.100')
    tempVariableId = int(
        config.get(
            'global', {
                "tempvariable": "28"}).get(
            'tempvariable', '28'))
    setpointDayVariableId = config.get(
        'global', {
            "setpointdayvariable": "29"}).get(
        'setpointdayvariable', '29')
    setpointNightVariableId = config.get(
        'global', {
            "setpointnightvariable": "29"}).get(
        'setpointnightvariable', '30')
    modeVariableId = config.get(
        'global', {
            "modevariable": "29"}).get(
        'modevariable', '31')
    stateVariableId = config.get(
        'global', {
            "statevariable": "13"}).get(
        'statevariable', '13')
    thermostatScenarioId = config.get(
        'global', {
            "thermostatscenario": "17"}).get(
        'thermostatscenario', '17')
    thermostatProbeId = config.get(
        'global', {
            "thermostatprobeid": "13"}).get(
        'thermostatprobeid', '13')
    thermostat = Thermostat(
        ip,
        int(tempVariableId),
        int(setpointDayVariableId),
        int(setpointNightVariableId),
        int(modeVariableId),
        int(stateVariableId),
        int(thermostatScenarioId),
        int(thermostatProbeId))

    logger.debug(" Address ip zibase:{}".format(ip))
    logger.debug(" Indoor Temperature:{}".format(
        thermostat.tempStr(thermostat.getTemp() / 10.0)))
    logger.debug(" Thermostat Mode:{}".format(thermostat.getModeString()))
    logger.debug(" Thermostat State:{}".format(thermostat.getStateString()))
    logger.debug(" Thermostat runMode:{}".format(
        thermostat.getRunModeString()))
    logger.debug(" setpoint Day:  {}°C".format(
        thermostat.getSetpointDay() / 10.0))
    logger.debug(" setpoint Night:{}°C".format(
        thermostat.getSetpointNight() / 10.0))
    return thermostat
예제 #4
0
    def test_should_heat(self):
        mock_temp_sensor_reader = MockTempSensorReader("")
        mock_temp_sensor_reader.set_temperature(10.0)
        thermostat = Thermostat(mock_temp_sensor_reader)

        thermostat.set_target_temperature(20.0)

        self.assertTrue(thermostat.should_heat())

        mock_temp_sensor_reader.set_temperature(25.0)
        self.assertFalse(thermostat.should_heat())
예제 #5
0
def main():
    home_thermostat = Thermostat(update_server)
    thermostat_server = create_server(home_thermostat.update_set_temperature)
    try:
        thermostat_thread = Thread(target=home_thermostat.run)
        #server_thread.daemon = True
        thermostat_thread.start()
        thermostat_server.run(host='0.0.0.0')
    except Exception as e:
        print('An Exception Occured!')
        print(e.message)
    finally:
        home_thermostat.shutdown()
예제 #6
0
 def test_dont_keep_heater_on_forever(self):
     # use the real heater controller, not the test heater
     self.heater = HeaterCycleProtection(self.clock)
     self.thermostat = Thermostat(self.heater, self.thermometer, self.clock)
     self.thermostat.set_mode('on')
     # advance to just before time limit
     self.clock.advance(minutes=59)
     self.thermostat.iterate()
     self.assertTrue(self.heater.is_on())
     # advance past limit, heater should go off
     self.clock.advance(minutes=1)
     self.thermostat.iterate()
     self.assertFalse(self.heater.is_on())
예제 #7
0
    def setUp(self):
        # create instances
        self.heater = TestHeater()
        self.thermometer = TestThermometer()
        self.clock = TestClock()
        self.thermostat = Thermostat(self.heater, self.thermometer, self.clock)

        # setup testing environment
        # in the beginning, temperature is above threshold, heater is off, both exceptions are on
        self.clock.set_clock(0)
        self.thermometer.temperature = 68
        self.heater._is_turned_on = False
        self.heater.exception_if_turned_on = True
        self.heater.exception_if_turned_off = True

        # start thermostat in target mode with target=68 (thresholds of 67/69)
        self.thermostat.set_target_temperature(68)
        self.thermostat.set_mode('target')
예제 #8
0
 def initFromDataFile(self):
     data = self.fileService.getComponents(self.dataFileName)
     if "components" not in data:
         raise BadHomeDataFileFormatError(
             "Home data JSON file missing key \"{0}\"".format("components"))
     for comp in data["components"]:
         if comp["name"] in self.data:
             raise BadHomeDataFileFormatError(
                 "Duplicate component name \"{0}\" found in file".format(
                     comp["name"]))
         if comp["type"] == "Thermostat":
             self.data[comp["name"]] = Thermostat(comp["name"],
                                                  comp["temperature"])
         elif comp["type"] == "Light":
             self.data[comp["name"]] = Light(comp["name"], comp["status"])
         else:
             logging.warning(
                 "InMemoryRepository.initFromDataFile - Component with name \"{0}\" not recognized, will not be included in initial data"
                 .format(comp["name"]))
예제 #9
0
파일: main.py 프로젝트: Munken/eco2mqtt
def _load_settings(settings, guess_mode):
    with open(settings) as f:
        raw = safe_load(f)

        parsed = {}
        for thermo in raw["thermostats"]:
            name = thermo["name"]
            addr = thermo["address"]
            secret = bytes.fromhex(thermo["secret"])
            set_point = thermo["set_point"]
            offset = float(thermo["offset"])
            remote_topic = thermo.get("remote")

            parsed[addr] = Thermostat(name=name,
                                      addr=addr,
                                      secret=secret,
                                      set_points=set_point,
                                      offset=offset,
                                      remote_topic=remote_topic,
                                      guess_mode=guess_mode)
        return parsed
예제 #10
0
 def test_get_thermostat(self):
     thermo = Thermostat("Thermostat", temp=68)
     self.home.repository.get = MagicMock(return_value=thermo)
     self.assertEqual(self.home.getThermostat(), thermo)
예제 #11
0
 def test_read_temperature(self):
     self.home.repository.get = MagicMock(
         return_value=Thermostat("Thermostat", temp=68))
     self.assertEqual(self.home.getTemperature(), 68)
예제 #12
0
def main(t, g):
    while True:
        griddy_data = g.query()
        current_price = griddy_data["now"]["price_ckwh"]
        price_display = g.format_price(current_price)

        if g.price_is_high(current_price):
            t.set_spike_active(True)
            log.info("Spike active. Current price: {}".format(price_display))
        else:
            t.set_spike_active(False)

        t.run()

        time.sleep(POLL_FREQUENCY)


if __name__ == "__main__":
    log.info("Thermostat monitor started.")

    t = Thermostat(config["thermostat"]["address"])

    g = griddy.Griddy(config["griddy"]["meter_id"],
                      config["griddy"]["member_id"],
                      config["griddy"]["settlement_point"])

    m = Process(target=main, args=(t, g))
    m.start()
    m.join()
예제 #13
0
 def setTemperature(self, newValue):
     self.repository.update(Thermostat("Thermostat", temp=newValue))
     logging.info("Set temperature to \"{0}\"".format(newValue))
예제 #14
0
def format_date(d):
    return "%d/%d" % (d[1], d[2])


def format_datetime_short(t):
    return time.strftime("%Y%m%dT%H%M%S", time.localtime(t))


logging.basicConfig(level="INFO")

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

thermostat = Thermostat(pref_file="prefs/thermostat.json",
                        schedule_file="prefs/schedule.json",
                        runhistory_file="prefs/usage.csv",
                        activitydata_file="prefs/activity.csv",
                        tempdata_file="prefs/stats.csv")

dayNames = [
    "Every Day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
    "Saturday", "Sunday"
]
timeCommandRE = re.compile(
    "(deleteTime|ignoreTime)([0-7])([0-2][0-9])([0-5][0-9])")


def simpleStats():
    (last_temp, last_humi) = thermostat.getLastReading()
    if last_temp != None:
        last_temp = round(last_temp, 2)
예제 #15
0
from PySide2 import QtWidgets
from thermostat import Room, Sensor, Actuator, Thermostat, OutsideTemperature
from thermostat_gui import MyWidget
from test_framework import TestCase, TestRunner
import threading
import time
import sys

outside_temperature = 20.
target_temperature = 22.

room = Room(outside_temperature)
sensor = Sensor(room)
actuator = Actuator(room)
thermostat = Thermostat(sensor, actuator, target_temperature)
outside_temperature_mod = OutsideTemperature(room, outside_temperature)

tc0 = TestCase(name="Heat if current temperature is below target",
         preconditions=[
           lambda: actuator.state == "OFF",
           lambda: room.temperature < thermostat.target - thermostat.slack
         ],
         invariants=[
           lambda: actuator.state == "HEATING"
         ],
         invariants_at_least_once=True,
         postconditions=[
           lambda: actuator.state == "OFF",
           lambda: room.temperature >= thermostat.target - thermostat.slack,
           lambda: room.temperature <= thermostat.target + thermostat.slack
         ])
예제 #16
0
    ip = None
    thermostat = None

    if config and config.get('secret', None) is not None:
        if config.get('secret').get('ip_zibase', None) is not None:
            ip = config.get('secret').get('ip_zibase')
            if ip == "":
                ip = None

        print("Address ip zibase:{}").format(ip)
        for x, y in config.items():
            print(x, y)

    if ip is not None:
        try:
            thermostat = Thermostat(ip)
            thermostat.setSetpointDay(207)
            thermostat.setSetpointNight(195)
            thermostat.addSetpointDay(1)
            thermostat.addSetpointNight(5)
            thermostat.setMode(0)
            thermostat.update()

            thermostat.read()

        except Exception as e:
            zibase = None
            print('Error Thermostat {}'.format(e))

    h.subscribe_intents(intent_received).start()
예제 #17
0
 def setUp(self):
     self.thermostat = Thermostat("Upstairs")
예제 #18
0
 def __init__(self, thermostatName, target):
     logger.info("Initializing extender")
     self.sensor = Sensor()
     self.thermostat = Thermostat(thermostatName)
     self.reporter = Reporter()
     self.target = target
예제 #19
0
파일: main.py 프로젝트: stormaaja/thermopy
    "{0}.csv".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
BASE_DIR = '/sys/bus/w1/devices/'
DEVICE_FOLDER = glob.glob(BASE_DIR + '28*')[0]
DEVICE_FILE = DEVICE_FOLDER + '/w1_slave'
RELAY_PIN = 17

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

heating_relay = HeatingRelay(RELAY_PIN)


def signal_handler(signal, frame):
    heating_relay.cleanup()
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)

thermostat = Thermostat(TempSensorReader(DEVICE_FILE))
thermostat.set_target_temperature(thermostat.read_current_temperature() +
                                  TARGET_TEMPERATURE_CHANGE)

thermo_logger = ThermoLogger()

thermo_logger.set_csv_logger(CSVLogger(LOG_FILENAME))
thermo_logger.set_thermostat(thermostat)
thermo_logger.set_heating_relay(heating_relay)

thermo_logger.run()
예제 #20
0
from config import Config

from LCD_1602 import LCD_1602
from ds1820 import DS1820
from thermostat import Thermostat
from thermometre import Thermometre

import time

ECO = 1
CONF = 2


if __name__ == '__main__':
    config = Config()
    consigne = Thermostat(config)
    GPIO.setwarnings = False
    thermometre = Thermometre()
    lcd = LCD_1602(config.pin['rs'], config.pin['e'], config.pin['db'], config.pin['GPIO'])
    sondes = DS1820("/sys/bus/w1/devices/", ("28-011561577dff", "28-0115615a35ff"))
    channel = 23
    GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    try:
        GPIO.add_event_detect(channel, GPIO.BOTH, callback=thermometre.change_mode, bouncetime=75)
        while True:
            now = time.localtime()
            thermometre.read_temp(sondes)
            thermometre.save_temp(now, 1)
            (mode, temp_consigne) = consigne.get_tranche_infos(config.conf, now)
            status = consigne.get_status(thermometre.get_temp(1), temp_consigne)
            lcd.clear()
예제 #21
0
#!/usr/bin/python

from threading import Thread
import thermostat
import time
from furnace import Furnace
from thermostat import Thermostat
from temperature_reader import TemperatureReader

print("Starting Runner.py")
f = Furnace()
furnaceThread = Thread(target = f.run, args = ())
furnaceThread.daemon = True
furnaceThread.start()

r = TemperatureReader()
readerThread = Thread(target = r.run, args = ())
readerThread.daemon = True
readerThread.start()

t = Thermostat()
thermostatThread = Thread(target = t.run, args = (f,))
thermostatThread.daemon = True
thermostatThread.start()

while True:
	time.sleep(1)
예제 #22
0
iconDay = Icon(path, '/icons/sun-2-32')
iconNight = Icon(path, '/icons/moon-2-32')
iconOff = Icon(path, '/icons/off')
iconFlame = Icon(path, '/icons/flame32')

zibaseId = None
tokenId = None
try:
    config = SnipsConfigParser.read_configuration_file(configPath)
    #print configPath, config
    zibaseId = config.get('secret').get('zibaseid')
    tokenId = config.get('secret').get('tokenid')
except:
    config = None

thermostat = Thermostat(config)

display = 3  # Set the Default display here

# update interval in seconds
if display == 2 or display == 3:
    updateRate = 60
else:
    updateRate = 60 * 5

lastupdate = 0

# define a variable to control the main loop
running = True
try:
예제 #23
0
 def initBaseComponents(self):
     self.repository.add(Thermostat("Thermostat", temp=68))
     self.repository.add(Light("Living Room Light"))
     logging.info("Initialized 1 thermostat and 1 light in memory")