homebridge-solar-monitor-ivk
Version:
Solar production monitor for Homebridge with Pushover notifications
187 lines (159 loc) • 5.73 kB
JavaScript
/**
* Debug script to test Solar Monitor plugin functionality
*/
const { spawn } = require('child_process');
const path = require('path');
// Test configuration
const config = {
username: '314',
password: 'solgen314',
updateInterval: 15,
pushoverUserKey: 'u1v2w3x4y5z6a7b8c9d0e1f2g3h4i5j6', // Replace with actual
pushoverAppToken: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6', // Replace with actual
secondUserKey: 'us5sg9aqb2i7iqbjmmocr7p2df1ymp'
};
// Mock log function
const log = {
info: (msg) => console.log(`[INFO] ${msg}`),
error: (msg) => console.log(`[ERROR] ${msg}`)
};
// Test solar hours check
function isSolarHours() {
const now = new Date();
const istTime = new Date(now.getTime() + (5.5 * 60 * 60 * 1000)); // IST is UTC+5:30
const hour = istTime.getHours();
const minute = istTime.getMinutes();
const currentTime = hour + minute / 60;
// Solar hours: 6:00 AM to 6:30 PM IST
return currentTime >= 6 && currentTime <= 18.5;
}
// Test Python scraper
function runPythonScript(scriptPath) {
return new Promise((resolve) => {
console.log(`Running Python script: ${scriptPath}`);
const pythonProcess = spawn('python3', [scriptPath]);
let output = '';
let error = '';
pythonProcess.stdout.on('data', (data) => {
output += data.toString();
console.log(`Python output: ${data.toString()}`);
});
pythonProcess.stderr.on('data', (data) => {
error += data.toString();
console.log(`Python error: ${data.toString()}`);
});
pythonProcess.on('close', (code) => {
console.log(`Python process exited with code: ${code}`);
if (code === 0) {
try {
// Parse the last JSON output from the script
const lines = output.split('\n');
for (let i = lines.length - 1; i >= 0; i--) {
if (lines[i].trim().startsWith('{')) {
const data = JSON.parse(lines[i]);
console.log('✅ Successfully parsed JSON data:', data);
resolve({ success: true, data });
return;
}
}
console.log('❌ No JSON data found in output');
resolve({ success: false, error: 'No JSON data found' });
} catch (e) {
console.log('❌ Failed to parse JSON:', e.message);
resolve({ success: false, error: 'Failed to parse JSON' });
}
} else {
console.log('❌ Python script failed:', error);
resolve({ success: false, error: error || 'Script failed' });
}
});
});
}
// Test Pushover notification
async function sendPushoverNotification(userKey, appToken, message) {
const https = require('https');
const querystring = require('querystring');
const postData = querystring.stringify({
token: appToken,
user: userKey,
message: message,
title: '⚡ Solar Monitor Debug Test',
sound: 'cosmic',
priority: 0
});
const options = {
hostname: 'api.pushover.net',
port: 443,
path: '/1/messages.json',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
console.log(`✅ Pushover notification sent to user ${userKey}`);
resolve(true);
} else {
console.log(`❌ Pushover API error: ${res.statusCode} - ${data}`);
reject(new Error(`Pushover API error: ${res.statusCode} - ${data}`));
}
});
});
req.on('error', (error) => {
console.log(`❌ Error sending notification: ${error.message}`);
reject(error);
});
req.write(postData);
req.end();
});
}
// Main test function
async function testPlugin() {
console.log('🧪 Testing Solar Monitor Plugin Functionality');
console.log(`⏰ Current time: ${new Date().toLocaleString()}`);
// Test 1: Solar hours check
console.log('\n📅 Testing solar hours check...');
const inSolarHours = isSolarHours();
console.log(`Solar hours check: ${inSolarHours ? '✅ Within solar hours' : '❌ Outside solar hours'}`);
if (!inSolarHours) {
console.log('⚠️ Outside solar hours, but continuing test...');
}
// Test 2: Python scraper
console.log('\n🐍 Testing Python scraper...');
const pythonScript = path.join(__dirname, 'solar_scraper.py');
const result = await runPythonScript(pythonScript);
if (result.success) {
console.log('✅ Python scraper successful!');
// Test 3: Pushover notification
console.log('\n📱 Testing Pushover notification...');
const message = `🧪 DEBUG TEST
🔋 Current Power: ${result.data.current_power}
📊 E Today: ${result.data.today_energy}
📈 E Yesterday: ${result.data.yesterday_energy}
📅 E This Month: ${result.data.monthly_energy || '0.00 kWh'}
⏰ ${new Date().toLocaleString()}
🎯 This is a debug test from RPi!`;
try {
await sendPushoverNotification(config.pushoverUserKey, config.pushoverAppToken, message);
if (config.secondUserKey) {
await sendPushoverNotification(config.secondUserKey, config.pushoverAppToken, message);
}
console.log('🎉 All tests completed successfully!');
} catch (error) {
console.log('❌ Pushover notification failed:', error.message);
}
} else {
console.log('❌ Python scraper failed:', result.error);
}
}
// Run the test
testPlugin().catch(console.error);