Bug when creating python script

Please use template to report bugs and problems. Post here your questions when not sure where else to post
Only for bugs in the Domoticz application! other problems go in different subforums!

Moderators: leecollings, remb0

Forum rules
Before posting here, make sure you are on the latest Beta or Stable version.
If you have problems related to the web gui, clear your browser cache + appcache first.

Use the following template when posting here:

Version: xxxx
Platform: xxxx
Plugin/Hardware: xxxx
Description:
.....

If you are having problems with scripts/blockly, always post the script (in a spoiler or code tag) or screenshots of your blockly

If you are replying, please do not quote images/code from the first post

Please mark your topic as Solved when the problem is solved.
Post Reply
HvdW
Posts: 540
Joined: Sunday 01 November 2015 22:45
Target OS: Raspberry Pi / ODroid
Domoticz version: 2023.2
Location: Twente
Contact:

Bug when creating python script

Post by HvdW »

Version: 2024.7
Platform: RPI 4
Script: self written, happens to any script

When a python script is created it is possible to choose a trigger.
Whateven trigger is chosen there is no option to fill out a trigger.

Code: Select all

"""
Script voor het monitoren van EV laadgegevens
Triggers:
    - time = "At 09:00 on Sunday"
    - device = "Charging Level"
"""
#!/usr/bin/env python
import DomoticzEvents as DE
import datetime
import csv
import os
from statistics import mean

class EVChargingMonitor:
    def __init__(self):
        self.BATTERY_CAPACITY = 79  # kWh
        self.CSV_FILE = '/home/hein/car-charging.csv'
        self.previous_level = None
        self.odometer_readings = []
        self.whtotal_readings = []
        self.temp_readings = []
        
    def on_start(self):
        # Initialize if file doesn't exist
        if not os.path.exists(self.CSV_FILE):
            with open(self.CSV_FILE, 'w', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(['datum', 'odometer', 'afstand', 'kWh', 'euro', 'average temp'])

    def calculate_weekly_consumption(self):
        if not self.odometer_readings or not self.whtotal_readings:
            return None
            
        # Calculate distance between first and last reading
        start_odometer = self.odometer_readings[0]
        end_odometer = self.odometer_readings[-1]
        distance = end_odometer - start_odometer
        
        # Calculate energy consumption
        start_whtotal = self.whtotal_readings[0]
        end_whtotal = self.whtotal_readings[-1]
        energy_consumed = (end_whtotal - start_whtotal) / 1000  # Convert Wh to kWh
        
        # Calculate average temperature
        avg_temp = mean(self.temp_readings) if self.temp_readings else None
        
        # Calculate cost (assuming €0.25 per kWh - adjust as needed)
        cost = energy_consumed * 0.25
        
        return {
            'timestamp': datetime.datetime.now().strftime('%d-%m-%Y %H:%M'),
            'odometer': end_odometer,
            'distance': distance,
            'kwh': energy_consumed,
            'euro': cost,
            'avg_temp': avg_temp
        }

    def save_to_csv(self, data):
        with open(self.CSV_FILE, 'a', newline='') as f:
            writer = csv.writer(f, delimiter=';')
            writer.writerow([
                data['timestamp'],
                data['odometer'],
                data['distance'],
                f"{data['kwh']:.3f}",
                f"{data['euro']:.2f}",
                f"{data['avg_temp']:.1f}" if data['avg_temp'] is not None else ''
            ])

    def update_display(self, data):
        display_text = f"""Wekelijkse verbruiksrapportage:
Datum/tijd: {data['timestamp']}
Eindstand: {data['odometer']} km
Afstand deze week: {data['distance']} km
Verbruik deze week: {data['kwh']:.3f} kWh
Kosten deze week: €{data['euro']:.2f}
Gem. temperatuur: {data['avg_temp']:.1f}°C"""
        
        domoticz.devices['Charging Display'].Update(nValue=0, sValue=display_text)
        
        # Log to Domoticz
        domoticz.log(f"EV Weekly Report: {display_text}")

    def on_time(self):
        # Deze functie wordt alleen opgeroepen op zondag 09:00
        data = self.calculate_weekly_consumption()
        if data:
            self.save_to_csv(data)
            self.update_display(data)
            # Reset weekly data
            self.odometer_readings = []
            self.whtotal_readings = []
            self.temp_readings = []

    def on_charging_level_change(self):
        # Deze functie wordt alleen opgeroepen bij wijziging van Charging Level
        current_level = domoticz.devices('Charging Level').levelVal
        
        if self.previous_level != current_level:
            # Sla huidige metingen op
            self.odometer_readings.append(domoticz.devices('Volvo-Odometer').nValue)
            self.whtotal_readings.append(domoticz.devices('Laadpaal').Whtotal)
            self.temp_readings.append(float(domoticz.devices('Buitentemperatuur').sValue))
            self.previous_level = current_level

# Global instance
monitor = EVChargingMonitor()

def onStart():
    monitor.on_start()

# Wordt alleen opgeroepen op zondag om 09:00
def onTime():
    monitor.on_time()

# Wordt alleen opgeroepen bij wijziging van Charging Level
def onDeviceChanged(unit, device):
    if device.name == 'Charging Level':
        monitor.on_charging_level_change()
Bugs bug me.
User avatar
waltervl
Posts: 5399
Joined: Monday 28 January 2019 18:48
Target OS: Linux
Domoticz version: 2024.7
Location: NL
Contact:

Re: Bug when creating python script

Post by waltervl »

There is no option to set specific triggers in Python scripting like in dzvents.
As stated in the wiki https://wiki.domoticz.com/Python_Events the triggers are:
All - Will run whenever anything happens that triggers the event system to run a script
Device - Will run whenever ANY device state/value change
Security - Will run whenever there is a security event
Time - Will run once per minute. Scripts are executed one at a time.
User Variable - Will run when User Variables are updated

You have to check in the script yourself if time is as set. So if you want to run the script at 21:00 the first part of the script will be the check if time = 21:00. If not stop the script else continue.
The same for a device change, first check it the changed device is the one you want to handle. If so continue, else stop.
Domoticz running on Udoo X86 (on Ubuntu)
Devices/plugins: ZigbeeforDomoticz (with Xiaomi, Ikea, Tuya devices), Nefit Easy, Midea Airco, Omnik Solar, Goodwe Solar
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest