""" Define custom user panels for the Raspberry Pi Python console for WeatherFlow Tempest and Smart Home Weather stations. Copyright (C) 2018-2022 Peter Davis This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ # customPanels.py # Load required modules from kivy.uix.relativelayout import RelativeLayout from kivy.clock import Clock from panels.template import panelTemplate import requests import xml.etree.ElementTree as ET import datetime # ============================================================================== # TIDES CUSTOM PANEL # ============================================================================== class TidesPanel(panelTemplate): def __init__(self, **kwargs): super().__init__(**kwargs) self.update_tides() Clock.schedule_interval(self.update_tides, 3600) # update every hour def update_tides(self, *args): # API endpoint URL url = "https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?date=today&range=48&station=8466791&product=predictions&datum=MLLW&time_zone=lst_ldt&interval=hilo&units=english&application=DataAPI_Sample&format=xml" try: # Make a GET request to the endpoint response = requests.get(url) # Save the API response to a local file with open("tidedata.xml", "w") as file: file.write(response.text) print("Tide data saved as xml file successfully!") # call the function to get the tides tides = self.get_tides() # Update the tides label with the new data tides_str = '\n'.join(["{} ({}): {}'".format(self.format_time(tide['attrib']['t']), tide['type'], round(float(tide['attrib']['v']), 1)) for tide in tides]) self.ids.tides_label.text = tides_str except requests.exceptions.RequestException as e: # Handle exceptions that may occur during the request print("Error getting tide data: ", e) self.ids.tides_label.text = "Error getting tide data." def get_tides(self): # parse the XML file tree = ET.parse("tidedata.xml") root = tree.getroot() # store the parsed data in a variable tides = [] # iterate through the elements in the XML file for elem in root: tide = { 'tag': elem.tag, 'attrib': elem.attrib } if elem.attrib['type'] == 'H': tide['type'] = 'High' else: tide['type'] = 'Low' tides.append(tide) # return the stored data return tides def format_time(self, time): # convert the string to a datetime object dt = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M') # format the datetime object into a 12-hour format string return dt.strftime('%I:%M %p') class TidesButton(RelativeLayout): pass