Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to display images #2

Open
BenJamesAndo opened this issue Mar 29, 2024 · 2 comments
Open

How to display images #2

BenJamesAndo opened this issue Mar 29, 2024 · 2 comments

Comments

@BenJamesAndo
Copy link

Hey, thanks so much for making this! My Displaypad can now finally be put to good use. I'm hoping Companion integration is possible at some point. For now I'm using it to toggle a smart fan on and off that is running ESPHome.

I'd like to use a png image instead of solid colours. Would you be able to point me in the right direction? When I try to use a png I get errors saying the image buffer size is wrong. My png's are 128x128px.

Here's my current code:

// Import necessary modules
const Displaypad = require('mountain-displaypad');
const axios = require('axios');

// Create a new Displaypad instance
const pad = new Displaypad();

// Function to toggle the fan state
async function toggleFanState() {
    try {
        // Perform HTTP POST request to toggle the fan
        await axios.post('http://192.168.1.113/fan/tower_fan/toggle');
    } catch (error) {
        console.error('Error toggling fan state:', error.message);
    }
}

// Function to get the fan state
async function getFanState() {
    try {
        // Fetch the updated fan state
        const response = await axios.get('http://192.168.1.113/fan/tower_fan/');
        
        // Return the fan state
        return response.data.state;
    } catch (error) {
        console.error('Error fetching fan state:', error.message);
        return null;
    }
}

// Function to update button color and image based on fan state
async function updateButtonColorAndImage() {
    try {
        // Fetch the updated fan state
        const fanState = await getFanState();
        
        // Set button color based on fan state
        if (fanState === 'ON') {
            pad.fillColor(0, 0, 0, 255); // Blue color
        } else {
            pad.fillColor(0, 255, 255, 255); // White color
        }
        
        // Log the fan state
        console.log('Fan state:', fanState);
        
        // Update fan image based on fan state
        updateFanImage(fanState);
    } catch (error) {
        console.error('Error updating button color and image:', error.message);
    }
}

// Function to update fan image based on fan state
function updateFanImage(fanState) {
    // Create a new image buffer
    const imageBuffer = Buffer.alloc(Displaypad.ICON_SIZE * Displaypad.ICON_SIZE * 3);

    // Fill the image buffer with appropriate color for fan state
    const color = fanState === 'ON' ? [0, 0, 255] : [255, 255, 255]; // Blue for 'ON', White for 'OFF'
    for (let i = 0; i < Displaypad.ICON_SIZE; i++) {
        const offset = i * Displaypad.ICON_SIZE * 3;
        imageBuffer[offset] = color[0];
        imageBuffer[offset + 1] = color[1];
        imageBuffer[offset + 2] = color[2];
    }

    // Display the image on the button
    pad.fillImage(9, imageBuffer);
}

// Handle button press event
pad.on('down', async (key) => {
    console.log('Button down:', key);
    
    try {
        // Toggle the fan state
        await toggleFanState();
        
        // Log the button press and toggle
        console.log('Button press: toggling fan state');
        
        // Wait for 500 milliseconds before updating button color and image
        setTimeout(updateButtonColorAndImage, 500);
    } catch (error) {
        // Log any errors that occur during the button press event
        console.error('Error during button press:', error.message);
    }
});

// Set initial button color to white and display fan image
pad.fillColor(0, 255, 255, 255); // White color
updateFanImage('OFF'); // Display fan image for 'OFF' state

// Update button color and image every 5 seconds
setInterval(updateButtonColorAndImage, 5000);

Here's the modified code to try to get png's to display

// Function to update fan image based on fan state
function updateFanImage(fanState) {
    // Read the image file
    let imageBuffer;
    if (fanState === 'ON') {
        imageBuffer = fs.readFileSync('fan_on.png'); // Path to the image file for 'ON' state
    } else {
        imageBuffer = fs.readFileSync('fan_off.png'); // Path to the image file for 'OFF' state
    }

    // Display the image on the button
    pad.fillImage(9, imageBuffer);
}

And here is the error I get

                        throw new RangeError(`Expected image buffer of length ${NUM_TOTAL_PIXELS*3}, got length ${imageBuffer.length}`);
                        ^

RangeError: Expected image buffer of length 31212, got length 5683
    at Displaypad.fillImage (G:\Documents\Scripts\node_modules\mountain-displaypad\index.js:176:10)
    at updateFanImage (G:\Documents\Scripts\Displaypad\display_pad_async_ESPhome.js:67:9)
    at Object.<anonymous> (G:\Documents\Scripts\Displaypad\display_pad_async_ESPhome.js:91:1)
    at Module._compile (node:internal/modules/cjs/loader:1241:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

Node.js v20.9.0

I did use ChatGPT heavily to make this so it's probably quite bad. Let me know what you think.
Cheers!

@peternewman
Copy link

Looking at the code, it wants to be 102 pixels square for your image:

const NUM_TOTAL_PIXELS = 102 * 102

But given your bigger dimensions image is smaller in file size, you're probably not getting the raw pixels from the PNG file, but trying to send the compressed bytes.

Hopefully that's enough to point you in the right direction, I can't just quote some code at you sorry.

@BenJamesAndo
Copy link
Author

Thank you for your assistance. I've not been able to get png's to work but I have now managed to get jpg's by ensuring they're 102px * 102px.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants