コード例 #1
0
ファイル: PIR.py プロジェクト: SWhardfish/WeatherPiDisplay
 def draw(self, screen, weather, updated):
     if GPIO.input(self.pin):
         Utils.display_wakeup()
         self.power_save_timer = 0
     else:
         self.power_save_timer += 1
         if self.power_save_timer > self.power_save_delay:
             logging.info("%s: screen sleep.", __class__.__name__)
             Utils.display_sleep()
コード例 #2
0
    def draw(self, screen, weather, updated):
        timestamp = time.time()
        locale_date = Utils.strftime(timestamp, "%A - %d %b %Y")
        locale_time = Utils.strftime(timestamp, "%H:%M:%S")

        self.clear_surface()
        self.draw_text(locale_date, (0, 0), "medium", "white", align="center")
        (right, _bottom) = self.draw_text(locale_time, (16, 20),
                                          "xlarge",
                                          "white",
                                          bold=True,
                                          align="center")
        self.update_screen(screen)
コード例 #3
0
    def draw(self, screen, weather, updated):
        timestamp = time.time()
        locale_date = Utils.strftime(timestamp, "%a, %x")
        locale_time = Utils.strftime(timestamp, "%H:%M")
        locale_second = Utils.strftime(timestamp, " %S")

        self.clear_surface()
        self.draw_text(locale_date, (0, 0), "small", "white")
        (right, _bottom) = self.draw_text(locale_time, (0, 20),
                                          "large",
                                          "white",
                                          bold=True)
        self.draw_text(locale_second, (right, 20), "medium", "gray", bold=True)
        self.update_screen(screen)
コード例 #4
0
def adjust_unit(values, condition, units):
    """adjust values units
    """
    value = values
    for key in condition.split("."):
        value = value[key] if key in value else None
    if condition == "dt":
        return datetime.datetime.fromtimestamp(value)
    if value is not None:
        value = float(value)
    if condition.startswith("temp") or condition == "dew_point":
        return value if units == "metric" else Utils.fahrenheit(value)
    if condition in ("wind_speed", "wind_deg"):
        return round(Utils.kilometer(value) if units == "metric" else value, 1)
    return value
コード例 #5
0
    def draw(self, screen, weather, updated):
        if weather is None or not updated:
            return

        current = weather["current"]
        sunrise = current["sunrise"]
        sunset = current["sunset"]

        surise = "{} \u2197".format(Utils.strftime(sunrise, "%H:%M"))
        sunset = "\u2198 {}".format(Utils.strftime(sunset, "%H:%M"))
        sun_icon = Utils.weather_icon("01d", self.icon_size)

        self.clear_surface()
        self.draw_image(sun_icon, ((self.rect.width - self.icon_size) / 2,
                                   (self.rect.height - self.icon_size) / 2))
        self.draw_text(surise, (0, 5), "small", "white", align="center")
        self.draw_text(sunset, (0, self.rect.height - 20),
                       "small",
                       "white",
                       align="center")
        self.update_screen(screen)
コード例 #6
0
    def draw(self, screen, weather, updated):
        if weather is None or not updated:
            return

        daily = weather["current"]
        wind_speed = daily["wind_speed"]
        wind_deg = daily["wind_deg"]

        wind_icon = Utils.wind_arrow_icon(wind_deg, self.icon_size)
        wind_speed = Utils.speed_text(wind_speed, self.units)
        wind_deg = Utils.wind_bearing_text(wind_deg)

        self.clear_surface()
        self.draw_text(wind_deg, (0, 5), "small", "white", align="center")
        self.draw_image(wind_icon,
                        ((self.rect.width - self.icon_size) / 2, 20 +
                         (self.rect.height - 40 - self.icon_size) / 2))
        self.draw_text(wind_speed, (0, self.rect.height - 20),
                       "small",
                       "white",
                       align="center")
        self.update_screen(screen)
コード例 #7
0
    def draw(self, screen, weather, updated):
        message = get_local_address()
        if message:
            self.seconds = 0
        else:
            message = "connection lost"
            self.seconds += 1
            if self.seconds_to_reboot and self.seconds > self.seconds_to_reboot:
                Utils.reboot()

        self.clear_surface()
        logging.info("%s: %s", __class__.__name__, message)
        for size in ("large", "medium", "small"):
            width, height = self.text_size(message, size, bold=True)
            if width <= self.rect.width and height <= self.rect.height:
                break
        self.draw_text(message, (0, 0),
                       size,
                       "white",
                       bold=True,
                       align="center")
        self.update_screen(screen)
コード例 #8
0
    def draw(self, screen, weather, updated):
        (celsius, humidity, data_changed) = self.get_sensor_value()
        if not data_changed:
            return

        color = Utils.heat_color(celsius, humidity,
                                 "metric") if humidity else "white"
        temperature = Utils.temperature_text(
            celsius if self.units == "metric" else Utils.fahrenheit(celsius),
            self.units)
        humidity = Utils.pressure_text(humidity) if humidity else None

        for size in ("large", "medium", "small"):
            # Horizontal
            message1 = "{} {}".format(temperature, humidity)
            message2 = None
            w, h = self.text_size(message1, size, bold=True)
            if w <= self.rect.width and 20 + h <= self.rect.height:
                break

            # Vertical
            message1 = temperature
            message2 = humidity if humidity else None
            w1, h1 = self.text_size(message1, size, bold=True)
            w2, h2 = self.text_size(message2, size, bold=True)
            if max(w1,
                   w2) <= self.rect.width and 20 + h1 + h2 <= self.rect.height:
                break

        self.clear_surface()
        self.draw_text(_("Indoor"), (0, 0), "small", "gray")
        (w, h) = self.draw_text(message1, (0, 20), size, color, bold=True)
        if message2:
            self.draw_text(message2, (0, 20 + h), size, color, bold=True)
        self.update_screen(screen)

        # draw the graph if necessary
        self.draw_graph(screen, weather, updated)
コード例 #9
0
    def draw(self, screen, weather, updated):
        if weather is None or not updated:
            return

        daily = weather["daily"][self.day]
        temperature_high = daily["temp"]["max"]
        temperature_low = daily["temp"]["min"]
        icon = daily["weather"][0]["icon"]

        weather_icon = Utils.weather_icon(icon, self.icon_size)
        day_of_week = Utils.strftime(daily["dt"], "%a")
        temperature_low = Utils.temperature_text(int(temperature_low),
                                                 self.units)
        temperature_high = Utils.temperature_text(int(temperature_high),
                                                  self.units)
        message = "{}-{}".format(temperature_low, temperature_high)

        self.clear_surface()
        self.draw_text(day_of_week, (0, 0), "small", "orange", align="center")
        self.draw_text(message, (0, 15), "small", "gray", align="center")
        self.draw_image(weather_icon,
                        ((self.rect.width - self.icon_size) / 2, 30 +
                         (self.rect.height - 30 - self.icon_size) / 2))
        self.update_screen(screen)
コード例 #10
0
def self_update():
    """Check git master repository and update
    """
    def execute_command(cmd):
        p = subprocess.Popen(cmd,
                             cwd=sys.path[0],
                             shell=True,
                             stdout=subprocess.PIPE)
        o, _e = p.communicate()
        return str(o.strip(), "utf-8")

    try:
        rid = execute_command("git ls-remote origin HEAD | cut -f1")
        lid = execute_command("git log --format='%H' -n 1")
        logging.info("remote: %s local: %s", rid, lid)
        if rid == lid:
            logging.debug("Up to date")
        else:
            execute_command("sudo -u pi git pull")
            logging.info("Updated to new version")
            Utils.restart()

    except Exception as e:
        logging.error(e, exc_info=True)
コード例 #11
0
    def draw(self, screen, weather, updated):
        if weather is None or not updated:
            return

        current = weather["current"]
        dt = datetime.datetime.fromtimestamp(int(current["dt"]))
        moon_age = (
            ((dt.year - 11) % 19) * 11 +
            [0, 2, 0, 2, 2, 4, 5, 6, 7, 8, 9, 10][dt.month - 1] + dt.day) % 30

        moon_icon = Utils.moon_icon(moon_age, self.icon_size)
        moon_age = str(moon_age)

        self.clear_surface()
        self.draw_image(moon_icon, ((self.rect.width - self.icon_size) / 2, 5))
        self.draw_text(moon_age, (0, self.rect.height - 20),
                       "small",
                       "white",
                       align="center")
        self.update_screen(screen)
コード例 #12
0
    def get_sensor_value(self):
        """read last sensor value
        """
        # No result yet
        result = self.sensor_thread.get_result()
        if result is None:
            logging.info("%s: No data from sensor", __class__.__name__)
            self.last_hash_value = None
            return (None, None, False)

        (celsius, humidity) = result

        # logging only once a minute
        dt = datetime.datetime.now()
        if dt.second == 0:
            self.times = self.times[1:] + [dt]
            if self.temperatures is not None:
                celsius = np.nan if celsius is None else float(
                    celsius if self.units ==
                    "metric" else Utils.fahrenheit(celsius))
                self.temperatures = self.temperatures[1:] + [celsius]
            else:
                celsius = None
            if self.humidities is not None:
                humidity = np.nan if humidity is None else float(humidity)
                self.humidities = self.humidities[1:] + [humidity]
            else:
                humidity = None
            if self.logfile:
                with open(self.logfile, mode="a") as f:
                    f.write("{},{},{}\n".format(dt, celsius, humidity))

        # Has the value changed
        hash_value = self.sensor_thread.get_hash_value()
        if self.last_hash_value == hash_value:
            return (celsius, humidity, False)

        self.last_hash_value = hash_value
        return (celsius, humidity, True)
コード例 #13
0
    def draw(self, screen, weather, updated):
        if weather is None or not updated:
            return

        current = weather["current"]
        daily = weather["daily"][0]

        short_summary = _(current["weather"][0]["main"])
        icon = current["weather"][0]["icon"]
        temperature = current["temp"]
        humidity = current["humidity"]
        feels_like = current["feels_like"]
        pressure = current["pressure"]
        uv_index = int(current["uvi"])
        long_summary = daily["weather"][0]["description"]
        temperature_high = daily["temp"]["max"]
        temperature_low = daily["temp"]["min"]

        heat_color = Utils.heat_color(temperature, humidity, self.units)
        uv_color = Utils.uv_color(uv_index)
        weather_icon = Utils.weather_icon(icon, self.icon_size)

        temperature = Utils.temperature_text(int(temperature), self.units)
        feels_like = Utils.temperature_text(int(feels_like), self.units)
        temperature_low = Utils.temperature_text(int(temperature_low),
                                                 self.units)
        temperature_high = Utils.temperature_text(int(temperature_high),
                                                  self.units)
        humidity = Utils.percentage_text(humidity)
        uv_index = str(uv_index)
        pressure = Utils.pressure_text(int(pressure))

        text_x = weather_icon.get_size()[0]
        text_width = self.rect.width - text_x

        message1 = self.text_warp("{} {}".format(temperature, short_summary),
                                  text_width,
                                  "medium",
                                  bold=True,
                                  max_lines=1)[0]
        message2 = "{} {}   {} {} {} {}".format(_("Feels Like"), feels_like,
                                                _("Low"), temperature_low,
                                                _("High"), temperature_high)
        if self.text_size(message2, "small")[0] > text_width:
            message2 = "Feel {}  {} - {}".format(feels_like, temperature_low,
                                                 temperature_high)
        message3 = "{} {}  {} {}  {} {}".format(_("Humidity"), humidity,
                                                _("Pressure"), pressure,
                                                _("UVindex"), uv_index)
        if self.text_size(message3, "small")[0] > text_width:
            message3 = "{}  {}  UV {}".format(humidity, pressure, uv_index)
        max_lines = int((self.rect.height - 55) / 15)
        message4s = self.text_warp(long_summary,
                                   text_width,
                                   "small",
                                   bold=True,
                                   max_lines=max_lines)

        self.clear_surface()
        self.draw_image(weather_icon, (0, 0))
        self.draw_text(message1, (text_x, 0), "medium", heat_color, bold=True)
        self.draw_text(message2, (text_x, 25), "small", "white")
        i = message3.index("UV")
        (right, _bottom) = self.draw_text(message3[:i], (text_x, 40), "small",
                                          "white")
        self.draw_text(message3[i:], (right, 40), "small", uv_color, bold=True)
        height = 55 + (15 * (max_lines - len(message4s))) / 2
        for message in message4s:
            self.draw_text(message, (text_x, height),
                           "small",
                           "white",
                           bold=True)
            height += 15
        self.update_screen(screen)
コード例 #14
0
    def draw(self, screen, weather, updated):
        if weather is None or not updated:
            return

        current = weather["current"]
        daily = weather["daily"][0]

        short_summary = _(current["weather"][0]["main"])
        icon = current["weather"][0]["icon"]
        temperature = current["temp"]
        humidity = current["humidity"]
        feels_like = current["feels_like"]
        pressure = current["pressure"]
        uv_index = int(current["uvi"])
        try:
            rain_1h = current["rain"]["1h"]
        except KeyError:
            rain_1h = '0'
        windspeed = current["wind_speed"]
        try:
            windgust = current["wind_gust"]
        except KeyError:
            windgust = 'nan'
        print(windgust)
        long_summary = daily["weather"][0]["description"]
        temperature_high = daily["temp"]["max"]
        temperature_low = daily["temp"]["min"]
        heat_color = Utils.heat_color(temperature, humidity, self.units)
        uv_color = Utils.uv_color(uv_index)
        weather_icon = Utils.weather_icon(icon, self.icon_size)

        #temperature = Utils.temperature_text(int(temperature), self.units)
        temperature = Utils.temperature_text(round(temperature, 1), self.units)
        feels_like = Utils.temperature_text(int(feels_like), self.units)
        temperature_low = Utils.temperature_text(int(temperature_low),
                                                 self.units)
        temperature_high = Utils.temperature_text(int(temperature_high),
                                                  self.units)
        humidity = Utils.percentage_text(humidity)
        uv_index = str(uv_index)
        pressure = Utils.pressure_text(int(pressure))

        """
        HistoryGraphLog - log data to GraphDatalog.txt
        """
        # TODO: Add maintenance of GraphDataLog.txt for removing old data to keep file small.
        xtemperature = temperature
        xtemperature = xtemperature[:-2]
        xpressure = pressure
        xpressure = xpressure[:-2]
        xtimestamp = time.strftime('%m-%d-%Y %H:%M:%S')

        graph = "GraphDataLog.txt"
        file = open(graph, "a", newline='')

        with file:
            myfields = ['xdate', 'temp', 'press', 'rain_1h', 'windspeed', 'windgust']
            writer = csv.DictWriter(file, fieldnames=myfields)
            #writer.writeheader()
            writer.writerow({'xdate': xtimestamp, 'temp': xtemperature, 'press': xpressure, 'rain_1h': rain_1h, 'windspeed': windspeed, 'windgust': windgust})
        #file.close()
        df = pandas.read_csv(graph)

        # convert to datetime
        df['xdate'] = pandas.to_datetime(df['xdate'])
        # calculate mask
        m1 = df['xdate'] >= (pandas.to_datetime('now') - pandas.DateOffset(days=1))
        m2 = df['xdate'] <= pandas.to_datetime('now')
        #mask = m1 & m2
        mask = m1
        # output masked dataframes
        # df[~mask].to_csv('out1.csv', index=False)
        #Remove time from datetime
        #df['xdate'] = pandas.to_datetime(df['xdate']).dt.date
        df[mask].to_csv('GraphData.csv', index=False)
        """
        END GraphLog
        """


        text_x = weather_icon.get_size()[0]
        text_width = self.rect.width - text_x

        message1 = self.text_warp("{} {}".format(temperature, short_summary),
                                  text_width,
                                  "medium",
                                  bold=True,
                                  max_lines=1)[0]
        message2 = "{} {}   {} {} {} {}".format(_("Feels Like"), feels_like,
                                                _("Low"), temperature_low,
                                                _("High"), temperature_high)
        if self.text_size(message2, "small")[0] > text_width:
            message2 = "Feel {}  {} - {}".format(feels_like, temperature_low,
                                                 temperature_high)
        message3 = "{} {}  {} {}  {} {}".format(_("Humidity"), humidity,
                                                _("Pressure"), pressure,
                                                _("UVindex"), uv_index)
        if self.text_size(message3, "small")[0] > text_width:
            message3 = "{}  {}  UV {}".format(humidity, pressure, uv_index)
        max_lines = int((self.rect.height - 55) / 15)
        message4s = self.text_warp(long_summary,
                                   text_width,
                                   "small",
                                   bold=True,
                                   max_lines=max_lines)

        self.clear_surface()
        self.draw_image(weather_icon, (0, 0))
        self.draw_text(message1, (text_x, 15), "large", heat_color, bold=True)
        self.draw_text(message2, (text_x, 52), "small", "white")
        i = message3.index("UV")
        (right, _bottom) = self.draw_text(message3[:i], (text_x, 70), "small",
                                          "white")
        self.draw_text(message3[i:], (right, 70), "small", uv_color, bold=True)
        height = 70 + (15 * (max_lines - len(message4s))) / 2
        for message in message4s:
            self.draw_text(message, (text_x, height),
                           "small",
                           "blue",
                           bold=True)
            height += 15
        self.update_screen(screen)