Raspberry Pi Thermostat Controller and Google Dwelling

The air-con in lots of properties lacks fashionable niceties like central automation, programmable thermostats, a number of sensors, or Wi-Fi management. However older air-conditioning tech continues to be dependable, so in lots of circumstances, it’s unlikely to be upgraded quickly.

That, nonetheless, requires customers to ceaselessly interrupt work or sleep to show an air conditioner on or off. That is notably true in homes with tight layouts, like mine:

A floor plan with an air-conditioning unit at the top, to the right of center. Its output has to round two corners to reach most rooms, including the bedroom at the bottom left.
My unorthodox ground plan makes cooling with a single in-window air-con unit a problem. There isn't a direct line of sight for distant management from the bed room and no direct path for cool air to achieve all of the rooms.

US properties generally have central air-con, however this isn’t the case globally. Not having central AC limits automation choices, making it tougher to attain the identical temperature all through the entire dwelling. Specifically, it makes it arduous to keep away from temperature fluctuations which will require handbook intervention to deal with.

As an engineer and Internet of Things (IoT) fanatic, I noticed a possibility to do a number of helpful issues without delay:

  • Assist preserve vitality by enhancing the effectivity of my stand-alone air-conditioning unit
  • Make my dwelling extra snug by means of automation and Google Dwelling integration
  • Customise my resolution precisely the best way I wished it, as an alternative of being restricted to commercially accessible choices
  • Brush up on a few of my skilled abilities, utilizing tried and examined {hardware}

My air conditioner is a primary machine with a easy infrared distant management. I used to be conscious of units that allow air-conditioning items for use with sensible dwelling techniques, comparable to Sensibo or Tado. As a substitute, I took a DIY method and created a Raspberry Pi thermostat, permitting for extra subtle management primarily based on sensor enter from varied rooms.

Raspberry Pi Thermostat {Hardware}

I used to be already utilizing a number of Raspberry Pi Zero Ws, coupled with DHT22 sensor modules, to watch the temperature and humidity in numerous rooms. Due to the segmented ground plan, I put in the sensors to watch how heat it was in numerous elements of my home.

I even have a house surveillance system (not required for this undertaking) on a Home windows 10 PC with WSL 2. I wished to combine the sensor readings into the surveillance movies, as a textual content overlay on the video feed.

Wiring the Sensor

The sensors had been simple to wire, having solely three connections:

The first connection is "VCC from sensor to PIN1 - 3v3," the second is "DATA from sensor to PIN7 - GPIO4", and the third is "GND from sensor to PIN9 - GND."
A wiring diagram for the DHT22 module, displaying the pins used to attach it to the Raspberry Pi.

I used Raspberry Pi OS Lite, putting in Python 3 with PiP and the Adafruit_DHT library for Python to learn the sensor knowledge. It’s technically deprecated however less complicated to put in and use. Plus, it requires fewer assets for our use case.

I additionally wished to have a log of all of the readings so I used a third-party server, ThingSpeak, to host my knowledge and serve it by way of API calls. It’s comparatively simple, and since I didn't want real-time readings, I opted to ship knowledge each 5 minutes.

import requests
import time
import random
import Adafruit_DHT
KEY = 'api key'
def pushData(temp:float, hum:float):
        '''Takes temp and humidity and pushes to ThingsSpeak'''
        url="https://api.thingspeak.com/replace"
        params = {'api_key': KEY, 'field5': temp, 'field6': hum}
        res = requests.get(url, params=params)
def getData(sensor:int, pin:int):
    '''
    Enter DHT sensor sort and RPi GPIO pin to gather a pattern of information

    Parameters:
    sensor: Both 11 or 22, relying on sensor used (DHT11 or DHT22)
    pin: GPIO pin used (e.g. 4)
    '''
    attempt:
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        return humidity, temperature
    besides:
        Exception("Error studying sensor knowledge")
        return False
if __name__ == "__main__":
    sensor = 22    # Change to 11 if utilizing DHT11
    pin = 4 # I used GPIO pin 4
    whereas True:
        h, t = getData(sensor, pin)
        pushData(t, h)
        time.sleep(300)

On my devoted surveillance PC, operating WSL 2, I arrange a PHP script that fetches the info from ThingSpeak, codecs it, and writes it in a easy .txt file. This .txt file is required for my surveillance software program to overlay it on prime of the video stream.

As a result of I had some automation in the home already, together with sensible mild bulbs and several other routines in Google Dwelling, it adopted that I'd use the sensor knowledge as a wise thermostat in Google Dwelling. My plan was to create a Google Dwelling routine that might flip the air-con on or off routinely primarily based on room temperature, with out the necessity for person enter.

A photograph of a black puck-shaped device.
The PNI SafeHome PT11IR Wi-Fi sensible distant management unit.

Pricier all-in-one options like these from Sensibo and Tado require much less technical setup, however for a fraction of the associated fee, the PNI SafeHome PT11IR enabled me to make use of my telephone to manage any variety of infrared units inside its vary. The management app, Tuya, integrates with Google Dwelling.

Overcoming Google Dwelling Integration Points

With a smart-enabled air conditioner and sensor knowledge accessible, I attempted to get the Raspberry acknowledged as a thermostat in Google Dwelling however to no avail. I used to be in a position to ship the sensor knowledge to Google IoT Cloud and its Pub/Sub service, however there was no option to ship it to Google Dwelling to create a routine primarily based on that knowledge.

After pondering this for a number of days, I considered a brand new method. What if I didn’t have to ship the info to Google Dwelling? What if I might verify the info regionally and ship a command to Google Dwelling to show the air conditioner on or off? I examined voice instructions with success, so this method appeared promising.

A fast search turned up Assistant Relay, a Node.js-powered system that permits a person to ship instructions to Google Assistant, permitting the person to tie something to Google Assistant so long as it is aware of what to do with the enter it receives.

Even higher, with Assistant Relay, I might finish instructions to my Google Assistant by merely sending POST requests to the machine operating the Node.js server (on this case, my Raspberry Pi Zero W) with some required parameters. That’s it. The script is well documented so I gained’t get into a lot element right here.

Because the sensor knowledge was already being learn on the surveillance PC, I figured I might combine the request into the PHP script to maintain issues in a single place.

Because you probably don’t have the .txt file requirement, you'll be able to simplify the method by instantly studying the sensor knowledge and issuing instructions primarily based on that knowledge to the Google Assistant Service, by way of Assistant Relay. All of this may be carried out from a single Raspberry Pi machine, with out the necessity for extra {hardware}. Nonetheless, as I already had accomplished half of the work, it made sense to make use of what I had. Each scripts on this article can be utilized on a single machine; moreover, the PHP script might be rewritten in Python, if wanted.

Setting Situations and Automating Operation

I wished the automated energy biking to occur solely throughout nighttime, so I outlined the hours for which I wished to automate operation—10 PM to 7 AM—and set the popular temperature. Figuring out the right temperature intervals—to attain a cushty vary with out shortening the life span of the air-conditioning unit by biking its energy too usually—required a number of tries to get it proper.

The PHP script that created the sensor knowledge overlay was set as much as run each 5 minutes by way of a cron job, so the one issues I added to it had been the circumstances and the POST request.

Nonetheless, this created a difficulty. If the circumstances had been met, the script would ship a “activate” command each 5 minutes, even when the air-con was already on. This triggered the unit to beep annoyingly, even on the “flip off” command. To repair this, I wanted a option to learn the present standing of the unit.

Class wasn’t a precedence, so I made a JSON file containing an array. Each time the “activate” or “flip off” instructions would full efficiently, the script would then append the final standing to this array. This solved redundancy; nonetheless, notably sizzling days or extreme heating throughout the winter might trigger the circumstances to be met once more. I made a decision a handbook override would suffice in these conditions. I’ll depart including a return earlier than the swap snippet to this finish as an train for the reader:

<?php

swap(true)
{
    case $temperature > 27:
        turnAc('on');
        break;
    case $temperature < 24:
        turnAc('off');
        break;
}

operate turnAc($standing)
{
    $command = 'activate hallway ac'; // hallway ac is the Google Dwelling machine title for my AC
    if ($standing == 'off')
    {
        $command = 'flip off hallway ac';
    }

    if ($standing == 'on' && checkAc() == 'on')
    {
        return;
    }

    if ($standing == 'off' && checkAc() == 'off')
    {
        return;
    }

    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'native assistant server ip',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS =>'{
        "command": '.$command.',
        "converse": false,
        "person": "designated person"
        }',
      CURLOPT_HTTPHEADER => array(
        'Content material-Sort: utility/json'
      ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    $obj = null;

    attempt {
        $obj = json_decode($response);
    } catch (Exception $e) {
    }

    if (!$obj || $obj->success != true)
    {
        markAc($standing == 'on' ? 'off' : 'on'); // if error, mark it as reverse standing
        return;
    }

    markAc($standing);
}

operate markAc($standing)
{
    $file = __DIR__ . "/markAc.json";
    $json = json_decode(file_get_contents($file), true);
    $json[] = array(date('F j, Y H:i:s'), $standing);

    $handler = fopen($file, "w") or die("Unable to open file!");
    $txt = json_encode($json);
    fwrite($handler, $txt);
    fclose($handler);
}

operate checkAc()
{
    $file = __DIR__ . "/markAc.json";
    $json = json_decode(file_get_contents($file), true);
    $finish = array_pop($json);
    return $finish[1];
}

This labored however not on the primary try. I had to determine issues alongside the best way and tweak them as wanted. Hopefully, with the good thing about my expertise, you gained’t have to do as a lot to get it proper the primary time.

The Worth of a Raspberry Pi Thermostat Controller

I used to be motivated to automate my air-con as a result of the unconventional format of my dwelling typically resulted in vastly completely different temperatures in numerous rooms. However automating heating and cooling has advantages even for many who don’t face this explicit subject.

Individuals the world over dwell in varied climates and pay completely different costs for vitality (and completely different charges at completely different occasions of the day), so even modest enhancements in vitality effectivity could make automation worthwhile in sure areas.

Moreover, as increasingly properties grow to be automated, there's cause to discover the potential of automating older power-hungry units and home equipment comparable to air conditioners, electrical heaters, and water heaters. As a result of these units are usually cumbersome, troublesome to put in, and costly to improve, many individuals might be caught with them for years to return. Making these “dumb” units a bit smarter can't solely enhance consolation and vitality effectivity but additionally prolong their life spans.


Additional Studying on the Toptal Engineering Weblog:



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *