Example #1
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Environment Canada weather."""
    if config.get(CONF_STATION):
        ec_data = ECData(station_id=config[CONF_STATION])
    else:
        lat = config.get(CONF_LATITUDE, hass.config.latitude)
        lon = config.get(CONF_LONGITUDE, hass.config.longitude)
        ec_data = ECData(coordinates=(lat, lon))

    add_devices([ECWeather(ec_data, config)])
Example #2
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Environment Canada sensor."""

    if config.get(CONF_STATION):
        ec_data = ECData(
            station_id=config[CONF_STATION], language=config.get(CONF_LANGUAGE)
        )
    else:
        lat = config.get(CONF_LATITUDE, hass.config.latitude)
        lon = config.get(CONF_LONGITUDE, hass.config.longitude)
        ec_data = ECData(coordinates=(lat, lon), language=config.get(CONF_LANGUAGE))

    sensor_list = list(ec_data.conditions.keys()) + list(ec_data.alerts.keys())
    add_entities([ECSensor(sensor_type, ec_data) for sensor_type in sensor_list], True)
Example #3
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Environment Canada sensor."""
    from env_canada import ECData

    if config.get(CONF_STATION):
        ec_data = ECData(station_id=config[CONF_STATION])
    elif config.get(CONF_LATITUDE) and config.get(CONF_LONGITUDE):
        ec_data = ECData(coordinates=(config[CONF_LATITUDE],
                                      config[CONF_LONGITUDE]))
    else:
        ec_data = ECData(coordinates=(hass.config.latitude,
                                      hass.config.longitude))

    add_devices([
        ECSensor(sensor_type, ec_data, config.get(CONF_NAME))
        for sensor_type in config[CONF_MONITORED_CONDITIONS]
    ], True)
Example #4
0
def run():
    # Kill the splash screen if active
    stop_splash_service()

    # Get supplied command line arguments
    commandArgs = args()

    if commandArgs.terminal_mode and sys.stdin.isatty():
        height, width = os.popen('stty size', 'r').read().split()
        termMatrix = TermMatrix()
        termMatrix.width = int(width)
        termMatrix.height = int(height)
        matrix = Matrix(termMatrix)
    else:
        # Check for led configuration arguments
        matrixOptions = led_matrix_options(commandArgs)
        matrixOptions.drop_privileges = False

        # Initialize the matrix
        matrix = Matrix(RGBMatrix(options = matrixOptions))

     #Riff to add loading screen here
    loading = Loading(matrix)
    loading.render()

    # Read scoreboard options from config.json if it exists
    config = ScoreboardConfig("config", commandArgs, (matrix.width, matrix.height))

    data = Data(config)

    #If we pass the logging arguments on command line, override what's in the config.json, else use what's in config.json (color will always be false in config.json)
    if commandArgs.logcolor and commandArgs.loglevel != None:
        debug.set_debug_status(config,logcolor=commandArgs.logcolor,loglevel=commandArgs.loglevel)
    elif not commandArgs.logcolor and commandArgs.loglevel != None:
        debug.set_debug_status(config,loglevel=commandArgs.loglevel)
    elif commandArgs.logcolor and commandArgs.loglevel == None:
        debug.set_debug_status(config,logcolor=commandArgs.logcolor,loglevel=config.loglevel)
    else:
        debug.set_debug_status(config,loglevel=config.loglevel)

    # Print some basic info on startup
    debug.info("{} - v{} ({}x{})".format(SCRIPT_NAME, SCRIPT_VERSION, matrix.width, matrix.height))
    
    if data.latlng is not None:
        debug.info(data.latlng_msg)
    else:
        debug.error("Unable to find your location.")

    # Event used to sleep when rendering
    # Allows Web API (coming in V2) and pushbutton to cancel the sleep
    # Will also allow for weather alert to interrupt display board if you want
    sleepEvent = threading.Event()


    # Start task scheduler, used for UpdateChecker and screensaver, forecast, dimmer and weather
    scheduler = BackgroundScheduler()
    scheduler.start()

    # Any tasks that are scheduled go below this line

    # Make sure we have a valid location for the data.latlng as the geocode can return a None
    # If there is no valid location, skip the weather boards
    
    #Create EC data feed handler
    if data.config.weather_enabled or data.config.wxalert_show_alerts:
        if data.config.weather_data_feed.lower() == "ec" or data.config.wxalert_alert_feed.lower() == "ec":
            try:
                data.ecData = ECData(coordinates=(data.latlng))
            except Exception as e:
                debug.error("Unable to connect to EC, try running again in a few minutes")
                sys.exit(0)

    if data.config.weather_enabled:
        if data.config.weather_data_feed.lower() == "ec":
            ecWxWorker(data,scheduler)
        elif data.config.weather_data_feed.lower() == "owm":
            owmweather = owmWxWorker(data,scheduler)
        else:
            debug.error("No valid weather providers selected, skipping weather feed")
            data.config.weather_enabled = False


    if data.config.wxalert_show_alerts:
        if data.config.wxalert_alert_feed.lower() == "ec":
            ecalert = ecWxAlerts(data,scheduler,sleepEvent)
        elif data.config.wxalert_alert_feed.lower() == "nws":
            nwsalert = nwsWxAlerts(data,scheduler,sleepEvent)
        else:
            debug.error("No valid weather alerts providers selected, skipping alerts feed")
            data.config.weather_show_alerts = False

    if data.config.weather_forecast_enabled and data.config.weather_enabled:
        wxForecast(data,scheduler)
    #
    # Run check for updates against github on a background thread on a scheduler
    #
    if commandArgs.updatecheck:
        data.UpdateRepo = commandArgs.updaterepo
        checkupdate = UpdateChecker(data,scheduler,commandArgs.ghtoken)

    if data.config.dimmer_enabled:
        dimmer = Dimmer(data, matrix,scheduler)

    screensaver = None
    if data.config.screensaver_enabled:
        screensaver = screenSaver(data, matrix, sleepEvent, scheduler)
        if data.config.screensaver_motionsensor:
            motionsensor = Motion(data,matrix,sleepEvent,scheduler,screensaver)
            motionsensorThread = threading.Thread(target=motionsensor.run, args=())
            motionsensorThread.daemon = True
            motionsensorThread.start()

    if data.config.pushbutton_enabled:
        pushbutton = PushButton(data,matrix,sleepEvent)
        pushbuttonThread = threading.Thread(target=pushbutton.run, args=())
        pushbuttonThread.daemon = True
        pushbuttonThread.start()
    

    MainRenderer(matrix, data, sleepEvent).render()
Example #5
0
root.wm_title("wpg-weatherchan_V0.0.17")

# Clock - Top RIGHT

timeText = Label(root, text="", font=("VCR OSD Mono", 36), fg="white", bg="green")
timeText.place(x=425, y=40)
clock()

# Title - Top LEFT

Title = Label(root, text="ENVIRONMENT CANADA", font=("VCR OSD Mono", 22), fg="white", bg="green")
Title.place(x=80, y=55)

# use ECData to gather weather data, station_id is from the csv file provided with ECDada -- homepage: https://github.com/michaeldavie/env_canada

ec_en = ECData(station_id='MB/s0000193', language='english')
ec_en.update()

# Middle Section (Cycling weather pages, every 30sec)

weather_page()

# scrolling text canvas

marquee = Canvas(root, height=120, width=580, bg="green")
marquee.config(highlightbackground="green")
marquee.place(x=80, y=375)

# read in RSS data and prepare it

width = 35
Example #6
0
    def run(self):

        while True:
            try:
                debug.info("Refreshing EC current observations weather")
                ecData = ECData(coordinates=(self.data.latlng))
                self.data.wx_updated = True
                self.network_issues = False
            # except (requests.exceptions) as e:
            #     #raise ValueError(e)
            #     debug.error("Unable to get EC data error:{0}".format(e))
            #     self.data.wx_updated = False
            #     self.network_issues = True
            #     pass
            except Exception as e:
                debug.error("Unable to get EC data error:{0}".format(e))
                self.data.wx_updated = False
                self.network_issues = True
                pass

            if self.data.wx_updated:
                #Set up units [temp, wind speed,precip, storm distance]
                #Use these eventhough some are included in data feed
                if self.data.config.weather_units == "metric":
                    self.data.wx_units = [
                        "C", "kph", "mm", "miles", "hPa", "ca"
                    ]
                else:
                    self.data.wx_units = [
                        "F", "mph", "in", "miles", "MB", "us"
                    ]

                curr_cond = ecData.conditions

                #Uncomment next line if you want to see what is being returned back from EC
                #debug.info(curr_cond)

                if self.time_format == "%H:%M":
                    wx_timestamp = datetime.datetime.now().strftime(
                        "%m/%d %H:%M")
                else:
                    wx_timestamp = datetime.datetime.now().strftime(
                        "%m/%d %I:%M %p")

                #Check current temperature to determine if using windchill or heat for apparent temperature
                #Make sure we have a value.  Sometimes, the feed will not contain a value
                curr_temp = curr_cond.get("temperature").get("value", {})
                curr_humidity = curr_cond.get("humidity").get("value", {})
                if curr_humidity == None:
                    curr_humidity = "0"
                    wx_humidity = "N/A"
                else:
                    wx_humidity = curr_humidity + "%"

                if curr_temp != None:
                    curr_temp = float(curr_cond["temperature"]["value"])
                    check_windchill = 10.0
                    if self.data.config.weather_units == "imperial":
                        curr_temp = temp_f(curr_temp)
                        check_windchill = 50.0

                    if curr_temp < check_windchill:
                        windchill = round(
                            wind_chill(
                                float(curr_cond["temperature"]["value"]),
                                float(curr_cond["wind_speed"]["value"]),
                                self.data.wx_units[1]), 1)
                        wx_app_temp = str(windchill) + self.data.wx_units[0]
                    else:
                        humidex = round(
                            cadhumidex(curr_temp, int(curr_humidity)), 1)
                        wx_app_temp = str(humidex) + self.data.wx_units[0]
                    wx_temp = str(round(curr_temp, 1)) + self.data.wx_units[0]

                else:
                    wx_temp = "N/A"
                    wx_app_temp = "N/A"

                if curr_cond.get("icon_code").get("value", "90") == None:
                    wx_icon = '\uf07b'
                else:
                    #Get condition and icon from dictionary
                    for row in range(len(self.icons)):
                        if int(self.icons[row]["Code"]) == int(
                                curr_cond.get("icon_code").get("value", "90")):
                            wx_icon = self.icons[row]['font']
                            break
                        else:
                            wx_icon = '\uf07b'

                wx_summary = curr_cond.get("condition").get("value", "N/A")

                if wx_summary == None:
                    wx_summary = "Curr Cond N/A"

                curr_dewpoint = curr_cond.get("dewpoint").get("value", "0.0")

                if curr_dewpoint == None:
                    curr_dewpoint = 0.0
                else:
                    curr_dewpoint = float(curr_dewpoint)

                if self.data.config.weather_units == "imperial":
                    curr_dewpoint = round(temp_f(curr_dewpoint), 1)

                if curr_dewpoint == 0.0:
                    wx_dewpoint = "N/A"
                else:
                    wx_dewpoint = str(curr_dewpoint) + self.data.wx_units[0]

                self.data.wx_current = [
                    wx_timestamp, wx_icon, wx_summary, wx_temp, wx_app_temp,
                    wx_humidity, wx_dewpoint
                ]

                winddir = degrees_to_direction(
                    float(curr_cond.get("wind_bearing").get("value", "0")))

                curr_windspeed = float(
                    curr_cond.get("wind_speed").get("value", "0.0"))

                if self.data.config.weather_units == "imperial":
                    curr_windspeed = round(wind_mph(curr_windspeed), 1)

                wx_windspeed = str(
                    curr_windspeed) + " " + self.data.wx_units[1]

                if curr_cond.get("wind_gust").get("value", "0.0") != None:
                    curr_windgust = float(
                        curr_cond.get("wind_gust").get("value", "0.0"))
                    if self.data.config.weather_units == "imperial":
                        curr_windgust = round(wind_mph(curr_windgust), 1)

                    wx_windgust = str(
                        curr_windgust) + " " + self.data.wx_units[1]
                else:
                    wx_windgust = "0.0 " + self.data.wx_units[1]

                wx_pressure = str(
                    round(float(curr_cond.get("pressure").get("value", "0")),
                          1) * 10) + " " + self.data.wx_units[4]

                for row in range(len(self.icons)):
                    if self.icons[row]["Description"].lower() == curr_cond.get(
                            "tendency").get("value", "N/A"):
                        wx_tendency = self.icons[row]['font']
                        break
                    else:
                        wx_tendency = '\uf07b'

                if curr_cond.get("visibility").get("value", "24") == None:
                    if self.data.config.weather_units == "imperial":
                        wx_visibility = "14.9 mi"
                    else:
                        wx_visibility = "24.1 km"
                else:
                    if self.data.config.weather_units == "imperial":
                        imp_visibility = round(
                            float(
                                curr_cond.get("visibility").get("value", "24"))
                            * 0.621371, 1)
                        wx_visibility = str(imp_visibility) + " mi"
                    else:
                        wx_visibility = curr_cond.get("visibility").get(
                            "value",
                            "24") + " " + curr_cond.get("visibility").get(
                                "unit", "km")

                self.data.wx_curr_wind = [
                    wx_windspeed, winddir[0], winddir[1], wx_windgust,
                    wx_pressure, wx_tendency, wx_visibility
                ]
            else:
                debug.error("Unable to get EC data error")

            debug.info(self.data.wx_current)
            debug.info(self.data.wx_curr_wind)

            # Run every 'x' minutes
            sleep(60 * self.weather_frequency)
    def run(self):

        while True:
            try:
                debug.info("Checking for EC weather alerts")
                ecData = ECData(coordinates=(self.data.latlng))
                curr_alerts = ecData.alerts
                self.network_issues = False
            except Exception as e:
                debug.error("Unable to get EC data error:{0}".format(e))
                num_alerts = 0
                self.network_issues = True
                pass
            
            
            debug.info("Last Alert: {0}".format(self.data.wx_alerts))
            # Check if there's more than a length of 5 returned back as if there's
            # No alerts, the dictionary still comes back with empty values for 
            # warning, watch, advisory, statements and endings
            # Currently don't do anything with a statement
            #debug.info(curr_alerts)

            #Find the latest date in the curr_alerts



            len_warn = len(curr_alerts.get("warnings").get("value"))
            len_watch = len(curr_alerts.get("watches").get("value"))
            len_advisory = len(curr_alerts.get("advisories").get("value"))

            num_alerts = len_warn + len_watch + len_advisory

            if num_alerts > 0:
                # Only get the latest alert
                i = 0
                # Create the warnings, watches and advisory lists from curr_alerts but only take the most recent one

                wx_num_endings = len(curr_alerts.get("endings").get("value","0"))
                wx_num_warning = len(curr_alerts.get("warnings").get("value","0"))
                wx_num_watch = len(curr_alerts.get("watches").get("value","0"))
                wx_num_advisory = len(curr_alerts.get("advisories").get("value","0"))

                wx_total_alerts = wx_num_endings + wx_num_warning + wx_num_watch + wx_num_advisory
                warn_datetime = 0
                watch_datetime = 0
                advisory_datetime = 0
                warning = []
                watch = []
                advisory = []
                alerts = []
                
                if wx_num_warning > 0:
                    warn_date = curr_alerts["warnings"]["value"][i]["date"]
                    #Convert to date for display
                    warn_datetime = datetime.datetime.strptime(warn_date,self.alert_date_format)
                    if self.time_format == "%H:%M":
                        wx_alert_time = warn_datetime.strftime("%m/%d %H:%M")
                    else:
                        wx_alert_time = warn_datetime.strftime("%m/%d %I:%M %p")
                    #Strip out the Warning at end of string for the title
                    wx_alert_title = curr_alerts["warnings"]["value"][i]["title"][:-(len(" Warning"))]
                    warning = [wx_alert_title,"warning",wx_alert_time]
                    alerts.append(warning)
                
                

                if wx_num_watch > 0:
                    watch_date = curr_alerts["watches"]["value"][i]["date"]
                    #Convert to date for display
                    watch_datetime = datetime.datetime.strptime(watch_date,self.alert_date_format)
                    if self.time_format == "%H:%M":
                        wx_alert_time = watch_datetime.strftime("%m/%d %H:%M")
                    else:
                        wx_alert_time = watch_datetime.strftime("%m/%d %I:%M %p")
                    wx_alert_title = curr_alerts["watches"]["value"][i]["title"][:-(len(" Watch"))]
                    watch = [wx_alert_title,"watch",wx_alert_time]
                    alerts.append(watch)

                

                if wx_num_advisory > 0:
                    advisory_date = curr_alerts["advisories"]["value"][i]["date"]
                    #Convert to date for display
                    advisory_datetime = datetime.datetime.strptime(advisory_date,self.alert_date_format)
                    
                    if self.time_format == "%H:%M":
                        wx_alert_time = advisory_datetime.strftime("%m/%d %H:%M")
                    else:
                        wx_alert_time = advisory_datetime.strftime("%m/%d %I:%M %p")

                    wx_alert_title = curr_alerts["advisories"]["value"][i]["title"][:-(len(" Advisory"))]
                    advisory = [wx_alert_title,"advisory",wx_alert_time]
                    alerts.append(advisory)

                
                #Find the latest alert time to set what the alert should be shown
                #debug.info(alerts)
                alerts.sort(key = lambda x: x[2],reverse=True)
                

                if alerts[0][0] == "Severe Thunderstorm":
                    alerts[0][0] = "Svr T-Storm"
                if alerts[0][0] == "Freezing Rain":
                    alerts[0][0] = "Frzn Rain"
                if alerts[0][0] == "Freezing Drizzle":
                    alerts[0][0] = "Frzn Drzl"
                
                #debug.info(alerts)

                if self.data.wx_alerts != alerts[0]:
                    self.data.wx_alerts = alerts[0]
                    self.weather_alert = 0

                if wx_num_endings > 0:
                    ending_date = curr_alerts["endings"]["value"][i]["date"]
                    #Convert to date for display
                    ending_datetime = datetime.datetime.strptime(ending_date,self.alert_date_format)
                    if self.time_format == "%H:%M":
                        wx_alert_time = ending_datetime.strftime("%m/%d %H:%M")
                    else:
                        wx_alert_time = ending_datetime.strftime("%m/%d %I:%M %p")

                    endings = [curr_alerts["endings"]["value"][i]["title"],"ended",wx_alert_time]
                    self.data.wx_alert_interrupt = False
                    self.weather_alert = 0
                    self.data.wx_alerts = []
                    debug.info(endings)
                # else:
                #     self.data.wx_alert_interrupt = False
                #     self.weather_alert = 0

                if len(self.data.wx_alerts) > 0:
                    debug.info("Current Alert: {0}".format(self.data.wx_alerts))

                if wx_num_endings == 0:
                    if self.weather_alert == 0:
                        self.data.wx_alert_interrupt = True
                        self.sleepEvent.set()
                    self.weather_alert += 1
                    
                
            else:
                debug.info("No active EC weather alerts in your area")
                self.data.wx_alert_interrupt = False
                self.data.wx_alerts.clear()
                self.weather_alert = 0
            # Run every 'x' minutes
            sleep(60 * self.alert_frequency)
Example #8
0
                 bg="green")
timeText.place(x=425, y=40)
clock()

# Title - Top LEFT

Title = Label(root,
              text="ENVIRONMENT CANADA",
              font=("VCR OSD Mono", 22),
              fg="white",
              bg="green")
Title.place(x=80, y=55)

# use ECData to gather weather data, station_id is from the csv file provided with ECData -- homepage: https://github.com/michaeldavie/env_canada

ec_en = ECData(station_id='AB/s0000045', language='english')
ec_en.update()

# Middle Section (Cycling weather pages, every 30sec)

weather_page()

# scrolling text canvas

marquee = Canvas(root, height=120, width=580, bg="green")
marquee.config(highlightbackground="green")
marquee.place(x=80, y=375)

# read in RSS data and prepare it

width = 35