# Doubt regarding message handlers

**URL:** <https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743>\
**Category:** Ignition\
**Tags:** ignition81, perspective\
**Created:** [March 4, 2024, 9:19am UTC](https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743 "2024-03-04T09:19:28Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Surya\_Chandra\_Mohan](https://avatars.discourse-cdn.com/v4/letter/s/a9adbd/32.png) [@Surya\_Chandra\_Mohan](https://forum.inductiveautomation.com/u/Surya_Chandra_Mohan)\
**Post date:** [March 4, 2024, 9:19am UTC](https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743/1 "2024-03-04T09:19:29Z")

</div>

Hello,

I am working on getting the daily, weekly and monthly data reflected based on the dropdown selection. It is working and next when I launch the perspective project, by default I should get the daily data and I have written the script in message handler section -

```auto
	
	# Fetch the start date from the date picker component
	start_date = self.getChild("Date_Flex").getChild("StartDate_Flex").getChild("DateTimeInput").props.value
	#start_date = system.date.now()
	end_date = None
	
	# Fetch the selected duration type from the dropdown component
	duration_type = self.getChild("Date_Flex").getChild("StartDate_Flex").getChild("Dropdown").props.value
	
	duration_type = 1
	
	# Initialize address_durations
	address_durations = {}
	
	hourly_consumption_kwh = 0.0
	total_consumption_str = 0.0
	
	# Calculate end_date based on the selected duration_type from the dropdown
	if duration_type == 1: # Daily
		total_consumption_str = 8400
		end_date = system.date.addDays(start_date, 1)
		
		hourly_consumption_kwh = float(total_consumption_str) / 24
	elif duration_type == 7: # Weekly
		total_consumption_str = 58800
		end_date = system.date.addWeeks(start_date, 1)
		
		hourly_consumption_kwh = float(total_consumption_str) / 168
	elif duration_type == 30: # Monthly
		total_consumption_str = 252000
		end_date = system.date.addMonths(start_date, 1)
		
		hourly_consumption_kwh = float(total_consumption_str) / 720
	
	# Update the end_date_picker's value based on the calculated end_date
	end_date_picker = self.getChild("Date_Flex").getChild("StartDate_Flex").getChild("DateTimeInput_0")
	end_date_picker.props.value = end_date
	
	# Named query with the start_date and end_date as parameters
	data = system.db.runNamedQuery("Demo", {"start_date": start_date, "end_date": end_date})
	
	# Check if the named query returned any rows
	if data.getRowCount() == 0:
	    print("No logs were processed during the selected period")
	else:
	    prev_state = {}
	    prev_timestamp = {}
		
	    for row in range(data.getRowCount()):
	        network_address = data.getValueAt(row, 'NETWORKADDRESS')
	        node_address = data.getValueAt(row, 'NODEADDRESS')
	        address = str(network_address) + "." + str(node_address)
	
	        timestamp = system.date.parse(data.getValueAt(row, 'TIMESTAMP'), "yyyy-MM-dd HH:mm:ss")
	        parameter = data.getValueAt(row, 'PARAMETERS')
	
	        if address not in prev_timestamp:
	            prev_timestamp[address] = timestamp
	            prev_state[address] = parameter
	            address_durations[address] = {"ON": 0, "OFF": 0}
	        else:
	            duration = system.date.secondsBetween(prev_timestamp[address], timestamp)
	            if prev_state[address] == 'ON':
	                address_durations[address]['ON'] += duration
	            elif prev_state[address] == 'OFF':
	                address_durations[address]['OFF'] += duration
	            prev_state[address] = parameter
	            prev_timestamp[address] = timestamp
	
	    # Handle duration for the last state until the end_date
	    for address in prev_state.keys():
	        if prev_state[address] == 'OFF': # Check if the last state is OFF
	            if prev_timestamp[address] < end_date:
	                duration = system.date.secondsBetween(prev_timestamp[address], end_date)
	                address_durations[address]['OFF'] += duration
	        elif prev_state[address] == 'ON': # Check if the last state is ON
	            if prev_timestamp[address] < end_date:
	                duration = system.date.secondsBetween(prev_timestamp[address], end_date)
	                address_durations[address]['ON'] += duration
	
	    # Prepare data for XY Chart
	    duration_data_xy_chart = []
	    for address, durations in address_durations.items():
	        duration_data_xy_chart.append({
	            "address": address,
	            "ON": durations['ON']/60,
	        })
	    print(duration_data_xy_chart)
	    
	    # Append the processed data to the XY Chart's data source
	    for entry in duration_data_xy_chart:
	        self.getChild("XYGraph_Flex").getChild("XYChart").props.dataSources.example.append({
	            "address": entry["address"],
	            "ON": entry["ON"],
	        })
	    
 	# Calculation of Power Consumption with device (ON duration)
    # ON durations in minutes
	devices_data = sum([durations['ON'] / 60 for address, durations in address_durations.items()])

    # Calculate per minute consumption
	minute_consumption_kwh = hourly_consumption_kwh / 60
	print(minute_consumption_kwh)
	
	duration_data = minute_consumption_kwh * devices_data

    # Format the values for display
	total_kwh_consumed_with_unit = "{:.2f}kWh".format(duration_data)
	print(total_kwh_consumed_with_unit)
	
	# Calculate the difference
	difference_kwh = total_consumption_str - duration_data
	
	# Format the values for display
	difference_with_unit = "{:.2f}kWh".format(difference_kwh)
	print("Difference:", difference_with_unit)
	
	
	#Updating in gauge component
	gauge_day = self.getChild("FlexContainer_1").getChild("FlexContainer_0").getChild("SimpleGauge")
	gauge_week = self.getChild("FlexContainer_1").getChild("FlexContainer_0").getChild("SimpleGauge_0")
	gauge_month = self.getChild("FlexContainer_1").getChild("FlexContainer_0").getChild("SimpleGauge_1")
	
	# Now, depending on the duration_type, update the corresponding gauge
	if duration_type == 1: # Daily
	    gauge_day.props.value = difference_with_unit
	    print("Daily gauge updated:", difference_with_unit)
	elif duration_type == 7: # Weekly
	    gauge_week.props.value = difference_with_unit
	    print("Weekly gauge updated:", difference_with_unit)
	elif duration_type == 30: # Monthly
	    gauge_month.props.value = difference_with_unit
	    print("Monthly gauge updated:", difference_with_unit)

```

And I am calling the message handler from the button on performed action script -

```auto
# Fetch the start date from the date picker component
start_date = system.date.now()
end_date = None
# Fetch the selected duration type from the dropdown component
duration_type = self.getSibling(Dropdown).props.value
# Update the end_date_picker's value based on the calculated end_date
end_date_picker = self.parent.parent.getChild(StartDate_Flex).getChild(DateTimeInput_0)
end_date_picker.props.value = end_date
payload = {start_date: start_date, duration_type: duration_type, end_date:end_date}
# Call the message handler with the parameters
system.perspective.sendMessage(Fetch DailyData, payload)

```

How to get the daily data as soon as the project is launched?  
Can anyone please help me out with this issue?

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![Transistor](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/transistor/32/3380_2.png) [@Transistor](https://forum.inductiveautomation.com/u/Transistor)\
**Post date:** [March 4, 2024, 10:15am UTC](https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743/2 "2024-03-04T10:15:30Z")

</div>

Tip: why have you got `import datetime` at the top of each script? You're not using it and you shouldn't without special reason as `system.date` functions will be much better.

---

<div class="post-metadata">

**Author:** ![Surya\_Chandra\_Mohan](https://avatars.discourse-cdn.com/v4/letter/s/a9adbd/32.png) [@Surya\_Chandra\_Mohan](https://forum.inductiveautomation.com/u/Surya_Chandra_Mohan)\
**Post date:** [March 4, 2024, 10:19am UTC](https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743/3 "2024-03-04T10:19:23Z")

</div>

Yes @Transistor, I am not using it and I have made use of the built in date functions available in ignition.

---

<div class="post-metadata">

**Author:** ![Transistor](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/transistor/32/3380_2.png) [@Transistor](https://forum.inductiveautomation.com/u/Transistor)\
**Post date:** [March 4, 2024, 10:21am UTC](https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743/4 "2024-03-04T10:21:58Z")

</div>

Edit it out of your first post. It will cause confusion.

I note that you didn't take my advice regarding the brittleness of the code as discussed in [Issue while displaying value in gauge - #2 by Transistor](https://forum.inductiveautomation.com/t/issue-while-displaying-value-in-gauge/86665/2). 🤔

---

<div class="post-metadata">

**Author:** ![Surya\_Chandra\_Mohan](https://avatars.discourse-cdn.com/v4/letter/s/a9adbd/32.png) [@Surya\_Chandra\_Mohan](https://forum.inductiveautomation.com/u/Surya_Chandra_Mohan)\
**Post date:** [March 4, 2024, 10:26am UTC](https://forum.inductiveautomation.com/t/doubt-regarding-message-handlers/86743/5 "2024-03-04T10:26:52Z")

</div>

Yes I remember @Transistor

I actually wanted to try through scripting so went ahead with writing python script and working on the functionalities from the same
