diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index ca71a77..ec39bff 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -20,3 +20,4 @@ Contributors * Tomislav Kopić (@Tkopic001) * Maciej Sokolowski (@matemaciek) * Sangho Kim (@rlaace423) +* Breno RdV (@brenordv) diff --git a/examples/sys_info.py b/examples/sys_info.py index e42f7cd..07500a4 100755 --- a/examples/sys_info.py +++ b/examples/sys_info.py @@ -16,6 +16,7 @@ import os import sys import time +import socket from pathlib import Path from datetime import datetime @@ -37,6 +38,32 @@ # TODO: Load histogram +class IPAddressChecker: + def __init__(self, cache_duration_in_seconds=14400): + """ + :param cache_duration_in_seconds: The duration in seconds to cache the IP address for. Default is 4 hours. + """ + self._ip_address = None + self._last_checked = None + self._cache_duration = cache_duration_in_seconds + + def get_ip_address(self): + if self._last_checked is None or time.time() - self._last_checked > self._cache_duration: + self._ip_address = self._retrieve_ip_address() + self._last_checked = time.time() + return self._ip_address + + @staticmethod + def _retrieve_ip_address(): + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("8.8.8.8", 80)) # Google DNS. Probably will never be down. + return s.getsockname()[0] + except Exception as e: + print(f"Error: {e}") + return "" + + def bytes2human(n): """ >>> bytes2human(10000) @@ -95,6 +122,7 @@ def stats(device): draw.text((0, 26), disk_usage('/'), font=font2, fill="white") try: draw.text((0, 38), network('wlan0'), font=font2, fill="white") + draw.text((0, 50), ip_address_checker.get_ip_address(), font=font2, fill="white") except KeyError: # no wifi enabled/available pass @@ -109,6 +137,7 @@ def main(): if __name__ == "__main__": try: device = get_device() + ip_address_checker = IPAddressChecker() main() except KeyboardInterrupt: pass diff --git a/setup.cfg b/setup.cfg index a7b5b4a..3ccd3f0 100644 --- a/setup.cfg +++ b/setup.cfg @@ -32,6 +32,7 @@ install_requires = luma.lcd>=2.5.0 luma.led_matrix>=1.5.0 argcomplete + psutil = "==7.0.0" tests_require = pytest pytest-cov