Omlet Smart Automatic Chicken Coop Door: Automation using Homey Script

I faced the issue of not being able to control this door through automation since it is only controlled by Google Home normally, and since Google Home wont allow any sort of automation for device type “Door” for security reasons, we simply cannot open/close the door through flows or even Google Home routines, we are stuck with manually opening/closing the door, which kinda sucks.

Luckily, Omlet provides an API (Open API 3.0) that we can use inside Homey Scripts to open/close the door and fetch some current status for it and I thought I’d share them with you if you ever need to do the same.

This will in the end allow us to add these scripts to our Advanced Flows to read and/or change the state of the door as we would with other supported devices.
For example, I have now created a flow that will open the door at 5:30 in the morning but only if the temperature outside is more than 0 degrees celsius.
I can start heaters in the coop in whenever the temperature drops below 0 AND the door is closed.
Just to name a few obvious examples.
Anyways, onwards with the scripts!

1. Creating an API key
This step is required to authorize Homey to Omlet when running open/close commands.

Go to the Omlet Developer page and login using your Omlet credentials here:
https://smart.omlet.com/developers/

Click on API Keys and hit “Generate”, this will create a Token that you will use in the later steps in the tutorial so keep it nearby! :slight_smile:

2. Finding out the deviceID of you Omlet door
We also need to find out the deviceID for the door to be able to send the calls to the correct device, this can be easily done using Homey Script.
Create a new Homey Script and paste the following code, then just hit the “Test” button and your deviceID will be printed to the output window below the code.

NOTE: You don’t need to keep this script so you can just delete it once you ran it and got your deviceID.

// USER SECTION: Change YOUR_API_KEY_HERE to the API Key on the Omlet Developer Page
const apiKey = 'YOUR_API_KEY_HERE'
// END USER SECTION

// Define the URL of the API endpoint
const apiUrl = 'https://x107.omlet.co.uk/api/v1'; // The URL to the API
const command = '/device'; // The endpoint we are trying to fetch
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer '+apiKey,
};

// Create a function to retrieve and parse data
async function fetchData() {
  try {
    // Fetch data from the API
    const response = await fetch(apiUrl + command, {
      method: 'GET',
      headers: headers,
    });

    // Check if the response is successful
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON data
    const data = await response.json();

    var deviceID = data[0]['deviceId'];
    console.log('DeviceID: ' +deviceID);
    return deviceID;
  } catch (error) {
    // Handle errors (e.g., log them)
    console.error('Error fetching data:', error);
    throw new Error(`ERROR`);
  }
}
// Run the function that returns the deviceID
return fetchData();

3. Script for performing actions, such as closing/opening the door
Create a new homey script and paste the following code.
This time you need to change 3 things at the very top of the code.

  1. The API key
  2. The DeviceID
  3. The action you want to perform

There are quite a few actions you can do, but the most useful are the following:
‘on’ = turn on the light (if you have the optional light)
‘off’ = turn off the light (if you have the optional light)
‘open’ = open the door
‘close’ = close the door
‘stop’ = stop the door
‘restart’ = restart the omlet controller

// USER SECTION: You need to change the values of variables below

// Change to your preferred action
// 'on' = turn on the light (if you have the optional light)
// 'off' = turn off the light (if you have the optional light)
// 'open' = open the door
// 'close' = close the door
// 'stop' = stop the door
// 'restart' = restart the omlet controller
const action = 'open';

// Change YOUR_API_KEY_HERE to the API Key on the Omlet Developer Page in step 1.
const apiKey = 'YOUR_API_KEY_HERE';  

// Change YOUR_DEVICE_ID_HERE to the deviceID you got from the script in step 2.
const deviceID = 'YOUR_DEVICE_ID_HERE'; 

// END USER SECTION -- No need to change anything below this point

// Define the URL of the API endpoint
const apiUrl = 'https://x107.omlet.co.uk/api/v1/device/'+deviceID+'/action/'+action;

// Set up the request headers
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer '+apiKey,
};

// Define the body parameters
const body = JSON.stringify({
  deviceId: deviceID,
  action: action,
});

// Function to send POST request to open the Smart Coop door
async function postAction() {
  try {    
    // Send a POST request to the Omlet Smart Coop API     
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: headers,
      body: body,
    });

    // Check if the response is successful
    if (response.ok) {
      const responseText = await response.text();

      // Only parse as JSON if the responseText is not empty
      if (responseText) {
        const responseData = JSON.parse(responseText);
        console.log('Action called successfully:', responseData);
      }else {
        console.log('Action called successfully, but no response body.');
      }
    }else {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
  }catch (error) {
    console.error('Error performing the action:', error);
  }
}

// Call the function to close the door
postAction();

4. Script for retrieving the current status (open/closed) for the door
Again, create new script → paste code → replace API key and DeviceID and save.

// USER SECTION:
const deviceID = 'YOUR_DEVICE_ID_HERE'; // Change YOUR_DEVICE_ID_HERE to the deviceID you got from the script in 2.
const apiKey = 'YOUR_API_KEY_HERE';  // Change YOUR_API_KEY_HERE to the API Key on the Omlet Developer Page
// END USER SECTION

// Define the URL of the API endpoint
const apiUrl = 'https://x107.omlet.co.uk/api/v1/device';
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer '+apiKey,
};

// Create a function to retrieve and parse data
async function fetchData() {
  try {
    // Fetch data from the API
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: headers,
    });

    // Check if the response is successful
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON data
    const data = await response.json();
    
    // Return true if the door is open
    return data[0]['state']['door']['state'] == 'open';
    
  }
  catch (error) 
  {
    // Handle errors (e.g., log them)
    console.error('Error fetching data:', error);
    throw new Error(`ERROR`);
  }
}

// Run the fetchData function
return fetchData();

5. Script for retrieving the current state (on/off) of the optional lamp
Again, create new script → paste code → replace API key and DeviceID and save.

// USER SECTION:
const deviceID = 'YOUR_DEVICE_ID_HERE'; // Change YOUR_DEVICE_ID_HERE to the deviceID you got from the script in 2.
const apiKey = 'YOUR_API_KEY_HERE';  // Change YOUR_API_KEY_HERE to the API Key on the Omlet Developer Page
// END USER SECTION

// Define the URL of the API endpoint
const apiUrl = 'https://x107.omlet.co.uk/api/v1/device';
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer '+apiKey,
};

// Create a function to retrieve and parse data
async function fetchData() {
  try {
    // Fetch data from the API
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: headers,
    });

    // Check if the response is successful
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON data
    const data = await response.json();
    
    // Return true if the light is "on"
    return data[0]['state']['light']['state'] == 'on';
  } catch (error) {
    // Handle errors (e.g., log them)
    console.error('Error fetching data:', error);
    throw new Error(`ERROR`);
  }
}

// Run the fetchData function
return fetchData();
4 Likes

Thank you for your explanation! It works perfectly. Additionally, I’d like to add something: retrieving the battery status:

// USER SECTION:
const deviceID = 'YOUR_DEVICE_ID_HERE'; // Change YOUR_DEVICE_ID_HERE to the deviceID you got from the script in 2.
const apiKey = 'YOUR_API_KEY_HERE';  // Change YOUR_API_KEY_HERE to the API Key on the Omlet Developer Page
// END USER SECTION

// Define the URL of the API endpoint
const apiUrl = `https://x107.omlet.co.uk/api/v1/device/${deviceID}`;
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + apiKey,
};

// Create a function to retrieve the battery level
async function fetchBatteryLevel() {
  try {
    // Fetch data from the API
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: headers,
    });

    // Check if the response is successful
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON data
    const data = await response.json();

    // Return the battery level as a number
    return data['state']['general']['batteryLevel'];
  } catch (error) {
    // Handle errors
    console.error('Error fetching battery level:', error);
    throw new Error(`ERROR`);
  }
}

// Run the fetchBatteryLevel function
return fetchBatteryLevel();